repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/SearchEngine/Elastic/ElasticSearchEngine.php
ElasticSearchEngine.query
public function query($queryText, SearchEngineOptions $options = null) { $options = $options ?: new SearchEngineOptions(); $context = $this->context_factory->createContext($options); /** @var QueryCompiler $query_compiler */ $query_compiler = $this->app['query_compiler']; $queryAST = $query_compiler->parse($queryText)->dump(); $queryCompiled = $query_compiler->compile($queryText, $context); $queryESLib = $this->createRecordQueryParams($queryCompiled, $options, null); // ask ES to return field _version (incremental version number of document) $queryESLib['body']['version'] = true; $queryESLib['body']['from'] = $options->getFirstResult(); $queryESLib['body']['size'] = $options->getMaxResults(); if($this->options->getHighlight()) { $queryESLib['body']['highlight'] = $this->buildHighlightRules($context); } $aggs = $this->getAggregationQueryParams($options); if ($aggs) { $queryESLib['body']['aggs'] = $aggs; } $res = $this->client->search($queryESLib); $results = new ArrayCollection(); $n = 0; foreach ($res['hits']['hits'] as $hit) { $results[] = ElasticsearchRecordHydrator::hydrate($hit, $n++); } /** @var FacetsResponse $facets */ $facets = $this->facetsResponseFactory->__invoke($res); return new SearchEngineResult( $options, $results, // ArrayCollection of results $queryText, // the query as typed by the user $queryAST, $queryCompiled, $queryESLib, $res['took'], // duration $options->getFirstResult(), $res['hits']['total'], // available $res['hits']['total'], // total null, // error null, // warning $facets->getAsSuggestions(), // ArrayCollection of suggestions [], // propositions $this->indexName, $facets ); }
php
public function query($queryText, SearchEngineOptions $options = null) { $options = $options ?: new SearchEngineOptions(); $context = $this->context_factory->createContext($options); /** @var QueryCompiler $query_compiler */ $query_compiler = $this->app['query_compiler']; $queryAST = $query_compiler->parse($queryText)->dump(); $queryCompiled = $query_compiler->compile($queryText, $context); $queryESLib = $this->createRecordQueryParams($queryCompiled, $options, null); // ask ES to return field _version (incremental version number of document) $queryESLib['body']['version'] = true; $queryESLib['body']['from'] = $options->getFirstResult(); $queryESLib['body']['size'] = $options->getMaxResults(); if($this->options->getHighlight()) { $queryESLib['body']['highlight'] = $this->buildHighlightRules($context); } $aggs = $this->getAggregationQueryParams($options); if ($aggs) { $queryESLib['body']['aggs'] = $aggs; } $res = $this->client->search($queryESLib); $results = new ArrayCollection(); $n = 0; foreach ($res['hits']['hits'] as $hit) { $results[] = ElasticsearchRecordHydrator::hydrate($hit, $n++); } /** @var FacetsResponse $facets */ $facets = $this->facetsResponseFactory->__invoke($res); return new SearchEngineResult( $options, $results, // ArrayCollection of results $queryText, // the query as typed by the user $queryAST, $queryCompiled, $queryESLib, $res['took'], // duration $options->getFirstResult(), $res['hits']['total'], // available $res['hits']['total'], // total null, // error null, // warning $facets->getAsSuggestions(), // ArrayCollection of suggestions [], // propositions $this->indexName, $facets ); }
[ "public", "function", "query", "(", "$", "queryText", ",", "SearchEngineOptions", "$", "options", "=", "null", ")", "{", "$", "options", "=", "$", "options", "?", ":", "new", "SearchEngineOptions", "(", ")", ";", "$", "context", "=", "$", "this", "->", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/Elastic/ElasticSearchEngine.php#L277-L332
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/SearchEngine/Elastic/ElasticSearchEngine.php
ElasticSearchEngine.computeAccess
private function computeAccess($and, $xor, $bit) { $xorBit = \databox_status::bitIsSet($xor, $bit); $andBit = \databox_status::bitIsSet($and, $bit); if (!$xorBit && !$andBit) { return self::FLAG_ALLOW_BOTH; } if ($xorBit && $andBit) { return self::FLAG_SET_ONLY; } return self::FLAG_UNSET_ONLY; }
php
private function computeAccess($and, $xor, $bit) { $xorBit = \databox_status::bitIsSet($xor, $bit); $andBit = \databox_status::bitIsSet($and, $bit); if (!$xorBit && !$andBit) { return self::FLAG_ALLOW_BOTH; } if ($xorBit && $andBit) { return self::FLAG_SET_ONLY; } return self::FLAG_UNSET_ONLY; }
[ "private", "function", "computeAccess", "(", "$", "and", ",", "$", "xor", ",", "$", "bit", ")", "{", "$", "xorBit", "=", "\\", "databox_status", "::", "bitIsSet", "(", "$", "xor", ",", "$", "bit", ")", ";", "$", "andBit", "=", "\\", "databox_status",...
Truth table for status rights +-----------+ | and | xor | +-----------+ | 0 | 0 | -> BOTH STATES ARE CHECKED +-----------+ | 1 | 0 | -> UNSET STATE IS CHECKED +-----------+ | 0 | 1 | -> UNSET STATE IS CHECKED (not possible) +-----------+ | 1 | 1 | -> SET STATE IS CHECKED +-----------+
[ "Truth", "table", "for", "status", "rights" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/Elastic/ElasticSearchEngine.php#L521-L535
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/SearchEngine/Elastic/ElasticSearchEngine.php
ElasticSearchEngine.autocomplete
public function autocomplete($query, SearchEngineOptions $options) { $params = $this->createCompletionParams($query, $options); $res = $this->client->suggest($params); $ret = [ 'text' => [], 'byField' => [] ]; foreach (array_keys($params['body']) as $fname) { $t = []; foreach ($res[$fname] as $suggest) { // don't know why there is a sub-array level foreach ($suggest['options'] as $option) { $text = $option['text']; if (!in_array($text, $ret['text'])) { $ret['text'][] = $text; } $t[] = [ 'label' => $text, 'query' => $fname . ':' . $text ]; } } if (!empty($t)) { $ret['byField'][$fname] = $t; } } return $ret; }
php
public function autocomplete($query, SearchEngineOptions $options) { $params = $this->createCompletionParams($query, $options); $res = $this->client->suggest($params); $ret = [ 'text' => [], 'byField' => [] ]; foreach (array_keys($params['body']) as $fname) { $t = []; foreach ($res[$fname] as $suggest) { // don't know why there is a sub-array level foreach ($suggest['options'] as $option) { $text = $option['text']; if (!in_array($text, $ret['text'])) { $ret['text'][] = $text; } $t[] = [ 'label' => $text, 'query' => $fname . ':' . $text ]; } } if (!empty($t)) { $ret['byField'][$fname] = $t; } } return $ret; }
[ "public", "function", "autocomplete", "(", "$", "query", ",", "SearchEngineOptions", "$", "options", ")", "{", "$", "params", "=", "$", "this", "->", "createCompletionParams", "(", "$", "query", ",", "$", "options", ")", ";", "$", "res", "=", "$", "this"...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/Elastic/ElasticSearchEngine.php#L690-L720
alchemy-fr/Phraseanet
lib/classes/DailymotionWithoutOauth2.php
DailymotionWithoutOauth2.call
public function call($method, $args = [], $access_token = null) { $headers = ['Content-Type: application/json']; $payload = json_encode([ 'call' => $method, 'args' => $args, ]); $status_code = null; try { $result = json_decode($this->oauthRequest($this->apiEndpointUrl, $payload, $access_token, $headers, $status_code), true); } catch (DailymotionAuthException $e) { if ($e->error === 'invalid_token') { throw new Bridge_Exception_ActionAuthNeedReconnect(); } else { throw $e; } } if ( ! isset($result)) { throw new DailymotionApiException('Invalid API server response.'); } elseif ($status_code !== 200) { throw new DailymotionApiException('Unknown error: ' . $status_code, $status_code); } elseif (is_array($result) && isset($result['error'])) { $message = isset($result['error']['message']) ? $result['error']['message'] : null; $code = isset($result['error']['code']) ? $result['error']['code'] : null; if ($code === 403) { throw new DailymotionAuthRequiredException($message, $code); } else { throw new DailymotionApiException($message, $code); } } elseif ( ! isset($result['result'])) { throw new DailymotionApiException("Invalid API server response: no `result' key found."); } return $result['result']; }
php
public function call($method, $args = [], $access_token = null) { $headers = ['Content-Type: application/json']; $payload = json_encode([ 'call' => $method, 'args' => $args, ]); $status_code = null; try { $result = json_decode($this->oauthRequest($this->apiEndpointUrl, $payload, $access_token, $headers, $status_code), true); } catch (DailymotionAuthException $e) { if ($e->error === 'invalid_token') { throw new Bridge_Exception_ActionAuthNeedReconnect(); } else { throw $e; } } if ( ! isset($result)) { throw new DailymotionApiException('Invalid API server response.'); } elseif ($status_code !== 200) { throw new DailymotionApiException('Unknown error: ' . $status_code, $status_code); } elseif (is_array($result) && isset($result['error'])) { $message = isset($result['error']['message']) ? $result['error']['message'] : null; $code = isset($result['error']['code']) ? $result['error']['code'] : null; if ($code === 403) { throw new DailymotionAuthRequiredException($message, $code); } else { throw new DailymotionApiException($message, $code); } } elseif ( ! isset($result['result'])) { throw new DailymotionApiException("Invalid API server response: no `result' key found."); } return $result['result']; }
[ "public", "function", "call", "(", "$", "method", ",", "$", "args", "=", "[", "]", ",", "$", "access_token", "=", "null", ")", "{", "$", "headers", "=", "[", "'Content-Type: application/json'", "]", ";", "$", "payload", "=", "json_encode", "(", "[", "'...
Call a remote method. @param String $method the method name to call. @param Array $args an associative array of arguments. @param String $access_token @return mixed the method response @throws DailymotionApiException if API return an error @throws DailymotionAuthException if can't authenticate the request @throws DailymotionAuthRequiredException if not authentication info is available @throws DailymotionTransportException if an error occurs during request.
[ "Call", "a", "remote", "method", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/DailymotionWithoutOauth2.php#L20-L57
alchemy-fr/Phraseanet
lib/classes/DailymotionWithoutOauth2.php
DailymotionWithoutOauth2.sendFile
public function sendFile($filePath, $oauth_token) { $result = $this->call('file.upload', [], $oauth_token); $timeout = $this->timeout; $this->timeout = null; $result = json_decode($this->httpRequest($result['upload_url'], ['file' => '@' . $filePath]), true); $this->timeout = $timeout; return $result['url']; }
php
public function sendFile($filePath, $oauth_token) { $result = $this->call('file.upload', [], $oauth_token); $timeout = $this->timeout; $this->timeout = null; $result = json_decode($this->httpRequest($result['upload_url'], ['file' => '@' . $filePath]), true); $this->timeout = $timeout; return $result['url']; }
[ "public", "function", "sendFile", "(", "$", "filePath", ",", "$", "oauth_token", ")", "{", "$", "result", "=", "$", "this", "->", "call", "(", "'file.upload'", ",", "[", "]", ",", "$", "oauth_token", ")", ";", "$", "timeout", "=", "$", "this", "->", ...
Upload a file on the Dailymotion servers and generate an URL to be used with API methods. @param String $filePath a path to the file to upload @param String $oauth_token a path to the file to upload @return String the resulting URL
[ "Upload", "a", "file", "on", "the", "Dailymotion", "servers", "and", "generate", "an", "URL", "to", "be", "used", "with", "API", "methods", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/DailymotionWithoutOauth2.php#L67-L76
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Model/Repositories/FeedEntryRepository.php
FeedEntryRepository.findByFeeds
public function findByFeeds($feeds, $offset_start = null, $how_many = null) { $dql = 'SELECT f FROM Phraseanet:FeedEntry f WHERE f.feed IN (:feeds) order by f.updatedOn DESC'; $query = $this->_em->createQuery($dql); $query->setParameter('feeds', $feeds); if (null !== $offset_start && 0 !== $offset_start) { $query->setFirstResult($offset_start); } if (null !== $how_many) { $query->setMaxResults($how_many); } return $query->getResult(); }
php
public function findByFeeds($feeds, $offset_start = null, $how_many = null) { $dql = 'SELECT f FROM Phraseanet:FeedEntry f WHERE f.feed IN (:feeds) order by f.updatedOn DESC'; $query = $this->_em->createQuery($dql); $query->setParameter('feeds', $feeds); if (null !== $offset_start && 0 !== $offset_start) { $query->setFirstResult($offset_start); } if (null !== $how_many) { $query->setMaxResults($how_many); } return $query->getResult(); }
[ "public", "function", "findByFeeds", "(", "$", "feeds", ",", "$", "offset_start", "=", "null", ",", "$", "how_many", "=", "null", ")", "{", "$", "dql", "=", "'SELECT f FROM Phraseanet:FeedEntry f\n WHERE f.feed IN (:feeds) order by f.updatedOn DESC'", ";", ...
Returns a collection of FeedEntry from given feeds, limited to $how_many results, starting with $offset_start @param array $feeds @param integer $offset_start @param integer $how_many @return FeedEntry[]
[ "Returns", "a", "collection", "of", "FeedEntry", "from", "given", "feeds", "limited", "to", "$how_many", "results", "starting", "with", "$offset_start" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Repositories/FeedEntryRepository.php#L35-L51
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/TaskManager/Job/WebhookJob.php
WebhookJob.doJob
protected function doJob(JobData $data) { $app = $data->getApplication(); $thirdPartyApplications = $app['repo.api-applications']->findWithDefinedWebhookCallback(); $that = $this; if ($this->firstRun) { $this->httpClient->getEventDispatcher()->addListener('request.error', function (Event $event) { // override guzzle default behavior of throwing exceptions // when 4xx & 5xx responses are encountered $event->stopPropagation(); }, -254); // Set callback which logs success or failure $subscriber = new CallbackBackoffStrategy(function ($retries, Request $request, $response, $e) use ($app, $that) { $retry = true; if ($response && (null !== $deliverId = parse_url($request->getUrl(), PHP_URL_FRAGMENT))) { $delivery = $app['repo.webhook-delivery']->find($deliverId); $logContext = [ 'host' => $request->getHost() ]; if ($response->isSuccessful()) { $app['manipulator.webhook-delivery']->deliverySuccess($delivery); $logType = 'info'; $logEntry = sprintf('Deliver success event "%d:%s" for app "%s"', $delivery->getWebhookEvent()->getId(), $delivery->getWebhookEvent()->getName(), $delivery->getThirdPartyApplication()->getName() ); $retry = false; } else { $app['manipulator.webhook-delivery']->deliveryFailure($delivery); $logType = 'error'; $logEntry = sprintf('Deliver failure event "%d:%s" for app "%s"', $delivery->getWebhookEvent()->getId(), $delivery->getWebhookEvent()->getName(), $delivery->getThirdPartyApplication()->getName() ); } $that->log($logType, $logEntry, $logContext); return $retry; } }, true, new CurlBackoffStrategy()); // set max retries $subscriber = new TruncatedBackoffStrategy(WebhookEventDelivery::MAX_DELIVERY_TRIES, $subscriber); $subscriber = new BackoffPlugin($subscriber); $this->httpClient->addSubscriber($subscriber); $this->firstRun = false; } /** @var EventProcessorFactory $eventFactory */ $eventFactory = $app['webhook.processor_factory']; foreach ($app['repo.webhook-event']->getUnprocessedEventIterator() as $row) { $event = $row[0]; // set event as processed $app['manipulator.webhook-event']->processed($event); $this->log('info', sprintf('Processing event "%s" with id %d', $event->getName(), $event->getId())); // send requests $this->deliverEvent($eventFactory, $app, $thirdPartyApplications, $event); } }
php
protected function doJob(JobData $data) { $app = $data->getApplication(); $thirdPartyApplications = $app['repo.api-applications']->findWithDefinedWebhookCallback(); $that = $this; if ($this->firstRun) { $this->httpClient->getEventDispatcher()->addListener('request.error', function (Event $event) { // override guzzle default behavior of throwing exceptions // when 4xx & 5xx responses are encountered $event->stopPropagation(); }, -254); // Set callback which logs success or failure $subscriber = new CallbackBackoffStrategy(function ($retries, Request $request, $response, $e) use ($app, $that) { $retry = true; if ($response && (null !== $deliverId = parse_url($request->getUrl(), PHP_URL_FRAGMENT))) { $delivery = $app['repo.webhook-delivery']->find($deliverId); $logContext = [ 'host' => $request->getHost() ]; if ($response->isSuccessful()) { $app['manipulator.webhook-delivery']->deliverySuccess($delivery); $logType = 'info'; $logEntry = sprintf('Deliver success event "%d:%s" for app "%s"', $delivery->getWebhookEvent()->getId(), $delivery->getWebhookEvent()->getName(), $delivery->getThirdPartyApplication()->getName() ); $retry = false; } else { $app['manipulator.webhook-delivery']->deliveryFailure($delivery); $logType = 'error'; $logEntry = sprintf('Deliver failure event "%d:%s" for app "%s"', $delivery->getWebhookEvent()->getId(), $delivery->getWebhookEvent()->getName(), $delivery->getThirdPartyApplication()->getName() ); } $that->log($logType, $logEntry, $logContext); return $retry; } }, true, new CurlBackoffStrategy()); // set max retries $subscriber = new TruncatedBackoffStrategy(WebhookEventDelivery::MAX_DELIVERY_TRIES, $subscriber); $subscriber = new BackoffPlugin($subscriber); $this->httpClient->addSubscriber($subscriber); $this->firstRun = false; } /** @var EventProcessorFactory $eventFactory */ $eventFactory = $app['webhook.processor_factory']; foreach ($app['repo.webhook-event']->getUnprocessedEventIterator() as $row) { $event = $row[0]; // set event as processed $app['manipulator.webhook-event']->processed($event); $this->log('info', sprintf('Processing event "%s" with id %d', $event->getName(), $event->getId())); // send requests $this->deliverEvent($eventFactory, $app, $thirdPartyApplications, $event); } }
[ "protected", "function", "doJob", "(", "JobData", "$", "data", ")", "{", "$", "app", "=", "$", "data", "->", "getApplication", "(", ")", ";", "$", "thirdPartyApplications", "=", "$", "app", "[", "'repo.api-applications'", "]", "->", "findWithDefinedWebhookCall...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/TaskManager/Job/WebhookJob.php#L88-L157
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/Upgrade39Feeds.php
Upgrade39Feeds.apply
public function apply(EntityManager $em, \appbox $appbox, Configuration $conf) { $this->doBackupFeedsTable($em); }
php
public function apply(EntityManager $em, \appbox $appbox, Configuration $conf) { $this->doBackupFeedsTable($em); }
[ "public", "function", "apply", "(", "EntityManager", "$", "em", ",", "\\", "appbox", "$", "appbox", ",", "Configuration", "$", "conf", ")", "{", "$", "this", "->", "doBackupFeedsTable", "(", "$", "em", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/Upgrade39Feeds.php#L25-L28
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/Upgrade39Feeds.php
Upgrade39Feeds.rollback
public function rollback(EntityManager $em, \appbox $appbox, Configuration $conf) { if ($this->tableExists($em, 'feeds_backup')) { $em->getConnection()->getSchemaManager()->renameTable('feeds_backup', 'feeds'); } }
php
public function rollback(EntityManager $em, \appbox $appbox, Configuration $conf) { if ($this->tableExists($em, 'feeds_backup')) { $em->getConnection()->getSchemaManager()->renameTable('feeds_backup', 'feeds'); } }
[ "public", "function", "rollback", "(", "EntityManager", "$", "em", ",", "\\", "appbox", "$", "appbox", ",", "Configuration", "$", "conf", ")", "{", "if", "(", "$", "this", "->", "tableExists", "(", "$", "em", ",", "'feeds_backup'", ")", ")", "{", "$", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/Upgrade39Feeds.php#L41-L46
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Model/Repositories/UsrListRepository.php
UsrListRepository.findUserListLike
public function findUserListLike(User $user, $name) { $dql = 'SELECT l FROM Phraseanet:UsrList l JOIN l.owners o WHERE o.user = :usr_id AND l.name LIKE :name'; $params = [ 'usr_id' => $user->getId(), 'name' => $name . '%' ]; $query = $this->_em->createQuery($dql); $query->setParameters($params); return $query->getResult(); }
php
public function findUserListLike(User $user, $name) { $dql = 'SELECT l FROM Phraseanet:UsrList l JOIN l.owners o WHERE o.user = :usr_id AND l.name LIKE :name'; $params = [ 'usr_id' => $user->getId(), 'name' => $name . '%' ]; $query = $this->_em->createQuery($dql); $query->setParameters($params); return $query->getResult(); }
[ "public", "function", "findUserListLike", "(", "User", "$", "user", ",", "$", "name", ")", "{", "$", "dql", "=", "'SELECT l FROM Phraseanet:UsrList l\n JOIN l.owners o\n WHERE o.user = :usr_id AND l.name LIKE :name'", ";", "$", "params", "=", "[", "'...
Search for a UsrList like '' with a given value, for a user @param User $user @param type $name @return \Doctrine\Common\Collections\ArrayCollection
[ "Search", "for", "a", "UsrList", "like", "with", "a", "given", "value", "for", "a", "user" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Repositories/UsrListRepository.php#L80-L95
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Authentication/Provider/Facebook.php
Facebook.authenticate
public function authenticate(array $params = array()) { $params = array_merge(['providerId' => $this->getId()], $params); return new RedirectResponse( $this->facebook->getRedirectLoginHelper()->getLoginUrl( $this->generator->generate( 'login_authentication_provider_callback', $params, UrlGenerator::ABSOLUTE_URL ), ['email'] ) ); }
php
public function authenticate(array $params = array()) { $params = array_merge(['providerId' => $this->getId()], $params); return new RedirectResponse( $this->facebook->getRedirectLoginHelper()->getLoginUrl( $this->generator->generate( 'login_authentication_provider_callback', $params, UrlGenerator::ABSOLUTE_URL ), ['email'] ) ); }
[ "public", "function", "authenticate", "(", "array", "$", "params", "=", "array", "(", ")", ")", "{", "$", "params", "=", "array_merge", "(", "[", "'providerId'", "=>", "$", "this", "->", "getId", "(", ")", "]", ",", "$", "params", ")", ";", "return",...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/Provider/Facebook.php#L53-L67
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Authentication/Provider/Facebook.php
Facebook.getIdentity
public function getIdentity() { $user = $this->getGraphUser(['id', 'name', 'email', 'picture', 'last_name', 'first_name']); $identity = new Identity(); $identity->set(Identity::PROPERTY_ID, $user['id']); $identity->set(Identity::PROPERTY_IMAGEURL, $user['picture']); $identity->set(Identity::PROPERTY_EMAIL, $user['email']); $identity->set(Identity::PROPERTY_FIRSTNAME, $user['first_name']); $identity->set(Identity::PROPERTY_LASTNAME, $user['last_name']); $identity->set(Identity::PROPERTY_USERNAME, $user['first_name']); return $identity; }
php
public function getIdentity() { $user = $this->getGraphUser(['id', 'name', 'email', 'picture', 'last_name', 'first_name']); $identity = new Identity(); $identity->set(Identity::PROPERTY_ID, $user['id']); $identity->set(Identity::PROPERTY_IMAGEURL, $user['picture']); $identity->set(Identity::PROPERTY_EMAIL, $user['email']); $identity->set(Identity::PROPERTY_FIRSTNAME, $user['first_name']); $identity->set(Identity::PROPERTY_LASTNAME, $user['last_name']); $identity->set(Identity::PROPERTY_USERNAME, $user['first_name']); return $identity; }
[ "public", "function", "getIdentity", "(", ")", "{", "$", "user", "=", "$", "this", "->", "getGraphUser", "(", "[", "'id'", ",", "'name'", ",", "'email'", ",", "'picture'", ",", "'last_name'", ",", "'first_name'", "]", ")", ";", "$", "identity", "=", "n...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/Provider/Facebook.php#L127-L141
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Authentication/Provider/Facebook.php
Facebook.onCallback
public function onCallback(Request $request) { $helper = $this->facebook->getRedirectLoginHelper(); try { $accessToken = $helper->getAccessToken(); } catch(\Facebook\Exceptions\FacebookResponseException $e) { throw new NotAuthenticatedException('Graph returned an error: ' . $e->getMessage()); exit; } catch(\Facebook\Exceptions\FacebookSDKException $e) { throw new NotAuthenticatedException('Facebook SDK returned an error: ' . $e->getMessage()); exit; } if (! isset($accessToken)) { if ($helper->getError()) { $error = "Error: " . $helper->getError() . "\n"; $error .= "Error Code: " . $helper->getErrorCode() . "\n"; $error .= "Error Reason: " . $helper->getErrorReason() . "\n"; $error .= "Error Description: " . $helper->getErrorDescription() . "\n"; throw new NotAuthenticatedException($error); } else { throw new NotAuthenticatedException('Facebook authentication failed'); } exit; } $oAuth2Client = $this->facebook->getOAuth2Client(); if (! $accessToken->isLongLived()) { try { $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken); } catch (\Facebook\Exceptions\FacebookSDKException $e) { throw new NotAuthenticatedException('Error getting long-lived access token: ' . $e->getMessage() ); exit; } } $this->session->set('fb_access_token', (string) $accessToken); }
php
public function onCallback(Request $request) { $helper = $this->facebook->getRedirectLoginHelper(); try { $accessToken = $helper->getAccessToken(); } catch(\Facebook\Exceptions\FacebookResponseException $e) { throw new NotAuthenticatedException('Graph returned an error: ' . $e->getMessage()); exit; } catch(\Facebook\Exceptions\FacebookSDKException $e) { throw new NotAuthenticatedException('Facebook SDK returned an error: ' . $e->getMessage()); exit; } if (! isset($accessToken)) { if ($helper->getError()) { $error = "Error: " . $helper->getError() . "\n"; $error .= "Error Code: " . $helper->getErrorCode() . "\n"; $error .= "Error Reason: " . $helper->getErrorReason() . "\n"; $error .= "Error Description: " . $helper->getErrorDescription() . "\n"; throw new NotAuthenticatedException($error); } else { throw new NotAuthenticatedException('Facebook authentication failed'); } exit; } $oAuth2Client = $this->facebook->getOAuth2Client(); if (! $accessToken->isLongLived()) { try { $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken); } catch (\Facebook\Exceptions\FacebookSDKException $e) { throw new NotAuthenticatedException('Error getting long-lived access token: ' . $e->getMessage() ); exit; } } $this->session->set('fb_access_token', (string) $accessToken); }
[ "public", "function", "onCallback", "(", "Request", "$", "request", ")", "{", "$", "helper", "=", "$", "this", "->", "facebook", "->", "getRedirectLoginHelper", "(", ")", ";", "try", "{", "$", "accessToken", "=", "$", "helper", "->", "getAccessToken", "(",...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/Provider/Facebook.php#L146-L186
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Authentication/Provider/Facebook.php
Facebook.create
public static function create(UrlGenerator $generator, SessionInterface $session, array $options) { $config['app_id'] = $options['app-id']; $config['app_secret'] = $options['secret']; $config['default_graph_version'] = $options['default-graph-version']; $facebook = new \Facebook\Facebook($config); return new static($facebook, $generator, $session); }
php
public static function create(UrlGenerator $generator, SessionInterface $session, array $options) { $config['app_id'] = $options['app-id']; $config['app_secret'] = $options['secret']; $config['default_graph_version'] = $options['default-graph-version']; $facebook = new \Facebook\Facebook($config); return new static($facebook, $generator, $session); }
[ "public", "static", "function", "create", "(", "UrlGenerator", "$", "generator", ",", "SessionInterface", "$", "session", ",", "array", "$", "options", ")", "{", "$", "config", "[", "'app_id'", "]", "=", "$", "options", "[", "'app-id'", "]", ";", "$", "c...
{@inheritdoc} @return Facebook
[ "{", "@inheritdoc", "}" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/Provider/Facebook.php#L253-L262
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/ControllerProvider/Prod/DoDownload.php
DoDownload.connect
public function connect(Application $app) { $controllers = $this->createCollection($app); $controllers->get('/{token}/prepare/', 'controller.prod.do-download:prepareDownload') ->before($app['middleware.token.converter']) ->bind('prepare_download') ->assert('token', '[a-zA-Z0-9]{8,32}'); $controllers->match('/{token}/get/', 'controller.prod.do-download:downloadDocuments') ->before($app['middleware.token.converter']) ->bind('document_download') ->assert('token', '[a-zA-Z0-9]{8,32}'); $controllers->post('/{token}/execute/', 'controller.prod.do-download:downloadExecute') ->before($app['middleware.token.converter']) ->bind('execute_download') ->assert('token', '[a-zA-Z0-9]{8,32}'); return $controllers; }
php
public function connect(Application $app) { $controllers = $this->createCollection($app); $controllers->get('/{token}/prepare/', 'controller.prod.do-download:prepareDownload') ->before($app['middleware.token.converter']) ->bind('prepare_download') ->assert('token', '[a-zA-Z0-9]{8,32}'); $controllers->match('/{token}/get/', 'controller.prod.do-download:downloadDocuments') ->before($app['middleware.token.converter']) ->bind('document_download') ->assert('token', '[a-zA-Z0-9]{8,32}'); $controllers->post('/{token}/execute/', 'controller.prod.do-download:downloadExecute') ->before($app['middleware.token.converter']) ->bind('execute_download') ->assert('token', '[a-zA-Z0-9]{8,32}'); return $controllers; }
[ "public", "function", "connect", "(", "Application", "$", "app", ")", "{", "$", "controllers", "=", "$", "this", "->", "createCollection", "(", "$", "app", ")", ";", "$", "controllers", "->", "get", "(", "'/{token}/prepare/'", ",", "'controller.prod.do-downloa...
{@inheritDoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/ControllerProvider/Prod/DoDownload.php#L45-L65
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Setup/Version/MailChecker.php
MailChecker.getWrongEmailUsers
public function getWrongEmailUsers() { if (version_compare($this->appbox->get_version(), '3.9', '>=')) { return []; } $builder = $this->appbox->get_connection()->createQueryBuilder(); /** @var Statement $stmt */ $stmt = $builder ->select('u.usr_mail', 'u.usr_id', 'u.last_conn', 'u.usr_login') ->from($this->table, 'u') ->where($builder->expr()->isNotNull('u.usr_mail')) ->execute() ; $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); $users = []; foreach ($rs as $row) { if (!isset($users[$row['usr_mail']])) { $users[$row['usr_mail']] = []; } $users[$row['usr_mail']][] = $row; } $badUsers = []; foreach ($users as $email => $usrs) { if (count($usrs) > 1) { $badUsers[$email] = []; foreach ($usrs as $usrInfo) { $badUsers[$email][$usrInfo['usr_id']] = $usrInfo; } } } unset($users); return $badUsers; }
php
public function getWrongEmailUsers() { if (version_compare($this->appbox->get_version(), '3.9', '>=')) { return []; } $builder = $this->appbox->get_connection()->createQueryBuilder(); /** @var Statement $stmt */ $stmt = $builder ->select('u.usr_mail', 'u.usr_id', 'u.last_conn', 'u.usr_login') ->from($this->table, 'u') ->where($builder->expr()->isNotNull('u.usr_mail')) ->execute() ; $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); $users = []; foreach ($rs as $row) { if (!isset($users[$row['usr_mail']])) { $users[$row['usr_mail']] = []; } $users[$row['usr_mail']][] = $row; } $badUsers = []; foreach ($users as $email => $usrs) { if (count($usrs) > 1) { $badUsers[$email] = []; foreach ($usrs as $usrInfo) { $badUsers[$email][$usrInfo['usr_id']] = $usrInfo; } } } unset($users); return $badUsers; }
[ "public", "function", "getWrongEmailUsers", "(", ")", "{", "if", "(", "version_compare", "(", "$", "this", "->", "appbox", "->", "get_version", "(", ")", ",", "'3.9'", ",", "'>='", ")", ")", "{", "return", "[", "]", ";", "}", "$", "builder", "=", "$"...
Returns users with duplicated emails @return array An array of User
[ "Returns", "users", "with", "duplicated", "emails" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Setup/Version/MailChecker.php#L46-L87
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Helper/Record/Helper.php
Helper.get_grouping_head
public function get_grouping_head() { if (!$this->is_single_grouping()) throw new \Exception('Cannot use ' . __METHOD__ . ' here'); foreach ($this->get_elements() as $record) { return $record; } }
php
public function get_grouping_head() { if (!$this->is_single_grouping()) throw new \Exception('Cannot use ' . __METHOD__ . ' here'); foreach ($this->get_elements() as $record) { return $record; } }
[ "public", "function", "get_grouping_head", "(", ")", "{", "if", "(", "!", "$", "this", "->", "is_single_grouping", "(", ")", ")", "throw", "new", "\\", "Exception", "(", "'Cannot use '", ".", "__METHOD__", ".", "' here'", ")", ";", "foreach", "(", "$", "...
When action on a single grouping, returns the image of himself @return \record_adapter
[ "When", "action", "on", "a", "single", "grouping", "returns", "the", "image", "of", "himself" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Helper/Record/Helper.php#L189-L196
alchemy-fr/Phraseanet
lib/classes/patch/384alpha2a.php
patch_384alpha2a.apply
public function apply(base $appbox, Application $app) { $finder = new Finder(); $fs = new Filesystem(); foreach ($finder->files()->in($app['root.path'].'/config/status') as $file) { if (!$file->isFile()) { continue; } $fileName = $file->getFileName(); $chunks = explode('-', $fileName); if (count($chunks) < 4) { continue; } $suffix = array_pop($chunks); $uniqid = md5(implode('-', $chunks)); $fs->rename($file->getRealPath(), $app['root.path'].'/config/status/' . $uniqid . '-' . $suffix); if ($fs->exists($app['root.path'] . '/www/custom/status/' . $file->getFileName())) { $fs->remove($app['root.path'] . '/www/custom/status/' . $file->getFileName()); } } $app['filesystem']->mirror($app['root.path'] . '/config/status/', $app['root.path'] . '/www/custom/status/'); }
php
public function apply(base $appbox, Application $app) { $finder = new Finder(); $fs = new Filesystem(); foreach ($finder->files()->in($app['root.path'].'/config/status') as $file) { if (!$file->isFile()) { continue; } $fileName = $file->getFileName(); $chunks = explode('-', $fileName); if (count($chunks) < 4) { continue; } $suffix = array_pop($chunks); $uniqid = md5(implode('-', $chunks)); $fs->rename($file->getRealPath(), $app['root.path'].'/config/status/' . $uniqid . '-' . $suffix); if ($fs->exists($app['root.path'] . '/www/custom/status/' . $file->getFileName())) { $fs->remove($app['root.path'] . '/www/custom/status/' . $file->getFileName()); } } $app['filesystem']->mirror($app['root.path'] . '/config/status/', $app['root.path'] . '/www/custom/status/'); }
[ "public", "function", "apply", "(", "base", "$", "appbox", ",", "Application", "$", "app", ")", "{", "$", "finder", "=", "new", "Finder", "(", ")", ";", "$", "fs", "=", "new", "Filesystem", "(", ")", ";", "foreach", "(", "$", "finder", "->", "files...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/384alpha2a.php#L59-L85
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/TaskManager/Editor/AbstractEditor.php
AbstractEditor.updateXMLWithRequest
public function updateXMLWithRequest(Request $request) { $dom = $this->createBlankDom(); if (false === @$dom->loadXML($request->request->get('xml'))) { throw new BadRequestHttpException('Invalid XML data.'); } foreach ($this->getFormProperties() as $name => $type) { $value = $request->request->get($name); if (null !== $node = $dom->getElementsByTagName($name)->item(0)) { // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) while ($child = $node->firstChild) { $node->removeChild($child); } } else { // le champ n'existait pas dans le xml, on le cree $node = $dom->documentElement->appendChild($dom->createElement($name)); } // on fixe sa valeur switch ($type) { case static::FORM_TYPE_STRING: default: $node->appendChild($dom->createTextNode($value)); break; case static::FORM_TYPE_BOOLEAN: $node->appendChild($dom->createTextNode($value ? '1' : '0')); break; case static::FORM_TYPE_INTEGER: $node->appendChild($dom->createTextNode(null !== $value ? (int) $value : '')); break; } } return new Response($dom->saveXML(), 200, ['Content-type' => 'text/xml']); }
php
public function updateXMLWithRequest(Request $request) { $dom = $this->createBlankDom(); if (false === @$dom->loadXML($request->request->get('xml'))) { throw new BadRequestHttpException('Invalid XML data.'); } foreach ($this->getFormProperties() as $name => $type) { $value = $request->request->get($name); if (null !== $node = $dom->getElementsByTagName($name)->item(0)) { // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) while ($child = $node->firstChild) { $node->removeChild($child); } } else { // le champ n'existait pas dans le xml, on le cree $node = $dom->documentElement->appendChild($dom->createElement($name)); } // on fixe sa valeur switch ($type) { case static::FORM_TYPE_STRING: default: $node->appendChild($dom->createTextNode($value)); break; case static::FORM_TYPE_BOOLEAN: $node->appendChild($dom->createTextNode($value ? '1' : '0')); break; case static::FORM_TYPE_INTEGER: $node->appendChild($dom->createTextNode(null !== $value ? (int) $value : '')); break; } } return new Response($dom->saveXML(), 200, ['Content-type' => 'text/xml']); }
[ "public", "function", "updateXMLWithRequest", "(", "Request", "$", "request", ")", "{", "$", "dom", "=", "$", "this", "->", "createBlankDom", "(", ")", ";", "if", "(", "false", "===", "@", "$", "dom", "->", "loadXML", "(", "$", "request", "->", "reques...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/TaskManager/Editor/AbstractEditor.php#L34-L69
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/TaskManager/Editor/AbstractEditor.php
AbstractEditor.createBlankDom
protected function createBlankDom() { $dom = new \DOMDocument(); $dom->preserveWhiteSpace = false; $dom->formatOutput = true; return $dom; }
php
protected function createBlankDom() { $dom = new \DOMDocument(); $dom->preserveWhiteSpace = false; $dom->formatOutput = true; return $dom; }
[ "protected", "function", "createBlankDom", "(", ")", "{", "$", "dom", "=", "new", "\\", "DOMDocument", "(", ")", ";", "$", "dom", "->", "preserveWhiteSpace", "=", "false", ";", "$", "dom", "->", "formatOutput", "=", "true", ";", "return", "$", "dom", "...
Returns a new blank DOM document. @return \DOMDocument
[ "Returns", "a", "new", "blank", "DOM", "document", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/TaskManager/Editor/AbstractEditor.php#L84-L91
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Root/DeveloperController.php
DeveloperController.deleteApp
public function deleteApp(Request $request, ApiApplication $application) { $this->assertJsonRequestFormat($request); $this->getApiApplicationManipulator()->delete($application); return $this->app->json(['success' => true]); }
php
public function deleteApp(Request $request, ApiApplication $application) { $this->assertJsonRequestFormat($request); $this->getApiApplicationManipulator()->delete($application); return $this->app->json(['success' => true]); }
[ "public", "function", "deleteApp", "(", "Request", "$", "request", ",", "ApiApplication", "$", "application", ")", "{", "$", "this", "->", "assertJsonRequestFormat", "(", "$", "request", ")", ";", "$", "this", "->", "getApiApplicationManipulator", "(", ")", "-...
Delete application. @param Request $request @param ApiApplication $application @return JsonResponse
[ "Delete", "application", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Root/DeveloperController.php#L40-L47
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Root/DeveloperController.php
DeveloperController.renewAppCallback
public function renewAppCallback(Request $request, ApiApplication $application) { $this->assertJsonRequestFormat($request); try { $this->getApiApplicationManipulator() ->setRedirectUri($application, $request->request->get("callback")); } catch (InvalidArgumentException $e) { return $this->app->json(['success' => false]); } return $this->app->json(['success' => true]); }
php
public function renewAppCallback(Request $request, ApiApplication $application) { $this->assertJsonRequestFormat($request); try { $this->getApiApplicationManipulator() ->setRedirectUri($application, $request->request->get("callback")); } catch (InvalidArgumentException $e) { return $this->app->json(['success' => false]); } return $this->app->json(['success' => true]); }
[ "public", "function", "renewAppCallback", "(", "Request", "$", "request", ",", "ApiApplication", "$", "application", ")", "{", "$", "this", "->", "assertJsonRequestFormat", "(", "$", "request", ")", ";", "try", "{", "$", "this", "->", "getApiApplicationManipulat...
Change application callback. @param Request $request @param ApiApplication $application @return JsonResponse
[ "Change", "application", "callback", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Root/DeveloperController.php#L81-L93
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Root/DeveloperController.php
DeveloperController.renewAppWebhook
public function renewAppWebhook(Request $request, ApiApplication $application) { $this->assertJsonRequestFormat($request); if (null !== $request->request->get("webhook")) { $this->getApiApplicationManipulator() ->setWebhookUrl($application, $request->request->get("webhook")); } else { return $this->app->json(['success' => false]); } return $this->app->json(['success' => true]); }
php
public function renewAppWebhook(Request $request, ApiApplication $application) { $this->assertJsonRequestFormat($request); if (null !== $request->request->get("webhook")) { $this->getApiApplicationManipulator() ->setWebhookUrl($application, $request->request->get("webhook")); } else { return $this->app->json(['success' => false]); } return $this->app->json(['success' => true]); }
[ "public", "function", "renewAppWebhook", "(", "Request", "$", "request", ",", "ApiApplication", "$", "application", ")", "{", "$", "this", "->", "assertJsonRequestFormat", "(", "$", "request", ")", ";", "if", "(", "null", "!==", "$", "request", "->", "reques...
Change application webhook @param Request $request The current request @param ApiApplication $application @return JsonResponse
[ "Change", "application", "webhook" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Root/DeveloperController.php#L102-L114
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Root/DeveloperController.php
DeveloperController.renewAccessToken
public function renewAccessToken(Request $request, ApiApplication $application) { $this->assertJsonRequestFormat($request); $account = $this->getApiAccountRepository() ->findByUserAndApplication($this->getAuthenticatedUser(), $application); if (null === $account) { $this->app->abort(404, sprintf('Account not found for application %s', $application->getName())); } if (null !== $devToken = $this->getApiOAuthTokenRepository()->findDeveloperToken($account)) { $this->getApiOAuthTokenManipulator()->renew($devToken); } else { // dev tokens do not expires $devToken = $this->getApiOAuthTokenManipulator()->create($account); } return $this->app->json(['success' => true, 'token' => $devToken->getOauthToken()]); }
php
public function renewAccessToken(Request $request, ApiApplication $application) { $this->assertJsonRequestFormat($request); $account = $this->getApiAccountRepository() ->findByUserAndApplication($this->getAuthenticatedUser(), $application); if (null === $account) { $this->app->abort(404, sprintf('Account not found for application %s', $application->getName())); } if (null !== $devToken = $this->getApiOAuthTokenRepository()->findDeveloperToken($account)) { $this->getApiOAuthTokenManipulator()->renew($devToken); } else { // dev tokens do not expires $devToken = $this->getApiOAuthTokenManipulator()->create($account); } return $this->app->json(['success' => true, 'token' => $devToken->getOauthToken()]); }
[ "public", "function", "renewAccessToken", "(", "Request", "$", "request", ",", "ApiApplication", "$", "application", ")", "{", "$", "this", "->", "assertJsonRequestFormat", "(", "$", "request", ")", ";", "$", "account", "=", "$", "this", "->", "getApiAccountRe...
Authorize application to use a grant password type. @param Request $request @param ApiApplication $application @return JsonResponse
[ "Authorize", "application", "to", "use", "a", "grant", "password", "type", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Root/DeveloperController.php#L124-L142
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Root/DeveloperController.php
DeveloperController.authorizeGrantPassword
public function authorizeGrantPassword(Request $request, ApiApplication $application) { $this->assertJsonRequestFormat($request); $application->setGrantPassword((bool)$request->request->get('grant')); $this->getApiApplicationManipulator()->update($application); return $this->app->json(['success' => true]); }
php
public function authorizeGrantPassword(Request $request, ApiApplication $application) { $this->assertJsonRequestFormat($request); $application->setGrantPassword((bool)$request->request->get('grant')); $this->getApiApplicationManipulator()->update($application); return $this->app->json(['success' => true]); }
[ "public", "function", "authorizeGrantPassword", "(", "Request", "$", "request", ",", "ApiApplication", "$", "application", ")", "{", "$", "this", "->", "assertJsonRequestFormat", "(", "$", "request", ")", ";", "$", "application", "->", "setGrantPassword", "(", "...
Authorize application to use a grant password type. @param Request $request @param ApiApplication $application @return JsonResponse
[ "Authorize", "application", "to", "use", "a", "grant", "password", "type", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Root/DeveloperController.php#L152-L160
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Root/DeveloperController.php
DeveloperController.newApp
public function newApp(Request $request) { if ($request->request->get('type') === ApiApplication::DESKTOP_TYPE) { $form = new \API_OAuth2_Form_DevAppDesktop($request); } else { $form = new \API_OAuth2_Form_DevAppInternet($request); } $violations = $this->getValidator()->validate($form); if ($violations->count() === 0) { $user = $this->getAuthenticatedUser(); $application = $this->getApiApplicationManipulator() ->create( $form->getName(), $form->getType(), $form->getDescription(), sprintf('%s%s', $form->getSchemeWebsite(), $form->getWebsite()), $user, sprintf('%s%s', $form->getSchemeCallback(), $form->getCallback()) ); // create an account as well $this->getApiAccountManipulator()->create($application, $user, V2::VERSION); return $this->app->redirectPath('developers_application', ['application' => $application->getId()]); } return $this->render('/developers/application_form.html.twig', [ "violations" => $violations, "form" => $form, ]); }
php
public function newApp(Request $request) { if ($request->request->get('type') === ApiApplication::DESKTOP_TYPE) { $form = new \API_OAuth2_Form_DevAppDesktop($request); } else { $form = new \API_OAuth2_Form_DevAppInternet($request); } $violations = $this->getValidator()->validate($form); if ($violations->count() === 0) { $user = $this->getAuthenticatedUser(); $application = $this->getApiApplicationManipulator() ->create( $form->getName(), $form->getType(), $form->getDescription(), sprintf('%s%s', $form->getSchemeWebsite(), $form->getWebsite()), $user, sprintf('%s%s', $form->getSchemeCallback(), $form->getCallback()) ); // create an account as well $this->getApiAccountManipulator()->create($application, $user, V2::VERSION); return $this->app->redirectPath('developers_application', ['application' => $application->getId()]); } return $this->render('/developers/application_form.html.twig', [ "violations" => $violations, "form" => $form, ]); }
[ "public", "function", "newApp", "(", "Request", "$", "request", ")", "{", "if", "(", "$", "request", "->", "request", "->", "get", "(", "'type'", ")", "===", "ApiApplication", "::", "DESKTOP_TYPE", ")", "{", "$", "form", "=", "new", "\\", "API_OAuth2_For...
Create a new developer applications @param Request $request The current request @return Response
[ "Create", "a", "new", "developer", "applications" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Root/DeveloperController.php#L168-L200
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Root/DeveloperController.php
DeveloperController.getApp
public function getApp(ApiApplication $application) { $user = $this->getAuthenticatedUser(); $account = $this->getApiAccountRepository()->findByUserAndApplication($user, $application); $token = $account ? $this->getApiOAuthTokenRepository()->findDeveloperToken($account) : null; if (! $account) { throw new AccessDeniedHttpException(); } $deliveries = $this->getWebhookDeliveryRepository() ->findLastDeliveries($account->getApplication(), 10); return $this->render('developers/application.html.twig', [ "application" => $application, "deliveries" => $deliveries, "user" => $user, "token" => $token, ]); }
php
public function getApp(ApiApplication $application) { $user = $this->getAuthenticatedUser(); $account = $this->getApiAccountRepository()->findByUserAndApplication($user, $application); $token = $account ? $this->getApiOAuthTokenRepository()->findDeveloperToken($account) : null; if (! $account) { throw new AccessDeniedHttpException(); } $deliveries = $this->getWebhookDeliveryRepository() ->findLastDeliveries($account->getApplication(), 10); return $this->render('developers/application.html.twig', [ "application" => $application, "deliveries" => $deliveries, "user" => $user, "token" => $token, ]); }
[ "public", "function", "getApp", "(", "ApiApplication", "$", "application", ")", "{", "$", "user", "=", "$", "this", "->", "getAuthenticatedUser", "(", ")", ";", "$", "account", "=", "$", "this", "->", "getApiAccountRepository", "(", ")", "->", "findByUserAnd...
Gets application information. @param ApiApplication $application @return mixed
[ "Gets", "application", "information", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Root/DeveloperController.php#L236-L257
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Feed/Formatter/CoolirisFormatter.php
CoolirisFormatter.format
public function format(FeedInterface $feed, $page, User $user = null, $generator = 'Phraseanet', Application $app = null) { $doc = new \DOMDocument('1.0', 'UTF-8'); $doc->formatOutput = true; $doc->standalone = true; $root = $this->addTag($doc, $doc, 'rss'); $root->setAttribute('version', self::VERSION); $root->setAttribute('xmlns:media', 'http://search.yahoo.com/mrss/'); $root->setAttribute('xmlns:atom', 'http://www.w3.org/2005/Atom'); $root->setAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); $channel = $this->addTag($doc, $root, 'channel'); $this->addTag($doc, $channel, 'title', $feed->getTitle()); $this->addTag($doc, $channel, 'dc:title', $feed->getTitle()); $this->addTag($doc, $channel, 'description', $feed->getSubtitle()); if (null !== $user) { $link = $this->linkGenerator->generate($feed, $user, self::FORMAT, $page); } else { $link = $this->linkGenerator->generatePublic($feed, self::FORMAT, $page); } if ($link instanceof FeedLink) { $this->addTag($doc, $channel, 'link', $link->getURI()); } if (isset($this->language)) $this->addTag($doc, $channel, 'language', $this->language); if (isset($this->copyright)) $this->addTag($doc, $channel, 'copyright', $this->copyright); if (isset($this->managingEditor)) $this->addTag($doc, $channel, 'managingEditor', $this->managingEditor); if (isset($this->webMaster)) $this->addTag($doc, $channel, 'webMaster', $this->webMaster); if (null !== $updated_on = NullableDateTime::format($feed->getUpdatedOn(), DATE_RFC2822)) { $this->addTag($doc, $channel, 'pubDate', $updated_on); } if (isset($this->lastBuildDate) && $this->lastBuildDate instanceof DateTime) { $last_build = $this->lastBuildDate->format(DATE_RFC2822); $this->addTag($doc, $channel, 'lastBuildDate', $last_build); } if (isset($this->categories) && count($this->categories) > 0) { foreach ($this->categories as $category) { $this->addTag($doc, $channel, 'category', $category); } } if (isset($this->linkgenerator)) $this->addTag($doc, $channel, 'generator', $this->linkgenerator); if (isset($this->docs)) $this->addTag($doc, $channel, 'docs', $this->docs); if (isset($this->ttl)) $this->addTag($doc, $channel, 'ttl', $this->ttl); if (isset($this->image) && $this->image instanceof FeedRSSImage) { $image = $this->addTag($doc, $channel, 'image'); $this->addTag($doc, $image, 'url', $this->image->getUrl()); $this->addTag($doc, $image, 'title', $this->image->getTitle()); $this->addTag($doc, $image, 'link', $this->image->getLink()); if ($this->image->getWidth()) $this->addTag($doc, $image, 'width', $this->image->getWidth()); if ($this->image->getHeight()) $this->addTag($doc, $image, 'height', $this->image->getHeight()); if ($this->image->getDescription()) $this->addTag($doc, $image, 'description', $this->image->getDescription()); } if (isset($this->skipHours) && count($this->skipHours)) { $skipHours = $this->addTag($doc, $channel, 'skipHours'); foreach ($this->skipHours as $hour) { $this->addTag($doc, $skipHours, 'hour', $hour); } } if (isset($this->skipDays) && count($this->skipDays) > 0) { $skipDays = $this->addTag($doc, $channel, 'skipDays'); foreach ($this->skipDays as $day) { $this->addTag($doc, $skipDays, 'day', $day); } } if ($link instanceof FeedLink) { $self_link = $this->addTag($doc, $channel, 'atom:link'); $self_link->setAttribute('rel', 'self'); $self_link->setAttribute('href', $link->getURI()); } $next = $prev = null; if ($feed->hasPage($page + 1, self::PAGE_SIZE)) { if (null === $user) { $next = $this->linkGenerator->generatePublic($feed, self::FORMAT, $page + 1); } else { $next = $this->linkGenerator->generate($feed, $user, self::FORMAT, $page + 1); } } if ($feed->hasPage($page - 1, self::PAGE_SIZE)) { if (null === $user) { $prev = $this->linkGenerator->generatePublic($feed, self::FORMAT, $page - 1); } else { $prev = $this->linkGenerator->generate($feed, $user, self::FORMAT, $page - 1); } } $prefix = 'atom'; if ($prev instanceof FeedLink) { $prev_link = $this->addTag($doc, $channel, $prefix . 'link'); $prev_link->setAttribute('rel', 'previous'); $prev_link->setAttribute('href', $prev->getURI()); } if ($next instanceof FeedLink) { $next_link = $this->addTag($doc, $channel, $prefix . 'link'); $next_link->setAttribute('rel', 'next'); $next_link->setAttribute('href', $next->getURI()); } foreach ($feed->getEntries() as $item) { $this->addItem($app, $doc, $channel, $item); } return $doc->saveXML(); }
php
public function format(FeedInterface $feed, $page, User $user = null, $generator = 'Phraseanet', Application $app = null) { $doc = new \DOMDocument('1.0', 'UTF-8'); $doc->formatOutput = true; $doc->standalone = true; $root = $this->addTag($doc, $doc, 'rss'); $root->setAttribute('version', self::VERSION); $root->setAttribute('xmlns:media', 'http://search.yahoo.com/mrss/'); $root->setAttribute('xmlns:atom', 'http://www.w3.org/2005/Atom'); $root->setAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); $channel = $this->addTag($doc, $root, 'channel'); $this->addTag($doc, $channel, 'title', $feed->getTitle()); $this->addTag($doc, $channel, 'dc:title', $feed->getTitle()); $this->addTag($doc, $channel, 'description', $feed->getSubtitle()); if (null !== $user) { $link = $this->linkGenerator->generate($feed, $user, self::FORMAT, $page); } else { $link = $this->linkGenerator->generatePublic($feed, self::FORMAT, $page); } if ($link instanceof FeedLink) { $this->addTag($doc, $channel, 'link', $link->getURI()); } if (isset($this->language)) $this->addTag($doc, $channel, 'language', $this->language); if (isset($this->copyright)) $this->addTag($doc, $channel, 'copyright', $this->copyright); if (isset($this->managingEditor)) $this->addTag($doc, $channel, 'managingEditor', $this->managingEditor); if (isset($this->webMaster)) $this->addTag($doc, $channel, 'webMaster', $this->webMaster); if (null !== $updated_on = NullableDateTime::format($feed->getUpdatedOn(), DATE_RFC2822)) { $this->addTag($doc, $channel, 'pubDate', $updated_on); } if (isset($this->lastBuildDate) && $this->lastBuildDate instanceof DateTime) { $last_build = $this->lastBuildDate->format(DATE_RFC2822); $this->addTag($doc, $channel, 'lastBuildDate', $last_build); } if (isset($this->categories) && count($this->categories) > 0) { foreach ($this->categories as $category) { $this->addTag($doc, $channel, 'category', $category); } } if (isset($this->linkgenerator)) $this->addTag($doc, $channel, 'generator', $this->linkgenerator); if (isset($this->docs)) $this->addTag($doc, $channel, 'docs', $this->docs); if (isset($this->ttl)) $this->addTag($doc, $channel, 'ttl', $this->ttl); if (isset($this->image) && $this->image instanceof FeedRSSImage) { $image = $this->addTag($doc, $channel, 'image'); $this->addTag($doc, $image, 'url', $this->image->getUrl()); $this->addTag($doc, $image, 'title', $this->image->getTitle()); $this->addTag($doc, $image, 'link', $this->image->getLink()); if ($this->image->getWidth()) $this->addTag($doc, $image, 'width', $this->image->getWidth()); if ($this->image->getHeight()) $this->addTag($doc, $image, 'height', $this->image->getHeight()); if ($this->image->getDescription()) $this->addTag($doc, $image, 'description', $this->image->getDescription()); } if (isset($this->skipHours) && count($this->skipHours)) { $skipHours = $this->addTag($doc, $channel, 'skipHours'); foreach ($this->skipHours as $hour) { $this->addTag($doc, $skipHours, 'hour', $hour); } } if (isset($this->skipDays) && count($this->skipDays) > 0) { $skipDays = $this->addTag($doc, $channel, 'skipDays'); foreach ($this->skipDays as $day) { $this->addTag($doc, $skipDays, 'day', $day); } } if ($link instanceof FeedLink) { $self_link = $this->addTag($doc, $channel, 'atom:link'); $self_link->setAttribute('rel', 'self'); $self_link->setAttribute('href', $link->getURI()); } $next = $prev = null; if ($feed->hasPage($page + 1, self::PAGE_SIZE)) { if (null === $user) { $next = $this->linkGenerator->generatePublic($feed, self::FORMAT, $page + 1); } else { $next = $this->linkGenerator->generate($feed, $user, self::FORMAT, $page + 1); } } if ($feed->hasPage($page - 1, self::PAGE_SIZE)) { if (null === $user) { $prev = $this->linkGenerator->generatePublic($feed, self::FORMAT, $page - 1); } else { $prev = $this->linkGenerator->generate($feed, $user, self::FORMAT, $page - 1); } } $prefix = 'atom'; if ($prev instanceof FeedLink) { $prev_link = $this->addTag($doc, $channel, $prefix . 'link'); $prev_link->setAttribute('rel', 'previous'); $prev_link->setAttribute('href', $prev->getURI()); } if ($next instanceof FeedLink) { $next_link = $this->addTag($doc, $channel, $prefix . 'link'); $next_link->setAttribute('rel', 'next'); $next_link->setAttribute('href', $next->getURI()); } foreach ($feed->getEntries() as $item) { $this->addItem($app, $doc, $channel, $item); } return $doc->saveXML(); }
[ "public", "function", "format", "(", "FeedInterface", "$", "feed", ",", "$", "page", ",", "User", "$", "user", "=", "null", ",", "$", "generator", "=", "'Phraseanet'", ",", "Application", "$", "app", "=", "null", ")", "{", "$", "doc", "=", "new", "\\...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Feed/Formatter/CoolirisFormatter.php#L54-L176
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Http/H264PseudoStreaming/Nginx.php
Nginx.getUrl
public function getUrl($pathfile) { if (!is_file($pathfile)) { return null; } $pathfile = realpath($pathfile); foreach ($this->mapping as $entry) { if (0 !== strpos($pathfile, $entry['directory'])) { continue; } return $this->generateUrl($pathfile, $entry); } }
php
public function getUrl($pathfile) { if (!is_file($pathfile)) { return null; } $pathfile = realpath($pathfile); foreach ($this->mapping as $entry) { if (0 !== strpos($pathfile, $entry['directory'])) { continue; } return $this->generateUrl($pathfile, $entry); } }
[ "public", "function", "getUrl", "(", "$", "pathfile", ")", "{", "if", "(", "!", "is_file", "(", "$", "pathfile", ")", ")", "{", "return", "null", ";", "}", "$", "pathfile", "=", "realpath", "(", "$", "pathfile", ")", ";", "foreach", "(", "$", "this...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Http/H264PseudoStreaming/Nginx.php#L63-L77
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Notification/Mail/AbstractMailWithLink.php
AbstractMailWithLink.create
public static function create(Application $app, ReceiverInterface $receiver, EmitterInterface $emitter = null, $message = null, $url = null, \DateTime $expiration = null) { $mail = new static($app, $receiver, $emitter, $message); $mail->setButtonUrl($url); $mail->setExpiration($expiration); return $mail; }
php
public static function create(Application $app, ReceiverInterface $receiver, EmitterInterface $emitter = null, $message = null, $url = null, \DateTime $expiration = null) { $mail = new static($app, $receiver, $emitter, $message); $mail->setButtonUrl($url); $mail->setExpiration($expiration); return $mail; }
[ "public", "static", "function", "create", "(", "Application", "$", "app", ",", "ReceiverInterface", "$", "receiver", ",", "EmitterInterface", "$", "emitter", "=", "null", ",", "$", "message", "=", "null", ",", "$", "url", "=", "null", ",", "\\", "DateTime"...
Creates a new Mail @param Application $app @param ReceiverInterface $receiver @param EmitterInterface $emitter @param string $message @param string $url @param \DateTime $expiration @return static
[ "Creates", "a", "new", "Mail" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Notification/Mail/AbstractMailWithLink.php#L42-L49
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Model/Entities/Task.php
Task.setStatus
public function setStatus($status) { if (!in_array($status, [static::STATUS_STARTED, static::STATUS_STOPPED], true)) { throw new InvalidArgumentException('Invalid status value.'); } $this->status = $status; return $this; }
php
public function setStatus($status) { if (!in_array($status, [static::STATUS_STARTED, static::STATUS_STOPPED], true)) { throw new InvalidArgumentException('Invalid status value.'); } $this->status = $status; return $this; }
[ "public", "function", "setStatus", "(", "$", "status", ")", "{", "if", "(", "!", "in_array", "(", "$", "status", ",", "[", "static", "::", "STATUS_STARTED", ",", "static", "::", "STATUS_STOPPED", "]", ",", "true", ")", ")", "{", "throw", "new", "Invali...
Set status @param string $status @return Task
[ "Set", "status" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Entities/Task.php#L199-L208
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Model/Entities/ElasticsearchRecord.php
ElasticsearchRecord.getTitle
public function getTitle($locale = null) { if ($locale && isset($this->title[$locale])) { return $this->title[$locale]; } if (isset($this->title['default'])) { return $this->title['default']; } return $this->getOriginalName(); }
php
public function getTitle($locale = null) { if ($locale && isset($this->title[$locale])) { return $this->title[$locale]; } if (isset($this->title['default'])) { return $this->title['default']; } return $this->getOriginalName(); }
[ "public", "function", "getTitle", "(", "$", "locale", "=", "null", ")", "{", "if", "(", "$", "locale", "&&", "isset", "(", "$", "this", "->", "title", "[", "$", "locale", "]", ")", ")", "{", "return", "$", "this", "->", "title", "[", "$", "locale...
@param string|null $locale @return string
[ "@param", "string|null", "$locale" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Entities/ElasticsearchRecord.php#L315-L326
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Cache/Factory.php
Factory.create
public function create($name, $options) { switch (strtolower($name)) { case 'apc': case 'apccache': $cache = $this->createApc(); break; case 'array': case 'arraycache': $cache = new ArrayCache(); break; case 'memcache': case 'memcachecache': $cache = $this->createMemcache($options); break; case 'memcached': case 'memcachedcache': $cache = $this->createMemcached($options); break; case 'redis': case 'rediscache': $cache = $this->createRedis($options); break; case 'wincache': case 'wincachecache': $cache = $this->createWincache(); break; case 'xcache': case 'xcachecache': $cache = $this->createXcache(); break; default: throw new RuntimeException(sprintf('Unnown cache type %s', $name)); } return $cache; }
php
public function create($name, $options) { switch (strtolower($name)) { case 'apc': case 'apccache': $cache = $this->createApc(); break; case 'array': case 'arraycache': $cache = new ArrayCache(); break; case 'memcache': case 'memcachecache': $cache = $this->createMemcache($options); break; case 'memcached': case 'memcachedcache': $cache = $this->createMemcached($options); break; case 'redis': case 'rediscache': $cache = $this->createRedis($options); break; case 'wincache': case 'wincachecache': $cache = $this->createWincache(); break; case 'xcache': case 'xcachecache': $cache = $this->createXcache(); break; default: throw new RuntimeException(sprintf('Unnown cache type %s', $name)); } return $cache; }
[ "public", "function", "create", "(", "$", "name", ",", "$", "options", ")", "{", "switch", "(", "strtolower", "(", "$", "name", ")", ")", "{", "case", "'apc'", ":", "case", "'apccache'", ":", "$", "cache", "=", "$", "this", "->", "createApc", "(", ...
@param type $name @param type $options @return Cache @throws RuntimeException
[ "@param", "type", "$name", "@param", "type", "$options" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Cache/Factory.php#L33-L69
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/SearchEngine/Elastic/Structure/Flag.php
Flag.getBitPositionInDatabox
public function getBitPositionInDatabox(\databox $databox) { foreach ($databox->getStatusStructure() as $bit => $status) { $candidate_name = self::normalizeName($status['labelon']); if ($candidate_name === $this->name) { return (int) $status['bit']; } } }
php
public function getBitPositionInDatabox(\databox $databox) { foreach ($databox->getStatusStructure() as $bit => $status) { $candidate_name = self::normalizeName($status['labelon']); if ($candidate_name === $this->name) { return (int) $status['bit']; } } }
[ "public", "function", "getBitPositionInDatabox", "(", "\\", "databox", "$", "databox", ")", "{", "foreach", "(", "$", "databox", "->", "getStatusStructure", "(", ")", "as", "$", "bit", "=>", "$", "status", ")", "{", "$", "candidate_name", "=", "self", "::"...
/* TODO: Rewrite to have all data injected at construct time in createFromLegacyStatus()
[ "/", "*", "TODO", ":", "Rewrite", "to", "have", "all", "data", "injected", "at", "construct", "time", "in", "createFromLegacyStatus", "()" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/Elastic/Structure/Flag.php#L45-L53
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Authentication/Provider/Token/Identity.php
Identity.getDisplayName
public function getDisplayName() { $data = array_filter([ $this->get(self::PROPERTY_FIRSTNAME), $this->get(self::PROPERTY_LASTNAME), ]); return implode(' ', $data); }
php
public function getDisplayName() { $data = array_filter([ $this->get(self::PROPERTY_FIRSTNAME), $this->get(self::PROPERTY_LASTNAME), ]); return implode(' ', $data); }
[ "public", "function", "getDisplayName", "(", ")", "{", "$", "data", "=", "array_filter", "(", "[", "$", "this", "->", "get", "(", "self", "::", "PROPERTY_FIRSTNAME", ")", ",", "$", "this", "->", "get", "(", "self", "::", "PROPERTY_LASTNAME", ")", ",", ...
Returns the display name (first and last name) @return string
[ "Returns", "the", "display", "name", "(", "first", "and", "last", "name", ")" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/Provider/Token/Identity.php#L56-L64
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Authentication/Provider/Token/Identity.php
Identity.get
public function get($property) { if (!array_key_exists($property, $this->data)) { throw new InvalidArgumentException(sprintf('Property %s does not exist', $property)); } return $this->data[$property]; }
php
public function get($property) { if (!array_key_exists($property, $this->data)) { throw new InvalidArgumentException(sprintf('Property %s does not exist', $property)); } return $this->data[$property]; }
[ "public", "function", "get", "(", "$", "property", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "property", ",", "$", "this", "->", "data", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Property %s does not exis...
Get a property value @param $property string @return string @throws InvalidArgumentException In case the property does not exists
[ "Get", "a", "property", "value" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/Provider/Token/Identity.php#L157-L164
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Authentication/Provider/Token/Identity.php
Identity.remove
public function remove($property) { if (!array_key_exists($property, $this->data)) { throw new InvalidArgumentException(sprintf('Property %s does not exist', $property)); } $value = $this->data[$property]; unset($this->data[$property]); return $value; }
php
public function remove($property) { if (!array_key_exists($property, $this->data)) { throw new InvalidArgumentException(sprintf('Property %s does not exist', $property)); } $value = $this->data[$property]; unset($this->data[$property]); return $value; }
[ "public", "function", "remove", "(", "$", "property", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "property", ",", "$", "this", "->", "data", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Property %s does not e...
Removes the property @return string The value that was stored for the given property
[ "Removes", "the", "property" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/Provider/Token/Identity.php#L186-L196
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/ControllerProvider/Prod/Export.php
Export.connect
public function connect(Application $app) { $controllers = $this->createCollection($app); $controllers->before(new OAuthListener(['exit_not_present' => false])); $this->getFirewall($app)->addMandatoryAuthentication($controllers); $controllers->post('/multi-export/', 'controller.prod.export:displayMultiExport') ->bind('export_multi_export'); $controllers->post('/mail/', 'controller.prod.export:exportMail') ->bind('export_mail'); $controllers->post('/ftp/', 'controller.prod.export:exportFtp') ->bind('export_ftp'); $controllers->post('/ftp/test/', 'controller.prod.export:testFtpConnexion') ->bind('export_ftp_test'); return $controllers; }
php
public function connect(Application $app) { $controllers = $this->createCollection($app); $controllers->before(new OAuthListener(['exit_not_present' => false])); $this->getFirewall($app)->addMandatoryAuthentication($controllers); $controllers->post('/multi-export/', 'controller.prod.export:displayMultiExport') ->bind('export_multi_export'); $controllers->post('/mail/', 'controller.prod.export:exportMail') ->bind('export_mail'); $controllers->post('/ftp/', 'controller.prod.export:exportFtp') ->bind('export_ftp'); $controllers->post('/ftp/test/', 'controller.prod.export:testFtpConnexion') ->bind('export_ftp_test'); return $controllers; }
[ "public", "function", "connect", "(", "Application", "$", "app", ")", "{", "$", "controllers", "=", "$", "this", "->", "createCollection", "(", "$", "app", ")", ";", "$", "controllers", "->", "before", "(", "new", "OAuthListener", "(", "[", "'exit_not_pres...
{@inheritDoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/ControllerProvider/Prod/Export.php#L46-L65
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Setup/DoctrineMigrations/AbstractMigration.php
AbstractMigration.tableExists
protected function tableExists($tableName) { $rs = $this->getEntityManager()->getConnection()->fetchAll('SHOW TABLE STATUS'); foreach ($rs as $row) { if ($tableName === $row['Name']) { return true; } } return false; }
php
protected function tableExists($tableName) { $rs = $this->getEntityManager()->getConnection()->fetchAll('SHOW TABLE STATUS'); foreach ($rs as $row) { if ($tableName === $row['Name']) { return true; } } return false; }
[ "protected", "function", "tableExists", "(", "$", "tableName", ")", "{", "$", "rs", "=", "$", "this", "->", "getEntityManager", "(", ")", "->", "getConnection", "(", ")", "->", "fetchAll", "(", "'SHOW TABLE STATUS'", ")", ";", "foreach", "(", "$", "rs", ...
Tells whether the table exists or not. @param $tableName @returns Boolean
[ "Tells", "whether", "the", "table", "exists", "or", "not", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/AbstractMigration.php#L105-L116
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Collection/Reference/CollectionReferenceCollection.php
CollectionReferenceCollection.groupByDataboxIdAndCollectionId
public function groupByDataboxIdAndCollectionId() { $groups = []; foreach ($this->references as $index => $reference) { $databoxId = $reference->getDataboxId(); $group = isset($groups[$databoxId]) ? $groups[$databoxId] : []; $group[$reference->getCollectionId()] = $index; $groups[$databoxId] = $group; } return $groups; }
php
public function groupByDataboxIdAndCollectionId() { $groups = []; foreach ($this->references as $index => $reference) { $databoxId = $reference->getDataboxId(); $group = isset($groups[$databoxId]) ? $groups[$databoxId] : []; $group[$reference->getCollectionId()] = $index; $groups[$databoxId] = $group; } return $groups; }
[ "public", "function", "groupByDataboxIdAndCollectionId", "(", ")", "{", "$", "groups", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "references", "as", "$", "index", "=>", "$", "reference", ")", "{", "$", "databoxId", "=", "$", "reference", "->...
Returns an array of array with actual index as leaf value. @return array<int,array<int,mixed>>
[ "Returns", "an", "array", "of", "array", "with", "actual", "index", "as", "leaf", "value", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Collection/Reference/CollectionReferenceCollection.php#L36-L49
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Prod/QueryController.php
QueryController.query
public function query(Request $request) { $query = (string) $request->request->get('qry'); // since the query comes from a submited form, normalize crlf,cr,lf ... $query = StringHelper::crlfNormalize($query); $json = [ 'query' => $query ]; $options = SearchEngineOptions::fromRequest($this->app, $request); $perPage = (int) $this->getSettings()->getUserSetting($this->getAuthenticatedUser(), 'images_per_page'); $page = (int) $request->request->get('pag'); $firstPage = $page < 1; $engine = $this->getSearchEngine(); if ($page < 1) { $engine->resetCache(); $page = 1; } $options->setFirstResult(($page - 1) * $perPage); $options->setMaxResults($perPage); $user = $this->getAuthenticatedUser(); $userManipulator = $this->getUserManipulator(); $userManipulator->logQuery($user, $query); try { $result = $engine->query($query, $options); if ($this->getSettings()->getUserSetting($user, 'start_page') === 'LAST_QUERY') { // try to save the "fulltext" query which will be restored on next session try { // local code to find "FULLTEXT" value from jsonQuery $findFulltext = function($clause) use(&$findFulltext) { if(array_key_exists('_ux_zone', $clause) && $clause['_ux_zone']=='FULLTEXT') { return $clause['value']; } if($clause['type']=='CLAUSES') { foreach($clause['clauses'] as $c) { if(($r = $findFulltext($c)) !== null) { return $r; } } } return null; }; $userManipulator->setUserSetting($user, 'last_jsonquery', (string)$request->request->get('jsQuery')); $jsQuery = @json_decode((string)$request->request->get('jsQuery'), true); if(($ft = $findFulltext($jsQuery['query'])) !== null) { $userManipulator->setUserSetting($user, 'start_page_query', $ft); } } catch(\Exception $e) { // no-op } } // log array of collectionIds (from $options) for each databox $collectionsReferencesByDatabox = $options->getCollectionsReferencesByDatabox(); foreach ($collectionsReferencesByDatabox as $sbid => $references) { $databox = $this->findDataboxById($sbid); $collectionsIds = array_map(function(CollectionReference $ref){return $ref->getCollectionId();}, $references); $this->getSearchEngineLogger()->log($databox, $result->getQueryText(), $result->getTotal(), $collectionsIds); } $proposals = $firstPage ? $result->getProposals() : false; $npages = $result->getTotalPages($perPage); $page = $result->getCurrentPage($perPage); $queryESLib = $result->getQueryESLib(); $string = ''; if ($npages > 1) { $d2top = ($npages - $page); $d2bottom = $page; if (min($d2top, $d2bottom) < 4) { if ($d2bottom < 4) { if($page != 1){ $string .= "<a id='PREV_PAGE' class='btn btn-primary btn-mini'></a>"; } for ($i = 1; ($i <= 4 && (($i <= $npages) === true)); $i++) { if ($i == $page) $string .= '<input type="text" value="' . $i . '" size="' . (strlen((string) $i)) . '" class="btn btn-mini search-navigate-input-action" data-initial-value="' . $i . '" data-total-pages="'.$npages.'"/>'; else $string .= '<a class="btn btn-primary btn-mini search-navigate-action" data-page="'.$i.'">' . $i . '</a>'; } if ($npages > 4) $string .= "<a id='NEXT_PAGE' class='btn btn-primary btn-mini'></a>"; $string .= '<a href="#" class="btn btn-primary btn-mini search-navigate-action" data-page="' . $npages . '" id="last"></a>'; } else { $start = $npages - 4; if (($start) > 0){ $string .= '<a class="btn btn-primary btn-mini search-navigate-action" data-page="1" id="first"></a>'; $string .= '<a id="PREV_PAGE" class="btn btn-primary btn-mini"></a>'; }else $start = 1; for ($i = ($start); $i <= $npages; $i++) { if ($i == $page) $string .= '<input type="text" value="' . $i . '" size="' . (strlen((string) $i)) . '" class="btn btn-mini search-navigate-input-action" data-initial-value="' . $i . '" data-total-pages="'.$npages.'" />'; else $string .= '<a class="btn btn-primary btn-mini search-navigate-action" data-page="'.$i.'">' . $i . '</a>'; } if($page < $npages){ $string .= "<a id='NEXT_PAGE' class='btn btn-primary btn-mini'></a>"; } } } else { $string .= '<a class="btn btn-primary btn-mini btn-mini search-navigate-action" data-page="1" id="first"></a>'; for ($i = ($page - 2); $i <= ($page + 2); $i++) { if ($i == $page) $string .= '<input type="text" value="' . $i . '" size="' . (strlen((string) $i)) . '" class="btn btn-mini search-navigate-input-action" data-initial-value="' . $i . '" data-total-pages="'.$npages.'" />'; else $string .= '<a class="btn btn-primary btn-mini search-navigate-action" data-page="'.$i.'">' . $i . '</a>'; } $string .= '<a href="#" class="btn btn-primary btn-mini search-navigate-action" data-page="' . $npages . '" id="last"></a>'; } } $string .= '<div style="display:none;"><div id="NEXT_PAGE"></div><div id="PREV_PAGE"></div></div>'; $explain = $this->render( "prod/results/infos.html.twig", [ 'results'=> $result, 'esquery' => $this->getAclForUser()->is_admin() ? json_encode($queryESLib['body'], JSON_PRETTY_PRINT | JSON_HEX_TAG | JSON_HEX_QUOT | JSON_UNESCAPED_SLASHES) : null ] ); $infoResult = '<div id="docInfo">' . $this->app->trans('%number% documents<br/>selectionnes', ['%number%' => '<span id="nbrecsel"></span>']) . '<div class="detailed_info_holder"><img src="/assets/common/images/icons/dots.png" class="image-normal"><img src="/assets/common/images/icons/dots-darkgreen-hover.png" class="image-hover">' . '<div class="detailed_info"> <table> <thead> <tr> <th>Nb</th> <th>Type</th> <th>File size</th> <th>Duration</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Audio</td> <td>1 Mb</td> <td>00:04:31</td> </tr> <tr> <td>1</td> <td>Documents</td> <td>20 Kb</td> <td>N/A</td> </tr> <tr> <td>4</td> <td>Images</td> <td>400 Kb</td> <td>N/A</td> </tr> <tr> <td>1</td> <td>Video</td> <td>19 Mb</td> <td>00:20:36</td> </tr> </tbody> <tfoot> <tr> <td>6</td> <td>Total</td> <td>24.20 Mb</td> <td>00:25:17</td> </tr> </tfoot> </table></div></div>' . '</div><a href="#" class="search-display-info" data-infos="' . str_replace('"', '&quot;', $explain) . '">' . $this->app->trans('%total% reponses', ['%total%' => '<span>'.$result->getTotal().'</span>']) . '</a>'; $json['infos'] = $infoResult; $json['navigationTpl'] = $string; $json['navigation'] = [ 'page' => $page, 'perPage' => $perPage ]; $prop = null; if ($firstPage) { $propals = $result->getSuggestions(); if (count($propals) > 0) { foreach ($propals as $prop_array) { if ($prop_array->getSuggestion() !== $query && $prop_array->getHits() > $result->getTotal()) { $prop = $prop_array->getSuggestion(); break; } } } } if ($result->getTotal() === 0) { $template = 'prod/results/help.html.twig'; } else { $template = 'prod/results/records.html.twig'; } $json['results'] = $this->render($template, ['results'=> $result]); // add technical fields $fieldsInfosByName = []; foreach(ElasticsearchOptions::getAggregableTechnicalFields() as $k => $f) { $fieldsInfosByName[$k] = $f; $fieldsInfosByName[$k]['trans_label'] = $this->app->trans($f['label']); $fieldsInfosByName[$k]['labels'] = []; foreach($this->app->getAvailableLanguages() as $locale => $lng) { $fieldsInfosByName[$k]['labels'][$locale] = $this->app->trans($f['label'], [], "messages", $locale); } } // add databox fields // get infos about fields, fusionned and by databox $fieldsInfos = []; // by databox foreach ($this->app->getDataboxes() as $databox) { $sbasId = $databox->get_sbas_id(); $fieldsInfos[$sbasId] = []; foreach ($databox->get_meta_structure() as $field) { $name = $field->get_name(); $fieldsInfos[$sbasId][$name] = [ 'label' => $field->get_label($this->app['locale']), 'labels' => $field->get_labels(), 'type' => $field->get_type(), 'business' => $field->isBusiness(), 'multi' => $field->is_multi(), ]; // infos on the "same" field (by name) on multiple databoxes !!! // label(s) can be inconsistants : the first databox wins if (!isset($fieldsInfosByName[$name])) { $fieldsInfosByName[$name] = [ 'label' => $field->get_label($this->app['locale']), 'labels' => $field->get_labels(), 'type' => $field->get_type(), 'field' => $field->get_name(), 'query' => "field." . $field->get_name() . ":%s", 'trans_label' => $field->get_label($this->app['locale']), ]; $field->get_label($this->app['locale']); } } } // populates fileds infos $json['fields'] = $fieldsInfos; // populates rawresults // need acl so the result will not include business fields where not allowed $acl = $this->getAclForUser(); $json['rawResults'] = []; /** @var ElasticsearchRecord $record */ foreach($result->getResults() as $record) { $rawRecord = $record->asArray(); $sbasId = $record->getDataboxId(); $baseId = $record->getBaseId(); $caption = $rawRecord['caption']; if($acl && $acl->has_right_on_base($baseId, \ACL::CANMODIFRECORD)) { $caption = array_merge($caption, $rawRecord['privateCaption']); } // read the fields following the structure order $rawCaption = []; foreach($fieldsInfos[$sbasId] as $fieldName=>$fieldInfos) { if(array_key_exists($fieldName, $caption)) { $rawCaption[$fieldName] = $caption[$fieldName]; } } $rawRecord['caption'] = $rawCaption; unset($rawRecord['privateCaption']); $json['rawResults'][$record->getId()] = $rawRecord; } // populates facets (aggregates) $facets = []; // $facetClauses = []; foreach ($result->getFacets() as $facet) { $facetName = $facet['name']; if(array_key_exists($facetName, $fieldsInfosByName)) { $f = $fieldsInfosByName[$facetName]; $facet['label'] = $f['trans_label']; $facet['labels'] = $f['labels']; $facet['type'] = strtoupper($f['type']) . "-AGGREGATE"; $facets[] = $facet; // $facetClauses[] = [ // 'type' => strtoupper($f['type']) . "-AGGREGATE", // 'field' => $f['field'], // 'facet' => $facet // ]; } } // $json['jsq'] = $facetClauses; $json['facets'] = $facets; $json['phrasea_props'] = $proposals; $json['total_answers'] = (int) $result->getAvailable(); $json['next_page'] = ($page < $npages && $result->getAvailable() > 0) ? ($page + 1) : false; $json['prev_page'] = ($page > 1 && $result->getAvailable() > 0) ? ($page - 1) : false; $json['form'] = $options->serialize(); $json['queryCompiled'] = $result->getQueryCompiled(); $json['queryAST'] = $result->getQueryAST(); $json['queryESLib'] = $queryESLib; } catch(\Exception $e) { // we'd like a message from the parser so get all the exceptions messages $msg = ''; for(; $e; $e=$e->getPrevious()) { $msg .= ($msg ? "\n":"") . $e->getMessage(); } $template = 'prod/results/help.html.twig'; $result = [ 'error' => $msg ]; $json['results'] = $this->render($template, ['results'=> $result]); } return $this->app->json($json); }
php
public function query(Request $request) { $query = (string) $request->request->get('qry'); // since the query comes from a submited form, normalize crlf,cr,lf ... $query = StringHelper::crlfNormalize($query); $json = [ 'query' => $query ]; $options = SearchEngineOptions::fromRequest($this->app, $request); $perPage = (int) $this->getSettings()->getUserSetting($this->getAuthenticatedUser(), 'images_per_page'); $page = (int) $request->request->get('pag'); $firstPage = $page < 1; $engine = $this->getSearchEngine(); if ($page < 1) { $engine->resetCache(); $page = 1; } $options->setFirstResult(($page - 1) * $perPage); $options->setMaxResults($perPage); $user = $this->getAuthenticatedUser(); $userManipulator = $this->getUserManipulator(); $userManipulator->logQuery($user, $query); try { $result = $engine->query($query, $options); if ($this->getSettings()->getUserSetting($user, 'start_page') === 'LAST_QUERY') { // try to save the "fulltext" query which will be restored on next session try { // local code to find "FULLTEXT" value from jsonQuery $findFulltext = function($clause) use(&$findFulltext) { if(array_key_exists('_ux_zone', $clause) && $clause['_ux_zone']=='FULLTEXT') { return $clause['value']; } if($clause['type']=='CLAUSES') { foreach($clause['clauses'] as $c) { if(($r = $findFulltext($c)) !== null) { return $r; } } } return null; }; $userManipulator->setUserSetting($user, 'last_jsonquery', (string)$request->request->get('jsQuery')); $jsQuery = @json_decode((string)$request->request->get('jsQuery'), true); if(($ft = $findFulltext($jsQuery['query'])) !== null) { $userManipulator->setUserSetting($user, 'start_page_query', $ft); } } catch(\Exception $e) { // no-op } } // log array of collectionIds (from $options) for each databox $collectionsReferencesByDatabox = $options->getCollectionsReferencesByDatabox(); foreach ($collectionsReferencesByDatabox as $sbid => $references) { $databox = $this->findDataboxById($sbid); $collectionsIds = array_map(function(CollectionReference $ref){return $ref->getCollectionId();}, $references); $this->getSearchEngineLogger()->log($databox, $result->getQueryText(), $result->getTotal(), $collectionsIds); } $proposals = $firstPage ? $result->getProposals() : false; $npages = $result->getTotalPages($perPage); $page = $result->getCurrentPage($perPage); $queryESLib = $result->getQueryESLib(); $string = ''; if ($npages > 1) { $d2top = ($npages - $page); $d2bottom = $page; if (min($d2top, $d2bottom) < 4) { if ($d2bottom < 4) { if($page != 1){ $string .= "<a id='PREV_PAGE' class='btn btn-primary btn-mini'></a>"; } for ($i = 1; ($i <= 4 && (($i <= $npages) === true)); $i++) { if ($i == $page) $string .= '<input type="text" value="' . $i . '" size="' . (strlen((string) $i)) . '" class="btn btn-mini search-navigate-input-action" data-initial-value="' . $i . '" data-total-pages="'.$npages.'"/>'; else $string .= '<a class="btn btn-primary btn-mini search-navigate-action" data-page="'.$i.'">' . $i . '</a>'; } if ($npages > 4) $string .= "<a id='NEXT_PAGE' class='btn btn-primary btn-mini'></a>"; $string .= '<a href="#" class="btn btn-primary btn-mini search-navigate-action" data-page="' . $npages . '" id="last"></a>'; } else { $start = $npages - 4; if (($start) > 0){ $string .= '<a class="btn btn-primary btn-mini search-navigate-action" data-page="1" id="first"></a>'; $string .= '<a id="PREV_PAGE" class="btn btn-primary btn-mini"></a>'; }else $start = 1; for ($i = ($start); $i <= $npages; $i++) { if ($i == $page) $string .= '<input type="text" value="' . $i . '" size="' . (strlen((string) $i)) . '" class="btn btn-mini search-navigate-input-action" data-initial-value="' . $i . '" data-total-pages="'.$npages.'" />'; else $string .= '<a class="btn btn-primary btn-mini search-navigate-action" data-page="'.$i.'">' . $i . '</a>'; } if($page < $npages){ $string .= "<a id='NEXT_PAGE' class='btn btn-primary btn-mini'></a>"; } } } else { $string .= '<a class="btn btn-primary btn-mini btn-mini search-navigate-action" data-page="1" id="first"></a>'; for ($i = ($page - 2); $i <= ($page + 2); $i++) { if ($i == $page) $string .= '<input type="text" value="' . $i . '" size="' . (strlen((string) $i)) . '" class="btn btn-mini search-navigate-input-action" data-initial-value="' . $i . '" data-total-pages="'.$npages.'" />'; else $string .= '<a class="btn btn-primary btn-mini search-navigate-action" data-page="'.$i.'">' . $i . '</a>'; } $string .= '<a href="#" class="btn btn-primary btn-mini search-navigate-action" data-page="' . $npages . '" id="last"></a>'; } } $string .= '<div style="display:none;"><div id="NEXT_PAGE"></div><div id="PREV_PAGE"></div></div>'; $explain = $this->render( "prod/results/infos.html.twig", [ 'results'=> $result, 'esquery' => $this->getAclForUser()->is_admin() ? json_encode($queryESLib['body'], JSON_PRETTY_PRINT | JSON_HEX_TAG | JSON_HEX_QUOT | JSON_UNESCAPED_SLASHES) : null ] ); $infoResult = '<div id="docInfo">' . $this->app->trans('%number% documents<br/>selectionnes', ['%number%' => '<span id="nbrecsel"></span>']) . '<div class="detailed_info_holder"><img src="/assets/common/images/icons/dots.png" class="image-normal"><img src="/assets/common/images/icons/dots-darkgreen-hover.png" class="image-hover">' . '<div class="detailed_info"> <table> <thead> <tr> <th>Nb</th> <th>Type</th> <th>File size</th> <th>Duration</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Audio</td> <td>1 Mb</td> <td>00:04:31</td> </tr> <tr> <td>1</td> <td>Documents</td> <td>20 Kb</td> <td>N/A</td> </tr> <tr> <td>4</td> <td>Images</td> <td>400 Kb</td> <td>N/A</td> </tr> <tr> <td>1</td> <td>Video</td> <td>19 Mb</td> <td>00:20:36</td> </tr> </tbody> <tfoot> <tr> <td>6</td> <td>Total</td> <td>24.20 Mb</td> <td>00:25:17</td> </tr> </tfoot> </table></div></div>' . '</div><a href="#" class="search-display-info" data-infos="' . str_replace('"', '&quot;', $explain) . '">' . $this->app->trans('%total% reponses', ['%total%' => '<span>'.$result->getTotal().'</span>']) . '</a>'; $json['infos'] = $infoResult; $json['navigationTpl'] = $string; $json['navigation'] = [ 'page' => $page, 'perPage' => $perPage ]; $prop = null; if ($firstPage) { $propals = $result->getSuggestions(); if (count($propals) > 0) { foreach ($propals as $prop_array) { if ($prop_array->getSuggestion() !== $query && $prop_array->getHits() > $result->getTotal()) { $prop = $prop_array->getSuggestion(); break; } } } } if ($result->getTotal() === 0) { $template = 'prod/results/help.html.twig'; } else { $template = 'prod/results/records.html.twig'; } $json['results'] = $this->render($template, ['results'=> $result]); // add technical fields $fieldsInfosByName = []; foreach(ElasticsearchOptions::getAggregableTechnicalFields() as $k => $f) { $fieldsInfosByName[$k] = $f; $fieldsInfosByName[$k]['trans_label'] = $this->app->trans($f['label']); $fieldsInfosByName[$k]['labels'] = []; foreach($this->app->getAvailableLanguages() as $locale => $lng) { $fieldsInfosByName[$k]['labels'][$locale] = $this->app->trans($f['label'], [], "messages", $locale); } } // add databox fields // get infos about fields, fusionned and by databox $fieldsInfos = []; // by databox foreach ($this->app->getDataboxes() as $databox) { $sbasId = $databox->get_sbas_id(); $fieldsInfos[$sbasId] = []; foreach ($databox->get_meta_structure() as $field) { $name = $field->get_name(); $fieldsInfos[$sbasId][$name] = [ 'label' => $field->get_label($this->app['locale']), 'labels' => $field->get_labels(), 'type' => $field->get_type(), 'business' => $field->isBusiness(), 'multi' => $field->is_multi(), ]; // infos on the "same" field (by name) on multiple databoxes !!! // label(s) can be inconsistants : the first databox wins if (!isset($fieldsInfosByName[$name])) { $fieldsInfosByName[$name] = [ 'label' => $field->get_label($this->app['locale']), 'labels' => $field->get_labels(), 'type' => $field->get_type(), 'field' => $field->get_name(), 'query' => "field." . $field->get_name() . ":%s", 'trans_label' => $field->get_label($this->app['locale']), ]; $field->get_label($this->app['locale']); } } } // populates fileds infos $json['fields'] = $fieldsInfos; // populates rawresults // need acl so the result will not include business fields where not allowed $acl = $this->getAclForUser(); $json['rawResults'] = []; /** @var ElasticsearchRecord $record */ foreach($result->getResults() as $record) { $rawRecord = $record->asArray(); $sbasId = $record->getDataboxId(); $baseId = $record->getBaseId(); $caption = $rawRecord['caption']; if($acl && $acl->has_right_on_base($baseId, \ACL::CANMODIFRECORD)) { $caption = array_merge($caption, $rawRecord['privateCaption']); } // read the fields following the structure order $rawCaption = []; foreach($fieldsInfos[$sbasId] as $fieldName=>$fieldInfos) { if(array_key_exists($fieldName, $caption)) { $rawCaption[$fieldName] = $caption[$fieldName]; } } $rawRecord['caption'] = $rawCaption; unset($rawRecord['privateCaption']); $json['rawResults'][$record->getId()] = $rawRecord; } // populates facets (aggregates) $facets = []; // $facetClauses = []; foreach ($result->getFacets() as $facet) { $facetName = $facet['name']; if(array_key_exists($facetName, $fieldsInfosByName)) { $f = $fieldsInfosByName[$facetName]; $facet['label'] = $f['trans_label']; $facet['labels'] = $f['labels']; $facet['type'] = strtoupper($f['type']) . "-AGGREGATE"; $facets[] = $facet; // $facetClauses[] = [ // 'type' => strtoupper($f['type']) . "-AGGREGATE", // 'field' => $f['field'], // 'facet' => $facet // ]; } } // $json['jsq'] = $facetClauses; $json['facets'] = $facets; $json['phrasea_props'] = $proposals; $json['total_answers'] = (int) $result->getAvailable(); $json['next_page'] = ($page < $npages && $result->getAvailable() > 0) ? ($page + 1) : false; $json['prev_page'] = ($page > 1 && $result->getAvailable() > 0) ? ($page - 1) : false; $json['form'] = $options->serialize(); $json['queryCompiled'] = $result->getQueryCompiled(); $json['queryAST'] = $result->getQueryAST(); $json['queryESLib'] = $queryESLib; } catch(\Exception $e) { // we'd like a message from the parser so get all the exceptions messages $msg = ''; for(; $e; $e=$e->getPrevious()) { $msg .= ($msg ? "\n":"") . $e->getMessage(); } $template = 'prod/results/help.html.twig'; $result = [ 'error' => $msg ]; $json['results'] = $this->render($template, ['results'=> $result]); } return $this->app->json($json); }
[ "public", "function", "query", "(", "Request", "$", "request", ")", "{", "$", "query", "=", "(", "string", ")", "$", "request", "->", "request", "->", "get", "(", "'qry'", ")", ";", "// since the query comes from a submited form, normalize crlf,cr,lf ...", "$", ...
Query Phraseanet to fetch records @param Request $request @return Response
[ "Query", "Phraseanet", "to", "fetch", "records" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Prod/QueryController.php#L129-L476
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Prod/QueryController.php
QueryController.queryAnswerTrain
public function queryAnswerTrain(Request $request) { if (null === $optionsSerial = $request->get('options_serial')) { $this->app->abort(400, 'Search engine options are missing'); } try { $options = SearchEngineOptions::hydrate($this->app, $optionsSerial); } catch (\Exception $e) { $this->app->abort(400, 'Provided search engine options are not valid'); } $pos = (int) $request->request->get('pos', 0); $query = $request->request->get('query', ''); $record = new \record_preview($this->app, 'RESULT', $pos, '', $this->getSearchEngine(), $query, $options); $index = ($pos - 3) < 0 ? 0 : ($pos - 3); return $this->app->json([ 'current' => $this->render('prod/preview/result_train.html.twig', [ 'records' => $record->get_train(), 'index' => $index, 'selected' => $pos, ]) ]); }
php
public function queryAnswerTrain(Request $request) { if (null === $optionsSerial = $request->get('options_serial')) { $this->app->abort(400, 'Search engine options are missing'); } try { $options = SearchEngineOptions::hydrate($this->app, $optionsSerial); } catch (\Exception $e) { $this->app->abort(400, 'Provided search engine options are not valid'); } $pos = (int) $request->request->get('pos', 0); $query = $request->request->get('query', ''); $record = new \record_preview($this->app, 'RESULT', $pos, '', $this->getSearchEngine(), $query, $options); $index = ($pos - 3) < 0 ? 0 : ($pos - 3); return $this->app->json([ 'current' => $this->render('prod/preview/result_train.html.twig', [ 'records' => $record->get_train(), 'index' => $index, 'selected' => $pos, ]) ]); }
[ "public", "function", "queryAnswerTrain", "(", "Request", "$", "request", ")", "{", "if", "(", "null", "===", "$", "optionsSerial", "=", "$", "request", "->", "get", "(", "'options_serial'", ")", ")", "{", "$", "this", "->", "app", "->", "abort", "(", ...
Get a preview answer train @param Request $request @return Response
[ "Get", "a", "preview", "answer", "train" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Prod/QueryController.php#L484-L509
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Authentication/PersistentCookie/Manager.php
Manager.getSession
public function getSession($cookieValue) { $session = $this->repository->findOneBy(['token' => $cookieValue]); if (!$session) { return false; } $string = sprintf('%s_%s', $this->browser->getBrowser(), $this->browser->getPlatform()); if (!$this->encoder->isPasswordValid($session->getToken(), $string, $session->getNonce())) { return false; } return $session; }
php
public function getSession($cookieValue) { $session = $this->repository->findOneBy(['token' => $cookieValue]); if (!$session) { return false; } $string = sprintf('%s_%s', $this->browser->getBrowser(), $this->browser->getPlatform()); if (!$this->encoder->isPasswordValid($session->getToken(), $string, $session->getNonce())) { return false; } return $session; }
[ "public", "function", "getSession", "(", "$", "cookieValue", ")", "{", "$", "session", "=", "$", "this", "->", "repository", "->", "findOneBy", "(", "[", "'token'", "=>", "$", "cookieValue", "]", ")", ";", "if", "(", "!", "$", "session", ")", "{", "r...
Returns a Session give a cookie value @param string $cookieValue @return false|Session
[ "Returns", "a", "Session", "give", "a", "cookie", "value" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/PersistentCookie/Manager.php#L38-L52
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Notification/Mail/MailRequestPasswordUpdate.php
MailRequestPasswordUpdate.getMessage
public function getMessage() { if (!$this->login) { throw new LogicException('You must set a login before calling getMessage'); } return $this->app->trans('Password renewal for login "%login%" has been requested', ['%login%' => $this->login]) . "\n" . $this->app->trans('login:: Visitez le lien suivant et suivez les instructions pour continuer, sinon ignorez cet email et il ne se passera rien'); }
php
public function getMessage() { if (!$this->login) { throw new LogicException('You must set a login before calling getMessage'); } return $this->app->trans('Password renewal for login "%login%" has been requested', ['%login%' => $this->login]) . "\n" . $this->app->trans('login:: Visitez le lien suivant et suivez les instructions pour continuer, sinon ignorez cet email et il ne se passera rien'); }
[ "public", "function", "getMessage", "(", ")", "{", "if", "(", "!", "$", "this", "->", "login", ")", "{", "throw", "new", "LogicException", "(", "'You must set a login before calling getMessage'", ")", ";", "}", "return", "$", "this", "->", "app", "->", "tran...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Notification/Mail/MailRequestPasswordUpdate.php#L42-L51
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Http/StaticFile/StaticMode.php
StaticMode.ensureSymlink
private function ensureSymlink($pathFile) { if (false === $this->symlinker->hasSymlink($pathFile)) { $this->symlinker->symlink($pathFile); } }
php
private function ensureSymlink($pathFile) { if (false === $this->symlinker->hasSymlink($pathFile)) { $this->symlinker->symlink($pathFile); } }
[ "private", "function", "ensureSymlink", "(", "$", "pathFile", ")", "{", "if", "(", "false", "===", "$", "this", "->", "symlinker", "->", "hasSymlink", "(", "$", "pathFile", ")", ")", "{", "$", "this", "->", "symlinker", "->", "symlink", "(", "$", "path...
Creates a link if it does not exists @param $pathFile
[ "Creates", "a", "link", "if", "it", "does", "not", "exists" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Http/StaticFile/StaticMode.php#L48-L53
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Notification/Mail/MailInfoValidationRequest.php
MailInfoValidationRequest.getMessage
public function getMessage() { if (0 < $this->duration) { if (1 < $this->duration) { return $this->message . "\n\n" . $this->app->trans("You have %quantity% days to validate the selection.", ['%quantity%' => $this->duration]); } else { return $this->message . "\n\n" . $this->app->trans("You have 1 day to validate the selection."); } } return $this->message; }
php
public function getMessage() { if (0 < $this->duration) { if (1 < $this->duration) { return $this->message . "\n\n" . $this->app->trans("You have %quantity% days to validate the selection.", ['%quantity%' => $this->duration]); } else { return $this->message . "\n\n" . $this->app->trans("You have 1 day to validate the selection."); } } return $this->message; }
[ "public", "function", "getMessage", "(", ")", "{", "if", "(", "0", "<", "$", "this", "->", "duration", ")", "{", "if", "(", "1", "<", "$", "this", "->", "duration", ")", "{", "return", "$", "this", "->", "message", ".", "\"\\n\\n\"", ".", "$", "t...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Notification/Mail/MailInfoValidationRequest.php#L69-L80
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Filesystem/LazaretFilesystemService.php
LazaretFilesystemService.writeLazaret
public function writeLazaret(File $file) { $lazaretPathname = $this->booker->bookFile($file->getOriginalName()); $this->filesystem->copy($file->getFile()->getRealPath(), $lazaretPathname, true); $lazaretPathnameThumb = $this->booker->bookFile($file->getOriginalName(), 'thumb'); try { $this->alchemyst->turnInto($file->getFile()->getPathname(), $lazaretPathnameThumb, $this->createThumbnailSpecification()); } catch (ExceptionInterface $e) { // Ignore, an empty file should be present } return new PersistedLazaretInformation($lazaretPathname, $lazaretPathnameThumb); }
php
public function writeLazaret(File $file) { $lazaretPathname = $this->booker->bookFile($file->getOriginalName()); $this->filesystem->copy($file->getFile()->getRealPath(), $lazaretPathname, true); $lazaretPathnameThumb = $this->booker->bookFile($file->getOriginalName(), 'thumb'); try { $this->alchemyst->turnInto($file->getFile()->getPathname(), $lazaretPathnameThumb, $this->createThumbnailSpecification()); } catch (ExceptionInterface $e) { // Ignore, an empty file should be present } return new PersistedLazaretInformation($lazaretPathname, $lazaretPathnameThumb); }
[ "public", "function", "writeLazaret", "(", "File", "$", "file", ")", "{", "$", "lazaretPathname", "=", "$", "this", "->", "booker", "->", "bookFile", "(", "$", "file", "->", "getOriginalName", "(", ")", ")", ";", "$", "this", "->", "filesystem", "->", ...
Write a file in storage and mark it lazaret @param File $file @return PersistedLazaretInformation
[ "Write", "a", "file", "in", "storage", "and", "mark", "it", "lazaret" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Filesystem/LazaretFilesystemService.php#L50-L63
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Prod/ToolsController.php
ToolsController.editRecordSharing
public function editRecordSharing(Request $request, $base_id, $record_id) { $record = new \record_adapter($this->app, \phrasea::sbasFromBas($this->app, $base_id), $record_id); $subdefName = (string)$request->request->get('name'); $state = $request->request->get('state') == 'true' ? true : false; $acl = $this->getAclForUser(); if (!$acl->has_right(\ACL::BAS_CHUPUB) || !$acl->has_right_on_base($record->getBaseId(), \ACL::CANMODIFRECORD) || !$acl->has_right_on_base($record->getBaseId(), \ACL::IMGTOOLS) || ('document' == $subdefName && !$acl->has_right_on_base($record->getBaseId(), \ACL::CANDWNLDHD)) || ('document' != $subdefName && !$acl->has_access_to_subdef($record, $subdefName)) ) { $this->app->abort(403); } $subdef = $record->get_subdef($subdefName); if (null === $permalink = $subdef->get_permalink()) { return $this->app->json(['success' => false, 'state' => false], 400); } try { $permalink->set_is_activated($state); $return = ['success' => true, 'state' => $permalink->get_is_activated()]; } catch (\Exception $e) { $return = ['success' => false, 'state' => $permalink->get_is_activated()]; } return $this->app->json($return); }
php
public function editRecordSharing(Request $request, $base_id, $record_id) { $record = new \record_adapter($this->app, \phrasea::sbasFromBas($this->app, $base_id), $record_id); $subdefName = (string)$request->request->get('name'); $state = $request->request->get('state') == 'true' ? true : false; $acl = $this->getAclForUser(); if (!$acl->has_right(\ACL::BAS_CHUPUB) || !$acl->has_right_on_base($record->getBaseId(), \ACL::CANMODIFRECORD) || !$acl->has_right_on_base($record->getBaseId(), \ACL::IMGTOOLS) || ('document' == $subdefName && !$acl->has_right_on_base($record->getBaseId(), \ACL::CANDWNLDHD)) || ('document' != $subdefName && !$acl->has_access_to_subdef($record, $subdefName)) ) { $this->app->abort(403); } $subdef = $record->get_subdef($subdefName); if (null === $permalink = $subdef->get_permalink()) { return $this->app->json(['success' => false, 'state' => false], 400); } try { $permalink->set_is_activated($state); $return = ['success' => true, 'state' => $permalink->get_is_activated()]; } catch (\Exception $e) { $return = ['success' => false, 'state' => $permalink->get_is_activated()]; } return $this->app->json($return); }
[ "public", "function", "editRecordSharing", "(", "Request", "$", "request", ",", "$", "base_id", ",", "$", "record_id", ")", "{", "$", "record", "=", "new", "\\", "record_adapter", "(", "$", "this", "->", "app", ",", "\\", "phrasea", "::", "sbasFromBas", ...
Edit a record share state @param Request $request @param $base_id @param $record_id @return \Symfony\Component\HttpFoundation\JsonResponse
[ "Edit", "a", "record", "share", "state" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Prod/ToolsController.php#L329-L360
alchemy-fr/Phraseanet
lib/classes/patch/370alpha6a.php
patch_370alpha6a.apply
public function apply(base $databox, Application $app) { /** * @var databox $databox */ $structure = $databox->get_structure(); $DOM = new DOMDocument(); $DOM->loadXML($structure); $xpath = new DOMXpath($DOM); foreach ($xpath->query('/record/subdefs/subdefgroup[@name="video"]/subdef[@name="preview"]/acodec') as $node) { $node->nodeValue = 'libvo_aacenc'; } foreach ($xpath->query('/record/subdefs/subdefgroup[@name="video"]/subdef[@name="preview"]/vcodec') as $node) { $node->nodeValue = 'libx264'; } $databox->saveStructure($DOM); $subdefgroups = $databox->get_subdef_structure(); foreach ($subdefgroups as $groupname => $subdefs) { foreach ($subdefs as $name => $subdef) { $this->addScreenDeviceOption($subdefgroups, $subdef, $groupname); if (in_array($name, ['preview', 'thumbnail'])) { if ($name == 'thumbnail' || $subdef->getSubdefType()->getType() != \Alchemy\Phrasea\Media\Subdef\Subdef::TYPE_VIDEO) { $this->addMobileSubdefImage($subdefgroups, $subdef, $groupname); } else { $this->addMobileSubdefVideo($subdefgroups, $subdef, $groupname); } } if ($subdef->getSubdefType()->getType() != \Alchemy\Phrasea\Media\Subdef\Subdef::TYPE_VIDEO) { continue; } $this->addHtml5Video($subdefgroups, $subdef, $groupname); } } return true; }
php
public function apply(base $databox, Application $app) { /** * @var databox $databox */ $structure = $databox->get_structure(); $DOM = new DOMDocument(); $DOM->loadXML($structure); $xpath = new DOMXpath($DOM); foreach ($xpath->query('/record/subdefs/subdefgroup[@name="video"]/subdef[@name="preview"]/acodec') as $node) { $node->nodeValue = 'libvo_aacenc'; } foreach ($xpath->query('/record/subdefs/subdefgroup[@name="video"]/subdef[@name="preview"]/vcodec') as $node) { $node->nodeValue = 'libx264'; } $databox->saveStructure($DOM); $subdefgroups = $databox->get_subdef_structure(); foreach ($subdefgroups as $groupname => $subdefs) { foreach ($subdefs as $name => $subdef) { $this->addScreenDeviceOption($subdefgroups, $subdef, $groupname); if (in_array($name, ['preview', 'thumbnail'])) { if ($name == 'thumbnail' || $subdef->getSubdefType()->getType() != \Alchemy\Phrasea\Media\Subdef\Subdef::TYPE_VIDEO) { $this->addMobileSubdefImage($subdefgroups, $subdef, $groupname); } else { $this->addMobileSubdefVideo($subdefgroups, $subdef, $groupname); } } if ($subdef->getSubdefType()->getType() != \Alchemy\Phrasea\Media\Subdef\Subdef::TYPE_VIDEO) { continue; } $this->addHtml5Video($subdefgroups, $subdef, $groupname); } } return true; }
[ "public", "function", "apply", "(", "base", "$", "databox", ",", "Application", "$", "app", ")", "{", "/**\n * @var databox $databox\n */", "$", "structure", "=", "$", "databox", "->", "get_structure", "(", ")", ";", "$", "DOM", "=", "new", "DO...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/370alpha6a.php#L49-L94
alchemy-fr/Phraseanet
lib/classes/Bridge/Api/Youtube/Element.php
Bridge_Api_Youtube_Element.get_thumbnail
public function get_thumbnail() { $video_thumbnails = $this->entry->getVideoThumbnails(); foreach ($video_thumbnails as $thumb) { if (120 == $thumb['width'] && 90 == $thumb['height']) { return $thumb['url']; } } }
php
public function get_thumbnail() { $video_thumbnails = $this->entry->getVideoThumbnails(); foreach ($video_thumbnails as $thumb) { if (120 == $thumb['width'] && 90 == $thumb['height']) { return $thumb['url']; } } }
[ "public", "function", "get_thumbnail", "(", ")", "{", "$", "video_thumbnails", "=", "$", "this", "->", "entry", "->", "getVideoThumbnails", "(", ")", ";", "foreach", "(", "$", "video_thumbnails", "as", "$", "thumb", ")", "{", "if", "(", "120", "==", "$",...
Return the thumbnail of the element Available size : 120*90;480*360; @return string
[ "Return", "the", "thumbnail", "of", "the", "element", "Available", "size", ":", "120", "*", "90", ";", "480", "*", "360", ";" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/Bridge/Api/Youtube/Element.php#L55-L64
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/SearchEngine/Elastic/Thesaurus.php
Thesaurus.findConceptsBulk
public function findConceptsBulk(array $terms, $lang = null, $filter = null, $strict = false) { $this->logger->debug(sprintf('Finding linked concepts in bulk for %d terms', count($terms))); // We use the same filter for all terms when a single one is given $filters = is_array($filter) ? $filter : array_fill_keys(array_keys($terms), $filter); if (array_diff_key($terms, $filters)) { throw new InvalidArgumentException('Filters list must contain a filter for each term'); } // TODO Use bulk queries for performance $concepts = array(); foreach ($terms as $index => $term) { $strict |= ($term instanceof AST\TermNode); // a "term" node is [strict group of words] $concepts[] = $this->findConcepts($term, $lang, $filters[$index], $strict); } return $concepts; }
php
public function findConceptsBulk(array $terms, $lang = null, $filter = null, $strict = false) { $this->logger->debug(sprintf('Finding linked concepts in bulk for %d terms', count($terms))); // We use the same filter for all terms when a single one is given $filters = is_array($filter) ? $filter : array_fill_keys(array_keys($terms), $filter); if (array_diff_key($terms, $filters)) { throw new InvalidArgumentException('Filters list must contain a filter for each term'); } // TODO Use bulk queries for performance $concepts = array(); foreach ($terms as $index => $term) { $strict |= ($term instanceof AST\TermNode); // a "term" node is [strict group of words] $concepts[] = $this->findConcepts($term, $lang, $filters[$index], $strict); } return $concepts; }
[ "public", "function", "findConceptsBulk", "(", "array", "$", "terms", ",", "$", "lang", "=", "null", ",", "$", "filter", "=", "null", ",", "$", "strict", "=", "false", ")", "{", "$", "this", "->", "logger", "->", "debug", "(", "sprintf", "(", "'Findi...
Find concepts linked to a bulk of Terms @param Term[]|string[] $terms Term objects or strings @param string|null $lang Input language @param Filter[]|Filter|null $filter Single filter or a filter for each term @param boolean $strict Strict mode matching @return Concept[][] List of matching concepts for each term
[ "Find", "concepts", "linked", "to", "a", "bulk", "of", "Terms" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/Elastic/Thesaurus.php#L48-L68
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/SearchEngine/Elastic/Thesaurus.php
Thesaurus.findConcepts
public function findConcepts($term, $lang = null, Filter $filter = null, $strict = false) { return $strict ? $this->findConceptsStrict($term, $lang, $filter) : $this->findConceptsFuzzy($term, $lang, $filter) ; }
php
public function findConcepts($term, $lang = null, Filter $filter = null, $strict = false) { return $strict ? $this->findConceptsStrict($term, $lang, $filter) : $this->findConceptsFuzzy($term, $lang, $filter) ; }
[ "public", "function", "findConcepts", "(", "$", "term", ",", "$", "lang", "=", "null", ",", "Filter", "$", "filter", "=", "null", ",", "$", "strict", "=", "false", ")", "{", "return", "$", "strict", "?", "$", "this", "->", "findConceptsStrict", "(", ...
Find concepts linked to the provided Term In strict mode, term context matching is enforced: `orange (color)` will *not* match `orange` in the index @param Term|string $term Term object or a string containing term's value @param string|null $lang Input language ("fr", "en", ...) for more effective results @param Filter|null $filter Filter to restrict search on a specified subset @param boolean $strict Whether to enable strict search or not @return Concept[] Matching concepts
[ "Find", "concepts", "linked", "to", "the", "provided", "Term" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/Elastic/Thesaurus.php#L82-L89
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/SearchEngine/Elastic/Thesaurus.php
Thesaurus.addFilters
private static function addFilters(array &$current_filters, array $new_filters) { foreach($new_filters as $verb=>$new_filter) { foreach ($new_filter as $f=>$v) { if(count($current_filters) == 0) { $current_filters = [$verb => [$f=>$v]]; } else { if (!isset($current_filters['bool']['must'])) { // Wrap the previous filter in a boolean (must) filter $current_filters = ['bool' => ['must' => [$current_filters]]]; } $current_filters['bool']['must'][] = [$verb => [$f => $v]]; } } } }
php
private static function addFilters(array &$current_filters, array $new_filters) { foreach($new_filters as $verb=>$new_filter) { foreach ($new_filter as $f=>$v) { if(count($current_filters) == 0) { $current_filters = [$verb => [$f=>$v]]; } else { if (!isset($current_filters['bool']['must'])) { // Wrap the previous filter in a boolean (must) filter $current_filters = ['bool' => ['must' => [$current_filters]]]; } $current_filters['bool']['must'][] = [$verb => [$f => $v]]; } } } }
[ "private", "static", "function", "addFilters", "(", "array", "&", "$", "current_filters", ",", "array", "$", "new_filters", ")", "{", "foreach", "(", "$", "new_filters", "as", "$", "verb", "=>", "$", "new_filter", ")", "{", "foreach", "(", "$", "new_filter...
@param array $current_filters BY REF ! @param array $new_filters add filters to existing filters, wrapping with bool/must if necessary
[ "@param", "array", "$current_filters", "BY", "REF", "!", "@param", "array", "$new_filters" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/Elastic/Thesaurus.php#L310-L326
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Border/MetaFieldsBag.php
MetaFieldsBag.toMetadataArray
public function toMetadataArray(\databox_descriptionStructure $metadatasStructure) { $metas = []; $unicode = new \unicode(); /** @var databox_field $databox_field */ foreach ($metadatasStructure as $databox_field) { $field_name = $databox_field->get_name(); if ($this->containsKey($field_name)) { if ($databox_field->is_multi()) { $values = $this->get($field_name)->getValue(); $tmp = []; foreach ($values as $value) { foreach (\caption_field::get_multi_values($value, $databox_field->get_separator()) as $v) { $tmp[] = $v; } } $values = array_unique($tmp); foreach ($values as $value) { $value = $unicode->substituteCtrlCharacters($value, ' '); $value = $unicode->toUTF8($value); if ($databox_field->get_type() == 'date') { $value = $unicode->parseDate($value); } $metas[] = [ 'meta_struct_id' => $databox_field->get_id(), 'value' => $value, 'meta_id' => null ]; } } else { $values = $this->get($field_name)->getValue(); $value = array_shift($values); $value = $unicode->substituteCtrlCharacters($value, ' '); $value = $unicode->toUTF8($value); if ($databox_field->get_type() == 'date') { $value = $unicode->parseDate($value); } $metas[] = [ 'meta_struct_id' => $databox_field->get_id(), 'value' => $value, 'meta_id' => null ]; } } } return $metas; }
php
public function toMetadataArray(\databox_descriptionStructure $metadatasStructure) { $metas = []; $unicode = new \unicode(); /** @var databox_field $databox_field */ foreach ($metadatasStructure as $databox_field) { $field_name = $databox_field->get_name(); if ($this->containsKey($field_name)) { if ($databox_field->is_multi()) { $values = $this->get($field_name)->getValue(); $tmp = []; foreach ($values as $value) { foreach (\caption_field::get_multi_values($value, $databox_field->get_separator()) as $v) { $tmp[] = $v; } } $values = array_unique($tmp); foreach ($values as $value) { $value = $unicode->substituteCtrlCharacters($value, ' '); $value = $unicode->toUTF8($value); if ($databox_field->get_type() == 'date') { $value = $unicode->parseDate($value); } $metas[] = [ 'meta_struct_id' => $databox_field->get_id(), 'value' => $value, 'meta_id' => null ]; } } else { $values = $this->get($field_name)->getValue(); $value = array_shift($values); $value = $unicode->substituteCtrlCharacters($value, ' '); $value = $unicode->toUTF8($value); if ($databox_field->get_type() == 'date') { $value = $unicode->parseDate($value); } $metas[] = [ 'meta_struct_id' => $databox_field->get_id(), 'value' => $value, 'meta_id' => null ]; } } } return $metas; }
[ "public", "function", "toMetadataArray", "(", "\\", "databox_descriptionStructure", "$", "metadatasStructure", ")", "{", "$", "metas", "=", "[", "]", ";", "$", "unicode", "=", "new", "\\", "unicode", "(", ")", ";", "/** @var databox_field $databox_field */", "fore...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Border/MetaFieldsBag.php#L27-L85
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Command/Developer/Uninstaller.php
Uninstaller.doExecute
protected function doExecute(InputInterface $input, OutputInterface $output) { $root = $this->container['root.path']; $path = $this->container['cache.path']; $paths = [ $root . '/config/configuration.yml', $root . '/config/services.yml', $root . '/config/connexions.yml', $root . '/config/config.yml', $root . '/config/config.inc', $root . '/config/connexion.inc', $root . '/config/_GV.php', $root . '/config/_GV.php.old', $root . '/config/configuration-compiled.php', $this->container['tmp.download.path'], $this->container['tmp.lazaret.path'], $this->container['tmp.caption.path'], $this->container['tmp.path'] . '/sessions', $this->container['tmp.path'] . '/locks', $path . '/cache_registry.php', $path . '/cache_registry.yml', $path . '/serializer', $path . '/doctrine', $path . '/twig', $path . '/translations', $path . '/minify', $path . '/profiler', ]; $files = $directories = []; foreach ($paths as $path) { if (is_dir($path)) { $directories[] = $path; } elseif (is_file($path)) { $files[] = $path; } } $this->container['filesystem']->remove($files); $this->container['filesystem']->remove(Finder::create()->in($directories)); return 0; }
php
protected function doExecute(InputInterface $input, OutputInterface $output) { $root = $this->container['root.path']; $path = $this->container['cache.path']; $paths = [ $root . '/config/configuration.yml', $root . '/config/services.yml', $root . '/config/connexions.yml', $root . '/config/config.yml', $root . '/config/config.inc', $root . '/config/connexion.inc', $root . '/config/_GV.php', $root . '/config/_GV.php.old', $root . '/config/configuration-compiled.php', $this->container['tmp.download.path'], $this->container['tmp.lazaret.path'], $this->container['tmp.caption.path'], $this->container['tmp.path'] . '/sessions', $this->container['tmp.path'] . '/locks', $path . '/cache_registry.php', $path . '/cache_registry.yml', $path . '/serializer', $path . '/doctrine', $path . '/twig', $path . '/translations', $path . '/minify', $path . '/profiler', ]; $files = $directories = []; foreach ($paths as $path) { if (is_dir($path)) { $directories[] = $path; } elseif (is_file($path)) { $files[] = $path; } } $this->container['filesystem']->remove($files); $this->container['filesystem']->remove(Finder::create()->in($directories)); return 0; }
[ "protected", "function", "doExecute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "root", "=", "$", "this", "->", "container", "[", "'root.path'", "]", ";", "$", "path", "=", "$", "this", "->", "container", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/Developer/Uninstaller.php#L31-L75
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Border/MimeGuesserConfiguration.php
MimeGuesserConfiguration.register
public function register() { $guesser = MimeTypeGuesser::getInstance(); $guesser->register(new RawImageMimeTypeGuesser()); $guesser->register(new PostScriptMimeTypeGuesser()); $guesser->register(new AudioMimeTypeGuesser()); $guesser->register(new VideoMimeTypeGuesser()); $guesser->register(new CustomExtensionGuesser($this->conf->get(['border-manager', 'extension-mapping'], []))); }
php
public function register() { $guesser = MimeTypeGuesser::getInstance(); $guesser->register(new RawImageMimeTypeGuesser()); $guesser->register(new PostScriptMimeTypeGuesser()); $guesser->register(new AudioMimeTypeGuesser()); $guesser->register(new VideoMimeTypeGuesser()); $guesser->register(new CustomExtensionGuesser($this->conf->get(['border-manager', 'extension-mapping'], []))); }
[ "public", "function", "register", "(", ")", "{", "$", "guesser", "=", "MimeTypeGuesser", "::", "getInstance", "(", ")", ";", "$", "guesser", "->", "register", "(", "new", "RawImageMimeTypeGuesser", "(", ")", ")", ";", "$", "guesser", "->", "register", "(",...
Registers mime type guessers given the configuration
[ "Registers", "mime", "type", "guessers", "given", "the", "configuration" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Border/MimeGuesserConfiguration.php#L34-L44
alchemy-fr/Phraseanet
lib/classes/patch/320alpha4a.php
patch_320alpha4a.apply
public function apply(base $databox, Application $app) { $sql = 'TRUNCATE metadatas'; $stmt = $databox->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $sql = 'TRUNCATE metadatas_structure'; $stmt = $databox->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $sql = 'TRUNCATE technical_datas'; $stmt = $databox->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $phrasea_maps = [ 'pdftext' => 'Phraseanet:pdftext' , 'tf-archivedate' => 'Phraseanet:tf-archivedate' , 'tf-atime' => 'Phraseanet:tf-atime' , 'tf-chgdocdate' => 'Phraseanet:tf-chgdocdate' , 'tf-ctime' => 'Phraseanet:tf-ctime' , 'tf-editdate' => 'Phraseanet:tf-editdate' , 'tf-mtime' => 'Phraseanet:tf-mtime' , 'tf-parentdir' => 'Phraseanet:tf-parentdir' , 'tf-bits' => 'Phraseanet:tf-bits' , 'tf-channels' => 'Phraseanet:tf-channels' , 'tf-extension' => 'Phraseanet:tf-extension' , 'tf-filename' => 'Phraseanet:tf-filename' , 'tf-filepath' => 'Phraseanet:tf-filepath' , 'tf-height' => 'Phraseanet:tf-height' , 'tf-mimetype' => 'Phraseanet:tf-mimetype' , 'tf-recordid' => 'Phraseanet:tf-recordid' , 'tf-size' => 'Phraseanet:tf-size' , 'tf-width' => 'Phraseanet:tf-width' ]; $sxe = $databox->get_sxml_structure(); $dom_struct = $databox->get_dom_structure(); $xp_struct = $databox->get_xpath_structure(); foreach ($sxe->description->children() as $fname => $field) { $src = trim(isset($field['src']) ? $field['src'] : ''); if (array_key_exists($src, $phrasea_maps)) { $src = $phrasea_maps[$src]; } $nodes = $xp_struct->query('/record/description/' . $fname); if ($nodes->length > 0) { $node = $nodes->item(0); $node->setAttribute('src', $src); $node->removeAttribute('meta_id'); } } $databox->saveStructure($dom_struct); $databox->feed_meta_fields(); $databox->delete_data_from_cache(databox::CACHE_STRUCTURE); $databox->delete_data_from_cache(databox::CACHE_META_STRUCT); $conn = $app->getApplicationBox()->get_connection(); $sql = 'DELETE FROM `task2` WHERE class="readmeta"'; $stmt = $conn->prepare($sql); $stmt->execute(); $stmt->closeCursor(); unset($stmt); return true; }
php
public function apply(base $databox, Application $app) { $sql = 'TRUNCATE metadatas'; $stmt = $databox->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $sql = 'TRUNCATE metadatas_structure'; $stmt = $databox->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $sql = 'TRUNCATE technical_datas'; $stmt = $databox->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $phrasea_maps = [ 'pdftext' => 'Phraseanet:pdftext' , 'tf-archivedate' => 'Phraseanet:tf-archivedate' , 'tf-atime' => 'Phraseanet:tf-atime' , 'tf-chgdocdate' => 'Phraseanet:tf-chgdocdate' , 'tf-ctime' => 'Phraseanet:tf-ctime' , 'tf-editdate' => 'Phraseanet:tf-editdate' , 'tf-mtime' => 'Phraseanet:tf-mtime' , 'tf-parentdir' => 'Phraseanet:tf-parentdir' , 'tf-bits' => 'Phraseanet:tf-bits' , 'tf-channels' => 'Phraseanet:tf-channels' , 'tf-extension' => 'Phraseanet:tf-extension' , 'tf-filename' => 'Phraseanet:tf-filename' , 'tf-filepath' => 'Phraseanet:tf-filepath' , 'tf-height' => 'Phraseanet:tf-height' , 'tf-mimetype' => 'Phraseanet:tf-mimetype' , 'tf-recordid' => 'Phraseanet:tf-recordid' , 'tf-size' => 'Phraseanet:tf-size' , 'tf-width' => 'Phraseanet:tf-width' ]; $sxe = $databox->get_sxml_structure(); $dom_struct = $databox->get_dom_structure(); $xp_struct = $databox->get_xpath_structure(); foreach ($sxe->description->children() as $fname => $field) { $src = trim(isset($field['src']) ? $field['src'] : ''); if (array_key_exists($src, $phrasea_maps)) { $src = $phrasea_maps[$src]; } $nodes = $xp_struct->query('/record/description/' . $fname); if ($nodes->length > 0) { $node = $nodes->item(0); $node->setAttribute('src', $src); $node->removeAttribute('meta_id'); } } $databox->saveStructure($dom_struct); $databox->feed_meta_fields(); $databox->delete_data_from_cache(databox::CACHE_STRUCTURE); $databox->delete_data_from_cache(databox::CACHE_META_STRUCT); $conn = $app->getApplicationBox()->get_connection(); $sql = 'DELETE FROM `task2` WHERE class="readmeta"'; $stmt = $conn->prepare($sql); $stmt->execute(); $stmt->closeCursor(); unset($stmt); return true; }
[ "public", "function", "apply", "(", "base", "$", "databox", ",", "Application", "$", "app", ")", "{", "$", "sql", "=", "'TRUNCATE metadatas'", ";", "$", "stmt", "=", "$", "databox", "->", "get_connection", "(", ")", "->", "prepare", "(", "$", "sql", ")...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/320alpha4a.php#L49-L120
alchemy-fr/Phraseanet
lib/classes/caption/Field/Value.php
caption_Field_Value.get_cache_key
public function get_cache_key($option = null) { return 'caption_fieldvalue_' . $this->record->getDatabox()->get_sbas_id() . '_' . $this->id . '_' . ($option ? '_' . $option : ''); }
php
public function get_cache_key($option = null) { return 'caption_fieldvalue_' . $this->record->getDatabox()->get_sbas_id() . '_' . $this->id . '_' . ($option ? '_' . $option : ''); }
[ "public", "function", "get_cache_key", "(", "$", "option", "=", "null", ")", "{", "return", "'caption_fieldvalue_'", ".", "$", "this", "->", "record", "->", "getDatabox", "(", ")", "->", "get_sbas_id", "(", ")", ".", "'_'", ".", "$", "this", "->", "id", ...
Part of the cache_cacheableInterface @param string $option @return string
[ "Part", "of", "the", "cache_cacheableInterface" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/caption/Field/Value.php#L431-L434
alchemy-fr/Phraseanet
lib/classes/caption/Field/Value.php
caption_Field_Value.get_data_from_cache
public function get_data_from_cache($option = null) { if (isset(self::$localCache[$this->get_cache_key($option)])) { return self::$localCache[$this->get_cache_key($option)]; } throw new Exception('no value'); }
php
public function get_data_from_cache($option = null) { if (isset(self::$localCache[$this->get_cache_key($option)])) { return self::$localCache[$this->get_cache_key($option)]; } throw new Exception('no value'); }
[ "public", "function", "get_data_from_cache", "(", "$", "option", "=", "null", ")", "{", "if", "(", "isset", "(", "self", "::", "$", "localCache", "[", "$", "this", "->", "get_cache_key", "(", "$", "option", ")", "]", ")", ")", "{", "return", "self", ...
Part of the cache_cacheableInterface @param string $option @return mixed
[ "Part", "of", "the", "cache_cacheableInterface" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/caption/Field/Value.php#L442-L449
alchemy-fr/Phraseanet
lib/classes/caption/Field/Value.php
caption_Field_Value.set_data_to_cache
public function set_data_to_cache($value, $option = null, $duration = 360000) { return self::$localCache[$this->get_cache_key($option)] = $value; }
php
public function set_data_to_cache($value, $option = null, $duration = 360000) { return self::$localCache[$this->get_cache_key($option)] = $value; }
[ "public", "function", "set_data_to_cache", "(", "$", "value", ",", "$", "option", "=", "null", ",", "$", "duration", "=", "360000", ")", "{", "return", "self", "::", "$", "localCache", "[", "$", "this", "->", "get_cache_key", "(", "$", "option", ")", "...
Part of the cache_cacheableInterface @param mixed $value @param string $option @param int $duration @return caption_field
[ "Part", "of", "the", "cache_cacheableInterface" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/caption/Field/Value.php#L459-L462
alchemy-fr/Phraseanet
lib/classes/caption/Field/Value.php
caption_Field_Value.delete_data_from_cache
public function delete_data_from_cache($option = null) { $this->value = $this->vocabularyId = $this->vocabularyType = null; $this->record->delete_data_from_cache(record_adapter::CACHE_TITLE); $this->record->get_caption()->delete_data_from_cache(); unset(self::$localCache[$this->get_cache_key($option)]); }
php
public function delete_data_from_cache($option = null) { $this->value = $this->vocabularyId = $this->vocabularyType = null; $this->record->delete_data_from_cache(record_adapter::CACHE_TITLE); $this->record->get_caption()->delete_data_from_cache(); unset(self::$localCache[$this->get_cache_key($option)]); }
[ "public", "function", "delete_data_from_cache", "(", "$", "option", "=", "null", ")", "{", "$", "this", "->", "value", "=", "$", "this", "->", "vocabularyId", "=", "$", "this", "->", "vocabularyType", "=", "null", ";", "$", "this", "->", "record", "->", ...
Part of the cache_cacheableInterface @param string $option @return caption_field
[ "Part", "of", "the", "cache_cacheableInterface" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/caption/Field/Value.php#L470-L477
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Application/Helper/DelivererAware.php
DelivererAware.deliverFile
public function deliverFile($file, $filename = null, $disposition = DeliverDataInterface::DISPOSITION_INLINE, $mimeType = null, $cacheDuration = null) { return $this->getDeliverer()->deliverFile($file, $filename, $disposition, $mimeType, $cacheDuration); }
php
public function deliverFile($file, $filename = null, $disposition = DeliverDataInterface::DISPOSITION_INLINE, $mimeType = null, $cacheDuration = null) { return $this->getDeliverer()->deliverFile($file, $filename, $disposition, $mimeType, $cacheDuration); }
[ "public", "function", "deliverFile", "(", "$", "file", ",", "$", "filename", "=", "null", ",", "$", "disposition", "=", "DeliverDataInterface", "::", "DISPOSITION_INLINE", ",", "$", "mimeType", "=", "null", ",", "$", "cacheDuration", "=", "null", ")", "{", ...
Returns a HTTP Response ready to deliver a binary file @param string $file @param string $filename @param string $disposition @param string|null $mimeType @param integer $cacheDuration @return Response
[ "Returns", "a", "HTTP", "Response", "ready", "to", "deliver", "a", "binary", "file" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Application/Helper/DelivererAware.php#L68-L71
alchemy-fr/Phraseanet
lib/classes/patch/370alpha8a.php
patch_370alpha8a.apply
public function apply(base $appbox, Application $app) { $ttasks = []; $conn = $appbox->get_connection(); $sql = 'SELECT task_id, active, name, class, settings FROM task2 WHERE class=\'task_period_workflow01\''; if (($stmt = $conn->prepare($sql)) !== FALSE) { $stmt->execute(); $ttasks = $stmt->fetchAll(); } $stmt->closeCursor(); $tdom = []; // key = period $taskstodel = []; foreach ($ttasks as $task) { $active = true; $warning = []; /* * migrating task 'workflow01' */ $x = $task['settings']; if (false !== $sx = simplexml_load_string($x)) { $period = (int) ($sx->period); if ( ! array_key_exists('_' . $period, $tdom)) { $dom = new DOMDocument('1.0', 'UTF-8'); $dom->formatOutput = true; $dom->preserveWhiteSpace = false; $ts = $dom->appendChild($dom->createElement('tasksettings')); $ts->appendChild($dom->createElement('period'))->appendChild($dom->createTextNode(60 * $period)); $ts->appendChild($dom->createElement('logsql'))->appendChild($dom->createTextNode('1')); $tasks = $ts->appendChild($dom->createElement('tasks')); $tdom['_' . $period] = ['dom' => $dom, 'tasks' => $tasks]; } else { $dom = &$tdom['_' . $period]['dom']; $tasks = &$tdom['_' . $period]['tasks']; } /* * migrating task 'workflow01' */ if ($task['class'] === 'task_period_workflow01') { $t = $tasks->appendChild($dom->createElement('task')); $t->setAttribute('active', '0'); $t->setAttribute('name', 'imported from \'' . $task['name'] . '\''); $t->setAttribute('action', 'update'); if ($sx->sbas_id) { $sbas_id = trim($sx->sbas_id); if ($sbas_id != '' && is_numeric($sbas_id)) { $t->setAttribute('sbas_id', $sx->sbas_id); } else { $warning[] = sprintf("Bad sbas_id '%s'", $sbas_id); $active = false; } } else { $warning[] = sprintf("missing sbas_id"); $active = false; } // 'from' section $from = $t->appendChild($dom->createElement('from')); if ($sx->coll0) { if (($coll0 = trim($sx->coll0)) != '') { if (is_numeric($coll0)) { $n = $from->appendChild($dom->createElement('coll')); $n->setAttribute('compare', '='); $n->setAttribute('id', $coll0); } else { $warning[] = sprintf("Bad (from) coll_id '%s'", $coll0); $active = false; } } } if ($sx->status0 && trim($sx->status0) != '') { $st = explode('_', trim($sx->status0)); if (count($st) == 2) { $bit = (int) ($st[0]); if ($bit >= 0 && $bit < 32 && ($st[1] == '0' || $st[1] == '1')) { $from->appendChild($dom->createElement('status')) ->setAttribute('mask', $st[1] . str_repeat('x', $bit - 1)); } else { $warning[] = sprintf("Bad (from) status '%s'", trim($sx->status0)); $active = false; } } else { $warning[] = sprintf("Bad (from) status '%s'", trim($sx->status0)); $active = false; } } // 'to' section $to = $t->appendChild($dom->createElement('to')); if ($sx->coll1) { if (($coll1 = trim($sx->coll1)) != '') { if (is_numeric($coll1)) { $n = $to->appendChild($dom->createElement('coll')); $n->setAttribute('id', $coll1); } else { $warning[] = sprintf("Bad (to) coll_id '%s'", $coll1); $active = false; } } } if ($sx->status1 && trim($sx->status1) != '') { $st = explode('_', trim($sx->status1)); if (count($st) == 2) { $bit = (int) ($st[0]); if ($bit >= 0 && $bit < 32 && ($st[1] == '0' || $st[1] == '1')) { $to->appendChild($dom->createElement('status')) ->setAttribute('mask', $st[1] . str_repeat('x', $bit - 1)); } else { $warning[] = sprintf("Bad (to) status '%s'", trim($sx->status1)); $active = false; } } else { $warning[] = sprintf("Bad (to) status '%s'", trim($sx->status1)); $active = false; } } if ($active && $task['active'] == '1') { $t->setAttribute('active', '1'); } foreach ($warning as $w) { $t->appendChild($dom->createComment($w)); } $taskstodel[] = $task['task_id']; } } if (count($taskstodel) > 0) { $conn->exec('DELETE FROM task2 WHERE task_id IN(' . implode(',', $taskstodel) . ')'); } } /* * save new tasks */ foreach ($tdom as $newtask) { $settings = $newtask['dom']->saveXML(); $sxml = simplexml_load_string($settings); $period = $sxml->period ? (int) $sxml->period : 300; $task = new Task(); $task ->setName('Record mover') ->setJobId('RecordMover') ->setSettings($settings) ->setPeriod($period) ->setStatus(Task::STATUS_STARTED); $app['orm.em']->persist($task); } $app['orm.em']->flush(); return true; }
php
public function apply(base $appbox, Application $app) { $ttasks = []; $conn = $appbox->get_connection(); $sql = 'SELECT task_id, active, name, class, settings FROM task2 WHERE class=\'task_period_workflow01\''; if (($stmt = $conn->prepare($sql)) !== FALSE) { $stmt->execute(); $ttasks = $stmt->fetchAll(); } $stmt->closeCursor(); $tdom = []; // key = period $taskstodel = []; foreach ($ttasks as $task) { $active = true; $warning = []; /* * migrating task 'workflow01' */ $x = $task['settings']; if (false !== $sx = simplexml_load_string($x)) { $period = (int) ($sx->period); if ( ! array_key_exists('_' . $period, $tdom)) { $dom = new DOMDocument('1.0', 'UTF-8'); $dom->formatOutput = true; $dom->preserveWhiteSpace = false; $ts = $dom->appendChild($dom->createElement('tasksettings')); $ts->appendChild($dom->createElement('period'))->appendChild($dom->createTextNode(60 * $period)); $ts->appendChild($dom->createElement('logsql'))->appendChild($dom->createTextNode('1')); $tasks = $ts->appendChild($dom->createElement('tasks')); $tdom['_' . $period] = ['dom' => $dom, 'tasks' => $tasks]; } else { $dom = &$tdom['_' . $period]['dom']; $tasks = &$tdom['_' . $period]['tasks']; } /* * migrating task 'workflow01' */ if ($task['class'] === 'task_period_workflow01') { $t = $tasks->appendChild($dom->createElement('task')); $t->setAttribute('active', '0'); $t->setAttribute('name', 'imported from \'' . $task['name'] . '\''); $t->setAttribute('action', 'update'); if ($sx->sbas_id) { $sbas_id = trim($sx->sbas_id); if ($sbas_id != '' && is_numeric($sbas_id)) { $t->setAttribute('sbas_id', $sx->sbas_id); } else { $warning[] = sprintf("Bad sbas_id '%s'", $sbas_id); $active = false; } } else { $warning[] = sprintf("missing sbas_id"); $active = false; } // 'from' section $from = $t->appendChild($dom->createElement('from')); if ($sx->coll0) { if (($coll0 = trim($sx->coll0)) != '') { if (is_numeric($coll0)) { $n = $from->appendChild($dom->createElement('coll')); $n->setAttribute('compare', '='); $n->setAttribute('id', $coll0); } else { $warning[] = sprintf("Bad (from) coll_id '%s'", $coll0); $active = false; } } } if ($sx->status0 && trim($sx->status0) != '') { $st = explode('_', trim($sx->status0)); if (count($st) == 2) { $bit = (int) ($st[0]); if ($bit >= 0 && $bit < 32 && ($st[1] == '0' || $st[1] == '1')) { $from->appendChild($dom->createElement('status')) ->setAttribute('mask', $st[1] . str_repeat('x', $bit - 1)); } else { $warning[] = sprintf("Bad (from) status '%s'", trim($sx->status0)); $active = false; } } else { $warning[] = sprintf("Bad (from) status '%s'", trim($sx->status0)); $active = false; } } // 'to' section $to = $t->appendChild($dom->createElement('to')); if ($sx->coll1) { if (($coll1 = trim($sx->coll1)) != '') { if (is_numeric($coll1)) { $n = $to->appendChild($dom->createElement('coll')); $n->setAttribute('id', $coll1); } else { $warning[] = sprintf("Bad (to) coll_id '%s'", $coll1); $active = false; } } } if ($sx->status1 && trim($sx->status1) != '') { $st = explode('_', trim($sx->status1)); if (count($st) == 2) { $bit = (int) ($st[0]); if ($bit >= 0 && $bit < 32 && ($st[1] == '0' || $st[1] == '1')) { $to->appendChild($dom->createElement('status')) ->setAttribute('mask', $st[1] . str_repeat('x', $bit - 1)); } else { $warning[] = sprintf("Bad (to) status '%s'", trim($sx->status1)); $active = false; } } else { $warning[] = sprintf("Bad (to) status '%s'", trim($sx->status1)); $active = false; } } if ($active && $task['active'] == '1') { $t->setAttribute('active', '1'); } foreach ($warning as $w) { $t->appendChild($dom->createComment($w)); } $taskstodel[] = $task['task_id']; } } if (count($taskstodel) > 0) { $conn->exec('DELETE FROM task2 WHERE task_id IN(' . implode(',', $taskstodel) . ')'); } } /* * save new tasks */ foreach ($tdom as $newtask) { $settings = $newtask['dom']->saveXML(); $sxml = simplexml_load_string($settings); $period = $sxml->period ? (int) $sxml->period : 300; $task = new Task(); $task ->setName('Record mover') ->setJobId('RecordMover') ->setSettings($settings) ->setPeriod($period) ->setStatus(Task::STATUS_STARTED); $app['orm.em']->persist($task); } $app['orm.em']->flush(); return true; }
[ "public", "function", "apply", "(", "base", "$", "appbox", ",", "Application", "$", "app", ")", "{", "$", "ttasks", "=", "[", "]", ";", "$", "conn", "=", "$", "appbox", "->", "get_connection", "(", ")", ";", "$", "sql", "=", "'SELECT task_id, active, n...
transform tasks 'workflow 01' to 'RecordMover' will group tasks(01) with same period to a single task(02) @param base $appbox @param Application $app @return boolean
[ "transform", "tasks", "workflow", "01", "to", "RecordMover", "will", "group", "tasks", "(", "01", ")", "with", "same", "period", "to", "a", "single", "task", "(", "02", ")" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/370alpha8a.php#L61-L220
alchemy-fr/Phraseanet
lib/classes/patch/373alpha1a.php
patch_373alpha1a.apply
public function apply(base $appbox, Application $app) { $sql = 'SELECT * FROM registry WHERE `key` = :key'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $Regbinaries = [ 'GV_cli', 'GV_swf_extract', 'GV_pdf2swf', 'GV_swf_render', 'GV_unoconv', 'GV_ffmpeg', 'GV_ffprobe', 'GV_mp4box', 'GV_pdftotext', ]; $mapping = [ 'GV_cli' => 'php_binary', 'GV_swf_extract' => 'swf_extract_binary', 'GV_pdf2swf' => 'pdf2swf_binary', 'GV_swf_render' => 'swf_render_binary', 'GV_unoconv' => 'unoconv_binary', 'GV_ffmpeg' => 'ffmpeg_binary', 'GV_ffprobe' => 'ffprobe_binary', 'GV_mp4box' => 'mp4box_binary', 'GV_pdftotext' => 'pdftotext_binary', ]; $binaries = ['ghostscript_binary' => null]; foreach ($Regbinaries as $name) { $stmt->execute([':key' => $name]); $row = $stmt->fetch(\PDO::FETCH_ASSOC); $value = is_executable($row['value']) ? $row['value'] : null; $binaries[$mapping[$name]] = $value; } $stmt->closeCursor(); $config = $app['configuration.store']->getConfig(); $config['binaries'] = $binaries; $sql = 'DELETE FROM registry WHERE `key` = :key'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); foreach ($Regbinaries as $name) { $stmt->execute([':key' => $name]); } $stmt->closeCursor(); $sql = 'SELECT value FROM registry WHERE `key` = :key'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute([':key'=>'GV_sit']); $row = $stmt->fetch(\PDO::FETCH_ASSOC); $stmt->closeCursor(); $config['main']['key'] = $row['value']; $app['configuration.store']->setConfig($config); $sql = 'DELETE FROM registry WHERE `key` = :key'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute([':key'=>'GV_sit']); $stmt->closeCursor(); return true; }
php
public function apply(base $appbox, Application $app) { $sql = 'SELECT * FROM registry WHERE `key` = :key'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $Regbinaries = [ 'GV_cli', 'GV_swf_extract', 'GV_pdf2swf', 'GV_swf_render', 'GV_unoconv', 'GV_ffmpeg', 'GV_ffprobe', 'GV_mp4box', 'GV_pdftotext', ]; $mapping = [ 'GV_cli' => 'php_binary', 'GV_swf_extract' => 'swf_extract_binary', 'GV_pdf2swf' => 'pdf2swf_binary', 'GV_swf_render' => 'swf_render_binary', 'GV_unoconv' => 'unoconv_binary', 'GV_ffmpeg' => 'ffmpeg_binary', 'GV_ffprobe' => 'ffprobe_binary', 'GV_mp4box' => 'mp4box_binary', 'GV_pdftotext' => 'pdftotext_binary', ]; $binaries = ['ghostscript_binary' => null]; foreach ($Regbinaries as $name) { $stmt->execute([':key' => $name]); $row = $stmt->fetch(\PDO::FETCH_ASSOC); $value = is_executable($row['value']) ? $row['value'] : null; $binaries[$mapping[$name]] = $value; } $stmt->closeCursor(); $config = $app['configuration.store']->getConfig(); $config['binaries'] = $binaries; $sql = 'DELETE FROM registry WHERE `key` = :key'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); foreach ($Regbinaries as $name) { $stmt->execute([':key' => $name]); } $stmt->closeCursor(); $sql = 'SELECT value FROM registry WHERE `key` = :key'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute([':key'=>'GV_sit']); $row = $stmt->fetch(\PDO::FETCH_ASSOC); $stmt->closeCursor(); $config['main']['key'] = $row['value']; $app['configuration.store']->setConfig($config); $sql = 'DELETE FROM registry WHERE `key` = :key'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute([':key'=>'GV_sit']); $stmt->closeCursor(); return true; }
[ "public", "function", "apply", "(", "base", "$", "appbox", ",", "Application", "$", "app", ")", "{", "$", "sql", "=", "'SELECT * FROM registry\n WHERE `key` = :key'", ";", "$", "stmt", "=", "$", "app", "->", "getApplicationBox", "(", ")", "->", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/373alpha1a.php#L49-L119
alchemy-fr/Phraseanet
lib/classes/patch/390alpha1a.php
patch_390alpha1a.apply
public function apply(base $appbox, Application $app) { $sql = 'DELETE FROM Orders'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $sql = 'DELETE FROM OrderElements'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $conn = $app->getApplicationBox()->get_connection(); $sql = 'SELECT id, usr_id, created_on, `usage`, deadline, ssel_id FROM `order`'; $stmt = $conn->prepare($sql); $stmt->execute(); $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); $n = 0; $em = $app['orm.em']; $em->getEventManager()->removeEventSubscriber(new TimestampableListener()); foreach ($rs as $row) { $sql = "SELECT count(id) as todo FROM order_elements WHERE deny = NULL AND order_id = :id"; $stmt = $conn->prepare($sql); $stmt->execute([':id' => $row['id']]); $todo = $stmt->fetch(\PDO::FETCH_ASSOC); $stmt->closeCursor(); if (null === $user = $this->loadUser($app['orm.em'], $row['usr_id'])) { continue; } try { $basket = $app['orm.em']->createQuery('SELECT PARTIAL b.{id} FROM Phraseanet:Basket b WHERE b.id = :id') ->setParameters(['id' => $row['ssel_id']]) ->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true) ->getSingleResult(); } catch (NoResultException $e) { continue; } $order = new Order(); $order->setUser($user) ->setTodo($todo['todo']) ->setOrderUsage($row['usage']) ->setDeadline(new \DateTime($row['deadline'])) ->setCreatedOn(new \DateTime($row['created_on'])) ->setBasket($basket); $em->persist($order); $sql = "SELECT base_id, record_id, order_master_id, deny FROM order_elements WHERE order_id = :id"; $stmt = $conn->prepare($sql); $stmt->execute([':id' => $row['id']]); $elements = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); foreach ($elements as $element) { $orderElement = new OrderElement(); $user = $this->loadUser($app['orm.em'], $row['usr_id']); $orderElement->setBaseId($element['base_id']) ->setDeny($element['deny'] === null ? null : (Boolean) $element['deny']) ->setOrder($order) ->setOrderMaster($user) ->setRecordId($element['record_id']); $order->addElement($orderElement); $em->persist($orderElement); } if ($n % 100 === 0) { $em->flush(); $em->clear(); } } $em->flush(); $em->clear(); $em->getEventManager()->addEventSubscriber(new TimestampableListener()); return true; }
php
public function apply(base $appbox, Application $app) { $sql = 'DELETE FROM Orders'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $sql = 'DELETE FROM OrderElements'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $conn = $app->getApplicationBox()->get_connection(); $sql = 'SELECT id, usr_id, created_on, `usage`, deadline, ssel_id FROM `order`'; $stmt = $conn->prepare($sql); $stmt->execute(); $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); $n = 0; $em = $app['orm.em']; $em->getEventManager()->removeEventSubscriber(new TimestampableListener()); foreach ($rs as $row) { $sql = "SELECT count(id) as todo FROM order_elements WHERE deny = NULL AND order_id = :id"; $stmt = $conn->prepare($sql); $stmt->execute([':id' => $row['id']]); $todo = $stmt->fetch(\PDO::FETCH_ASSOC); $stmt->closeCursor(); if (null === $user = $this->loadUser($app['orm.em'], $row['usr_id'])) { continue; } try { $basket = $app['orm.em']->createQuery('SELECT PARTIAL b.{id} FROM Phraseanet:Basket b WHERE b.id = :id') ->setParameters(['id' => $row['ssel_id']]) ->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true) ->getSingleResult(); } catch (NoResultException $e) { continue; } $order = new Order(); $order->setUser($user) ->setTodo($todo['todo']) ->setOrderUsage($row['usage']) ->setDeadline(new \DateTime($row['deadline'])) ->setCreatedOn(new \DateTime($row['created_on'])) ->setBasket($basket); $em->persist($order); $sql = "SELECT base_id, record_id, order_master_id, deny FROM order_elements WHERE order_id = :id"; $stmt = $conn->prepare($sql); $stmt->execute([':id' => $row['id']]); $elements = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); foreach ($elements as $element) { $orderElement = new OrderElement(); $user = $this->loadUser($app['orm.em'], $row['usr_id']); $orderElement->setBaseId($element['base_id']) ->setDeny($element['deny'] === null ? null : (Boolean) $element['deny']) ->setOrder($order) ->setOrderMaster($user) ->setRecordId($element['record_id']); $order->addElement($orderElement); $em->persist($orderElement); } if ($n % 100 === 0) { $em->flush(); $em->clear(); } } $em->flush(); $em->clear(); $em->getEventManager()->addEventSubscriber(new TimestampableListener()); return true; }
[ "public", "function", "apply", "(", "base", "$", "appbox", ",", "Application", "$", "app", ")", "{", "$", "sql", "=", "'DELETE FROM Orders'", ";", "$", "stmt", "=", "$", "app", "->", "getApplicationBox", "(", ")", "->", "get_connection", "(", ")", "->", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/390alpha1a.php#L62-L148
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Command/Upgrade/Step31.php
Step31.execute
public function execute(InputInterface $input, OutputInterface $output) { foreach ($this->app->getDataboxes() as $databox) { do { $records = $this->getNullUUIDs($databox); foreach ($records as $record) { $this->updateRecordUUID($databox, $record); } } while (count($records) > 0); } }
php
public function execute(InputInterface $input, OutputInterface $output) { foreach ($this->app->getDataboxes() as $databox) { do { $records = $this->getNullUUIDs($databox); foreach ($records as $record) { $this->updateRecordUUID($databox, $record); } } while (count($records) > 0); } }
[ "public", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "foreach", "(", "$", "this", "->", "app", "->", "getDataboxes", "(", ")", "as", "$", "databox", ")", "{", "do", "{", "$", "records", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/Upgrade/Step31.php#L42-L54
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Command/Upgrade/Step31.php
Step31.getTimeEstimation
public function getTimeEstimation() { $time = 0; foreach ($this->app->getDataboxes() as $databox) { $time += $this->getDataboxTimeEstimation($databox); } $time = $time / self::AVERAGE_PER_SECOND; return $time; }
php
public function getTimeEstimation() { $time = 0; foreach ($this->app->getDataboxes() as $databox) { $time += $this->getDataboxTimeEstimation($databox); } $time = $time / self::AVERAGE_PER_SECOND; return $time; }
[ "public", "function", "getTimeEstimation", "(", ")", "{", "$", "time", "=", "0", ";", "foreach", "(", "$", "this", "->", "app", "->", "getDataboxes", "(", ")", "as", "$", "databox", ")", "{", "$", "time", "+=", "$", "this", "->", "getDataboxTimeEstimat...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/Upgrade/Step31.php#L59-L70
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Command/Upgrade/Step31.php
Step31.getDataboxTimeEstimation
protected function getDataboxTimeEstimation(\databox $databox) { $sql = 'SELECT r.coll_id, r.type, r.record_id, s.path, s.file, r.xml FROM record r, subdef s WHERE ISNULL(uuid) AND s.record_id = r.record_id AND s.name="document" AND parent_record_id = 0'; $stmt = $databox->get_connection()->prepare($sql); $stmt->execute(); $quantity = $stmt->rowCount(); $stmt->closeCursor(); return $quantity; }
php
protected function getDataboxTimeEstimation(\databox $databox) { $sql = 'SELECT r.coll_id, r.type, r.record_id, s.path, s.file, r.xml FROM record r, subdef s WHERE ISNULL(uuid) AND s.record_id = r.record_id AND s.name="document" AND parent_record_id = 0'; $stmt = $databox->get_connection()->prepare($sql); $stmt->execute(); $quantity = $stmt->rowCount(); $stmt->closeCursor(); return $quantity; }
[ "protected", "function", "getDataboxTimeEstimation", "(", "\\", "databox", "$", "databox", ")", "{", "$", "sql", "=", "'SELECT r.coll_id, r.type, r.record_id, s.path, s.file, r.xml\n FROM record r, subdef s\n WHERE ISNULL(uuid)\n ...
Return the number of record which does not have a UUID @param \databox $databox
[ "Return", "the", "number", "of", "record", "which", "does", "not", "have", "a", "UUID" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/Upgrade/Step31.php#L77-L91
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Command/Upgrade/Step31.php
Step31.getNullUUIDs
protected function getNullUUIDs(\databox $databox) { $sql = 'SELECT r.coll_id, r.type, r.record_id, s.path, s.file, r.xml FROM record r, subdef s WHERE ISNULL(uuid) AND s.record_id = r.record_id AND s.name="document" AND parent_record_id = 0 LIMIT 100'; $stmt = $databox->get_connection()->prepare($sql); $stmt->execute(); $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); return $rs; }
php
protected function getNullUUIDs(\databox $databox) { $sql = 'SELECT r.coll_id, r.type, r.record_id, s.path, s.file, r.xml FROM record r, subdef s WHERE ISNULL(uuid) AND s.record_id = r.record_id AND s.name="document" AND parent_record_id = 0 LIMIT 100'; $stmt = $databox->get_connection()->prepare($sql); $stmt->execute(); $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); return $rs; }
[ "protected", "function", "getNullUUIDs", "(", "\\", "databox", "$", "databox", ")", "{", "$", "sql", "=", "'SELECT r.coll_id, r.type, r.record_id, s.path, s.file, r.xml\n FROM record r, subdef s\n WHERE ISNULL(uuid)\n AND s.recor...
Return a maximum of 100 recods without UUIDs @param \databox $databox @return array
[ "Return", "a", "maximum", "of", "100", "recods", "without", "UUIDs" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/Upgrade/Step31.php#L99-L113
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Command/Upgrade/Step31.php
Step31.updateRecordUUID
protected function updateRecordUUID(\databox $databox, array $record) { $pathfile = \p4string::addEndSlash($record['path']) . $record['file']; $uuid = Uuid::uuid4(); try { $media = $this->app->getMediaFromUri($pathfile); $collection = \collection::getByCollectionId($this->$app, $databox, (int) $record['coll_id']); $file = new File($this->app, $media, $collection); $uuid = $file->getUUID(true, true); $sha256 = $file->getSha256(); $this->app['monolog']->addInfo(sprintf("Upgrading record %d with uuid %s", $record['record_id'], $uuid)); } catch (\Exception $e) { $this->app['monolog']->addError(sprintf("Uuid upgrade for record %s failed", $record['record_id'])); } $sql = 'UPDATE record SET uuid = :uuid, sha256 = :sha256 WHERE record_id = :record_id'; $params = [ ':uuid' => $uuid, 'sha256' => $sha256, ':record_id' => $record['record_id'], ]; $stmt = $databox->get_connection()->prepare($sql); $stmt->execute($params); $stmt->closeCursor(); }
php
protected function updateRecordUUID(\databox $databox, array $record) { $pathfile = \p4string::addEndSlash($record['path']) . $record['file']; $uuid = Uuid::uuid4(); try { $media = $this->app->getMediaFromUri($pathfile); $collection = \collection::getByCollectionId($this->$app, $databox, (int) $record['coll_id']); $file = new File($this->app, $media, $collection); $uuid = $file->getUUID(true, true); $sha256 = $file->getSha256(); $this->app['monolog']->addInfo(sprintf("Upgrading record %d with uuid %s", $record['record_id'], $uuid)); } catch (\Exception $e) { $this->app['monolog']->addError(sprintf("Uuid upgrade for record %s failed", $record['record_id'])); } $sql = 'UPDATE record SET uuid = :uuid, sha256 = :sha256 WHERE record_id = :record_id'; $params = [ ':uuid' => $uuid, 'sha256' => $sha256, ':record_id' => $record['record_id'], ]; $stmt = $databox->get_connection()->prepare($sql); $stmt->execute($params); $stmt->closeCursor(); }
[ "protected", "function", "updateRecordUUID", "(", "\\", "databox", "$", "databox", ",", "array", "$", "record", ")", "{", "$", "pathfile", "=", "\\", "p4string", "::", "addEndSlash", "(", "$", "record", "[", "'path'", "]", ")", ".", "$", "record", "[", ...
Update a record with a UUID @param \databox $databox @param array $record
[ "Update", "a", "record", "with", "a", "UUID" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/Upgrade/Step31.php#L121-L149
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Model/Entities/ApiOauthToken.php
ApiOauthToken.setAccount
public function setAccount(ApiAccount $account) { $account->addTokens($this); $this->account = $account; return $this; }
php
public function setAccount(ApiAccount $account) { $account->addTokens($this); $this->account = $account; return $this; }
[ "public", "function", "setAccount", "(", "ApiAccount", "$", "account", ")", "{", "$", "account", "->", "addTokens", "(", "$", "this", ")", ";", "$", "this", "->", "account", "=", "$", "account", ";", "return", "$", "this", ";", "}" ]
@param ApiAccount $account @return ApiOauthTokens
[ "@param", "ApiAccount", "$account" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Entities/ApiOauthToken.php#L73-L80
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Databox/Subdef/MediaSubdefService.php
MediaSubdefService.findSubdefsByRecordReferenceFromCollection
public function findSubdefsByRecordReferenceFromCollection($records, array $names = null) { $subdefs = $this->reduceRecordReferenceCollection( $records, function (array &$carry, array $subdefs, array $references) { $subdefsByRecordId = []; /** @var \media_subdef $subdef */ foreach ($subdefs as $subdef) { $recordId = $subdef->get_record_id(); if (!isset($subdefsByRecordId[$recordId])) { $subdefsByRecordId[$recordId] = []; } $subdefsByRecordId[$recordId][$subdef->get_name()] = $subdef; } /** @var RecordReferenceInterface $reference */ foreach ($references as $index => $reference) { if (isset($subdefsByRecordId[$reference->getRecordId()])) { $carry[$index] = $subdefsByRecordId[$reference->getRecordId()]; }; } return $carry; }, array_fill_keys(array_keys($records instanceof \Traversable ? iterator_to_array($records) : $records), []), $names ); $reordered = []; foreach ($records as $index => $record) { $reordered[$index] = $subdefs[$index]; } return $reordered; }
php
public function findSubdefsByRecordReferenceFromCollection($records, array $names = null) { $subdefs = $this->reduceRecordReferenceCollection( $records, function (array &$carry, array $subdefs, array $references) { $subdefsByRecordId = []; /** @var \media_subdef $subdef */ foreach ($subdefs as $subdef) { $recordId = $subdef->get_record_id(); if (!isset($subdefsByRecordId[$recordId])) { $subdefsByRecordId[$recordId] = []; } $subdefsByRecordId[$recordId][$subdef->get_name()] = $subdef; } /** @var RecordReferenceInterface $reference */ foreach ($references as $index => $reference) { if (isset($subdefsByRecordId[$reference->getRecordId()])) { $carry[$index] = $subdefsByRecordId[$reference->getRecordId()]; }; } return $carry; }, array_fill_keys(array_keys($records instanceof \Traversable ? iterator_to_array($records) : $records), []), $names ); $reordered = []; foreach ($records as $index => $record) { $reordered[$index] = $subdefs[$index]; } return $reordered; }
[ "public", "function", "findSubdefsByRecordReferenceFromCollection", "(", "$", "records", ",", "array", "$", "names", "=", "null", ")", "{", "$", "subdefs", "=", "$", "this", "->", "reduceRecordReferenceCollection", "(", "$", "records", ",", "function", "(", "arr...
Returns all available subdefs grouped by each record reference and by its name @param RecordReferenceInterface[]|RecordReferenceCollection $records @param null|array $names @return \media_subdef[][]
[ "Returns", "all", "available", "subdefs", "grouped", "by", "each", "record", "reference", "and", "by", "its", "name" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Databox/Subdef/MediaSubdefService.php#L36-L74
alchemy-fr/Phraseanet
lib/classes/patch/380alpha3a.php
patch_380alpha3a.apply
public function apply(base $databox, Application $app) { $conn = $databox->get_connection(); $sql = "CREATE TABLE IF NOT EXISTS `log_colls` (\n" . " `id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n" . " `log_id` int(11) unsigned NOT NULL,\n" . " `coll_id` int(11) unsigned NOT NULL,\n" . " PRIMARY KEY (`id`),\n" . " UNIQUE KEY `couple` (`log_id`,`coll_id`),\n" . " KEY `log_id` (`log_id`),\n" . " KEY `coll_id` (`coll_id`)\n" . ") ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;"; $stmt = $conn->prepare($sql); $stmt->execute(); $stmt->closeCursor(); unset($stmt); $removeProc = "DROP PROCEDURE IF EXISTS explode_log_table"; $stmt = $conn->prepare($removeProc); $stmt->execute(); $stmt->closeCursor(); unset($stmt); $procedure = " CREATE PROCEDURE explode_log_table(bound VARCHAR(255)) BEGIN DECLARE l_log_id INT UNSIGNED DEFAULT 0; DECLARE l_coll_list TEXT; DECLARE occurance INT DEFAULT 0; DECLARE i INT DEFAULT 0; DECLARE dest_coll_id INT; DECLARE done INT DEFAULT 0; DECLARE result_set CURSOR FOR SELECT l.id, l.coll_list FROM log l LEFT JOIN log_colls lc ON (lc.log_id = l.id) WHERE (lc.log_id IS NULL) AND coll_list != ''; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; OPEN result_set; read_loop: LOOP FETCH result_set INTO l_log_id, l_coll_list; IF done THEN LEAVE read_loop; END IF; SET occurance = (SELECT LENGTH(l_coll_list) - LENGTH(REPLACE(l_coll_list, bound, ''))+1); SET i=1; START TRANSACTION; WHILE i <= occurance DO SET dest_coll_id = (SELECT REPLACE( SUBSTRING( SUBSTRING_INDEX(l_coll_list, bound, i), LENGTH(SUBSTRING_INDEX(l_coll_list, bound, i - 1)) + 1 ), ',', '' )); IF dest_coll_id > 0 THEN INSERT INTO log_colls VALUES (null, l_log_id, dest_coll_id); END IF; SET i = i + 1; END WHILE; COMMIT; END LOOP; CLOSE result_set; END;"; $stmt = $conn->prepare($procedure); $stmt->execute(); $stmt->closeCursor(); $sql = "CALL explode_log_table(',')"; $stmt = $conn->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $stmt = $conn->prepare($removeProc); $stmt->execute(); $stmt->closeCursor(); return true; }
php
public function apply(base $databox, Application $app) { $conn = $databox->get_connection(); $sql = "CREATE TABLE IF NOT EXISTS `log_colls` (\n" . " `id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n" . " `log_id` int(11) unsigned NOT NULL,\n" . " `coll_id` int(11) unsigned NOT NULL,\n" . " PRIMARY KEY (`id`),\n" . " UNIQUE KEY `couple` (`log_id`,`coll_id`),\n" . " KEY `log_id` (`log_id`),\n" . " KEY `coll_id` (`coll_id`)\n" . ") ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;"; $stmt = $conn->prepare($sql); $stmt->execute(); $stmt->closeCursor(); unset($stmt); $removeProc = "DROP PROCEDURE IF EXISTS explode_log_table"; $stmt = $conn->prepare($removeProc); $stmt->execute(); $stmt->closeCursor(); unset($stmt); $procedure = " CREATE PROCEDURE explode_log_table(bound VARCHAR(255)) BEGIN DECLARE l_log_id INT UNSIGNED DEFAULT 0; DECLARE l_coll_list TEXT; DECLARE occurance INT DEFAULT 0; DECLARE i INT DEFAULT 0; DECLARE dest_coll_id INT; DECLARE done INT DEFAULT 0; DECLARE result_set CURSOR FOR SELECT l.id, l.coll_list FROM log l LEFT JOIN log_colls lc ON (lc.log_id = l.id) WHERE (lc.log_id IS NULL) AND coll_list != ''; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; OPEN result_set; read_loop: LOOP FETCH result_set INTO l_log_id, l_coll_list; IF done THEN LEAVE read_loop; END IF; SET occurance = (SELECT LENGTH(l_coll_list) - LENGTH(REPLACE(l_coll_list, bound, ''))+1); SET i=1; START TRANSACTION; WHILE i <= occurance DO SET dest_coll_id = (SELECT REPLACE( SUBSTRING( SUBSTRING_INDEX(l_coll_list, bound, i), LENGTH(SUBSTRING_INDEX(l_coll_list, bound, i - 1)) + 1 ), ',', '' )); IF dest_coll_id > 0 THEN INSERT INTO log_colls VALUES (null, l_log_id, dest_coll_id); END IF; SET i = i + 1; END WHILE; COMMIT; END LOOP; CLOSE result_set; END;"; $stmt = $conn->prepare($procedure); $stmt->execute(); $stmt->closeCursor(); $sql = "CALL explode_log_table(',')"; $stmt = $conn->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $stmt = $conn->prepare($removeProc); $stmt->execute(); $stmt->closeCursor(); return true; }
[ "public", "function", "apply", "(", "base", "$", "databox", ",", "Application", "$", "app", ")", "{", "$", "conn", "=", "$", "databox", "->", "get_connection", "(", ")", ";", "$", "sql", "=", "\"CREATE TABLE IF NOT EXISTS `log_colls` (\\n\"", ".", "\" `id` int...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/380alpha3a.php#L49-L132
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Notification/Deliverer.php
Deliverer.deliver
public function deliver(MailInterface $mail, $readReceipt = false, array $attachments = null) { if (!$mail->getReceiver()) { throw new LogicException('You must provide a receiver for a mail notification'); } $message = \Swift_Message::newInstance($this->prefix . $mail->getSubject(), $mail->renderHTML(), 'text/html', 'utf-8'); $message->addPart($mail->getMessage(), 'text/plain', 'utf-8'); $message->setFrom($this->emitter->getEmail(), $this->emitter->getName()); $message->setTo($mail->getReceiver()->getEmail(), $mail->getReceiver()->getName()); if ($mail->getEmitter()) { $message->setReplyTo($mail->getEmitter()->getEmail(), $mail->getEmitter()->getName()); } if(is_array($attachments)) { foreach($attachments as $attachment) { $message->attach($attachment->As_Swift_Attachment()); } } if ($readReceipt) { if (!$mail->getEmitter()) { throw new LogicException('You must provide an emitter for a ReadReceipt'); } $message->setReadReceiptTo([$mail->getEmitter()->getEmail() => $mail->getEmitter()->getName()]); } if(!$this->mailer->getTransport()->isStarted()) { $this->mailer->getTransport()->start(); } $ret = $this->mailer->send($message); $this->mailer->getTransport()->stop(); $this->dispatcher->dispatch('phraseanet.notification.sent'); return $ret; }
php
public function deliver(MailInterface $mail, $readReceipt = false, array $attachments = null) { if (!$mail->getReceiver()) { throw new LogicException('You must provide a receiver for a mail notification'); } $message = \Swift_Message::newInstance($this->prefix . $mail->getSubject(), $mail->renderHTML(), 'text/html', 'utf-8'); $message->addPart($mail->getMessage(), 'text/plain', 'utf-8'); $message->setFrom($this->emitter->getEmail(), $this->emitter->getName()); $message->setTo($mail->getReceiver()->getEmail(), $mail->getReceiver()->getName()); if ($mail->getEmitter()) { $message->setReplyTo($mail->getEmitter()->getEmail(), $mail->getEmitter()->getName()); } if(is_array($attachments)) { foreach($attachments as $attachment) { $message->attach($attachment->As_Swift_Attachment()); } } if ($readReceipt) { if (!$mail->getEmitter()) { throw new LogicException('You must provide an emitter for a ReadReceipt'); } $message->setReadReceiptTo([$mail->getEmitter()->getEmail() => $mail->getEmitter()->getName()]); } if(!$this->mailer->getTransport()->isStarted()) { $this->mailer->getTransport()->start(); } $ret = $this->mailer->send($message); $this->mailer->getTransport()->stop(); $this->dispatcher->dispatch('phraseanet.notification.sent'); return $ret; }
[ "public", "function", "deliver", "(", "MailInterface", "$", "mail", ",", "$", "readReceipt", "=", "false", ",", "array", "$", "attachments", "=", "null", ")", "{", "if", "(", "!", "$", "mail", "->", "getReceiver", "(", ")", ")", "{", "throw", "new", ...
Delivers an email @param MailInterface $mail @param Boolean $readReceipt @return int the number of messages that have been sent @throws LogicException In case no Receiver provided @throws LogicException In case a read-receipt is asked but no Emitter provided
[ "Delivers", "an", "email" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Notification/Deliverer.php#L50-L88
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Command/AbstractCheckCommand.php
AbstractCheckCommand.doExecute
protected function doExecute(InputInterface $input, OutputInterface $output) { $ret = static::CHECK_OK; foreach ($this->provideRequirements() as $collection) { $output->writeln(''); $output->writeln($collection->getName() . ' requirements : '); $output->writeln(''); foreach ($collection->getRequirements() as $requirement) { $result = $requirement->isFulfilled() ? '<info>OK </info>' : ($requirement->isOptional() ? '<comment>WARNING</comment> ' : '<error>ERROR</error> '); $output->write(' ' . $result); $output->writeln($requirement->getTestMessage()); if (!$requirement->isFulfilled()) { $ret = static::CHECK_ERROR; $output->writeln(" " . $requirement->getHelpText()); $output->writeln(''); } } $output->writeln(''); $output->writeln($collection->getName() . ' recommendations : '); $output->writeln(''); foreach ($collection->getRecommendations() as $requirement) { $result = $requirement->isFulfilled() ? '<info>OK </info>' : ($requirement->isOptional() ? '<comment>WARNING</comment> ' : '<error>ERROR</error> '); $output->write(' ' . $result); $output->writeln($requirement->getTestMessage()); if (!$requirement->isFulfilled()) { if ($ret === static::CHECK_OK) { $ret = static::CHECK_WARNING; } $output->writeln(" " . $requirement->getHelpText()); $output->writeln(''); } } } return $ret; }
php
protected function doExecute(InputInterface $input, OutputInterface $output) { $ret = static::CHECK_OK; foreach ($this->provideRequirements() as $collection) { $output->writeln(''); $output->writeln($collection->getName() . ' requirements : '); $output->writeln(''); foreach ($collection->getRequirements() as $requirement) { $result = $requirement->isFulfilled() ? '<info>OK </info>' : ($requirement->isOptional() ? '<comment>WARNING</comment> ' : '<error>ERROR</error> '); $output->write(' ' . $result); $output->writeln($requirement->getTestMessage()); if (!$requirement->isFulfilled()) { $ret = static::CHECK_ERROR; $output->writeln(" " . $requirement->getHelpText()); $output->writeln(''); } } $output->writeln(''); $output->writeln($collection->getName() . ' recommendations : '); $output->writeln(''); foreach ($collection->getRecommendations() as $requirement) { $result = $requirement->isFulfilled() ? '<info>OK </info>' : ($requirement->isOptional() ? '<comment>WARNING</comment> ' : '<error>ERROR</error> '); $output->write(' ' . $result); $output->writeln($requirement->getTestMessage()); if (!$requirement->isFulfilled()) { if ($ret === static::CHECK_OK) { $ret = static::CHECK_WARNING; } $output->writeln(" " . $requirement->getHelpText()); $output->writeln(''); } } } return $ret; }
[ "protected", "function", "doExecute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "ret", "=", "static", "::", "CHECK_OK", ";", "foreach", "(", "$", "this", "->", "provideRequirements", "(", ")", "as", "$", "co...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/AbstractCheckCommand.php#L26-L70
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/TaskManager/Log/TaskLogFile.php
TaskLogFile.getVersions
public function getVersions() { $x = sprintf('/^task_%d-(|(.*))\.log$/', $this->task->getId()); $f = new Finder(); $versions = []; /** @var \SplFileInfo $file */ foreach($f->files()->in($this->root) as $file) { $matches = []; if(preg_match($x, $file->getBasename(), $matches)) { $versions[] = $matches[1]; } } return $versions; }
php
public function getVersions() { $x = sprintf('/^task_%d-(|(.*))\.log$/', $this->task->getId()); $f = new Finder(); $versions = []; /** @var \SplFileInfo $file */ foreach($f->files()->in($this->root) as $file) { $matches = []; if(preg_match($x, $file->getBasename(), $matches)) { $versions[] = $matches[1]; } } return $versions; }
[ "public", "function", "getVersions", "(", ")", "{", "$", "x", "=", "sprintf", "(", "'/^task_%d-(|(.*))\\.log$/'", ",", "$", "this", "->", "task", "->", "getId", "(", ")", ")", ";", "$", "f", "=", "new", "Finder", "(", ")", ";", "$", "versions", "=", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/TaskManager/Log/TaskLogFile.php#L32-L45
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/TaskManager/Log/TaskLogFile.php
TaskLogFile.getPath
public function getPath($version = '') { if (trim($version) != '') { $version = '-' . $version; } return sprintf('%s/task_%d%s.log', $this->root, $this->task->getId(), $version); }
php
public function getPath($version = '') { if (trim($version) != '') { $version = '-' . $version; } return sprintf('%s/task_%d%s.log', $this->root, $this->task->getId(), $version); }
[ "public", "function", "getPath", "(", "$", "version", "=", "''", ")", "{", "if", "(", "trim", "(", "$", "version", ")", "!=", "''", ")", "{", "$", "version", "=", "'-'", ".", "$", "version", ";", "}", "return", "sprintf", "(", "'%s/task_%d%s.log'", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/TaskManager/Log/TaskLogFile.php#L60-L67
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Command/Setup/FixLogCollId.php
FixLogCollId.sanitizeArgs
protected function sanitizeArgs(InputInterface $input, OutputInterface $output) { $argsOK = true; // find the databox / collection by id or by name $this->databoxes = []; if(!is_null($d = $input->getOption('databox'))) { $d = trim($d); } foreach ($this->container->getDataboxes() as $db) { if(is_null($d)){ $this->databoxes[] = $db; } else { if ($db->get_sbas_id() == (int)$d || $db->get_viewname() == $d || $db->get_dbname() == $d) { $this->databoxes[] = $db; } } } if (empty($this->databoxes)) { if(is_null($d)) { $output->writeln(sprintf("<error>No databox found</error>", $d)); } else { $output->writeln(sprintf("<error>Unknown databox \"%s\"</error>", $d)); } $argsOK = false; } // get options $this->batch_size = $input->getOption('batch_size'); $this->show_sql = $input->getOption('show_sql') ? true : false; $this->dry = $input->getOption('dry') ? true : false; $this->keep_tmp_table = $input->getOption('keep_tmp_table') ? true : false; if(is_null($this->batch_size)) { $this->batch_size = 100000; } if($this->batch_size < 1) { $output->writeln(sprintf('<error>batch_size must be > 0</error>')); $argsOK = false; } return $argsOK; }
php
protected function sanitizeArgs(InputInterface $input, OutputInterface $output) { $argsOK = true; // find the databox / collection by id or by name $this->databoxes = []; if(!is_null($d = $input->getOption('databox'))) { $d = trim($d); } foreach ($this->container->getDataboxes() as $db) { if(is_null($d)){ $this->databoxes[] = $db; } else { if ($db->get_sbas_id() == (int)$d || $db->get_viewname() == $d || $db->get_dbname() == $d) { $this->databoxes[] = $db; } } } if (empty($this->databoxes)) { if(is_null($d)) { $output->writeln(sprintf("<error>No databox found</error>", $d)); } else { $output->writeln(sprintf("<error>Unknown databox \"%s\"</error>", $d)); } $argsOK = false; } // get options $this->batch_size = $input->getOption('batch_size'); $this->show_sql = $input->getOption('show_sql') ? true : false; $this->dry = $input->getOption('dry') ? true : false; $this->keep_tmp_table = $input->getOption('keep_tmp_table') ? true : false; if(is_null($this->batch_size)) { $this->batch_size = 100000; } if($this->batch_size < 1) { $output->writeln(sprintf('<error>batch_size must be > 0</error>')); $argsOK = false; } return $argsOK; }
[ "protected", "function", "sanitizeArgs", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "argsOK", "=", "true", ";", "// find the databox / collection by id or by name", "$", "this", "->", "databoxes", "=", "[", "]", ";",...
sanity check the cmd line options @param InputInterface $input @param OutputInterface $output @return bool
[ "sanity", "check", "the", "cmd", "line", "options" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/Setup/FixLogCollId.php#L69-L113
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Command/Setup/FixLogCollId.php
FixLogCollId.doExecute
protected function doExecute(InputInterface $input, OutputInterface $output) { // $time_start = new \DateTime(); if(!$this->sanitizeArgs($input, $output)) { return -1; } $this->input = $input; $this->output = $output; foreach($this->databoxes as $databox) { $this->output->writeln(""); $this->output->writeln(sprintf("<info>================================ Working on databox %s (id:%s) ================================</info>", $databox->get_dbname(), $databox->get_sbas_id())); if (!$this->showCount($databox)) { // databox not patched break; } $this->createWorkingTable($databox); // loop to compute coll_id from top to bottom do { $n = $this->computeCollId($databox); // in dry mode, n=0 } while ($n > 0); // set the "from_coll_id" $this->computeCollIdFrom($databox); // copy results back to the log_docs $this->copyReults($databox); if (!$this->keep_tmp_table) { $this->dropWorkingTable($databox); } $this->output->writeln(""); } return 0; }
php
protected function doExecute(InputInterface $input, OutputInterface $output) { // $time_start = new \DateTime(); if(!$this->sanitizeArgs($input, $output)) { return -1; } $this->input = $input; $this->output = $output; foreach($this->databoxes as $databox) { $this->output->writeln(""); $this->output->writeln(sprintf("<info>================================ Working on databox %s (id:%s) ================================</info>", $databox->get_dbname(), $databox->get_sbas_id())); if (!$this->showCount($databox)) { // databox not patched break; } $this->createWorkingTable($databox); // loop to compute coll_id from top to bottom do { $n = $this->computeCollId($databox); // in dry mode, n=0 } while ($n > 0); // set the "from_coll_id" $this->computeCollIdFrom($databox); // copy results back to the log_docs $this->copyReults($databox); if (!$this->keep_tmp_table) { $this->dropWorkingTable($databox); } $this->output->writeln(""); } return 0; }
[ "protected", "function", "doExecute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "// $time_start = new \\DateTime();", "if", "(", "!", "$", "this", "->", "sanitizeArgs", "(", "$", "input", ",", "$", "output", ")", ")"...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/Setup/FixLogCollId.php#L118-L163
alchemy-fr/Phraseanet
lib/classes/media/Permalink/Adapter.php
media_Permalink_Adapter.fetchData
private static function fetchData(databox $databox, array $subdefIds) { $found = []; $missing = []; foreach ($subdefIds as $index => $subdefId) { try { $data = self::doGetDataFromCache($databox, $subdefId); } catch (Exception $exception) { $data = false; } if (is_array($data)) { $found[$index] = $data; continue; } $missing[$index] = $subdefId; } if (!$missing) { return $found; } $dbalData = $databox->get_connection()->fetchAll( self::getSelectSql(), ['subdef_id' => array_values($missing)], ['subdef_id' => Connection::PARAM_INT_ARRAY] ); foreach ($dbalData as $item) { $itemSubdefId = $item['subdef_id']; $databox->set_data_to_cache($item, self::generateCacheKey($itemSubdefId)); $foundIndexes = array_keys(array_intersect($missing, [$itemSubdefId])); foreach ($foundIndexes as $foundIndex) { $found[$foundIndex] = $item; unset($missing[$foundIndex]); } } return $found; }
php
private static function fetchData(databox $databox, array $subdefIds) { $found = []; $missing = []; foreach ($subdefIds as $index => $subdefId) { try { $data = self::doGetDataFromCache($databox, $subdefId); } catch (Exception $exception) { $data = false; } if (is_array($data)) { $found[$index] = $data; continue; } $missing[$index] = $subdefId; } if (!$missing) { return $found; } $dbalData = $databox->get_connection()->fetchAll( self::getSelectSql(), ['subdef_id' => array_values($missing)], ['subdef_id' => Connection::PARAM_INT_ARRAY] ); foreach ($dbalData as $item) { $itemSubdefId = $item['subdef_id']; $databox->set_data_to_cache($item, self::generateCacheKey($itemSubdefId)); $foundIndexes = array_keys(array_intersect($missing, [$itemSubdefId])); foreach ($foundIndexes as $foundIndex) { $found[$foundIndex] = $item; unset($missing[$foundIndex]); } } return $found; }
[ "private", "static", "function", "fetchData", "(", "databox", "$", "databox", ",", "array", "$", "subdefIds", ")", "{", "$", "found", "=", "[", "]", ";", "$", "missing", "=", "[", "]", ";", "foreach", "(", "$", "subdefIds", "as", "$", "index", "=>", ...
Returns present data in storage with same indexes but different order @param databox $databox @param int[] $subdefIds @return array
[ "Returns", "present", "data", "in", "storage", "with", "same", "indexes", "but", "different", "order" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/media/Permalink/Adapter.php#L332-L377
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/SearchEngine/Elastic/Thesaurus/Helper.php
Helper.filter
private static function filter(DOMNodeList $list, callable $callback) { $filtered = []; foreach ($list as $node) { if (call_user_func($callback, $node)) { $filtered[] = $node; } } return $filtered; }
php
private static function filter(DOMNodeList $list, callable $callback) { $filtered = []; foreach ($list as $node) { if (call_user_func($callback, $node)) { $filtered[] = $node; } } return $filtered; }
[ "private", "static", "function", "filter", "(", "DOMNodeList", "$", "list", ",", "callable", "$", "callback", ")", "{", "$", "filtered", "=", "[", "]", ";", "foreach", "(", "$", "list", "as", "$", "node", ")", "{", "if", "(", "call_user_func", "(", "...
DOM Helpers
[ "DOM", "Helpers" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/Elastic/Thesaurus/Helper.php#L133-L143
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Databox/CachingDataboxRepositoryDecorator.php
CachingDataboxRepositoryDecorator.mount
public function mount($host, $port, $user, $password, $dbname) { $databox = $this->repository->mount($host, $port, $user, $password, $dbname); $this->clearCache(); return $databox; }
php
public function mount($host, $port, $user, $password, $dbname) { $databox = $this->repository->mount($host, $port, $user, $password, $dbname); $this->clearCache(); return $databox; }
[ "public", "function", "mount", "(", "$", "host", ",", "$", "port", ",", "$", "user", ",", "$", "password", ",", "$", "dbname", ")", "{", "$", "databox", "=", "$", "this", "->", "repository", "->", "mount", "(", "$", "host", ",", "$", "port", ",",...
@param $host @param $port @param $user @param $password @param $dbname @return \databox
[ "@param", "$host", "@param", "$port", "@param", "$user", "@param", "$password", "@param", "$dbname" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Databox/CachingDataboxRepositoryDecorator.php#L95-L102
alchemy-fr/Phraseanet
lib/classes/databox.php
databox.isRegistrationEnabled
public function isRegistrationEnabled() { if (false !== $xml = $this->get_sxml_structure()) { foreach ($xml->xpath('/record/caninscript') as $canRegister) { if (false !== (Boolean) (string) $canRegister) { return true; } } } return false; }
php
public function isRegistrationEnabled() { if (false !== $xml = $this->get_sxml_structure()) { foreach ($xml->xpath('/record/caninscript') as $canRegister) { if (false !== (Boolean) (string) $canRegister) { return true; } } } return false; }
[ "public", "function", "isRegistrationEnabled", "(", ")", "{", "if", "(", "false", "!==", "$", "xml", "=", "$", "this", "->", "get_sxml_structure", "(", ")", ")", "{", "foreach", "(", "$", "xml", "->", "xpath", "(", "'/record/caninscript'", ")", "as", "$"...
Tells whether the registration is enable or not. @return boolean
[ "Tells", "whether", "the", "registration", "is", "enable", "or", "not", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/databox.php#L1413-L1424
alchemy-fr/Phraseanet
lib/classes/databox.php
databox.getAutoregisterModel
public function getAutoregisterModel($email) { if(!$this->isRegistrationEnabled()) { return null; } $ret = User::USER_AUTOREGISTER; // default if there is no whitelist defined at all // try to match against the whitelist if( ($xml = $this->get_sxml_structure()) !== false) { $wl = $xml->xpath('/record/registration/auto_register/email_whitelist'); if($wl !== false && count($wl) === 1) { $ret = null; // there IS a whitelist, the email must match foreach ($wl[0]->xpath('email') as $element) { if (preg_match($element['pattern'], $email) === 1) { return (string)$element['user_model']; } } } } return $ret; }
php
public function getAutoregisterModel($email) { if(!$this->isRegistrationEnabled()) { return null; } $ret = User::USER_AUTOREGISTER; // default if there is no whitelist defined at all // try to match against the whitelist if( ($xml = $this->get_sxml_structure()) !== false) { $wl = $xml->xpath('/record/registration/auto_register/email_whitelist'); if($wl !== false && count($wl) === 1) { $ret = null; // there IS a whitelist, the email must match foreach ($wl[0]->xpath('email') as $element) { if (preg_match($element['pattern'], $email) === 1) { return (string)$element['user_model']; } } } } return $ret; }
[ "public", "function", "getAutoregisterModel", "(", "$", "email", ")", "{", "if", "(", "!", "$", "this", "->", "isRegistrationEnabled", "(", ")", ")", "{", "return", "null", ";", "}", "$", "ret", "=", "User", "::", "USER_AUTOREGISTER", ";", "// default if t...
matches a email against the auto-register whitelist @param string $email @return null|string the user-model to apply if the email matches
[ "matches", "a", "email", "against", "the", "auto", "-", "register", "whitelist" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/databox.php#L1432-L1455
alchemy-fr/Phraseanet
lib/classes/databox.php
databox.getRawData
public function getRawData() { return [ 'ord' => $this->ord, 'viewname' => $this->viewname, 'label_en' => $this->labels['en'], 'label_fr' => $this->labels['fr'], 'label_de' => $this->labels['de'], 'label_nl' => $this->labels['nl'], ]; }
php
public function getRawData() { return [ 'ord' => $this->ord, 'viewname' => $this->viewname, 'label_en' => $this->labels['en'], 'label_fr' => $this->labels['fr'], 'label_de' => $this->labels['de'], 'label_nl' => $this->labels['nl'], ]; }
[ "public", "function", "getRawData", "(", ")", "{", "return", "[", "'ord'", "=>", "$", "this", "->", "ord", ",", "'viewname'", "=>", "$", "this", "->", "viewname", ",", "'label_en'", "=>", "$", "this", "->", "labels", "[", "'en'", "]", ",", "'label_fr'"...
Return an array that can be used to restore databox. @return array
[ "Return", "an", "array", "that", "can", "be", "used", "to", "restore", "databox", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/databox.php#L1463-L1473
alchemy-fr/Phraseanet
lib/classes/patch/390alpha7a.php
patch_390alpha7a.apply
public function apply(base $appbox, Application $app) { if (false === $this->hasFeedBackup($app)) { return false; } $sql = 'DELETE FROM Feeds'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $sql = 'DELETE FROM FeedEntries'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $sql = 'DELETE FROM FeedPublishers'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $sql = 'DELETE FROM FeedItems'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $sql = 'DELETE FROM FeedTokens'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $sql = 'DELETE FROM AggregateTokens'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $conn = $app->getApplicationBox()->get_connection(); $sql = 'SELECT id, title, subtitle, public, created_on, updated_on, base_id FROM feeds_backup;'; $stmt = $conn->prepare($sql); $stmt->execute(); $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); $n = 0; $em = $app['orm.em']; $fpSql = 'SELECT id, usr_id, owner, created_on FROM feed_publishers WHERE feed_id = :feed_id;'; $fpStmt = $conn->prepare($fpSql); $feSql = 'SELECT id, title, description, created_on, updated_on, author_name, author_email FROM feed_entries WHERE feed_id = :feed_id AND publisher = :publisher_id;'; $feStmt = $conn->prepare($feSql); $fiSql = 'SELECT sbas_id, record_id, ord FROM feed_entry_elements WHERE entry_id = :entry_id;'; $fiStmt = $conn->prepare($fiSql); $ftSql = 'SELECT token, usr_id, aggregated FROM feed_tokens WHERE feed_id = :feed_id;'; $ftStmt = $conn->prepare($ftSql); $faSql = 'SELECT token, usr_id FROM feed_tokens WHERE aggregated = 1;'; $faStmt = $conn->prepare($faSql); foreach ($rs as $row) { $feed = new Feed(); $feed->setTitle($row['title']); $feed->setSubtitle($row['subtitle']); $feed->setIconUrl(false); $feed->setIsPublic($row['public']); $feed->setCreatedOn(new \DateTime($row['created_on'])); $feed->setUpdatedOn(new \DateTime($row['updated_on'])); $feed->setBaseId($row['base_id']); $fpStmt->execute([':feed_id' => $row['id']]); $fpRes = $fpStmt->fetchAll(\PDO::FETCH_ASSOC); foreach ($fpRes as $fpRow) { if (null === $user = $this->loadUser($app['orm.em'], $fpRow['usr_id'])) { continue; } $feedPublisher = new FeedPublisher(); $feedPublisher->setFeed($feed); $feed->addPublisher($feedPublisher); $feedPublisher->setCreatedOn(new \DateTime($fpRow['created_on'])); $feedPublisher->setIsOwner((Boolean) $fpRow['owner']); $feedPublisher->setUser($user); $feStmt->execute([':feed_id' => $row['id'], ':publisher_id' => $fpRow['id']]); $feRes = $feStmt->fetchAll(\PDO::FETCH_ASSOC); foreach ($feRes as $feRow) { $feedEntry = new FeedEntry(); $feedEntry->setFeed($feed); $feed->addEntry($feedEntry); $feedEntry->setPublisher($feedPublisher); $feedEntry->setTitle($feRow['title']); $feedEntry->setSubtitle($feRow['description']); $feedEntry->setAuthorName((string) $feRow['author_name']); $feedEntry->setAuthorEmail((string) $feRow['author_email']); $feedEntry->setCreatedOn(new \DateTime($feRow['created_on'])); $feedEntry->setUpdatedOn(new \DateTime($feRow['updated_on'])); $fiStmt->execute([':entry_id' => $feRow['id']]); $fiRes = $fiStmt->fetchAll(\PDO::FETCH_ASSOC); foreach ($fiRes as $fiRow) { $feedItem = new FeedItem(); $feedItem->setEntry($feedEntry); $feedEntry->addItem($feedItem); $feedItem->setOrd($fiRow['ord']); $feedItem->setSbasId($fiRow['sbas_id']); $feedItem->setRecordId($fiRow['record_id']); $em->persist($feedItem); } $em->persist($feedEntry); } $em->persist($feedPublisher); } $ftStmt->execute([':feed_id' => $row['id']]); $ftRes = $ftStmt->fetchAll(\PDO::FETCH_ASSOC); foreach ($ftRes as $ftRow) { if (null === $user = $this->loadUser($app['orm.em'], $ftRow['usr_id'])) { continue; } $token = new FeedToken(); $token->setFeed($feed); $feed->addToken($token); $token->setUser($user); $token->setValue($ftRow['token']); $em->persist($token); } $em->persist($feed); $n++; if ($n % 100 === 0) { $em->flush(); $em->clear(); } } $fiStmt->closeCursor(); $feStmt->closeCursor(); $fpStmt->closeCursor(); $ftStmt->closeCursor(); $faStmt->execute(); $faRes = $faStmt->fetchAll(\PDO::FETCH_ASSOC); foreach ($faRes as $faRow) { if (null === $user = $this->loadUser($app['orm.em'], $faRow['usr_id'])) { continue; } $token = new AggregateToken(); $token->setUser($user); $token->setValue($faRow['token']); $em->persist($token); } $faStmt->closeCursor(); $em->flush(); $em->clear(); return true; }
php
public function apply(base $appbox, Application $app) { if (false === $this->hasFeedBackup($app)) { return false; } $sql = 'DELETE FROM Feeds'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $sql = 'DELETE FROM FeedEntries'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $sql = 'DELETE FROM FeedPublishers'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $sql = 'DELETE FROM FeedItems'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $sql = 'DELETE FROM FeedTokens'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $sql = 'DELETE FROM AggregateTokens'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $conn = $app->getApplicationBox()->get_connection(); $sql = 'SELECT id, title, subtitle, public, created_on, updated_on, base_id FROM feeds_backup;'; $stmt = $conn->prepare($sql); $stmt->execute(); $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); $n = 0; $em = $app['orm.em']; $fpSql = 'SELECT id, usr_id, owner, created_on FROM feed_publishers WHERE feed_id = :feed_id;'; $fpStmt = $conn->prepare($fpSql); $feSql = 'SELECT id, title, description, created_on, updated_on, author_name, author_email FROM feed_entries WHERE feed_id = :feed_id AND publisher = :publisher_id;'; $feStmt = $conn->prepare($feSql); $fiSql = 'SELECT sbas_id, record_id, ord FROM feed_entry_elements WHERE entry_id = :entry_id;'; $fiStmt = $conn->prepare($fiSql); $ftSql = 'SELECT token, usr_id, aggregated FROM feed_tokens WHERE feed_id = :feed_id;'; $ftStmt = $conn->prepare($ftSql); $faSql = 'SELECT token, usr_id FROM feed_tokens WHERE aggregated = 1;'; $faStmt = $conn->prepare($faSql); foreach ($rs as $row) { $feed = new Feed(); $feed->setTitle($row['title']); $feed->setSubtitle($row['subtitle']); $feed->setIconUrl(false); $feed->setIsPublic($row['public']); $feed->setCreatedOn(new \DateTime($row['created_on'])); $feed->setUpdatedOn(new \DateTime($row['updated_on'])); $feed->setBaseId($row['base_id']); $fpStmt->execute([':feed_id' => $row['id']]); $fpRes = $fpStmt->fetchAll(\PDO::FETCH_ASSOC); foreach ($fpRes as $fpRow) { if (null === $user = $this->loadUser($app['orm.em'], $fpRow['usr_id'])) { continue; } $feedPublisher = new FeedPublisher(); $feedPublisher->setFeed($feed); $feed->addPublisher($feedPublisher); $feedPublisher->setCreatedOn(new \DateTime($fpRow['created_on'])); $feedPublisher->setIsOwner((Boolean) $fpRow['owner']); $feedPublisher->setUser($user); $feStmt->execute([':feed_id' => $row['id'], ':publisher_id' => $fpRow['id']]); $feRes = $feStmt->fetchAll(\PDO::FETCH_ASSOC); foreach ($feRes as $feRow) { $feedEntry = new FeedEntry(); $feedEntry->setFeed($feed); $feed->addEntry($feedEntry); $feedEntry->setPublisher($feedPublisher); $feedEntry->setTitle($feRow['title']); $feedEntry->setSubtitle($feRow['description']); $feedEntry->setAuthorName((string) $feRow['author_name']); $feedEntry->setAuthorEmail((string) $feRow['author_email']); $feedEntry->setCreatedOn(new \DateTime($feRow['created_on'])); $feedEntry->setUpdatedOn(new \DateTime($feRow['updated_on'])); $fiStmt->execute([':entry_id' => $feRow['id']]); $fiRes = $fiStmt->fetchAll(\PDO::FETCH_ASSOC); foreach ($fiRes as $fiRow) { $feedItem = new FeedItem(); $feedItem->setEntry($feedEntry); $feedEntry->addItem($feedItem); $feedItem->setOrd($fiRow['ord']); $feedItem->setSbasId($fiRow['sbas_id']); $feedItem->setRecordId($fiRow['record_id']); $em->persist($feedItem); } $em->persist($feedEntry); } $em->persist($feedPublisher); } $ftStmt->execute([':feed_id' => $row['id']]); $ftRes = $ftStmt->fetchAll(\PDO::FETCH_ASSOC); foreach ($ftRes as $ftRow) { if (null === $user = $this->loadUser($app['orm.em'], $ftRow['usr_id'])) { continue; } $token = new FeedToken(); $token->setFeed($feed); $feed->addToken($token); $token->setUser($user); $token->setValue($ftRow['token']); $em->persist($token); } $em->persist($feed); $n++; if ($n % 100 === 0) { $em->flush(); $em->clear(); } } $fiStmt->closeCursor(); $feStmt->closeCursor(); $fpStmt->closeCursor(); $ftStmt->closeCursor(); $faStmt->execute(); $faRes = $faStmt->fetchAll(\PDO::FETCH_ASSOC); foreach ($faRes as $faRow) { if (null === $user = $this->loadUser($app['orm.em'], $faRow['usr_id'])) { continue; } $token = new AggregateToken(); $token->setUser($user); $token->setValue($faRow['token']); $em->persist($token); } $faStmt->closeCursor(); $em->flush(); $em->clear(); return true; }
[ "public", "function", "apply", "(", "base", "$", "appbox", ",", "Application", "$", "app", ")", "{", "if", "(", "false", "===", "$", "this", "->", "hasFeedBackup", "(", "$", "app", ")", ")", "{", "return", "false", ";", "}", "$", "sql", "=", "'DELE...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/390alpha7a.php#L64-L231
alchemy-fr/Phraseanet
lib/classes/patch/390alpha7a.php
patch_390alpha7a.hasFeedBackup
private function hasFeedBackup(Application $app) { $rsm = (new ResultSetMapping())->addScalarResult('Name', 'Name'); $backup = false; foreach ($app['orm.em']->createNativeQuery('SHOW TABLE STATUS', $rsm)->getResult() as $row) { if ('feeds_backup' === $row['Name']) { $backup = true; break; } } return $backup; }
php
private function hasFeedBackup(Application $app) { $rsm = (new ResultSetMapping())->addScalarResult('Name', 'Name'); $backup = false; foreach ($app['orm.em']->createNativeQuery('SHOW TABLE STATUS', $rsm)->getResult() as $row) { if ('feeds_backup' === $row['Name']) { $backup = true; break; } } return $backup; }
[ "private", "function", "hasFeedBackup", "(", "Application", "$", "app", ")", "{", "$", "rsm", "=", "(", "new", "ResultSetMapping", "(", ")", ")", "->", "addScalarResult", "(", "'Name'", ",", "'Name'", ")", ";", "$", "backup", "=", "false", ";", "foreach"...
Checks whether `feeds_backup` tables exists. @param Application $app @return boolean True if `feeds_backup` table exists.
[ "Checks", "whether", "feeds_backup", "tables", "exists", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/390alpha7a.php#L240-L253
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/MediaAccessorController.php
MediaAccessorController.validateToken
public function validateToken($token) { if (is_string($token)) { $token = $this->decodeToken($token); } if (!isset($token->sdef) || !is_array($token->sdef) || count($token->sdef) !== 3) { throw new BadRequestHttpException('sdef should be a sub-definition identifier.'); } list ($sbas_id, $record_id, $subdef) = $token->sdef; return array($sbas_id, $record_id, $subdef); }
php
public function validateToken($token) { if (is_string($token)) { $token = $this->decodeToken($token); } if (!isset($token->sdef) || !is_array($token->sdef) || count($token->sdef) !== 3) { throw new BadRequestHttpException('sdef should be a sub-definition identifier.'); } list ($sbas_id, $record_id, $subdef) = $token->sdef; return array($sbas_id, $record_id, $subdef); }
[ "public", "function", "validateToken", "(", "$", "token", ")", "{", "if", "(", "is_string", "(", "$", "token", ")", ")", "{", "$", "token", "=", "$", "this", "->", "decodeToken", "(", "$", "token", ")", ";", "}", "if", "(", "!", "isset", "(", "$"...
Validate token and returns triplet containing sbas_id, record_id and subdef. @param string|object $token @return array
[ "Validate", "token", "and", "returns", "triplet", "containing", "sbas_id", "record_id", "and", "subdef", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/MediaAccessorController.php#L107-L119
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Prod/DownloadController.php
DownloadController.checkDownload
public function checkDownload(Request $request) { $lst = $request->request->get('lst'); $ssttid = $request->request->get('ssttid', ''); $subdefs = $request->request->get('obj', []); $download = new \set_export($this->app, $lst, $ssttid); if (0 === $download->get_total_download()) { $this->app->abort(403); } $list = $download->prepare_export( $this->getAuthenticatedUser(), $this->app['filesystem'], $subdefs, $request->request->get('type') === 'title' ? true : false, $request->request->get('businessfields') ); $list['export_name'] = sprintf('%s.zip', $download->getExportName()); $token = $this->getTokenManipulator()->createDownloadToken($this->getAuthenticatedUser(), serialize($list)); $this->getDispatcher()->dispatch(PhraseaEvents::EXPORT_CREATE, new ExportEvent( $this->getAuthenticatedUser(), $ssttid, $lst, $subdefs, $download->getExportName()) ); return $this->app->redirectPath('prepare_download', ['token' => $token->getValue()]); }
php
public function checkDownload(Request $request) { $lst = $request->request->get('lst'); $ssttid = $request->request->get('ssttid', ''); $subdefs = $request->request->get('obj', []); $download = new \set_export($this->app, $lst, $ssttid); if (0 === $download->get_total_download()) { $this->app->abort(403); } $list = $download->prepare_export( $this->getAuthenticatedUser(), $this->app['filesystem'], $subdefs, $request->request->get('type') === 'title' ? true : false, $request->request->get('businessfields') ); $list['export_name'] = sprintf('%s.zip', $download->getExportName()); $token = $this->getTokenManipulator()->createDownloadToken($this->getAuthenticatedUser(), serialize($list)); $this->getDispatcher()->dispatch(PhraseaEvents::EXPORT_CREATE, new ExportEvent( $this->getAuthenticatedUser(), $ssttid, $lst, $subdefs, $download->getExportName()) ); return $this->app->redirectPath('prepare_download', ['token' => $token->getValue()]); }
[ "public", "function", "checkDownload", "(", "Request", "$", "request", ")", "{", "$", "lst", "=", "$", "request", "->", "request", "->", "get", "(", "'lst'", ")", ";", "$", "ssttid", "=", "$", "request", "->", "request", "->", "get", "(", "'ssttid'", ...
Download a set of documents @param Request $request @return RedirectResponse
[ "Download", "a", "set", "of", "documents" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Prod/DownloadController.php#L30-L57
alchemy-fr/Phraseanet
lib/classes/patch/370alpha3a.php
patch_370alpha3a.apply
public function apply(base $appbox, Application $app) { if (null === $app['repo.api-applications']->findByClientId(\API_OAuth2_Application_Navigator::CLIENT_ID)) { $application = $app['manipulator.api-application']->create( \API_OAuth2_Application_Navigator::CLIENT_NAME, ApiApplication::DESKTOP_TYPE, '', 'http://www.phraseanet.com', null, ApiApplication::NATIVE_APP_REDIRECT_URI ); $application->setGrantPassword(true); $application->setClientId(\API_OAuth2_Application_Navigator::CLIENT_ID); $application->setClientSecret(\API_OAuth2_Application_Navigator::CLIENT_SECRET); $app['manipulator.api-application']->update($application); } return true; }
php
public function apply(base $appbox, Application $app) { if (null === $app['repo.api-applications']->findByClientId(\API_OAuth2_Application_Navigator::CLIENT_ID)) { $application = $app['manipulator.api-application']->create( \API_OAuth2_Application_Navigator::CLIENT_NAME, ApiApplication::DESKTOP_TYPE, '', 'http://www.phraseanet.com', null, ApiApplication::NATIVE_APP_REDIRECT_URI ); $application->setGrantPassword(true); $application->setClientId(\API_OAuth2_Application_Navigator::CLIENT_ID); $application->setClientSecret(\API_OAuth2_Application_Navigator::CLIENT_SECRET); $app['manipulator.api-application']->update($application); } return true; }
[ "public", "function", "apply", "(", "base", "$", "appbox", ",", "Application", "$", "app", ")", "{", "if", "(", "null", "===", "$", "app", "[", "'repo.api-applications'", "]", "->", "findByClientId", "(", "\\", "API_OAuth2_Application_Navigator", "::", "CLIENT...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/370alpha3a.php#L59-L79
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Cache/Manager.php
Manager.flushAll
public function flushAll() { foreach ($this->drivers as $driver) { $driver->flushAll(); } $this->registry = []; $this->save(); return $this; }
php
public function flushAll() { foreach ($this->drivers as $driver) { $driver->flushAll(); } $this->registry = []; $this->save(); return $this; }
[ "public", "function", "flushAll", "(", ")", "{", "foreach", "(", "$", "this", "->", "drivers", "as", "$", "driver", ")", "{", "$", "driver", "->", "flushAll", "(", ")", ";", "}", "$", "this", "->", "registry", "=", "[", "]", ";", "$", "this", "->...
Flushes all registered cache @return Manager
[ "Flushes", "all", "registered", "cache" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Cache/Manager.php#L50-L60
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Cache/Manager.php
Manager.factory
public function factory($label, $name, $options) { if ($this->isAlreadyRegistered($name, $label) && $this->isAlreadyLoaded($label)) { return $this->drivers[$label]; } try { $cache = $this->factory->create($name, $options); } catch (RuntimeException $e) { $this->logger->error($e->getMessage()); $cache = $this->factory->create('array', []); } if (isset($options['namespace']) && is_string($options['namespace'])) { $cache->setNamespace($options['namespace']); } else { $cache->setNamespace(md5(gethostname() . '-' . __DIR__)); } $this->drivers[$label] = $cache; if (!$this->isAlreadyRegistered($name, $label)) { $this->register($name, $label); $cache->flushAll(); } return $cache; }
php
public function factory($label, $name, $options) { if ($this->isAlreadyRegistered($name, $label) && $this->isAlreadyLoaded($label)) { return $this->drivers[$label]; } try { $cache = $this->factory->create($name, $options); } catch (RuntimeException $e) { $this->logger->error($e->getMessage()); $cache = $this->factory->create('array', []); } if (isset($options['namespace']) && is_string($options['namespace'])) { $cache->setNamespace($options['namespace']); } else { $cache->setNamespace(md5(gethostname() . '-' . __DIR__)); } $this->drivers[$label] = $cache; if (!$this->isAlreadyRegistered($name, $label)) { $this->register($name, $label); $cache->flushAll(); } return $cache; }
[ "public", "function", "factory", "(", "$", "label", ",", "$", "name", ",", "$", "options", ")", "{", "if", "(", "$", "this", "->", "isAlreadyRegistered", "(", "$", "name", ",", "$", "label", ")", "&&", "$", "this", "->", "isAlreadyLoaded", "(", "$", ...
@param string $label @param string $name @param array $options @return Cache
[ "@param", "string", "$label", "@param", "string", "$name", "@param", "array", "$options" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Cache/Manager.php#L69-L96
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/TaskManager/Job/BridgeJob.php
BridgeJob.doJob
protected function doJob(JobData $data) { $app = $data->getApplication(); $status = [ \Bridge_Element::STATUS_PENDING, \Bridge_Element::STATUS_PROCESSING, \Bridge_Element::STATUS_PROCESSING_SERVER ]; $params = []; $n = 1; foreach ($status as $stat) { $params[':status' . $n] = $stat; $n ++; } $sql = 'SELECT id, account_id FROM bridge_elements' . ' WHERE (status = ' . implode(' OR status = ', array_keys($params)) . ')'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute($params); $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); foreach ($rs as $row) { if (!$this->isStarted()) { break; } try { $account = \Bridge_Account::load_account($app, $row['account_id']); $element = new \Bridge_Element($app, $account, $row['id']); $this->log('debug', "process " . $element->get_id() . " with status " . $element->get_status()); if ($element->get_status() == \Bridge_Element::STATUS_PENDING) { $this->upload_element($element); } else { $this->update_element($app, $element); } } catch (\Exception $e) { $this->log('error', sprintf("An error occured : %s", $e->getMessage())); $sql = 'UPDATE bridge_elements SET status = :status WHERE id = :id'; $params = [':status' => \Bridge_Element::STATUS_ERROR, ':id' => $row['id']]; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute($params); $stmt->closeCursor(); } } }
php
protected function doJob(JobData $data) { $app = $data->getApplication(); $status = [ \Bridge_Element::STATUS_PENDING, \Bridge_Element::STATUS_PROCESSING, \Bridge_Element::STATUS_PROCESSING_SERVER ]; $params = []; $n = 1; foreach ($status as $stat) { $params[':status' . $n] = $stat; $n ++; } $sql = 'SELECT id, account_id FROM bridge_elements' . ' WHERE (status = ' . implode(' OR status = ', array_keys($params)) . ')'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute($params); $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); foreach ($rs as $row) { if (!$this->isStarted()) { break; } try { $account = \Bridge_Account::load_account($app, $row['account_id']); $element = new \Bridge_Element($app, $account, $row['id']); $this->log('debug', "process " . $element->get_id() . " with status " . $element->get_status()); if ($element->get_status() == \Bridge_Element::STATUS_PENDING) { $this->upload_element($element); } else { $this->update_element($app, $element); } } catch (\Exception $e) { $this->log('error', sprintf("An error occured : %s", $e->getMessage())); $sql = 'UPDATE bridge_elements SET status = :status WHERE id = :id'; $params = [':status' => \Bridge_Element::STATUS_ERROR, ':id' => $row['id']]; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute($params); $stmt->closeCursor(); } } }
[ "protected", "function", "doJob", "(", "JobData", "$", "data", ")", "{", "$", "app", "=", "$", "data", "->", "getApplication", "(", ")", ";", "$", "status", "=", "[", "\\", "Bridge_Element", "::", "STATUS_PENDING", ",", "\\", "Bridge_Element", "::", "STA...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/TaskManager/Job/BridgeJob.php#L55-L106
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/TaskManager/Job/BridgeJob.php
BridgeJob.upload_element
private function upload_element(\Bridge_Element $element) { $account = $element->get_account(); $element->set_status(\Bridge_Element::STATUS_PROCESSING); $dist_id = null; try { $dist_id = $account->get_api()->upload($element->get_record(), $element->get_datas()); $element->set_uploaded_on(new \DateTime()); $element->set_status(\Bridge_Element::STATUS_DONE); } catch (\Exception $e) { $this->log('debug', 'Error while uploading : ' . $e->getMessage()); $element->set_status(\Bridge_Element::STATUS_ERROR); } $element->set_dist_id($dist_id); return $this; }
php
private function upload_element(\Bridge_Element $element) { $account = $element->get_account(); $element->set_status(\Bridge_Element::STATUS_PROCESSING); $dist_id = null; try { $dist_id = $account->get_api()->upload($element->get_record(), $element->get_datas()); $element->set_uploaded_on(new \DateTime()); $element->set_status(\Bridge_Element::STATUS_DONE); } catch (\Exception $e) { $this->log('debug', 'Error while uploading : ' . $e->getMessage()); $element->set_status(\Bridge_Element::STATUS_ERROR); } $element->set_dist_id($dist_id); return $this; }
[ "private", "function", "upload_element", "(", "\\", "Bridge_Element", "$", "element", ")", "{", "$", "account", "=", "$", "element", "->", "get_account", "(", ")", ";", "$", "element", "->", "set_status", "(", "\\", "Bridge_Element", "::", "STATUS_PROCESSING",...
@param Bridge_Element $element @return BridgeJob
[ "@param", "Bridge_Element", "$element" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/TaskManager/Job/BridgeJob.php#L113-L129
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/TaskManager/Job/BridgeJob.php
BridgeJob.update_element
protected function update_element(Application $app, \Bridge_Element $element) { $account = $element->get_account(); $connector_status = $account->get_api()->get_element_status($element); $status = $element->get_account()->get_api()->map_connector_to_element_status($connector_status); $error_message = $element->get_account()->get_api()->get_error_message_from_status($connector_status); $previous_status = $element->get_status(); if ($status) { $element->set_status($status); $this->log('debug', 'updating status for : ' . $element->get_id() . " to " . $status); } $element->set_connector_status($connector_status); if ($status === $previous_status) { return; } switch ($status) { case \Bridge_Element::STATUS_ERROR: $app['dispatcher']->dispatch(new BridgeUploadFailureEvent($element, $error_message)); break; default: case \Bridge_Element::STATUS_DONE: case \Bridge_Element::STATUS_PENDING: case \Bridge_Element::STATUS_PROCESSING_SERVER: case \Bridge_Element::STATUS_PROCESSING: break; } return $this; }
php
protected function update_element(Application $app, \Bridge_Element $element) { $account = $element->get_account(); $connector_status = $account->get_api()->get_element_status($element); $status = $element->get_account()->get_api()->map_connector_to_element_status($connector_status); $error_message = $element->get_account()->get_api()->get_error_message_from_status($connector_status); $previous_status = $element->get_status(); if ($status) { $element->set_status($status); $this->log('debug', 'updating status for : ' . $element->get_id() . " to " . $status); } $element->set_connector_status($connector_status); if ($status === $previous_status) { return; } switch ($status) { case \Bridge_Element::STATUS_ERROR: $app['dispatcher']->dispatch(new BridgeUploadFailureEvent($element, $error_message)); break; default: case \Bridge_Element::STATUS_DONE: case \Bridge_Element::STATUS_PENDING: case \Bridge_Element::STATUS_PROCESSING_SERVER: case \Bridge_Element::STATUS_PROCESSING: break; } return $this; }
[ "protected", "function", "update_element", "(", "Application", "$", "app", ",", "\\", "Bridge_Element", "$", "element", ")", "{", "$", "account", "=", "$", "element", "->", "get_account", "(", ")", ";", "$", "connector_status", "=", "$", "account", "->", "...
@param Bridge_Element $element @return BridgeJob
[ "@param", "Bridge_Element", "$element" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/TaskManager/Job/BridgeJob.php#L136-L170
alchemy-fr/Phraseanet
lib/classes/databox/subdef.php
databox_subdef.buildImageSubdef
protected function buildImageSubdef(SimpleXMLElement $sd) { $image = new Image($this->translator); if ($sd->icodec) { $image->setOptionValue(Image::OPTION_ICODEC, (string) $sd->icodec); } if ($sd->size) { $image->setOptionValue(Image::OPTION_SIZE, (int) $sd->size); } if ($sd->quality) { $image->setOptionValue(Image::OPTION_QUALITY, (int) $sd->quality); } if ($sd->strip) { $image->setOptionValue(Image::OPTION_STRIP, p4field::isyes($sd->strip)); } if ($sd->dpi) { $image->setOptionValue(Image::OPTION_RESOLUTION, (int) $sd->dpi); } if ($sd->flatten) { $image->setOptionValue(Image::OPTION_FLATTEN, p4field::isyes($sd->flatten)); } return $image; }
php
protected function buildImageSubdef(SimpleXMLElement $sd) { $image = new Image($this->translator); if ($sd->icodec) { $image->setOptionValue(Image::OPTION_ICODEC, (string) $sd->icodec); } if ($sd->size) { $image->setOptionValue(Image::OPTION_SIZE, (int) $sd->size); } if ($sd->quality) { $image->setOptionValue(Image::OPTION_QUALITY, (int) $sd->quality); } if ($sd->strip) { $image->setOptionValue(Image::OPTION_STRIP, p4field::isyes($sd->strip)); } if ($sd->dpi) { $image->setOptionValue(Image::OPTION_RESOLUTION, (int) $sd->dpi); } if ($sd->flatten) { $image->setOptionValue(Image::OPTION_FLATTEN, p4field::isyes($sd->flatten)); } return $image; }
[ "protected", "function", "buildImageSubdef", "(", "SimpleXMLElement", "$", "sd", ")", "{", "$", "image", "=", "new", "Image", "(", "$", "this", "->", "translator", ")", ";", "if", "(", "$", "sd", "->", "icodec", ")", "{", "$", "image", "->", "setOption...
Build Image Subdef object depending the SimpleXMLElement @param SimpleXMLElement $sd @return Image
[ "Build", "Image", "Subdef", "object", "depending", "the", "SimpleXMLElement" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/databox/subdef.php#L118-L140
alchemy-fr/Phraseanet
lib/classes/databox/subdef.php
databox_subdef.buildAudioSubdef
protected function buildAudioSubdef(SimpleXMLElement $sd) { $audio = new Audio($this->translator); if ($sd->acodec) { $audio->setOptionValue(Audio::OPTION_ACODEC, (string) $sd->acodec); } if ($sd->audiobitrate) { $audio->setOptionValue(Audio::OPTION_AUDIOBITRATE, (int) $sd->audiobitrate); } if ($sd->audiosamplerate) { $audio->setOptionValue(Audio::OPTION_AUDIOSAMPLERATE, (int) $sd->audiosamplerate); } if ($sd->audiochannel) { $audio->setOptionValue(Audio::OPTION_AUDIOCHANNEL, (string) $sd->audiochannel); } return $audio; }
php
protected function buildAudioSubdef(SimpleXMLElement $sd) { $audio = new Audio($this->translator); if ($sd->acodec) { $audio->setOptionValue(Audio::OPTION_ACODEC, (string) $sd->acodec); } if ($sd->audiobitrate) { $audio->setOptionValue(Audio::OPTION_AUDIOBITRATE, (int) $sd->audiobitrate); } if ($sd->audiosamplerate) { $audio->setOptionValue(Audio::OPTION_AUDIOSAMPLERATE, (int) $sd->audiosamplerate); } if ($sd->audiochannel) { $audio->setOptionValue(Audio::OPTION_AUDIOCHANNEL, (string) $sd->audiochannel); } return $audio; }
[ "protected", "function", "buildAudioSubdef", "(", "SimpleXMLElement", "$", "sd", ")", "{", "$", "audio", "=", "new", "Audio", "(", "$", "this", "->", "translator", ")", ";", "if", "(", "$", "sd", "->", "acodec", ")", "{", "$", "audio", "->", "setOption...
Build Audio Subdef object depending the SimpleXMLElement @param SimpleXMLElement $sd @return Audio
[ "Build", "Audio", "Subdef", "object", "depending", "the", "SimpleXMLElement" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/databox/subdef.php#L147-L164
alchemy-fr/Phraseanet
lib/classes/databox/subdef.php
databox_subdef.buildVideoSubdef
protected function buildVideoSubdef(SimpleXMLElement $sd) { $video = new Video($this->translator); if ($sd->size) { $video->setOptionValue(Video::OPTION_SIZE, (int) $sd->size); } if ($sd->acodec) { $video->setOptionValue(Video::OPTION_ACODEC, (string) $sd->acodec); } if ($sd->vcodec) { $video->setOptionValue(Video::OPTION_VCODEC, (string) $sd->vcodec); } if ($sd->fps) { $video->setOptionValue(Video::OPTION_FRAMERATE, (int) $sd->fps); } if ($sd->bitrate) { $video->setOptionValue(Video::OPTION_BITRATE, (int) $sd->bitrate); } if ($sd->audiobitrate) { $video->setOptionValue(Video::OPTION_AUDIOBITRATE, (int) $sd->audiobitrate); } if ($sd->audiosamplerate) { $video->setOptionValue(Video::OPTION_AUDIOSAMPLERATE, (int) $sd->audiosamplerate); } if ($sd->GOPsize) { $video->setOptionValue(Video::OPTION_GOPSIZE, (int) $sd->GOPsize); } return $video; }
php
protected function buildVideoSubdef(SimpleXMLElement $sd) { $video = new Video($this->translator); if ($sd->size) { $video->setOptionValue(Video::OPTION_SIZE, (int) $sd->size); } if ($sd->acodec) { $video->setOptionValue(Video::OPTION_ACODEC, (string) $sd->acodec); } if ($sd->vcodec) { $video->setOptionValue(Video::OPTION_VCODEC, (string) $sd->vcodec); } if ($sd->fps) { $video->setOptionValue(Video::OPTION_FRAMERATE, (int) $sd->fps); } if ($sd->bitrate) { $video->setOptionValue(Video::OPTION_BITRATE, (int) $sd->bitrate); } if ($sd->audiobitrate) { $video->setOptionValue(Video::OPTION_AUDIOBITRATE, (int) $sd->audiobitrate); } if ($sd->audiosamplerate) { $video->setOptionValue(Video::OPTION_AUDIOSAMPLERATE, (int) $sd->audiosamplerate); } if ($sd->GOPsize) { $video->setOptionValue(Video::OPTION_GOPSIZE, (int) $sd->GOPsize); } return $video; }
[ "protected", "function", "buildVideoSubdef", "(", "SimpleXMLElement", "$", "sd", ")", "{", "$", "video", "=", "new", "Video", "(", "$", "this", "->", "translator", ")", ";", "if", "(", "$", "sd", "->", "size", ")", "{", "$", "video", "->", "setOptionVa...
Build Video Subdef object depending the SimpleXMLElement @param SimpleXMLElement $sd @return Video
[ "Build", "Video", "Subdef", "object", "depending", "the", "SimpleXMLElement" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/databox/subdef.php#L171-L199
alchemy-fr/Phraseanet
lib/classes/databox/subdef.php
databox_subdef.buildGifSubdef
protected function buildGifSubdef(SimpleXMLElement $sd) { $gif = new Gif($this->translator); if ($sd->size) { $gif->setOptionValue(Gif::OPTION_SIZE, (int) $sd->size); } if ($sd->delay) { $gif->setOptionValue(Gif::OPTION_DELAY, (int) $sd->delay); } return $gif; }
php
protected function buildGifSubdef(SimpleXMLElement $sd) { $gif = new Gif($this->translator); if ($sd->size) { $gif->setOptionValue(Gif::OPTION_SIZE, (int) $sd->size); } if ($sd->delay) { $gif->setOptionValue(Gif::OPTION_DELAY, (int) $sd->delay); } return $gif; }
[ "protected", "function", "buildGifSubdef", "(", "SimpleXMLElement", "$", "sd", ")", "{", "$", "gif", "=", "new", "Gif", "(", "$", "this", "->", "translator", ")", ";", "if", "(", "$", "sd", "->", "size", ")", "{", "$", "gif", "->", "setOptionValue", ...
Build GIF Subdef object depending the SimpleXMLElement @param SimpleXMLElement $sd @return Gif
[ "Build", "GIF", "Subdef", "object", "depending", "the", "SimpleXMLElement" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/databox/subdef.php#L206-L216
alchemy-fr/Phraseanet
lib/classes/databox/subdef.php
databox_subdef.getAvailableSubdefTypes
public function getAvailableSubdefTypes() { $subdefTypes = []; $availableDevices = [ self::DEVICE_ALL, self::DEVICE_HANDHELD, self::DEVICE_PRINT, self::DEVICE_PROJECTION, self::DEVICE_SCREEN, self::DEVICE_TV, ]; if (isset(self::$mediaTypeToSubdefTypes[$this->subdef_group->getType()])) { foreach (self::$mediaTypeToSubdefTypes[$this->subdef_group->getType()] as $subdefType) { if ($subdefType == $this->subdef_type->getType()) { $mediatype_obj = $this->subdef_type; } else { switch ($subdefType) { case SubdefSpecs::TYPE_ANIMATION: $mediatype_obj = new Gif($this->translator); break; case SubdefSpecs::TYPE_AUDIO: $mediatype_obj = new Audio($this->translator); break; case SubdefSpecs::TYPE_FLEXPAPER: $mediatype_obj = new FlexPaper($this->translator); break; case SubdefSpecs::TYPE_IMAGE: $mediatype_obj = new Image($this->translator); break; case SubdefSpecs::TYPE_VIDEO: $mediatype_obj = new Video($this->translator); break; case SubdefSpecs::TYPE_PDF: $mediatype_obj = new Pdf($this->translator); break; case SubdefSpecs::TYPE_UNKNOWN: $mediatype_obj = new Unknown($this->translator); break; default: continue; break; } } $mediatype_obj->registerOption(new \Alchemy\Phrasea\Media\Subdef\OptionType\Multi($this->translator->trans('Target Device'), 'devices', $availableDevices, $this->devices)); $subdefTypes[] = $mediatype_obj; } } return $subdefTypes; }
php
public function getAvailableSubdefTypes() { $subdefTypes = []; $availableDevices = [ self::DEVICE_ALL, self::DEVICE_HANDHELD, self::DEVICE_PRINT, self::DEVICE_PROJECTION, self::DEVICE_SCREEN, self::DEVICE_TV, ]; if (isset(self::$mediaTypeToSubdefTypes[$this->subdef_group->getType()])) { foreach (self::$mediaTypeToSubdefTypes[$this->subdef_group->getType()] as $subdefType) { if ($subdefType == $this->subdef_type->getType()) { $mediatype_obj = $this->subdef_type; } else { switch ($subdefType) { case SubdefSpecs::TYPE_ANIMATION: $mediatype_obj = new Gif($this->translator); break; case SubdefSpecs::TYPE_AUDIO: $mediatype_obj = new Audio($this->translator); break; case SubdefSpecs::TYPE_FLEXPAPER: $mediatype_obj = new FlexPaper($this->translator); break; case SubdefSpecs::TYPE_IMAGE: $mediatype_obj = new Image($this->translator); break; case SubdefSpecs::TYPE_VIDEO: $mediatype_obj = new Video($this->translator); break; case SubdefSpecs::TYPE_PDF: $mediatype_obj = new Pdf($this->translator); break; case SubdefSpecs::TYPE_UNKNOWN: $mediatype_obj = new Unknown($this->translator); break; default: continue; break; } } $mediatype_obj->registerOption(new \Alchemy\Phrasea\Media\Subdef\OptionType\Multi($this->translator->trans('Target Device'), 'devices', $availableDevices, $this->devices)); $subdefTypes[] = $mediatype_obj; } } return $subdefTypes; }
[ "public", "function", "getAvailableSubdefTypes", "(", ")", "{", "$", "subdefTypes", "=", "[", "]", ";", "$", "availableDevices", "=", "[", "self", "::", "DEVICE_ALL", ",", "self", "::", "DEVICE_HANDHELD", ",", "self", "::", "DEVICE_PRINT", ",", "self", "::",...
Get an array of Alchemy\Phrasea\Media\Subdef\Subdef available for the current Media Type @return array
[ "Get", "an", "array", "of", "Alchemy", "\\", "Phrasea", "\\", "Media", "\\", "Subdef", "\\", "Subdef", "available", "for", "the", "current", "Media", "Type" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/databox/subdef.php#L349-L398