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/Command/Setup/FixAutoincrements.php
FixAutoincrements.ab_fix_Sessions
private function ab_fix_Sessions() { $ouputTable = new Table($this->output); $title = sprintf("fixing table \"%s.%s\"", $this->appBox->get_dbname(), "Sessions"); $ouputTable->setHeaders([new TableCell($title, ['colspan'=>2])]); $site = $this->getContainer()['conf']->get(['main', 'key']); // if autoincrement, get the current value as a minimum $max_SessionId = $this->box_getMax( $this->appBox, 'Sessions', [], // no sub-tables $ouputTable ); // get max session from databoxes, using the "log" table which refers to ab.Sessions ids foreach ($this->databoxes as $databox) { $db = $databox->get_connection(); $sql = "SELECT MAX(`sit_session`) FROM `log` WHERE `site` = :site"; $stmt = $db->executeQuery($sql, [':site' => $site]); $id = $stmt->fetchColumn(0); $ouputTable->addRow([sprintf("%s.log.sit_session", $databox->get_dbname()), sprintf("%s", is_null($id) ? 'null' : $id)]); if(!is_null($id)) { $id = (int)$id + 1; if ($id > $max_SessionId) { $max_SessionId = $id; } } $stmt->closeCursor(); } // fix using different methods foreach ([ // 4.0 with autoincrement [ 'sql' => "ALTER TABLE `Sessions` AUTO_INCREMENT = " . $max_SessionId, // can't use parameter here 'parms' => [], 'msg' => ["ab.Sessions.AUTO_INCREMENT set to", $max_SessionId], ], /* --- custon generators not yet implemented in phraseanet // 4.0 with custom generator already set [ 'sql' => "UPDATE `Id` SET value = :v WHERE `id` = :k", 'parms' => [':v' => $max_SessionId, ':k' => 'Alchemy\\Phrasea\\Model\\Entities\\Session'], 'msg' => ["ab.Id['Sessions']' set to", $max_SessionId], ], // 4.0 with custom generator not yet set [ 'sql' => "INSERT INTO `Id` (`id`, `value`) VALUES (:k, :v)", 'parms' => [':v' => $max_SessionId, ':k' => 'Alchemy\\Phrasea\\Model\\Entities\\Session'], 'msg' => ["ab.Id['Sessions']' set to", $max_SessionId], ] --- */ ] as $sql) { // one or more sql will fail, no pb $this->box_setSQL($this->appBox, $sql['sql'], $sql['parms'], $sql['msg'], $ouputTable); } $ouputTable->render(); $this->output->writeln(""); return $this; }
php
private function ab_fix_Sessions() { $ouputTable = new Table($this->output); $title = sprintf("fixing table \"%s.%s\"", $this->appBox->get_dbname(), "Sessions"); $ouputTable->setHeaders([new TableCell($title, ['colspan'=>2])]); $site = $this->getContainer()['conf']->get(['main', 'key']); // if autoincrement, get the current value as a minimum $max_SessionId = $this->box_getMax( $this->appBox, 'Sessions', [], // no sub-tables $ouputTable ); // get max session from databoxes, using the "log" table which refers to ab.Sessions ids foreach ($this->databoxes as $databox) { $db = $databox->get_connection(); $sql = "SELECT MAX(`sit_session`) FROM `log` WHERE `site` = :site"; $stmt = $db->executeQuery($sql, [':site' => $site]); $id = $stmt->fetchColumn(0); $ouputTable->addRow([sprintf("%s.log.sit_session", $databox->get_dbname()), sprintf("%s", is_null($id) ? 'null' : $id)]); if(!is_null($id)) { $id = (int)$id + 1; if ($id > $max_SessionId) { $max_SessionId = $id; } } $stmt->closeCursor(); } // fix using different methods foreach ([ // 4.0 with autoincrement [ 'sql' => "ALTER TABLE `Sessions` AUTO_INCREMENT = " . $max_SessionId, // can't use parameter here 'parms' => [], 'msg' => ["ab.Sessions.AUTO_INCREMENT set to", $max_SessionId], ], /* --- custon generators not yet implemented in phraseanet // 4.0 with custom generator already set [ 'sql' => "UPDATE `Id` SET value = :v WHERE `id` = :k", 'parms' => [':v' => $max_SessionId, ':k' => 'Alchemy\\Phrasea\\Model\\Entities\\Session'], 'msg' => ["ab.Id['Sessions']' set to", $max_SessionId], ], // 4.0 with custom generator not yet set [ 'sql' => "INSERT INTO `Id` (`id`, `value`) VALUES (:k, :v)", 'parms' => [':v' => $max_SessionId, ':k' => 'Alchemy\\Phrasea\\Model\\Entities\\Session'], 'msg' => ["ab.Id['Sessions']' set to", $max_SessionId], ] --- */ ] as $sql) { // one or more sql will fail, no pb $this->box_setSQL($this->appBox, $sql['sql'], $sql['parms'], $sql['msg'], $ouputTable); } $ouputTable->render(); $this->output->writeln(""); return $this; }
[ "private", "function", "ab_fix_Sessions", "(", ")", "{", "$", "ouputTable", "=", "new", "Table", "(", "$", "this", "->", "output", ")", ";", "$", "title", "=", "sprintf", "(", "\"fixing table \\\"%s.%s\\\"\"", ",", "$", "this", "->", "appBox", "->", "get_d...
fix AppBox "Sessions" autoincrement @return $this @throws \Doctrine\DBAL\DBALException
[ "fix", "AppBox", "Sessions", "autoincrement" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/Setup/FixAutoincrements.php#L308-L377
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Border/Attribute/Story.php
Story.loadFromString
public static function loadFromString(Application $app, $string) { $ids = explode('_', $string); try { $story = new \record_adapter($app, $ids[0], $ids[1]); } catch (NotFoundHttpException $e) { throw new \InvalidArgumentException('Unable to fetch a story from string'); } if (!$story->isStory()) { throw new \InvalidArgumentException('Unable to fetch a story from string'); } return new static($story); }
php
public static function loadFromString(Application $app, $string) { $ids = explode('_', $string); try { $story = new \record_adapter($app, $ids[0], $ids[1]); } catch (NotFoundHttpException $e) { throw new \InvalidArgumentException('Unable to fetch a story from string'); } if (!$story->isStory()) { throw new \InvalidArgumentException('Unable to fetch a story from string'); } return new static($story); }
[ "public", "static", "function", "loadFromString", "(", "Application", "$", "app", ",", "$", "string", ")", "{", "$", "ids", "=", "explode", "(", "'_'", ",", "$", "string", ")", ";", "try", "{", "$", "story", "=", "new", "\\", "record_adapter", "(", "...
{@inheritdoc} @return Story
[ "{", "@inheritdoc", "}" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Border/Attribute/Story.php#L80-L95
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Command/Setup/XSendFileMappingGenerator.php
XSendFileMappingGenerator.doExecute
protected function doExecute(InputInterface $input, OutputInterface $output) { $extractor = new DataboxPathExtractor($this->container->getApplicationBox()); $paths = $extractor->extractPaths('xsendfile'); foreach ($paths as $path) { $this->container['filesystem']->mkdir($path); } $type = strtolower($input->getArgument('type')); $enabled = $input->getOption('enabled'); $factory = new XSendFileFactory($this->container['monolog'], true, $type, $this->computeMapping($paths)); $mode = $factory->getMode(true); $conf = [ 'enabled' => $enabled, 'type' => $type, 'mapping' => $mode->getMapping(), ]; if ($input->getOption('write')) { $output->write("Writing configuration ..."); $this->container['conf']->set('xsendfile', $conf); $output->writeln(" <info>OK</info>"); $output->writeln(""); $output->writeln("It is now strongly recommended to use <info>xsendfile:dump-configuration</info> command to upgrade your virtual-host"); } else { $output->writeln("Configuration will <info>not</info> be written, use <info>--write</info> option to write it"); $output->writeln(""); $output->writeln(Yaml::dump(['xsendfile' => $conf], 4)); } $output->writeln(""); return 0; }
php
protected function doExecute(InputInterface $input, OutputInterface $output) { $extractor = new DataboxPathExtractor($this->container->getApplicationBox()); $paths = $extractor->extractPaths('xsendfile'); foreach ($paths as $path) { $this->container['filesystem']->mkdir($path); } $type = strtolower($input->getArgument('type')); $enabled = $input->getOption('enabled'); $factory = new XSendFileFactory($this->container['monolog'], true, $type, $this->computeMapping($paths)); $mode = $factory->getMode(true); $conf = [ 'enabled' => $enabled, 'type' => $type, 'mapping' => $mode->getMapping(), ]; if ($input->getOption('write')) { $output->write("Writing configuration ..."); $this->container['conf']->set('xsendfile', $conf); $output->writeln(" <info>OK</info>"); $output->writeln(""); $output->writeln("It is now strongly recommended to use <info>xsendfile:dump-configuration</info> command to upgrade your virtual-host"); } else { $output->writeln("Configuration will <info>not</info> be written, use <info>--write</info> option to write it"); $output->writeln(""); $output->writeln(Yaml::dump(['xsendfile' => $conf], 4)); } $output->writeln(""); return 0; }
[ "protected", "function", "doExecute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "extractor", "=", "new", "DataboxPathExtractor", "(", "$", "this", "->", "container", "->", "getApplicationBox", "(", ")", ")", ";"...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/Setup/XSendFileMappingGenerator.php#L37-L72
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Authentication/Provider/Github.php
Github.authenticate
public function authenticate(array $params = array()) { $params = array_merge(['providerId' => $this->getId()], $params); $state = $this->createState(); $this->session->set('github.provider.state', $state); return new RedirectResponse('https://github.com/login/oauth/authorize?' . http_build_query([ 'client_id' => $this->key, 'scope' => 'user,user:email', 'state' => $state, 'redirect_uri' => $this->generator->generate( 'login_authentication_provider_callback', $params, UrlGenerator::ABSOLUTE_URL ), ], '', '&')); }
php
public function authenticate(array $params = array()) { $params = array_merge(['providerId' => $this->getId()], $params); $state = $this->createState(); $this->session->set('github.provider.state', $state); return new RedirectResponse('https://github.com/login/oauth/authorize?' . http_build_query([ 'client_id' => $this->key, 'scope' => 'user,user:email', 'state' => $state, 'redirect_uri' => $this->generator->generate( 'login_authentication_provider_callback', $params, UrlGenerator::ABSOLUTE_URL ), ], '', '&')); }
[ "public", "function", "authenticate", "(", "array", "$", "params", "=", "array", "(", ")", ")", "{", "$", "params", "=", "array_merge", "(", "[", "'providerId'", "=>", "$", "this", "->", "getId", "(", ")", "]", ",", "$", "params", ")", ";", "$", "s...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/Provider/Github.php#L81-L99
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Authentication/Provider/Github.php
Github.onCallback
public function onCallback(Request $request) { if (!$this->session->has('github.provider.state')) { throw new NotAuthenticatedException('No state value in session ; CSRF try ?'); } if ($request->query->get('state') !== $this->session->remove('github.provider.state')) { throw new NotAuthenticatedException('Invalid state value ; CSRF try ?'); } try { $guzzleRequest = $this->client->post('access_token'); $guzzleRequest->addPostFields([ 'code' => $request->query->get('code'), 'redirect_uri' => $this->generator->generate( 'login_authentication_provider_callback', ['providerId' => $this->getId()], UrlGenerator::ABSOLUTE_URL ), 'client_id' => $this->key, 'client_secret' => $this->secret, ]); $guzzleRequest->setHeader('Accept', 'application/json'); $response = $guzzleRequest->send(); } catch (GuzzleException $e) { throw new NotAuthenticatedException('Guzzle error while authentication', $e->getCode(), $e); } if (200 !== $response->getStatusCode()) { throw new NotAuthenticatedException('Error while getting access_token'); } $data = @json_decode($response->getBody(true), true); if (JSON_ERROR_NONE !== json_last_error()) { throw new NotAuthenticatedException('Error while retrieving user info, unable to parse JSON.'); } $this->session->remove('github.provider.state'); $this->session->set('github.provider.access_token', $data['access_token']); try { $request = $this->client->get('https://api.github.com/user'); $request->getQuery()->add('access_token', $data['access_token']); $request->setHeader('Accept', 'application/json'); $response = $request->send(); } catch (GuzzleException $e) { throw new NotAuthenticatedException('Guzzle error while authentication', $e->getCode(), $e); } $data = @json_decode($response->getBody(true), true); if (200 !== $response->getStatusCode()) { throw new NotAuthenticatedException('Error while retrieving user info, invalid status code.'); } if (JSON_ERROR_NONE !== json_last_error()) { throw new NotAuthenticatedException('Error while retrieving user info, unable to parse JSON.'); } $this->session->set('github.provider.id', $data['id']); }
php
public function onCallback(Request $request) { if (!$this->session->has('github.provider.state')) { throw new NotAuthenticatedException('No state value in session ; CSRF try ?'); } if ($request->query->get('state') !== $this->session->remove('github.provider.state')) { throw new NotAuthenticatedException('Invalid state value ; CSRF try ?'); } try { $guzzleRequest = $this->client->post('access_token'); $guzzleRequest->addPostFields([ 'code' => $request->query->get('code'), 'redirect_uri' => $this->generator->generate( 'login_authentication_provider_callback', ['providerId' => $this->getId()], UrlGenerator::ABSOLUTE_URL ), 'client_id' => $this->key, 'client_secret' => $this->secret, ]); $guzzleRequest->setHeader('Accept', 'application/json'); $response = $guzzleRequest->send(); } catch (GuzzleException $e) { throw new NotAuthenticatedException('Guzzle error while authentication', $e->getCode(), $e); } if (200 !== $response->getStatusCode()) { throw new NotAuthenticatedException('Error while getting access_token'); } $data = @json_decode($response->getBody(true), true); if (JSON_ERROR_NONE !== json_last_error()) { throw new NotAuthenticatedException('Error while retrieving user info, unable to parse JSON.'); } $this->session->remove('github.provider.state'); $this->session->set('github.provider.access_token', $data['access_token']); try { $request = $this->client->get('https://api.github.com/user'); $request->getQuery()->add('access_token', $data['access_token']); $request->setHeader('Accept', 'application/json'); $response = $request->send(); } catch (GuzzleException $e) { throw new NotAuthenticatedException('Guzzle error while authentication', $e->getCode(), $e); } $data = @json_decode($response->getBody(true), true); if (200 !== $response->getStatusCode()) { throw new NotAuthenticatedException('Error while retrieving user info, invalid status code.'); } if (JSON_ERROR_NONE !== json_last_error()) { throw new NotAuthenticatedException('Error while retrieving user info, unable to parse JSON.'); } $this->session->set('github.provider.id', $data['id']); }
[ "public", "function", "onCallback", "(", "Request", "$", "request", ")", "{", "if", "(", "!", "$", "this", "->", "session", "->", "has", "(", "'github.provider.state'", ")", ")", "{", "throw", "new", "NotAuthenticatedException", "(", "'No state value in session ...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/Provider/Github.php#L112-L175
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Authentication/Provider/Github.php
Github.getIdentity
public function getIdentity() { $identity = new Identity(); try { $request = $this->client->get('https://api.github.com/user'); $request->getQuery()->add('access_token', $this->session->get('github.provider.access_token')); $request->setHeader('Accept', 'application/json'); $response = $request->send(); } catch (GuzzleException $e) { throw new NotAuthenticatedException('Error while retrieving user info', $e->getCode(), $e); } if (200 !== $response->getStatusCode()) { throw new NotAuthenticatedException('Error while retrieving user info'); } $data = @json_decode($response->getBody(true), true); if (JSON_ERROR_NONE !== json_last_error()) { throw new NotAuthenticatedException('Error while parsing json'); } list($firstname, $lastname) = explode(' ', $data['name'], 2); $identity->set(Identity::PROPERTY_EMAIL, $data['email']); $identity->set(Identity::PROPERTY_FIRSTNAME, $firstname); $identity->set(Identity::PROPERTY_ID, $data['id']); $identity->set(Identity::PROPERTY_IMAGEURL, $data['avatar_url']); $identity->set(Identity::PROPERTY_LASTNAME, $lastname); return $identity; }
php
public function getIdentity() { $identity = new Identity(); try { $request = $this->client->get('https://api.github.com/user'); $request->getQuery()->add('access_token', $this->session->get('github.provider.access_token')); $request->setHeader('Accept', 'application/json'); $response = $request->send(); } catch (GuzzleException $e) { throw new NotAuthenticatedException('Error while retrieving user info', $e->getCode(), $e); } if (200 !== $response->getStatusCode()) { throw new NotAuthenticatedException('Error while retrieving user info'); } $data = @json_decode($response->getBody(true), true); if (JSON_ERROR_NONE !== json_last_error()) { throw new NotAuthenticatedException('Error while parsing json'); } list($firstname, $lastname) = explode(' ', $data['name'], 2); $identity->set(Identity::PROPERTY_EMAIL, $data['email']); $identity->set(Identity::PROPERTY_FIRSTNAME, $firstname); $identity->set(Identity::PROPERTY_ID, $data['id']); $identity->set(Identity::PROPERTY_IMAGEURL, $data['avatar_url']); $identity->set(Identity::PROPERTY_LASTNAME, $lastname); return $identity; }
[ "public", "function", "getIdentity", "(", ")", "{", "$", "identity", "=", "new", "Identity", "(", ")", ";", "try", "{", "$", "request", "=", "$", "this", "->", "client", "->", "get", "(", "'https://api.github.com/user'", ")", ";", "$", "request", "->", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/Provider/Github.php#L192-L225
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Core/Profiler/CacheDataCollector.php
CacheDataCollector.collect
public function collect(Request $request, Response $response, \Exception $exception = null) { $this->startProfile = new CacheProfile($this->statsListener->getInitialStats() ?: []); $this->endProfile = new CacheProfile($this->statsListener->getCurrentStats() ?: []); $this->timeSpent = $this->statsListener->getTimeSpent(); $this->calls = $this->statsListener->getCalls(); $this->callSummary = $this->statsListener->getCallSummary(); $this->summary = new CacheProfileSummary( $this->statsListener->getCacheType(), $this->statsListener->getCacheNamespace(), $this->startProfile, $this->endProfile, $this->callSummary ); }
php
public function collect(Request $request, Response $response, \Exception $exception = null) { $this->startProfile = new CacheProfile($this->statsListener->getInitialStats() ?: []); $this->endProfile = new CacheProfile($this->statsListener->getCurrentStats() ?: []); $this->timeSpent = $this->statsListener->getTimeSpent(); $this->calls = $this->statsListener->getCalls(); $this->callSummary = $this->statsListener->getCallSummary(); $this->summary = new CacheProfileSummary( $this->statsListener->getCacheType(), $this->statsListener->getCacheNamespace(), $this->startProfile, $this->endProfile, $this->callSummary ); }
[ "public", "function", "collect", "(", "Request", "$", "request", ",", "Response", "$", "response", ",", "\\", "Exception", "$", "exception", "=", "null", ")", "{", "$", "this", "->", "startProfile", "=", "new", "CacheProfile", "(", "$", "this", "->", "st...
Collects data for the given Request and Response. @param Request $request A Request instance @param Response $response A Response instance @param \Exception $exception An Exception instance
[ "Collects", "data", "for", "the", "given", "Request", "and", "Response", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Core/Profiler/CacheDataCollector.php#L73-L89
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Model/Entities/Order.php
Order.addElement
public function addElement(OrderElement $elements) { $this->elements[] = $elements; $elements->setOrder($this); return $this; }
php
public function addElement(OrderElement $elements) { $this->elements[] = $elements; $elements->setOrder($this); return $this; }
[ "public", "function", "addElement", "(", "OrderElement", "$", "elements", ")", "{", "$", "this", "->", "elements", "[", "]", "=", "$", "elements", ";", "$", "elements", "->", "setOrder", "(", "$", "this", ")", ";", "return", "$", "this", ";", "}" ]
Add elements @param OrderElement $elements @return Order
[ "Add", "elements" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Entities/Order.php#L180-L186
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Model/Entities/Order.php
Order.removeElement
public function removeElement(OrderElement $elements) { $this->elements->removeElement($elements); $elements->setOrder(null); }
php
public function removeElement(OrderElement $elements) { $this->elements->removeElement($elements); $elements->setOrder(null); }
[ "public", "function", "removeElement", "(", "OrderElement", "$", "elements", ")", "{", "$", "this", "->", "elements", "->", "removeElement", "(", "$", "elements", ")", ";", "$", "elements", "->", "setOrder", "(", "null", ")", ";", "}" ]
Remove elements @param OrderElement $elements
[ "Remove", "elements" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Entities/Order.php#L193-L197
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Model/Entities/Order.php
Order.setBasket
public function setBasket(Basket $basket = null) { if ($this->basket) { $this->basket->setOrder(null); } $this->basket = $basket; if ($basket) { $basket->setOrder($this); } return $this; }
php
public function setBasket(Basket $basket = null) { if ($this->basket) { $this->basket->setOrder(null); } $this->basket = $basket; if ($basket) { $basket->setOrder($this); } return $this; }
[ "public", "function", "setBasket", "(", "Basket", "$", "basket", "=", "null", ")", "{", "if", "(", "$", "this", "->", "basket", ")", "{", "$", "this", "->", "basket", "->", "setOrder", "(", "null", ")", ";", "}", "$", "this", "->", "basket", "=", ...
Set basket @param Basket $basket @return Order
[ "Set", "basket" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Entities/Order.php#L300-L313
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Model/Entities/Order.php
Order.setNotificationMethod
public function setNotificationMethod($methodName) { if (trim($methodName) == '') { $methodName = self::NOTIFY_MAIL; } $this->notificationMethod = $methodName; }
php
public function setNotificationMethod($methodName) { if (trim($methodName) == '') { $methodName = self::NOTIFY_MAIL; } $this->notificationMethod = $methodName; }
[ "public", "function", "setNotificationMethod", "(", "$", "methodName", ")", "{", "if", "(", "trim", "(", "$", "methodName", ")", "==", "''", ")", "{", "$", "methodName", "=", "self", "::", "NOTIFY_MAIL", ";", "}", "$", "this", "->", "notificationMethod", ...
Sets the name of the notification method to handle this order's status change notifications. @param string $methodName @return void
[ "Sets", "the", "name", "of", "the", "notification", "method", "to", "handle", "this", "order", "s", "status", "change", "notifications", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Entities/Order.php#L330-L337
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/TaskManager/Job/EmptyCollectionJob.php
EmptyCollectionJob.doJob
protected function doJob(JobData $data) { $app = $data->getApplication(); $task = $data->getTask(); $settings = simplexml_load_string($task->getSettings()); $baseId = (string) $settings->bas_id; $collection = \collection::getByBaseId($app, $baseId); $collection->empty_collection(200); if (0 === $collection->get_record_amount()) { $this->stop(); $this->dispatcher->dispatch(JobEvents::FINISHED, new JobFinishedEvent($task)); } }
php
protected function doJob(JobData $data) { $app = $data->getApplication(); $task = $data->getTask(); $settings = simplexml_load_string($task->getSettings()); $baseId = (string) $settings->bas_id; $collection = \collection::getByBaseId($app, $baseId); $collection->empty_collection(200); if (0 === $collection->get_record_amount()) { $this->stop(); $this->dispatcher->dispatch(JobEvents::FINISHED, new JobFinishedEvent($task)); } }
[ "protected", "function", "doJob", "(", "JobData", "$", "data", ")", "{", "$", "app", "=", "$", "data", "->", "getApplication", "(", ")", ";", "$", "task", "=", "$", "data", "->", "getTask", "(", ")", ";", "$", "settings", "=", "simplexml_load_string", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/TaskManager/Job/EmptyCollectionJob.php#L55-L71
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Report/Report.php
Report.getCollIds
protected function getCollIds(\ACL $acl, $baseIds) { $ret = []; /** @var \collection $collection */ foreach($acl->get_granted_base([\ACL::CANREPORT]) as $collection) { if($collection->get_sbas_id() != $this->databox->get_sbas_id()) { continue; } if(!is_null($baseIds) && !in_array($collection->get_base_id(), $baseIds)) { continue; } $ret[] = $this->databox->get_connection()->quote($collection->get_coll_id()); } return $ret; }
php
protected function getCollIds(\ACL $acl, $baseIds) { $ret = []; /** @var \collection $collection */ foreach($acl->get_granted_base([\ACL::CANREPORT]) as $collection) { if($collection->get_sbas_id() != $this->databox->get_sbas_id()) { continue; } if(!is_null($baseIds) && !in_array($collection->get_base_id(), $baseIds)) { continue; } $ret[] = $this->databox->get_connection()->quote($collection->get_coll_id()); } return $ret; }
[ "protected", "function", "getCollIds", "(", "\\", "ACL", "$", "acl", ",", "$", "baseIds", ")", "{", "$", "ret", "=", "[", "]", ";", "/** @var \\collection $collection */", "foreach", "(", "$", "acl", "->", "get_granted_base", "(", "[", "\\", "ACL", "::", ...
get quoted coll id's granted for report, possibly filtered by baseIds : only from this list of bases @param \ACL $acl @param int[]|null $baseIds @return array
[ "get", "quoted", "coll", "id", "s", "granted", "for", "report", "possibly", "filtered", "by", "baseIds", ":", "only", "from", "this", "list", "of", "bases" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Report/Report.php#L71-L86
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Prod/DoDownloadController.php
DoDownloadController.prepareDownload
public function prepareDownload(Request $request, Token $token) { if (false === $list = @unserialize($token->getData())) { $this->app->abort(500, 'Invalid datas'); } if (!is_array($list)) { $this->app->abort(500, 'Invalid datas'); } foreach (['export_name', 'files'] as $key) { if (!isset($list[$key])) { $this->app->abort(500, 'Invalid datas'); } } $records = []; foreach ($list['files'] as $file) { if (!is_array($file) || !isset($file['base_id']) || !isset($file['record_id'])) { continue; } $sbasId = \phrasea::sbasFromBas($this->app, $file['base_id']); try { $record = new \record_adapter($this->app, $sbasId, $file['record_id']); } catch (\Exception $e) { continue; } $records[sprintf('%s_%s', $sbasId, $file['record_id'])] = $record; } return new Response($this->render( '/prod/actions/Download/prepare.html.twig', [ 'module_name' => $this->app->trans('Export'), 'module' => $this->app->trans('Export'), 'list' => $list, 'records' => $records, 'token' => $token, 'anonymous' => $request->query->get('anonymous', false), 'type' => $request->query->get('type', \Session_Logger::EVENT_EXPORTDOWNLOAD) ])); }
php
public function prepareDownload(Request $request, Token $token) { if (false === $list = @unserialize($token->getData())) { $this->app->abort(500, 'Invalid datas'); } if (!is_array($list)) { $this->app->abort(500, 'Invalid datas'); } foreach (['export_name', 'files'] as $key) { if (!isset($list[$key])) { $this->app->abort(500, 'Invalid datas'); } } $records = []; foreach ($list['files'] as $file) { if (!is_array($file) || !isset($file['base_id']) || !isset($file['record_id'])) { continue; } $sbasId = \phrasea::sbasFromBas($this->app, $file['base_id']); try { $record = new \record_adapter($this->app, $sbasId, $file['record_id']); } catch (\Exception $e) { continue; } $records[sprintf('%s_%s', $sbasId, $file['record_id'])] = $record; } return new Response($this->render( '/prod/actions/Download/prepare.html.twig', [ 'module_name' => $this->app->trans('Export'), 'module' => $this->app->trans('Export'), 'list' => $list, 'records' => $records, 'token' => $token, 'anonymous' => $request->query->get('anonymous', false), 'type' => $request->query->get('type', \Session_Logger::EVENT_EXPORTDOWNLOAD) ])); }
[ "public", "function", "prepareDownload", "(", "Request", "$", "request", ",", "Token", "$", "token", ")", "{", "if", "(", "false", "===", "$", "list", "=", "@", "unserialize", "(", "$", "token", "->", "getData", "(", ")", ")", ")", "{", "$", "this", ...
Prepare a set of documents for download @param Request $request @param Token $token @return Response
[ "Prepare", "a", "set", "of", "documents", "for", "download" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Prod/DoDownloadController.php#L40-L83
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Prod/DoDownloadController.php
DoDownloadController.downloadDocuments
public function downloadDocuments(Token $token) { if (false === $list = @unserialize($token->getData())) { $this->app->abort(500, 'Invalid datas'); } if (!is_array($list)) { $this->app->abort(500, 'Invalid datas'); } foreach (['export_name', 'files'] as $key) { if (!isset($list[$key])) { $this->app->abort(500, 'Invalid datas'); } } $exportName = $list['export_name']; if ($list['count'] === 1) { $file = end($list['files']); $subdef = end($file['subdefs']); $exportName = sprintf('%s%s.%s', $file['export_name'], $subdef['ajout'], $subdef['exportExt']); $exportFile = \p4string::addEndSlash($subdef['path']) . $subdef['file']; $mime = $subdef['mime']; $list['complete'] = true; } else { $exportFile = $this->app['tmp.download.path'].'/'.$token->getValue() . '.zip'; $mime = 'application/zip'; } if (!$this->getFilesystem()->exists($exportFile)) { $this->app->abort(404, 'Download file not found'); } $this->getDispatcher()->addListener(KernelEvents::RESPONSE, function (FilterResponseEvent $event) use ($list) { \set_export::log_download( $this->app, $list, $event->getRequest()->get('type'), !!$event->getRequest()->get('anonymous', false), (isset($list['email']) ? $list['email'] : '') ); }); return $this->deliverFile($exportFile, $exportName, DeliverDataInterface::DISPOSITION_ATTACHMENT, $mime); }
php
public function downloadDocuments(Token $token) { if (false === $list = @unserialize($token->getData())) { $this->app->abort(500, 'Invalid datas'); } if (!is_array($list)) { $this->app->abort(500, 'Invalid datas'); } foreach (['export_name', 'files'] as $key) { if (!isset($list[$key])) { $this->app->abort(500, 'Invalid datas'); } } $exportName = $list['export_name']; if ($list['count'] === 1) { $file = end($list['files']); $subdef = end($file['subdefs']); $exportName = sprintf('%s%s.%s', $file['export_name'], $subdef['ajout'], $subdef['exportExt']); $exportFile = \p4string::addEndSlash($subdef['path']) . $subdef['file']; $mime = $subdef['mime']; $list['complete'] = true; } else { $exportFile = $this->app['tmp.download.path'].'/'.$token->getValue() . '.zip'; $mime = 'application/zip'; } if (!$this->getFilesystem()->exists($exportFile)) { $this->app->abort(404, 'Download file not found'); } $this->getDispatcher()->addListener(KernelEvents::RESPONSE, function (FilterResponseEvent $event) use ($list) { \set_export::log_download( $this->app, $list, $event->getRequest()->get('type'), !!$event->getRequest()->get('anonymous', false), (isset($list['email']) ? $list['email'] : '') ); }); return $this->deliverFile($exportFile, $exportName, DeliverDataInterface::DISPOSITION_ATTACHMENT, $mime); }
[ "public", "function", "downloadDocuments", "(", "Token", "$", "token", ")", "{", "if", "(", "false", "===", "$", "list", "=", "@", "unserialize", "(", "$", "token", "->", "getData", "(", ")", ")", ")", "{", "$", "this", "->", "app", "->", "abort", ...
Download a set of documents @param Token $token @return Response
[ "Download", "a", "set", "of", "documents" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Prod/DoDownloadController.php#L92-L136
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Prod/DoDownloadController.php
DoDownloadController.downloadExecute
public function downloadExecute(Token $token) { if (false === $list = @unserialize($token->getData())) { return $this->app->json([ 'success' => false, 'message' => 'Invalid datas' ]); } set_time_limit(0); // Force the session to be saved and closed. /** @var Session $session */ $session = $this->app['session']; $session->save(); ignore_user_abort(true); if ($list['count'] > 1) { \set_export::build_zip( $this->app, $token, $list, sprintf('%s/%s.zip', $this->app['tmp.download.path'], $token->getValue()) // Dest file ); } else { $list['complete'] = true; $token->setData(serialize($list)); /** @var EntityManagerInterface $manager */ $manager = $this->app['orm.em']; $manager->persist($token); $manager->flush(); } return $this->app->json([ 'success' => true, 'message' => '' ]); }
php
public function downloadExecute(Token $token) { if (false === $list = @unserialize($token->getData())) { return $this->app->json([ 'success' => false, 'message' => 'Invalid datas' ]); } set_time_limit(0); // Force the session to be saved and closed. /** @var Session $session */ $session = $this->app['session']; $session->save(); ignore_user_abort(true); if ($list['count'] > 1) { \set_export::build_zip( $this->app, $token, $list, sprintf('%s/%s.zip', $this->app['tmp.download.path'], $token->getValue()) // Dest file ); } else { $list['complete'] = true; $token->setData(serialize($list)); /** @var EntityManagerInterface $manager */ $manager = $this->app['orm.em']; $manager->persist($token); $manager->flush(); } return $this->app->json([ 'success' => true, 'message' => '' ]); }
[ "public", "function", "downloadExecute", "(", "Token", "$", "token", ")", "{", "if", "(", "false", "===", "$", "list", "=", "@", "unserialize", "(", "$", "token", "->", "getData", "(", ")", ")", ")", "{", "return", "$", "this", "->", "app", "->", "...
Build a zip of downloaded documents @param Token $token @return Response
[ "Build", "a", "zip", "of", "downloaded", "documents" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Prod/DoDownloadController.php#L145-L181
alchemy-fr/Phraseanet
lib/classes/patch/380alpha8a.php
patch_380alpha8a.apply
public function apply(base $appbox, Application $app) { $conn = $appbox->get_connection(); $sql = 'SELECT settings FROM task2 WHERE class="task_period_cindexer" LIMIT 1'; $stmt = $conn->prepare($sql); $stmt->execute(); $row = $stmt->fetch(\PDO::FETCH_ASSOC); $stmt->closeCursor(); if (!$row) { return false; } $sxe = simplexml_load_string($row['settings']); $indexer = $sxe->binpath . '/phraseanet_indexer'; $app['conf']->set(['main', 'binaries', 'phraseanet_indexer'], $indexer); return true; }
php
public function apply(base $appbox, Application $app) { $conn = $appbox->get_connection(); $sql = 'SELECT settings FROM task2 WHERE class="task_period_cindexer" LIMIT 1'; $stmt = $conn->prepare($sql); $stmt->execute(); $row = $stmt->fetch(\PDO::FETCH_ASSOC); $stmt->closeCursor(); if (!$row) { return false; } $sxe = simplexml_load_string($row['settings']); $indexer = $sxe->binpath . '/phraseanet_indexer'; $app['conf']->set(['main', 'binaries', 'phraseanet_indexer'], $indexer); return true; }
[ "public", "function", "apply", "(", "base", "$", "appbox", ",", "Application", "$", "app", ")", "{", "$", "conn", "=", "$", "appbox", "->", "get_connection", "(", ")", ";", "$", "sql", "=", "'SELECT settings\n FROM task2\n WHERE class...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/380alpha8a.php#L49-L71
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Feed/Formatter/AtomFormatter.php
AtomFormatter.createResponse
public function createResponse(Application $app, FeedInterface $feed, $page, User $user = null, $generator = 'Phraseanet') { $content = $this->format($feed, $page, $user, $generator, $app); $response = new Response($content, 200, ['Content-Type' => 'application/atom+xml']); return $response; }
php
public function createResponse(Application $app, FeedInterface $feed, $page, User $user = null, $generator = 'Phraseanet') { $content = $this->format($feed, $page, $user, $generator, $app); $response = new Response($content, 200, ['Content-Type' => 'application/atom+xml']); return $response; }
[ "public", "function", "createResponse", "(", "Application", "$", "app", ",", "FeedInterface", "$", "feed", ",", "$", "page", ",", "User", "$", "user", "=", "null", ",", "$", "generator", "=", "'Phraseanet'", ")", "{", "$", "content", "=", "$", "this", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Feed/Formatter/AtomFormatter.php#L39-L45
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Feed/Formatter/AtomFormatter.php
AtomFormatter.format
public function format(FeedInterface $feed, $page, User $user = null, $generator = 'Phraseanet', Application $app = null) { $document = new \DOMDocument('1.0', 'UTF-8'); $document->formatOutput = true; $document->standalone = true; $root = $this->addTag($document, $document, 'feed'); $root->setAttribute('xmlns', 'http://www.w3.org/2005/Atom'); $root->setAttribute('xmlns:media', 'http://search.yahoo.com/mrss/'); $this->addTag($document, $root, 'title', $feed->getTitle()); if (null !== $updated_on = NullableDateTime::format($feed->getUpdatedOn())) { $this->addTag($document, $root, 'updated', $updated_on); } $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); } } if (null !== $user) { $feedlink = $this->linkGenerator->generate($feed, $user, self::FORMAT, $page); } else { $feedlink = $this->linkGenerator->generatePublic($feed, self::FORMAT, $page); } if ($feedlink instanceof FeedLink) { $link = $this->addTag($document, $root, 'link'); $link->setAttribute('rel', 'self'); $link->setAttribute('href', $feedlink->getURI()); $this->addTag($document, $root, 'id', $feedlink->getURI()); } if ($prev instanceof FeedLink) { $prev_link = $this->addTag($document, $root, 'link'); $prev_link->setAttribute('rel', 'previous'); $prev_link->setAttribute('href', $prev->getURI()); } if ($next instanceof FeedLink) { $next_link = $this->addTag($document, $root, 'link'); $next_link->setAttribute('rel', 'next'); $next_link->setAttribute('href', $next->getURI()); } if (null !== $generator) { $this->addTag($document, $root, 'generator', $generator); } if (null !== $feed->getSubtitle()) { $this->addTag($document, $root, 'subtitle', $feed->getSubtitle()); } if (null !== $feed->getIconUrl()) { $this->addTag($document, $root, 'icon', $feed->getIconUrl()); } if (isset($this->author)) { $author = $this->addTag($document, $root, 'author'); if (isset($this->author_email)) $this->addTag($document, $author, 'email', $this->author_email); if (isset($this->author_name)) $this->addTag($document, $author, 'name', $this->author_name); if (isset($this->author_url)) $this->addTag($document, $author, 'uri', $this->author_url); } foreach ($feed->getEntries() as $item) { $this->addItem($app, $document, $root, $item, $feedlink); } return $document->saveXML(); }
php
public function format(FeedInterface $feed, $page, User $user = null, $generator = 'Phraseanet', Application $app = null) { $document = new \DOMDocument('1.0', 'UTF-8'); $document->formatOutput = true; $document->standalone = true; $root = $this->addTag($document, $document, 'feed'); $root->setAttribute('xmlns', 'http://www.w3.org/2005/Atom'); $root->setAttribute('xmlns:media', 'http://search.yahoo.com/mrss/'); $this->addTag($document, $root, 'title', $feed->getTitle()); if (null !== $updated_on = NullableDateTime::format($feed->getUpdatedOn())) { $this->addTag($document, $root, 'updated', $updated_on); } $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); } } if (null !== $user) { $feedlink = $this->linkGenerator->generate($feed, $user, self::FORMAT, $page); } else { $feedlink = $this->linkGenerator->generatePublic($feed, self::FORMAT, $page); } if ($feedlink instanceof FeedLink) { $link = $this->addTag($document, $root, 'link'); $link->setAttribute('rel', 'self'); $link->setAttribute('href', $feedlink->getURI()); $this->addTag($document, $root, 'id', $feedlink->getURI()); } if ($prev instanceof FeedLink) { $prev_link = $this->addTag($document, $root, 'link'); $prev_link->setAttribute('rel', 'previous'); $prev_link->setAttribute('href', $prev->getURI()); } if ($next instanceof FeedLink) { $next_link = $this->addTag($document, $root, 'link'); $next_link->setAttribute('rel', 'next'); $next_link->setAttribute('href', $next->getURI()); } if (null !== $generator) { $this->addTag($document, $root, 'generator', $generator); } if (null !== $feed->getSubtitle()) { $this->addTag($document, $root, 'subtitle', $feed->getSubtitle()); } if (null !== $feed->getIconUrl()) { $this->addTag($document, $root, 'icon', $feed->getIconUrl()); } if (isset($this->author)) { $author = $this->addTag($document, $root, 'author'); if (isset($this->author_email)) $this->addTag($document, $author, 'email', $this->author_email); if (isset($this->author_name)) $this->addTag($document, $author, 'name', $this->author_name); if (isset($this->author_url)) $this->addTag($document, $author, 'uri', $this->author_url); } foreach ($feed->getEntries() as $item) { $this->addItem($app, $document, $root, $item, $feedlink); } return $document->saveXML(); }
[ "public", "function", "format", "(", "FeedInterface", "$", "feed", ",", "$", "page", ",", "User", "$", "user", "=", "null", ",", "$", "generator", "=", "'Phraseanet'", ",", "Application", "$", "app", "=", "null", ")", "{", "$", "document", "=", "new", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Feed/Formatter/AtomFormatter.php#L50-L132
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/SearchEngine/Elastic/Search/QueryHelper.php
QueryHelper.applyBooleanClause
public static function applyBooleanClause($query, $type, array $clause) { if (!in_array($type, ['must', 'should'])) { throw new \InvalidArgumentException(sprintf('Type must be either "must" or "should", "%s" given', $type)); } if ($query === null) { return $clause; } if (!is_array($query)) { throw new \InvalidArgumentException(sprintf('Query must be either an array or null, "%s" given', gettype($query))); } if (!isset($query['bool'])) { // Wrap in a boolean query $bool = []; $bool['bool'][$type][] = $query; $bool['bool'][$type][] = $clause; return $bool; } elseif (isset($query['bool'][$type])) { // Reuse the existing boolean clause group if (!is_array($query['bool'][$type])) { // Wrap the previous clause in an array $previous_clause = $query['bool'][$type]; $query['bool'][$type] = []; $query['bool'][$type][] = $previous_clause; } $query['bool'][$type][] = $clause; return $query; } else { $query['bool'][$type][] = $clause; return $query; } }
php
public static function applyBooleanClause($query, $type, array $clause) { if (!in_array($type, ['must', 'should'])) { throw new \InvalidArgumentException(sprintf('Type must be either "must" or "should", "%s" given', $type)); } if ($query === null) { return $clause; } if (!is_array($query)) { throw new \InvalidArgumentException(sprintf('Query must be either an array or null, "%s" given', gettype($query))); } if (!isset($query['bool'])) { // Wrap in a boolean query $bool = []; $bool['bool'][$type][] = $query; $bool['bool'][$type][] = $clause; return $bool; } elseif (isset($query['bool'][$type])) { // Reuse the existing boolean clause group if (!is_array($query['bool'][$type])) { // Wrap the previous clause in an array $previous_clause = $query['bool'][$type]; $query['bool'][$type] = []; $query['bool'][$type][] = $previous_clause; } $query['bool'][$type][] = $clause; return $query; } else { $query['bool'][$type][] = $clause; return $query; } }
[ "public", "static", "function", "applyBooleanClause", "(", "$", "query", ",", "$", "type", ",", "array", "$", "clause", ")", "{", "if", "(", "!", "in_array", "(", "$", "type", ",", "[", "'must'", ",", "'should'", "]", ")", ")", "{", "throw", "new", ...
Apply conjunction or disjunction between a query and a sub query clause @param array $query Query @param string $type "must" for conjunction, "should" for disjunction @param array $sub_query Clause query @return array Resulting query
[ "Apply", "conjunction", "or", "disjunction", "between", "a", "query", "and", "a", "sub", "query", "clause" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/Elastic/Search/QueryHelper.php#L74-L111
alchemy-fr/Phraseanet
lib/classes/patch/383alpha5a.php
patch_383alpha5a.apply
public function apply(base $appbox, Application $app) { $config = $app['phraseanet.configuration']->getConfig(); $config['main']['task-manager']['logger'] = [ 'enabled' => true, 'max-files' => 10, 'level' => 'INFO', ]; $app['phraseanet.configuration']->setConfig($config); return true; }
php
public function apply(base $appbox, Application $app) { $config = $app['phraseanet.configuration']->getConfig(); $config['main']['task-manager']['logger'] = [ 'enabled' => true, 'max-files' => 10, 'level' => 'INFO', ]; $app['phraseanet.configuration']->setConfig($config); return true; }
[ "public", "function", "apply", "(", "base", "$", "appbox", ",", "Application", "$", "app", ")", "{", "$", "config", "=", "$", "app", "[", "'phraseanet.configuration'", "]", "->", "getConfig", "(", ")", ";", "$", "config", "[", "'main'", "]", "[", "'tas...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/383alpha5a.php#L49-L62
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Model/Manipulator/TokenManipulator.php
TokenManipulator.create
public function create(User $user = null, $type, \DateTime $expiration = null, $data = null) { $this->removeExpiredTokens(); $n = 0; do { if ($n++ > 1024) { throw new \RuntimeException('Unable to create a token.'); } $value = $this->random->generateString(32, self::LETTERS_AND_NUMBERS); $found = null !== $this->om->getRepository('Phraseanet:Token')->find($value); } while ($found); $token = new Token(); $token->setUser($user) ->setType($type) ->setValue($value) ->setExpiration($expiration) ->setData($data); $this->om->persist($token); $this->om->flush(); return $token; }
php
public function create(User $user = null, $type, \DateTime $expiration = null, $data = null) { $this->removeExpiredTokens(); $n = 0; do { if ($n++ > 1024) { throw new \RuntimeException('Unable to create a token.'); } $value = $this->random->generateString(32, self::LETTERS_AND_NUMBERS); $found = null !== $this->om->getRepository('Phraseanet:Token')->find($value); } while ($found); $token = new Token(); $token->setUser($user) ->setType($type) ->setValue($value) ->setExpiration($expiration) ->setData($data); $this->om->persist($token); $this->om->flush(); return $token; }
[ "public", "function", "create", "(", "User", "$", "user", "=", "null", ",", "$", "type", ",", "\\", "DateTime", "$", "expiration", "=", "null", ",", "$", "data", "=", "null", ")", "{", "$", "this", "->", "removeExpiredTokens", "(", ")", ";", "$", "...
@param User|null $user @param string $type @param \DateTime|null $expiration @param mixed|null $data @return Token
[ "@param", "User|null", "$user", "@param", "string", "$type", "@param", "\\", "DateTime|null", "$expiration", "@param", "mixed|null", "$data" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Manipulator/TokenManipulator.php#L65-L90
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Model/Manipulator/TokenManipulator.php
TokenManipulator.createBasketValidationToken
public function createBasketValidationToken(Basket $basket, User $user = null) { if (null === $basket->getValidation()) { throw new \InvalidArgumentException('A validation token requires a validation basket.'); } return $this->create($user ?: $basket->getValidation()->getInitiator(), self::TYPE_VALIDATE, new \DateTime('+10 days'), $basket->getId()); }
php
public function createBasketValidationToken(Basket $basket, User $user = null) { if (null === $basket->getValidation()) { throw new \InvalidArgumentException('A validation token requires a validation basket.'); } return $this->create($user ?: $basket->getValidation()->getInitiator(), self::TYPE_VALIDATE, new \DateTime('+10 days'), $basket->getId()); }
[ "public", "function", "createBasketValidationToken", "(", "Basket", "$", "basket", ",", "User", "$", "user", "=", "null", ")", "{", "if", "(", "null", "===", "$", "basket", "->", "getValidation", "(", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentEx...
@param Basket $basket @param User $user @return Token
[ "@param", "Basket", "$basket", "@param", "User", "$user" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Manipulator/TokenManipulator.php#L98-L105
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Model/Manipulator/TokenManipulator.php
TokenManipulator.createBasketAccessToken
public function createBasketAccessToken(Basket $basket, User $user) { return $this->create($user, self::TYPE_VIEW, null, $basket->getId()); }
php
public function createBasketAccessToken(Basket $basket, User $user) { return $this->create($user, self::TYPE_VIEW, null, $basket->getId()); }
[ "public", "function", "createBasketAccessToken", "(", "Basket", "$", "basket", ",", "User", "$", "user", ")", "{", "return", "$", "this", "->", "create", "(", "$", "user", ",", "self", "::", "TYPE_VIEW", ",", "null", ",", "$", "basket", "->", "getId", ...
@param Basket $basket @param User $user @return Token
[ "@param", "Basket", "$basket", "@param", "User", "$user" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Manipulator/TokenManipulator.php#L113-L116
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Model/Manipulator/TokenManipulator.php
TokenManipulator.createFeedEntryToken
public function createFeedEntryToken(User $user, FeedEntry $entry) { return $this->create($user, self::TYPE_FEED_ENTRY, null, $entry->getId()); }
php
public function createFeedEntryToken(User $user, FeedEntry $entry) { return $this->create($user, self::TYPE_FEED_ENTRY, null, $entry->getId()); }
[ "public", "function", "createFeedEntryToken", "(", "User", "$", "user", ",", "FeedEntry", "$", "entry", ")", "{", "return", "$", "this", "->", "create", "(", "$", "user", ",", "self", "::", "TYPE_FEED_ENTRY", ",", "null", ",", "$", "entry", "->", "getId"...
@param User $user @param FeedEntry $entry @return Token
[ "@param", "User", "$user", "@param", "FeedEntry", "$entry" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Manipulator/TokenManipulator.php#L124-L127
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Model/Manipulator/TokenManipulator.php
TokenManipulator.createDownloadToken
public function createDownloadToken(User $user, $data) { return $this->create($user, self::TYPE_DOWNLOAD, new \DateTime('+3 hours'), $data); }
php
public function createDownloadToken(User $user, $data) { return $this->create($user, self::TYPE_DOWNLOAD, new \DateTime('+3 hours'), $data); }
[ "public", "function", "createDownloadToken", "(", "User", "$", "user", ",", "$", "data", ")", "{", "return", "$", "this", "->", "create", "(", "$", "user", ",", "self", "::", "TYPE_DOWNLOAD", ",", "new", "\\", "DateTime", "(", "'+3 hours'", ")", ",", "...
@param User $user @param $data @return Token
[ "@param", "User", "$user", "@param", "$data" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Manipulator/TokenManipulator.php#L135-L138
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Model/Manipulator/TokenManipulator.php
TokenManipulator.createResetEmailToken
public function createResetEmailToken(User $user, $email) { return $this->create($user, self::TYPE_EMAIL_RESET, new \DateTime('+1 day'), $email); }
php
public function createResetEmailToken(User $user, $email) { return $this->create($user, self::TYPE_EMAIL_RESET, new \DateTime('+1 day'), $email); }
[ "public", "function", "createResetEmailToken", "(", "User", "$", "user", ",", "$", "email", ")", "{", "return", "$", "this", "->", "create", "(", "$", "user", ",", "self", "::", "TYPE_EMAIL_RESET", ",", "new", "\\", "DateTime", "(", "'+1 day'", ")", ",",...
@param User $user @param $email @return Token
[ "@param", "User", "$user", "@param", "$email" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Manipulator/TokenManipulator.php#L156-L159
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Model/Manipulator/TokenManipulator.php
TokenManipulator.createAccountDeleteToken
public function createAccountDeleteToken(User $user, $email) { return $this->create($user, self::TYPE_ACCOUNT_DELETE, new \DateTime('+1 hour'), $email); }
php
public function createAccountDeleteToken(User $user, $email) { return $this->create($user, self::TYPE_ACCOUNT_DELETE, new \DateTime('+1 hour'), $email); }
[ "public", "function", "createAccountDeleteToken", "(", "User", "$", "user", ",", "$", "email", ")", "{", "return", "$", "this", "->", "create", "(", "$", "user", ",", "self", "::", "TYPE_ACCOUNT_DELETE", ",", "new", "\\", "DateTime", "(", "'+1 hour'", ")",...
@param User $user @return Token
[ "@param", "User", "$user" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Manipulator/TokenManipulator.php#L176-L179
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Model/Manipulator/TokenManipulator.php
TokenManipulator.update
public function update(Token $token) { $this->om->persist($token); $this->om->flush(); return $token; }
php
public function update(Token $token) { $this->om->persist($token); $this->om->flush(); return $token; }
[ "public", "function", "update", "(", "Token", "$", "token", ")", "{", "$", "this", "->", "om", "->", "persist", "(", "$", "token", ")", ";", "$", "this", "->", "om", "->", "flush", "(", ")", ";", "return", "$", "token", ";", "}" ]
Updates a token. @param Token $token @return Token
[ "Updates", "a", "token", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Manipulator/TokenManipulator.php#L198-L204
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Model/Manipulator/TokenManipulator.php
TokenManipulator.delete
public function delete(Token $token) { $this->om->remove($token); $this->om->flush(); }
php
public function delete(Token $token) { $this->om->remove($token); $this->om->flush(); }
[ "public", "function", "delete", "(", "Token", "$", "token", ")", "{", "$", "this", "->", "om", "->", "remove", "(", "$", "token", ")", ";", "$", "this", "->", "om", "->", "flush", "(", ")", ";", "}" ]
Removes a token. @param Token $token
[ "Removes", "a", "token", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Manipulator/TokenManipulator.php#L211-L215
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Model/Manipulator/TokenManipulator.php
TokenManipulator.removeExpiredTokens
public function removeExpiredTokens() { foreach ($this->repository->findExpiredTokens() as $token) { switch ($token->getType()) { case 'download': case 'email': $file = $this->temporaryDownloadPath . '/' . $token->getValue() . '.zip'; if (is_file($file)) { unlink($file); } break; } $this->om->remove($token); } $this->om->flush(); }
php
public function removeExpiredTokens() { foreach ($this->repository->findExpiredTokens() as $token) { switch ($token->getType()) { case 'download': case 'email': $file = $this->temporaryDownloadPath . '/' . $token->getValue() . '.zip'; if (is_file($file)) { unlink($file); } break; } $this->om->remove($token); } $this->om->flush(); }
[ "public", "function", "removeExpiredTokens", "(", ")", "{", "foreach", "(", "$", "this", "->", "repository", "->", "findExpiredTokens", "(", ")", "as", "$", "token", ")", "{", "switch", "(", "$", "token", "->", "getType", "(", ")", ")", "{", "case", "'...
Removes expired tokens
[ "Removes", "expired", "tokens" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Manipulator/TokenManipulator.php#L220-L235
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/SearchEngine/Elastic/Indexer/RecordIndexer.php
RecordIndexer.onBulkFlush
private function onBulkFlush(databox $databox, array $operation_identifiers, array &$submitted_records) { // nb: because the same bulk could be used by many "clients", this (each) callback may receive // operation_identifiers that does not belong to it. // flag only records that the fetcher worked on $records = array_intersect_key( $submitted_records, // this is OUR records list $operation_identifiers // reduce to the records indexed by this bulk (should be the same...) ); if (count($records) === 0) { return; } // Commit and remove "indexing" flag RecordQueuer::didFinishIndexingRecords(array_values($records), $databox); foreach (array_keys($records) as $id) { unset($submitted_records[$id]); } }
php
private function onBulkFlush(databox $databox, array $operation_identifiers, array &$submitted_records) { // nb: because the same bulk could be used by many "clients", this (each) callback may receive // operation_identifiers that does not belong to it. // flag only records that the fetcher worked on $records = array_intersect_key( $submitted_records, // this is OUR records list $operation_identifiers // reduce to the records indexed by this bulk (should be the same...) ); if (count($records) === 0) { return; } // Commit and remove "indexing" flag RecordQueuer::didFinishIndexingRecords(array_values($records), $databox); foreach (array_keys($records) as $id) { unset($submitted_records[$id]); } }
[ "private", "function", "onBulkFlush", "(", "databox", "$", "databox", ",", "array", "$", "operation_identifiers", ",", "array", "&", "$", "submitted_records", ")", "{", "// nb: because the same bulk could be used by many \"clients\", this (each) callback may receive", "// opera...
ES made a bulk op, check our (index) operations to drop the "indexing" & "to_index" jetons @param databox $databox @param array $operation_identifiers key:op_identifier ; value:operation result (json from es) @param array $submitted_records records indexed, key:op_identifier
[ "ES", "made", "a", "bulk", "op", "check", "our", "(", "index", ")", "operations", "to", "drop", "the", "indexing", "&", "to_index", "jetons" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/Elastic/Indexer/RecordIndexer.php#L91-L111
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/SearchEngine/Elastic/Indexer/RecordIndexer.php
RecordIndexer.populateIndex
public function populateIndex(BulkOperation $bulk, databox $databox) { $this->logger->info(sprintf('Indexing database %s...', $databox->get_viewname())); $submitted_records = []; // No delegate, scan all records $fetcher = $this->fetcherFactory->createFetcher($databox); // post fetch : flag records as "indexing" $fetcher->setPostFetch(function(array $records) use ($databox, $fetcher) { RecordQueuer::didStartIndexingRecords($records, $databox); // do not restart the fetcher since it has no clause on jetons }); // bulk flush : flag records as "indexed" $bulk->onFlush(function($operation_identifiers) use ($databox, &$submitted_records) { $this->onBulkFlush($databox, $operation_identifiers, $submitted_records); }); // Perform indexing $this->indexFromFetcher($bulk, $fetcher, $submitted_records); $this->logger->info(sprintf('Finished indexing %s', $databox->get_viewname())); }
php
public function populateIndex(BulkOperation $bulk, databox $databox) { $this->logger->info(sprintf('Indexing database %s...', $databox->get_viewname())); $submitted_records = []; // No delegate, scan all records $fetcher = $this->fetcherFactory->createFetcher($databox); // post fetch : flag records as "indexing" $fetcher->setPostFetch(function(array $records) use ($databox, $fetcher) { RecordQueuer::didStartIndexingRecords($records, $databox); // do not restart the fetcher since it has no clause on jetons }); // bulk flush : flag records as "indexed" $bulk->onFlush(function($operation_identifiers) use ($databox, &$submitted_records) { $this->onBulkFlush($databox, $operation_identifiers, $submitted_records); }); // Perform indexing $this->indexFromFetcher($bulk, $fetcher, $submitted_records); $this->logger->info(sprintf('Finished indexing %s', $databox->get_viewname())); }
[ "public", "function", "populateIndex", "(", "BulkOperation", "$", "bulk", ",", "databox", "$", "databox", ")", "{", "$", "this", "->", "logger", "->", "info", "(", "sprintf", "(", "'Indexing database %s...'", ",", "$", "databox", "->", "get_viewname", "(", "...
index whole databox(es), don't test actual "jetons" called by command "populate" @param BulkOperation $bulk @param databox $databox
[ "index", "whole", "databox", "(", "es", ")", "don", "t", "test", "actual", "jetons", "called", "by", "command", "populate" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/Elastic/Indexer/RecordIndexer.php#L120-L143
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/SearchEngine/Elastic/Indexer/RecordIndexer.php
RecordIndexer.indexScheduled
public function indexScheduled(BulkOperation $bulk, databox $databox) { $submitted_records = []; // Make fetcher $delegate = new ScheduledFetcherDelegate(); $fetcher = $this->fetcherFactory->createFetcher($databox, $delegate); // post fetch : flag records as "indexing" $fetcher->setPostFetch(function(array $records) use ($databox, $fetcher) { $this->logger->debug(sprintf("indexing %d records", count($records))); RecordQueuer::didStartIndexingRecords($records, $databox); // because changing the flag on the records affects the "where" clause of the fetcher, // restart it each time $fetcher->restart(); }); // bulk flush : flag records as "indexed" $bulk->onFlush(function($operation_identifiers) use ($databox, &$submitted_records) { $this->onBulkFlush($databox, $operation_identifiers, $submitted_records); }); // Perform indexing $this->indexFromFetcher($bulk, $fetcher, $submitted_records); }
php
public function indexScheduled(BulkOperation $bulk, databox $databox) { $submitted_records = []; // Make fetcher $delegate = new ScheduledFetcherDelegate(); $fetcher = $this->fetcherFactory->createFetcher($databox, $delegate); // post fetch : flag records as "indexing" $fetcher->setPostFetch(function(array $records) use ($databox, $fetcher) { $this->logger->debug(sprintf("indexing %d records", count($records))); RecordQueuer::didStartIndexingRecords($records, $databox); // because changing the flag on the records affects the "where" clause of the fetcher, // restart it each time $fetcher->restart(); }); // bulk flush : flag records as "indexed" $bulk->onFlush(function($operation_identifiers) use ($databox, &$submitted_records) { $this->onBulkFlush($databox, $operation_identifiers, $submitted_records); }); // Perform indexing $this->indexFromFetcher($bulk, $fetcher, $submitted_records); }
[ "public", "function", "indexScheduled", "(", "BulkOperation", "$", "bulk", ",", "databox", "$", "databox", ")", "{", "$", "submitted_records", "=", "[", "]", ";", "// Make fetcher", "$", "delegate", "=", "new", "ScheduledFetcherDelegate", "(", ")", ";", "$", ...
Index the records flagged as "to_index" on databox called by task "indexer" @param BulkOperation $bulk @param databox $databox
[ "Index", "the", "records", "flagged", "as", "to_index", "on", "databox", "called", "by", "task", "indexer" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/Elastic/Indexer/RecordIndexer.php#L152-L176
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/SearchEngine/Elastic/Indexer/RecordIndexer.php
RecordIndexer.index
public function index(BulkOperation $bulk, Iterator $records) { foreach ($this->createFetchersForRecords($records) as $fetcher) { $submitted_records = []; $databox = $fetcher->getDatabox(); // post fetch : flag records as "indexing" $fetcher->setPostFetch(function(array $records) use ($fetcher, $databox) { RecordQueuer::didStartIndexingRecords($records, $databox); // do not restart the fetcher since it has no clause on jetons }); // bulk flush : flag records as "indexed" $bulk->onFlush(function($operation_identifiers) use ($databox, &$submitted_records) { $this->onBulkFlush($databox, $operation_identifiers, $submitted_records); }); // Perform indexing $this->indexFromFetcher($bulk, $fetcher, $submitted_records); } }
php
public function index(BulkOperation $bulk, Iterator $records) { foreach ($this->createFetchersForRecords($records) as $fetcher) { $submitted_records = []; $databox = $fetcher->getDatabox(); // post fetch : flag records as "indexing" $fetcher->setPostFetch(function(array $records) use ($fetcher, $databox) { RecordQueuer::didStartIndexingRecords($records, $databox); // do not restart the fetcher since it has no clause on jetons }); // bulk flush : flag records as "indexed" $bulk->onFlush(function($operation_identifiers) use ($databox, &$submitted_records) { $this->onBulkFlush($databox, $operation_identifiers, $submitted_records); }); // Perform indexing $this->indexFromFetcher($bulk, $fetcher, $submitted_records); } }
[ "public", "function", "index", "(", "BulkOperation", "$", "bulk", ",", "Iterator", "$", "records", ")", "{", "foreach", "(", "$", "this", "->", "createFetchersForRecords", "(", "$", "records", ")", "as", "$", "fetcher", ")", "{", "$", "submitted_records", ...
Index a list of records @param BulkOperation $bulk @param Iterator $records
[ "Index", "a", "list", "of", "records" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/Elastic/Indexer/RecordIndexer.php#L184-L204
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/SearchEngine/Elastic/Indexer/RecordIndexer.php
RecordIndexer.delete
public function delete(BulkOperation $bulk, Iterator $records) { foreach ($records as $record) { $bulk->delete([ 'id' => $record->getId(), 'type' => self::TYPE_NAME ], null); } }
php
public function delete(BulkOperation $bulk, Iterator $records) { foreach ($records as $record) { $bulk->delete([ 'id' => $record->getId(), 'type' => self::TYPE_NAME ], null); } }
[ "public", "function", "delete", "(", "BulkOperation", "$", "bulk", ",", "Iterator", "$", "records", ")", "{", "foreach", "(", "$", "records", "as", "$", "record", ")", "{", "$", "bulk", "->", "delete", "(", "[", "'id'", "=>", "$", "record", "->", "ge...
Deleta a list of records @param BulkOperation $bulk @param Iterator $records
[ "Deleta", "a", "list", "of", "records" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/Elastic/Indexer/RecordIndexer.php#L212-L220
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Authentication/Provider/Viadeo.php
Viadeo.logout
public function logout() { try { $request = $this->client->get('https://secure.viadeo.com/oauth-provider/revoke_access_token2'); $request ->getQuery() ->add('access_token', $this->session->get('viadeo.provider.access_token')) ->add('client_id', $this->key) ->add('client_secret', $this->secret); $request->setHeader('Accept', 'application/json'); $response = $request->send(); } catch (GuzzleException $e) { throw new RuntimeException('Unable to revoke token from Viadeo', $e->getCode(), $e); } if (302 !== $response->getStatusCode()) { throw new RuntimeException('Error while revoking access token'); } }
php
public function logout() { try { $request = $this->client->get('https://secure.viadeo.com/oauth-provider/revoke_access_token2'); $request ->getQuery() ->add('access_token', $this->session->get('viadeo.provider.access_token')) ->add('client_id', $this->key) ->add('client_secret', $this->secret); $request->setHeader('Accept', 'application/json'); $response = $request->send(); } catch (GuzzleException $e) { throw new RuntimeException('Unable to revoke token from Viadeo', $e->getCode(), $e); } if (302 !== $response->getStatusCode()) { throw new RuntimeException('Error while revoking access token'); } }
[ "public", "function", "logout", "(", ")", "{", "try", "{", "$", "request", "=", "$", "this", "->", "client", "->", "get", "(", "'https://secure.viadeo.com/oauth-provider/revoke_access_token2'", ")", ";", "$", "request", "->", "getQuery", "(", ")", "->", "add",...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/Provider/Viadeo.php#L105-L125
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Authentication/Provider/Viadeo.php
Viadeo.getIdentity
public function getIdentity() { $identity = new Identity(); try { $request = $this->client->get('https://api.viadeo.com/me?secure=true'); $request->getQuery() ->add('access_token', $this->session->get('viadeo.provider.access_token')); $request->setHeader('Accept', 'application/json'); $response = $request->send(); } catch (GuzzleException $e) { throw new NotAuthenticatedException('Unable to retrieve Viadeo identity'); } if (200 !== $response->getStatusCode()) { throw new NotAuthenticatedException('Error while retrieving user info'); } $data = @json_decode($response->getBody(true), true); if (JSON_ERROR_NONE !== json_last_error()) { throw new NotAuthenticatedException('Unable to parse Viadeo identity.'); } $identity->set(Identity::PROPERTY_FIRSTNAME, $data['first_name']); $identity->set(Identity::PROPERTY_ID, $data['id']); $identity->set(Identity::PROPERTY_IMAGEURL, $data['picture_large']); $identity->set(Identity::PROPERTY_LASTNAME, $data['last_name']); $identity->set(Identity::PROPERTY_USERNAME, $data['nickname']); try { $request = $this->client->get('https://api.viadeo.com/me/career?secure=true'); $request->getQuery()->add('access_token', $this->session->get('viadeo.provider.access_token')); $request->setHeader('Accept', 'application/json'); $response = $request->send(); } catch (GuzzleException $e) { throw new NotAuthenticatedException('Unable to retrieve Viadeo career information.'); } if (200 !== $response->getStatusCode()) { throw new NotAuthenticatedException('Error while retrieving company info'); } $data = @json_decode($response->getBody(true), true); if (JSON_ERROR_NONE !== json_last_error()) { throw new NotAuthenticatedException('Unable to parse Viadeo career informations.'); } if (0 < count($data['data'])) { $job = array_shift($data['data']); $identity->set(Identity::PROPERTY_COMPANY, $job['company_name']); } return $identity; }
php
public function getIdentity() { $identity = new Identity(); try { $request = $this->client->get('https://api.viadeo.com/me?secure=true'); $request->getQuery() ->add('access_token', $this->session->get('viadeo.provider.access_token')); $request->setHeader('Accept', 'application/json'); $response = $request->send(); } catch (GuzzleException $e) { throw new NotAuthenticatedException('Unable to retrieve Viadeo identity'); } if (200 !== $response->getStatusCode()) { throw new NotAuthenticatedException('Error while retrieving user info'); } $data = @json_decode($response->getBody(true), true); if (JSON_ERROR_NONE !== json_last_error()) { throw new NotAuthenticatedException('Unable to parse Viadeo identity.'); } $identity->set(Identity::PROPERTY_FIRSTNAME, $data['first_name']); $identity->set(Identity::PROPERTY_ID, $data['id']); $identity->set(Identity::PROPERTY_IMAGEURL, $data['picture_large']); $identity->set(Identity::PROPERTY_LASTNAME, $data['last_name']); $identity->set(Identity::PROPERTY_USERNAME, $data['nickname']); try { $request = $this->client->get('https://api.viadeo.com/me/career?secure=true'); $request->getQuery()->add('access_token', $this->session->get('viadeo.provider.access_token')); $request->setHeader('Accept', 'application/json'); $response = $request->send(); } catch (GuzzleException $e) { throw new NotAuthenticatedException('Unable to retrieve Viadeo career information.'); } if (200 !== $response->getStatusCode()) { throw new NotAuthenticatedException('Error while retrieving company info'); } $data = @json_decode($response->getBody(true), true); if (JSON_ERROR_NONE !== json_last_error()) { throw new NotAuthenticatedException('Unable to parse Viadeo career informations.'); } if (0 < count($data['data'])) { $job = array_shift($data['data']); $identity->set(Identity::PROPERTY_COMPANY, $job['company_name']); } return $identity; }
[ "public", "function", "getIdentity", "(", ")", "{", "$", "identity", "=", "new", "Identity", "(", ")", ";", "try", "{", "$", "request", "=", "$", "this", "->", "client", "->", "get", "(", "'https://api.viadeo.com/me?secure=true'", ")", ";", "$", "request",...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/Provider/Viadeo.php#L207-L264
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Authentication/Provider/Viadeo.php
Viadeo.create
public static function create(UrlGenerator $generator, SessionInterface $session, array $options) { if (!isset($options['client-id'])) { throw new InvalidArgumentException('Missing Viadeo client-id parameter'); } if (!isset($options['client-secret'])) { throw new InvalidArgumentException('Missing Viadeo client-secret parameter'); } return new Viadeo($generator, $session, new Guzzle(), $options['client-id'], $options['client-secret']); }
php
public static function create(UrlGenerator $generator, SessionInterface $session, array $options) { if (!isset($options['client-id'])) { throw new InvalidArgumentException('Missing Viadeo client-id parameter'); } if (!isset($options['client-secret'])) { throw new InvalidArgumentException('Missing Viadeo client-secret parameter'); } return new Viadeo($generator, $session, new Guzzle(), $options['client-id'], $options['client-secret']); }
[ "public", "static", "function", "create", "(", "UrlGenerator", "$", "generator", ",", "SessionInterface", "$", "session", ",", "array", "$", "options", ")", "{", "if", "(", "!", "isset", "(", "$", "options", "[", "'client-id'", "]", ")", ")", "{", "throw...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/Provider/Viadeo.php#L327-L338
alchemy-fr/Phraseanet
lib/classes/patch/390alpha19a.php
patch_390alpha19a.apply
public function apply(base $appbox, Application $app) { $storage = $app['conf']->get(['main', 'storage']); $storage['cache'] = $app['root.path'].'/cache'; $storage['log'] = $app['root.path'].'/logs'; $storage['download'] = $app['root.path'].'/tmp/download'; $storage['lazaret'] = $app['root.path'].'/tmp/lazaret'; $storage['caption'] = $app['root.path'].'/tmp/caption'; $app['conf']->set(['main', 'storage'], $storage); // update file structure $this->removeDirectory($app, $app['root.path'].'/tmp/cache_twig'); $this->removeDirectory($app, $app['root.path'].'/tmp/doctrine'); $this->removeDirectory($app, $app['root.path'].'/tmp/profiler'); $this->removeDirectory($app, $app['root.path'].'/tmp/serializer'); $this->removeDirectory($app, $app['root.path'].'/tmp/translations'); $this->removeDirectory($app, $app['root.path'].'/tmp/cache_minify'); $this->removeDirectory($app, $app['root.path'].'/features'); $this->removeDirectory($app, $app['root.path'].'/hudson'); $this->removeDirectory($app, $app['root.path'].'/locales'); $this->removeDirectory($app, $app['root.path'].'/vagrant'); $this->removeDirectory($app, $app['root.path'].'/tmp/doctrine-proxies'); $this->copyFile($app, $app['root.path'].'/tmp/cache_registry.php', $app['cache.path'].'/cache_registry.php'); $this->copyFile($app, $app['root.path'].'/tmp/configuration-compiled.php', $app['root.path'].'/config/configuration-compiled.php'); return true; }
php
public function apply(base $appbox, Application $app) { $storage = $app['conf']->get(['main', 'storage']); $storage['cache'] = $app['root.path'].'/cache'; $storage['log'] = $app['root.path'].'/logs'; $storage['download'] = $app['root.path'].'/tmp/download'; $storage['lazaret'] = $app['root.path'].'/tmp/lazaret'; $storage['caption'] = $app['root.path'].'/tmp/caption'; $app['conf']->set(['main', 'storage'], $storage); // update file structure $this->removeDirectory($app, $app['root.path'].'/tmp/cache_twig'); $this->removeDirectory($app, $app['root.path'].'/tmp/doctrine'); $this->removeDirectory($app, $app['root.path'].'/tmp/profiler'); $this->removeDirectory($app, $app['root.path'].'/tmp/serializer'); $this->removeDirectory($app, $app['root.path'].'/tmp/translations'); $this->removeDirectory($app, $app['root.path'].'/tmp/cache_minify'); $this->removeDirectory($app, $app['root.path'].'/features'); $this->removeDirectory($app, $app['root.path'].'/hudson'); $this->removeDirectory($app, $app['root.path'].'/locales'); $this->removeDirectory($app, $app['root.path'].'/vagrant'); $this->removeDirectory($app, $app['root.path'].'/tmp/doctrine-proxies'); $this->copyFile($app, $app['root.path'].'/tmp/cache_registry.php', $app['cache.path'].'/cache_registry.php'); $this->copyFile($app, $app['root.path'].'/tmp/configuration-compiled.php', $app['root.path'].'/config/configuration-compiled.php'); return true; }
[ "public", "function", "apply", "(", "base", "$", "appbox", ",", "Application", "$", "app", ")", "{", "$", "storage", "=", "$", "app", "[", "'conf'", "]", "->", "get", "(", "[", "'main'", ",", "'storage'", "]", ")", ";", "$", "storage", "[", "'cache...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/390alpha19a.php#L49-L77
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Application.php
Application.form
public function form($type = 'form', $data = null, array $options = [], FormBuilderInterface $parent = null) { return $this['form.factory']->create($type, $data, $options, $parent); }
php
public function form($type = 'form', $data = null, array $options = [], FormBuilderInterface $parent = null) { return $this['form.factory']->create($type, $data, $options, $parent); }
[ "public", "function", "form", "(", "$", "type", "=", "'form'", ",", "$", "data", "=", "null", ",", "array", "$", "options", "=", "[", "]", ",", "FormBuilderInterface", "$", "parent", "=", "null", ")", "{", "return", "$", "this", "[", "'form.factory'", ...
Returns a form. @see FormFactory::create() @param string|FormTypeInterface $type The type of the form @param mixed $data The initial data @param array $options The options @param FormBuilderInterface $parent The parent builder @return FormInterface The form named after the type @throws ExceptionInterface if any given option is not applicable to the given type
[ "Returns", "a", "form", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Application.php#L328-L331
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Application.php
Application.addFlash
public function addFlash($type, $message) { if (!in_array($type, self::$flashTypes)) { throw new InvalidArgumentException(sprintf( 'Invalid flash message type `%s`, valid type are %s', $type, implode(', ', self::$flashTypes) )); } $this['session']->getFlashBag()->add($type, $message); return $this; }
php
public function addFlash($type, $message) { if (!in_array($type, self::$flashTypes)) { throw new InvalidArgumentException(sprintf( 'Invalid flash message type `%s`, valid type are %s', $type, implode(', ', self::$flashTypes) )); } $this['session']->getFlashBag()->add($type, $message); return $this; }
[ "public", "function", "addFlash", "(", "$", "type", ",", "$", "message", ")", "{", "if", "(", "!", "in_array", "(", "$", "type", ",", "self", "::", "$", "flashTypes", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Inv...
Adds a flash message for type. In Phraseanet, valid types are "warning", "info", "success" and "error" @param string $type @param string $message @return Application @throws InvalidArgumentException In case the type is not valid
[ "Adds", "a", "flash", "message", "for", "type", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Application.php#L371-L382
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Application.php
Application.isGuestAllowed
public function isGuestAllowed() { if (null === $user = $this['repo.users']->findByLogin(User::USER_GUEST)) { return false; } return count($this->getAclForUser($user)->get_granted_base()) > 0; }
php
public function isGuestAllowed() { if (null === $user = $this['repo.users']->findByLogin(User::USER_GUEST)) { return false; } return count($this->getAclForUser($user)->get_granted_base()) > 0; }
[ "public", "function", "isGuestAllowed", "(", ")", "{", "if", "(", "null", "===", "$", "user", "=", "$", "this", "[", "'repo.users'", "]", "->", "findByLogin", "(", "User", "::", "USER_GUEST", ")", ")", "{", "return", "false", ";", "}", "return", "count...
Returns true if guest access is allowed. @return boolean
[ "Returns", "true", "if", "guest", "access", "is", "allowed", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Application.php#L464-L471
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Application.php
Application.bindRoutes
public function bindRoutes() { $loader = new RouteLoader(); $loader->registerProviders(RouteLoader::$defaultProviders); $loader->bindRoutes($this); $this->bindPluginRoutes('plugin.controller_providers.root'); }
php
public function bindRoutes() { $loader = new RouteLoader(); $loader->registerProviders(RouteLoader::$defaultProviders); $loader->bindRoutes($this); $this->bindPluginRoutes('plugin.controller_providers.root'); }
[ "public", "function", "bindRoutes", "(", ")", "{", "$", "loader", "=", "new", "RouteLoader", "(", ")", ";", "$", "loader", "->", "registerProviders", "(", "RouteLoader", "::", "$", "defaultProviders", ")", ";", "$", "loader", "->", "bindRoutes", "(", "$", ...
Mount all controllers
[ "Mount", "all", "controllers" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Application.php#L496-L504
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/SearchEngine/Elastic/ElasticsearchOptions.php
ElasticsearchOptions.fromArray
public static function fromArray(array $options) { $defaultOptions = [ 'host' => '127.0.0.1', 'port' => 9200, 'index' => '', 'shards' => 3, 'replicas' => 0, 'minScore' => 4, 'highlight' => true, 'populate_order' => self::POPULATE_ORDER_RID, 'populate_direction' => self::POPULATE_DIRECTION_DESC, 'activeTab' => null, ]; foreach(self::getAggregableTechnicalFields() as $k => $f) { $defaultOptions[$k.'_limit'] = 0; } $options = array_replace($defaultOptions, $options); $self = new self(); $self->setHost($options['host']); $self->setPort($options['port']); $self->setIndexName($options['index']); $self->setShards($options['shards']); $self->setReplicas($options['replicas']); $self->setMinScore($options['minScore']); $self->setHighlight($options['highlight']); $self->setPopulateOrder($options['populate_order']); $self->setPopulateDirection($options['populate_direction']); $self->setActiveTab($options['activeTab']); foreach(self::getAggregableTechnicalFields() as $k => $f) { $self->setAggregableFieldLimit($k, $options[$k.'_limit']); } return $self; }
php
public static function fromArray(array $options) { $defaultOptions = [ 'host' => '127.0.0.1', 'port' => 9200, 'index' => '', 'shards' => 3, 'replicas' => 0, 'minScore' => 4, 'highlight' => true, 'populate_order' => self::POPULATE_ORDER_RID, 'populate_direction' => self::POPULATE_DIRECTION_DESC, 'activeTab' => null, ]; foreach(self::getAggregableTechnicalFields() as $k => $f) { $defaultOptions[$k.'_limit'] = 0; } $options = array_replace($defaultOptions, $options); $self = new self(); $self->setHost($options['host']); $self->setPort($options['port']); $self->setIndexName($options['index']); $self->setShards($options['shards']); $self->setReplicas($options['replicas']); $self->setMinScore($options['minScore']); $self->setHighlight($options['highlight']); $self->setPopulateOrder($options['populate_order']); $self->setPopulateDirection($options['populate_direction']); $self->setActiveTab($options['activeTab']); foreach(self::getAggregableTechnicalFields() as $k => $f) { $self->setAggregableFieldLimit($k, $options[$k.'_limit']); } return $self; }
[ "public", "static", "function", "fromArray", "(", "array", "$", "options", ")", "{", "$", "defaultOptions", "=", "[", "'host'", "=>", "'127.0.0.1'", ",", "'port'", "=>", "9200", ",", "'index'", "=>", "''", ",", "'shards'", "=>", "3", ",", "'replicas'", "...
Factory method to hydrate an instance from serialized options @param array $options @return self
[ "Factory", "method", "to", "hydrate", "an", "instance", "from", "serialized", "options" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/Elastic/ElasticsearchOptions.php#L47-L85
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/TaskManager/Editor/SubdefsEditor.php
SubdefsEditor.getFormProperties
protected function getFormProperties() { return [ 'sbas[]' => static::FORM_TYPE_INTEGER, 'type_image' => static::FORM_TYPE_BOOLEAN, 'type_video' => static::FORM_TYPE_BOOLEAN, 'type_audio' => static::FORM_TYPE_BOOLEAN, 'type_document' => static::FORM_TYPE_BOOLEAN, 'type_flash' => static::FORM_TYPE_BOOLEAN, 'type_unknown' => static::FORM_TYPE_BOOLEAN, 'flush' => static::FORM_TYPE_INTEGER, 'maxrecs' => static::FORM_TYPE_INTEGER, 'maxmegs' => static::FORM_TYPE_INTEGER, 'embedded' => static::FORM_TYPE_BOOLEAN, ]; }
php
protected function getFormProperties() { return [ 'sbas[]' => static::FORM_TYPE_INTEGER, 'type_image' => static::FORM_TYPE_BOOLEAN, 'type_video' => static::FORM_TYPE_BOOLEAN, 'type_audio' => static::FORM_TYPE_BOOLEAN, 'type_document' => static::FORM_TYPE_BOOLEAN, 'type_flash' => static::FORM_TYPE_BOOLEAN, 'type_unknown' => static::FORM_TYPE_BOOLEAN, 'flush' => static::FORM_TYPE_INTEGER, 'maxrecs' => static::FORM_TYPE_INTEGER, 'maxmegs' => static::FORM_TYPE_INTEGER, 'embedded' => static::FORM_TYPE_BOOLEAN, ]; }
[ "protected", "function", "getFormProperties", "(", ")", "{", "return", "[", "'sbas[]'", "=>", "static", "::", "FORM_TYPE_INTEGER", ",", "'type_image'", "=>", "static", "::", "FORM_TYPE_BOOLEAN", ",", "'type_video'", "=>", "static", "::", "FORM_TYPE_BOOLEAN", ",", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/TaskManager/Editor/SubdefsEditor.php#L64-L79
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/TaskManager/Editor/SubdefsEditor.php
SubdefsEditor.updateXMLWithRequest
public function updateXMLWithRequest(Request $request) { $dom = $this->createBlankDom(); $dom->formatOutput = true; $dom->preserveWhiteSpace = false; if (false === @$dom->loadXML($request->request->get('xml'))) { throw new BadRequestHttpException('Invalid XML data.'); } // delete empty /text-nodes so the output can be better formatted $nodesToDel = array(); for($node = $dom->documentElement->firstChild; $node; $node=$node->nextSibling) { if($node->nodeType == XML_TEXT_NODE && trim($node->data)=="") { $nodesToDel[] = $node; } } foreach($nodesToDel as $node) { $dom->documentElement->removeChild($node); } $dom->normalizeDocument(); foreach ($this->getFormProperties() as $name => $type) { $multi = false; if(substr($name, -2)== "[]") { $multi = true; $name = substr($name, 0, strlen($name)-2); } $values = $request->request->get($name); if($values === null && !$multi) { switch($type) { case static::FORM_TYPE_INTEGER: case static::FORM_TYPE_BOOLEAN: $values = "0"; break; case static::FORM_TYPE_STRING: $values = ""; break; } } // erase the former setting but keep the node in place. // in case on multi-valued, keep only the first node (except if no value at all: erase all) $nodesToDel = array(); foreach($dom->getElementsByTagName($name) as $i=>$node) { // empty while ($child = $node->firstChild) { $node->removeChild($child); } // keep the first for multi, only if there is something to write if($i > 0 || ($multi && $values===null) ) { $nodesToDel[] = $node; } } foreach($nodesToDel as $node) { $dom->documentElement->removeChild($node); } // if no multiple-setting to write, no reason to create an empty node if($values === null) { continue; } if(!is_array($values)) { $values = array($values); } // in case the node did not exist at all, create one if ( ($node = $dom->getElementsByTagName($name)->item(0)) === null) { $node = $dom->documentElement->appendChild($dom->createElement($name)); } // because dom::insertBefore is used, reverse allows to respect order while serializing. $values = array_reverse($values); // write foreach($values as $i=>$value) { if($i>0) { // multi-valued ? add an entry $node = $dom->documentElement->insertBefore($dom->createElement($name), $node); } $node->appendChild($dom->createTextNode($this->toXMLValue($type, $value))); } } $dom->normalizeDocument(); return new Response($dom->saveXML(), 200, ['Content-type' => 'text/xml']); }
php
public function updateXMLWithRequest(Request $request) { $dom = $this->createBlankDom(); $dom->formatOutput = true; $dom->preserveWhiteSpace = false; if (false === @$dom->loadXML($request->request->get('xml'))) { throw new BadRequestHttpException('Invalid XML data.'); } // delete empty /text-nodes so the output can be better formatted $nodesToDel = array(); for($node = $dom->documentElement->firstChild; $node; $node=$node->nextSibling) { if($node->nodeType == XML_TEXT_NODE && trim($node->data)=="") { $nodesToDel[] = $node; } } foreach($nodesToDel as $node) { $dom->documentElement->removeChild($node); } $dom->normalizeDocument(); foreach ($this->getFormProperties() as $name => $type) { $multi = false; if(substr($name, -2)== "[]") { $multi = true; $name = substr($name, 0, strlen($name)-2); } $values = $request->request->get($name); if($values === null && !$multi) { switch($type) { case static::FORM_TYPE_INTEGER: case static::FORM_TYPE_BOOLEAN: $values = "0"; break; case static::FORM_TYPE_STRING: $values = ""; break; } } // erase the former setting but keep the node in place. // in case on multi-valued, keep only the first node (except if no value at all: erase all) $nodesToDel = array(); foreach($dom->getElementsByTagName($name) as $i=>$node) { // empty while ($child = $node->firstChild) { $node->removeChild($child); } // keep the first for multi, only if there is something to write if($i > 0 || ($multi && $values===null) ) { $nodesToDel[] = $node; } } foreach($nodesToDel as $node) { $dom->documentElement->removeChild($node); } // if no multiple-setting to write, no reason to create an empty node if($values === null) { continue; } if(!is_array($values)) { $values = array($values); } // in case the node did not exist at all, create one if ( ($node = $dom->getElementsByTagName($name)->item(0)) === null) { $node = $dom->documentElement->appendChild($dom->createElement($name)); } // because dom::insertBefore is used, reverse allows to respect order while serializing. $values = array_reverse($values); // write foreach($values as $i=>$value) { if($i>0) { // multi-valued ? add an entry $node = $dom->documentElement->insertBefore($dom->createElement($name), $node); } $node->appendChild($dom->createTextNode($this->toXMLValue($type, $value))); } } $dom->normalizeDocument(); return new Response($dom->saveXML(), 200, ['Content-type' => 'text/xml']); }
[ "public", "function", "updateXMLWithRequest", "(", "Request", "$", "request", ")", "{", "$", "dom", "=", "$", "this", "->", "createBlankDom", "(", ")", ";", "$", "dom", "->", "formatOutput", "=", "true", ";", "$", "dom", "->", "preserveWhiteSpace", "=", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/TaskManager/Editor/SubdefsEditor.php#L84-L173
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Model/Repositories/UsrListEntryRepository.php
UsrListEntryRepository.findUserList
public function findUserList(User $user) { $dql = 'SELECT e FROM Phraseanet:UsrListEntry e WHERE e.user = :usr_id'; $params = [ 'usr_id' => $user->getId(), ]; $query = $this->_em->createQuery($dql); $query->setParameters($params); return $query->getResult(); }
php
public function findUserList(User $user) { $dql = 'SELECT e FROM Phraseanet:UsrListEntry e WHERE e.user = :usr_id'; $params = [ 'usr_id' => $user->getId(), ]; $query = $this->_em->createQuery($dql); $query->setParameters($params); return $query->getResult(); }
[ "public", "function", "findUserList", "(", "User", "$", "user", ")", "{", "$", "dql", "=", "'SELECT e FROM Phraseanet:UsrListEntry e\n WHERE e.user = :usr_id'", ";", "$", "params", "=", "[", "'usr_id'", "=>", "$", "user", "->", "getId", "(", ")", ",", ...
Get all lists entries matching a given User @param User $user @param type $like
[ "Get", "all", "lists", "entries", "matching", "a", "given", "User" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Repositories/UsrListEntryRepository.php#L37-L50
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Plugin/Importer/FolderImporter.php
FolderImporter.import
public function import($source, $target) { try { $this->fs->mirror($source, $target); } catch (FsException $e) { try { $this->fs->remove($target); } catch (FsException $e) { } throw new ImportFailureException(sprintf('Unable to import from `%s` to `%s`', $source, $target), $e->getCode(), $e); } }
php
public function import($source, $target) { try { $this->fs->mirror($source, $target); } catch (FsException $e) { try { $this->fs->remove($target); } catch (FsException $e) { } throw new ImportFailureException(sprintf('Unable to import from `%s` to `%s`', $source, $target), $e->getCode(), $e); } }
[ "public", "function", "import", "(", "$", "source", ",", "$", "target", ")", "{", "try", "{", "$", "this", "->", "fs", "->", "mirror", "(", "$", "source", ",", "$", "target", ")", ";", "}", "catch", "(", "FsException", "$", "e", ")", "{", "try", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Plugin/Importer/FolderImporter.php#L30-L43
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Prod/LazaretController.php
LazaretController.listElement
public function listElement(Request $request) { $baseIds = array_keys($this->getAclForUser()->get_granted_base([\ACL::CANADDRECORD])); $lazaretFiles = null; $perPage = 10; $page = max(1, $request->query->get('page', 1)); $offset = ($page - 1) * $perPage; if (count($baseIds) > 0) { $lazaretFiles = $this->getLazaretFileRepository()->findPerPage($baseIds, $offset, $perPage); } return $this->render('prod/upload/lazaret.html.twig', [ 'lazaretFiles' => $lazaretFiles, 'currentPage' => $page, 'perPage' => $perPage, ]); }
php
public function listElement(Request $request) { $baseIds = array_keys($this->getAclForUser()->get_granted_base([\ACL::CANADDRECORD])); $lazaretFiles = null; $perPage = 10; $page = max(1, $request->query->get('page', 1)); $offset = ($page - 1) * $perPage; if (count($baseIds) > 0) { $lazaretFiles = $this->getLazaretFileRepository()->findPerPage($baseIds, $offset, $perPage); } return $this->render('prod/upload/lazaret.html.twig', [ 'lazaretFiles' => $lazaretFiles, 'currentPage' => $page, 'perPage' => $perPage, ]); }
[ "public", "function", "listElement", "(", "Request", "$", "request", ")", "{", "$", "baseIds", "=", "array_keys", "(", "$", "this", "->", "getAclForUser", "(", ")", "->", "get_granted_base", "(", "[", "\\", "ACL", "::", "CANADDRECORD", "]", ")", ")", ";"...
List all elements in lazaret @param Request $request The current request @return Response
[ "List", "all", "elements", "in", "lazaret" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Prod/LazaretController.php#L43-L61
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Prod/LazaretController.php
LazaretController.getElement
public function getElement($file_id) { $ret = ['success' => false, 'message' => '', 'result' => []]; /* @var LazaretFile $lazaretFile */ $lazaretFile = $this->getLazaretFileRepository()->find($file_id); if (null === $lazaretFile) { $ret['message'] = $this->app->trans('File is not present in quarantine anymore, please refresh'); return $this->app->json($ret); } $ret['result'] = [ 'filename' => $lazaretFile->getOriginalName(), 'base_id' => $lazaretFile->getBaseId(), 'created' => $lazaretFile->getCreated()->format(\DateTime::ATOM), 'updated' => $lazaretFile->getUpdated()->format(\DateTime::ATOM), 'pathname' => $this->app['tmp.lazaret.path'].'/'.$lazaretFile->getFilename(), 'sha256' => $lazaretFile->getSha256(), 'uuid' => $lazaretFile->getUuid(), ]; $ret['success'] = true; return $this->app->json($ret); }
php
public function getElement($file_id) { $ret = ['success' => false, 'message' => '', 'result' => []]; /* @var LazaretFile $lazaretFile */ $lazaretFile = $this->getLazaretFileRepository()->find($file_id); if (null === $lazaretFile) { $ret['message'] = $this->app->trans('File is not present in quarantine anymore, please refresh'); return $this->app->json($ret); } $ret['result'] = [ 'filename' => $lazaretFile->getOriginalName(), 'base_id' => $lazaretFile->getBaseId(), 'created' => $lazaretFile->getCreated()->format(\DateTime::ATOM), 'updated' => $lazaretFile->getUpdated()->format(\DateTime::ATOM), 'pathname' => $this->app['tmp.lazaret.path'].'/'.$lazaretFile->getFilename(), 'sha256' => $lazaretFile->getSha256(), 'uuid' => $lazaretFile->getUuid(), ]; $ret['success'] = true; return $this->app->json($ret); }
[ "public", "function", "getElement", "(", "$", "file_id", ")", "{", "$", "ret", "=", "[", "'success'", "=>", "false", ",", "'message'", "=>", "''", ",", "'result'", "=>", "[", "]", "]", ";", "/* @var LazaretFile $lazaretFile */", "$", "lazaretFile", "=", "$...
Get one lazaret Element @param int $file_id A lazaret element id @return Response
[ "Get", "one", "lazaret", "Element" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Prod/LazaretController.php#L70-L95
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Prod/LazaretController.php
LazaretController.addElement
public function addElement(Request $request, $file_id) { $ret = ['success' => false, 'message' => '', 'result' => []]; //Mandatory parameter if (null === $request->request->get('bas_id')) { $ret['message'] = $this->app->trans('You must give a destination collection'); return $this->app->json($ret); } //Optional parameter $keepAttributes = !!$request->request->get('keep_attributes', false); $attributesToKeep = $request->request->get('attributes', []); /** @var LazaretManipulator $lazaretManipulator */ $lazaretManipulator = $this->app['manipulator.lazaret']; $ret = $lazaretManipulator->add($file_id, $keepAttributes, $attributesToKeep); return $this->app->json($ret); }
php
public function addElement(Request $request, $file_id) { $ret = ['success' => false, 'message' => '', 'result' => []]; //Mandatory parameter if (null === $request->request->get('bas_id')) { $ret['message'] = $this->app->trans('You must give a destination collection'); return $this->app->json($ret); } //Optional parameter $keepAttributes = !!$request->request->get('keep_attributes', false); $attributesToKeep = $request->request->get('attributes', []); /** @var LazaretManipulator $lazaretManipulator */ $lazaretManipulator = $this->app['manipulator.lazaret']; $ret = $lazaretManipulator->add($file_id, $keepAttributes, $attributesToKeep); return $this->app->json($ret); }
[ "public", "function", "addElement", "(", "Request", "$", "request", ",", "$", "file_id", ")", "{", "$", "ret", "=", "[", "'success'", "=>", "false", ",", "'message'", "=>", "''", ",", "'result'", "=>", "[", "]", "]", ";", "//Mandatory parameter", "if", ...
Add an element to phraseanet @param Request $request The current request @param int $file_id A lazaret element id parameters : 'bas_id' int (mandatory) : The id of the destination collection 'keep_attributes' boolean (optional) : Keep all attributes attached to the lazaret element 'attributes' array (optional) : Attributes id's to attach to the lazaret element @return Response
[ "Add", "an", "element", "to", "phraseanet" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Prod/LazaretController.php#L109-L130
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Prod/LazaretController.php
LazaretController.denyElement
public function denyElement($file_id) { /** @var LazaretManipulator $lazaretManipulator */ $lazaretManipulator = $this->app['manipulator.lazaret']; $ret = $lazaretManipulator->deny($file_id); return $this->app->json($ret); }
php
public function denyElement($file_id) { /** @var LazaretManipulator $lazaretManipulator */ $lazaretManipulator = $this->app['manipulator.lazaret']; $ret = $lazaretManipulator->deny($file_id); return $this->app->json($ret); }
[ "public", "function", "denyElement", "(", "$", "file_id", ")", "{", "/** @var LazaretManipulator $lazaretManipulator */", "$", "lazaretManipulator", "=", "$", "this", "->", "app", "[", "'manipulator.lazaret'", "]", ";", "$", "ret", "=", "$", "lazaretManipulator", "-...
Delete a lazaret element @param int $file_id A lazaret element id @return Response
[ "Delete", "a", "lazaret", "element" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Prod/LazaretController.php#L139-L147
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Prod/LazaretController.php
LazaretController.emptyLazaret
public function emptyLazaret(Request $request) { $maxTodo = -1; // all if($request->get('max') !== null) { $maxTodo = (int)($request->get('max')); } if( $maxTodo <= 0) { $maxTodo = -1; // all } /** @var LazaretManipulator $lazaretManipulator */ $lazaretManipulator = $this->app['manipulator.lazaret']; $ret = $lazaretManipulator->clear($maxTodo); return $this->app->json($ret); }
php
public function emptyLazaret(Request $request) { $maxTodo = -1; // all if($request->get('max') !== null) { $maxTodo = (int)($request->get('max')); } if( $maxTodo <= 0) { $maxTodo = -1; // all } /** @var LazaretManipulator $lazaretManipulator */ $lazaretManipulator = $this->app['manipulator.lazaret']; $ret = $lazaretManipulator->clear($maxTodo); return $this->app->json($ret); }
[ "public", "function", "emptyLazaret", "(", "Request", "$", "request", ")", "{", "$", "maxTodo", "=", "-", "1", ";", "// all", "if", "(", "$", "request", "->", "get", "(", "'max'", ")", "!==", "null", ")", "{", "$", "maxTodo", "=", "(", "int", ")", ...
Empty lazaret @param Request $request @return Response
[ "Empty", "lazaret" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Prod/LazaretController.php#L156-L172
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Prod/LazaretController.php
LazaretController.acceptElement
public function acceptElement(Request $request, $file_id) { $ret = ['success' => false, 'message' => '', 'result' => []]; //Mandatory parameter if (null === $recordId = $request->request->get('record_id')) { $ret['message'] = $this->app->trans('You must give a destination record'); return $this->app->json($ret); } /** @var LazaretFile $lazaretFile */ $lazaretFile = $this->getLazaretFileRepository()->find($file_id); if (null === $lazaretFile) { $ret['message'] = $this->app->trans('File is not present in quarantine anymore, please refresh'); return $this->app->json($ret); } $found = false; //Check if the chosen record is eligible to the substitution foreach ($lazaretFile->getRecordsToSubstitute($this->app) as $record) { if ($record->getRecordId() !== (int) $recordId) { continue; } $found = true; break; } if (!$found) { $ret['message'] = $this->app->trans('The destination record provided is not allowed'); return $this->app->json($ret); } $path = $this->app['tmp.lazaret.path'] . '/'; $lazaretFileName = $path .$lazaretFile->getFilename(); $lazaretThumbFileName = $path .$lazaretFile->getThumbFilename(); try { $media = $this->app->getMediaFromUri($lazaretFileName); $record = $lazaretFile->getCollection($this->app)->get_databox()->get_record($recordId); $this->getSubDefinitionSubstituer()->substituteDocument($record, $media); $this->getDataboxLogger($record->getDatabox())->log( $record, \Session_Logger::EVENT_SUBSTITUTE, 'HD', '' ); //Delete lazaret file $manager = $this->getEntityManager(); $manager->remove($lazaretFile); $manager->flush(); $ret['success'] = true; } catch (\Exception $e) { $ret['message'] = $this->app->trans('An error occured'); } try { $this->getFilesystem()->remove([$lazaretFileName, $lazaretThumbFileName]); } catch (IOException $e) { } return $this->app->json($ret); }
php
public function acceptElement(Request $request, $file_id) { $ret = ['success' => false, 'message' => '', 'result' => []]; //Mandatory parameter if (null === $recordId = $request->request->get('record_id')) { $ret['message'] = $this->app->trans('You must give a destination record'); return $this->app->json($ret); } /** @var LazaretFile $lazaretFile */ $lazaretFile = $this->getLazaretFileRepository()->find($file_id); if (null === $lazaretFile) { $ret['message'] = $this->app->trans('File is not present in quarantine anymore, please refresh'); return $this->app->json($ret); } $found = false; //Check if the chosen record is eligible to the substitution foreach ($lazaretFile->getRecordsToSubstitute($this->app) as $record) { if ($record->getRecordId() !== (int) $recordId) { continue; } $found = true; break; } if (!$found) { $ret['message'] = $this->app->trans('The destination record provided is not allowed'); return $this->app->json($ret); } $path = $this->app['tmp.lazaret.path'] . '/'; $lazaretFileName = $path .$lazaretFile->getFilename(); $lazaretThumbFileName = $path .$lazaretFile->getThumbFilename(); try { $media = $this->app->getMediaFromUri($lazaretFileName); $record = $lazaretFile->getCollection($this->app)->get_databox()->get_record($recordId); $this->getSubDefinitionSubstituer()->substituteDocument($record, $media); $this->getDataboxLogger($record->getDatabox())->log( $record, \Session_Logger::EVENT_SUBSTITUTE, 'HD', '' ); //Delete lazaret file $manager = $this->getEntityManager(); $manager->remove($lazaretFile); $manager->flush(); $ret['success'] = true; } catch (\Exception $e) { $ret['message'] = $this->app->trans('An error occured'); } try { $this->getFilesystem()->remove([$lazaretFileName, $lazaretThumbFileName]); } catch (IOException $e) { } return $this->app->json($ret); }
[ "public", "function", "acceptElement", "(", "Request", "$", "request", ",", "$", "file_id", ")", "{", "$", "ret", "=", "[", "'success'", "=>", "false", ",", "'message'", "=>", "''", ",", "'result'", "=>", "[", "]", "]", ";", "//Mandatory parameter", "if"...
Substitute a record element by a lazaret element @param Request $request The current request @param int $file_id A lazaret element id @return Response
[ "Substitute", "a", "record", "element", "by", "a", "lazaret", "element" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Prod/LazaretController.php#L182-L253
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Prod/LazaretController.php
LazaretController.thumbnailElement
public function thumbnailElement($file_id) { /** @var LazaretFile $lazaretFile */ $lazaretFile = $this->getLazaretFileRepository()->find($file_id); if (null === $lazaretFile) { return new Response(null, 404); } $lazaretThumbFileName = $this->app['tmp.lazaret.path'].'/'.$lazaretFile->getThumbFilename(); return $this->deliverFile( $lazaretThumbFileName, $lazaretFile->getOriginalName(), DeliverDataInterface::DISPOSITION_INLINE, 'image/jpeg' ); }
php
public function thumbnailElement($file_id) { /** @var LazaretFile $lazaretFile */ $lazaretFile = $this->getLazaretFileRepository()->find($file_id); if (null === $lazaretFile) { return new Response(null, 404); } $lazaretThumbFileName = $this->app['tmp.lazaret.path'].'/'.$lazaretFile->getThumbFilename(); return $this->deliverFile( $lazaretThumbFileName, $lazaretFile->getOriginalName(), DeliverDataInterface::DISPOSITION_INLINE, 'image/jpeg' ); }
[ "public", "function", "thumbnailElement", "(", "$", "file_id", ")", "{", "/** @var LazaretFile $lazaretFile */", "$", "lazaretFile", "=", "$", "this", "->", "getLazaretFileRepository", "(", ")", "->", "find", "(", "$", "file_id", ")", ";", "if", "(", "null", "...
Get the associated lazaret element thumbnail @param int $file_id A lazaret element id @return Response
[ "Get", "the", "associated", "lazaret", "element", "thumbnail" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Prod/LazaretController.php#L262-L279
alchemy-fr/Phraseanet
lib/classes/patch/380alpha4a.php
patch_380alpha4a.apply
public function apply(base $appbox, Application $app) { $conn = $app->getApplicationBox()->get_connection(); $sql = 'SELECT date, login, ip, locked FROM badlog ORDER BY id ASC'; $stmt = $conn->prepare($sql); $stmt->execute(); $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); $n = 1; foreach ($rs as $row) { $date = Datetime::createFromFormat('Y-m-d h:i:s', $row['date']); $failure = new AuthFailure(); if ($date) { $failure->setCreated($date); } $failure->setIp($row['ip']); $failure->setLocked(!!$row['locked']); $failure->setUsername($row['login']); $app['orm.em']->persist($failure); if (0 === $n++ % 1000) { $app['orm.em']->flush(); $app['orm.em']->clear(); } } $app['orm.em']->flush(); $app['orm.em']->clear(); return true; }
php
public function apply(base $appbox, Application $app) { $conn = $app->getApplicationBox()->get_connection(); $sql = 'SELECT date, login, ip, locked FROM badlog ORDER BY id ASC'; $stmt = $conn->prepare($sql); $stmt->execute(); $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); $n = 1; foreach ($rs as $row) { $date = Datetime::createFromFormat('Y-m-d h:i:s', $row['date']); $failure = new AuthFailure(); if ($date) { $failure->setCreated($date); } $failure->setIp($row['ip']); $failure->setLocked(!!$row['locked']); $failure->setUsername($row['login']); $app['orm.em']->persist($failure); if (0 === $n++ % 1000) { $app['orm.em']->flush(); $app['orm.em']->clear(); } } $app['orm.em']->flush(); $app['orm.em']->clear(); return true; }
[ "public", "function", "apply", "(", "base", "$", "appbox", ",", "Application", "$", "app", ")", "{", "$", "conn", "=", "$", "app", "->", "getApplicationBox", "(", ")", "->", "get_connection", "(", ")", ";", "$", "sql", "=", "'SELECT date, login, ip, locked...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/380alpha4a.php#L58-L93
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Status/StatusStructureFactory.php
StatusStructureFactory.getStructure
public function getStructure(\databox $databox) { $databox_id = $databox->get_sbas_id(); if (isset($this->statusStructure[$databox_id])) { return $this->statusStructure[$databox_id]; } $this->statusStructure[$databox_id] = $this->provider->getStructure($databox); return $this->statusStructure[$databox_id]; }
php
public function getStructure(\databox $databox) { $databox_id = $databox->get_sbas_id(); if (isset($this->statusStructure[$databox_id])) { return $this->statusStructure[$databox_id]; } $this->statusStructure[$databox_id] = $this->provider->getStructure($databox); return $this->statusStructure[$databox_id]; }
[ "public", "function", "getStructure", "(", "\\", "databox", "$", "databox", ")", "{", "$", "databox_id", "=", "$", "databox", "->", "get_sbas_id", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "statusStructure", "[", "$", "databox_id", "]", ...
Get the status structure according to the given databox @param \databox $databox @return StatusStructure
[ "Get", "the", "status", "structure", "according", "to", "the", "given", "databox" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Status/StatusStructureFactory.php#L45-L56
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/PreSchemaUpgradeCollection.php
PreSchemaUpgradeCollection.apply
public function apply(Application $app) { $applied = []; foreach ($this->upgrades as $upgrade) { if ($upgrade->isApplyable($app)) { try { $upgrade->apply( $app['orm.em'], $app['phraseanet.appbox'], $app['doctrine-migration.configuration'] ); $applied[] = $upgrade; } catch (\Exception $e) { $upgrade->rollback( $app['orm.em'], $app['phraseanet.appbox'], $app['doctrine-migration.configuration'] ); foreach (array_reverse($applied) as $done) { $done->rollback( $app['orm.em'], $app['phraseanet.appbox'], $app['doctrine-migration.configuration'] ); } throw $e; } } } }
php
public function apply(Application $app) { $applied = []; foreach ($this->upgrades as $upgrade) { if ($upgrade->isApplyable($app)) { try { $upgrade->apply( $app['orm.em'], $app['phraseanet.appbox'], $app['doctrine-migration.configuration'] ); $applied[] = $upgrade; } catch (\Exception $e) { $upgrade->rollback( $app['orm.em'], $app['phraseanet.appbox'], $app['doctrine-migration.configuration'] ); foreach (array_reverse($applied) as $done) { $done->rollback( $app['orm.em'], $app['phraseanet.appbox'], $app['doctrine-migration.configuration'] ); } throw $e; } } } }
[ "public", "function", "apply", "(", "Application", "$", "app", ")", "{", "$", "applied", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "upgrades", "as", "$", "upgrade", ")", "{", "if", "(", "$", "upgrade", "->", "isApplyable", "(", "$", "a...
Applies all applyable upgrades @param Application $app
[ "Applies", "all", "applyable", "upgrades" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/PreSchemaUpgradeCollection.php#L34-L64
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Border/Checker/Sha256.php
Sha256.check
public function check(EntityManager $em, File $file) { $boolean = empty($file->getCollection()->get_databox()->getRecordRepository()->findBySha256($file->getSha256())); return new Response($boolean, $this); }
php
public function check(EntityManager $em, File $file) { $boolean = empty($file->getCollection()->get_databox()->getRecordRepository()->findBySha256($file->getSha256())); return new Response($boolean, $this); }
[ "public", "function", "check", "(", "EntityManager", "$", "em", ",", "File", "$", "file", ")", "{", "$", "boolean", "=", "empty", "(", "$", "file", "->", "getCollection", "(", ")", "->", "get_databox", "(", ")", "->", "getRecordRepository", "(", ")", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Border/Checker/Sha256.php#L35-L40
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Cache/ConnectionFactory.php
ConnectionFactory.getRedisConnection
public function getRedisConnection(array $options = []) { $options = array_replace(['host' => 'localhost', 'port' => 6379], $options); if (null !== $cache = $this->getConnection('redis', $options)) { return $cache; } if (!extension_loaded('redis')) { throw new RuntimeException('The Redis cache requires the Redis extension.'); } $redis = new \Redis(); if (!@$redis->connect($options['host'], $options['port'])) { throw new RuntimeException(sprintf("Redis instance with host '%s' and port '%s' is not reachable.", $options['host'], $options['port'])); } if (!defined('Redis::SERIALIZER_IGBINARY') || !$redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_IGBINARY)) { $redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_PHP); } return $this->setConnection('redis', $options, $redis); }
php
public function getRedisConnection(array $options = []) { $options = array_replace(['host' => 'localhost', 'port' => 6379], $options); if (null !== $cache = $this->getConnection('redis', $options)) { return $cache; } if (!extension_loaded('redis')) { throw new RuntimeException('The Redis cache requires the Redis extension.'); } $redis = new \Redis(); if (!@$redis->connect($options['host'], $options['port'])) { throw new RuntimeException(sprintf("Redis instance with host '%s' and port '%s' is not reachable.", $options['host'], $options['port'])); } if (!defined('Redis::SERIALIZER_IGBINARY') || !$redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_IGBINARY)) { $redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_PHP); } return $this->setConnection('redis', $options, $redis); }
[ "public", "function", "getRedisConnection", "(", "array", "$", "options", "=", "[", "]", ")", "{", "$", "options", "=", "array_replace", "(", "[", "'host'", "=>", "'localhost'", ",", "'port'", "=>", "6379", "]", ",", "$", "options", ")", ";", "if", "("...
Returns a Redis connection. @param array $options Available options are 'host' and 'port' @return \Redis @throws RuntimeException
[ "Returns", "a", "Redis", "connection", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Cache/ConnectionFactory.php#L29-L50
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Cache/ConnectionFactory.php
ConnectionFactory.getMemcacheConnection
public function getMemcacheConnection(array $options = []) { $options = array_replace(['host' => 'localhost', 'port' => 11211], $options); if (null !== $cache = $this->getConnection('memcache', $options)) { return $cache; } if (!extension_loaded('memcache')) { throw new RuntimeException('The Memcache cache requires the Memcache extension.'); } $memcache = new \Memcache(); $memcache->addServer($options['host'], $options['port']); $key = sprintf("%s:%s", $options['host'], $options['port']); $stats = @$memcache->getExtendedStats(); if (!isset($stats[$key]) || false === $stats[$key]) { throw new RuntimeException(sprintf("Memcache instance with host '%s' and port '%s' is not reachable.", $options['host'], $options['port'])); } return $this->setConnection('memcache', $options, $memcache); }
php
public function getMemcacheConnection(array $options = []) { $options = array_replace(['host' => 'localhost', 'port' => 11211], $options); if (null !== $cache = $this->getConnection('memcache', $options)) { return $cache; } if (!extension_loaded('memcache')) { throw new RuntimeException('The Memcache cache requires the Memcache extension.'); } $memcache = new \Memcache(); $memcache->addServer($options['host'], $options['port']); $key = sprintf("%s:%s", $options['host'], $options['port']); $stats = @$memcache->getExtendedStats(); if (!isset($stats[$key]) || false === $stats[$key]) { throw new RuntimeException(sprintf("Memcache instance with host '%s' and port '%s' is not reachable.", $options['host'], $options['port'])); } return $this->setConnection('memcache', $options, $memcache); }
[ "public", "function", "getMemcacheConnection", "(", "array", "$", "options", "=", "[", "]", ")", "{", "$", "options", "=", "array_replace", "(", "[", "'host'", "=>", "'localhost'", ",", "'port'", "=>", "11211", "]", ",", "$", "options", ")", ";", "if", ...
Returns a Memcache connection. @param array $options Available options are 'host' and 'port' @return \Memcache @throws RuntimeException
[ "Returns", "a", "Memcache", "connection", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Cache/ConnectionFactory.php#L61-L83
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Cache/ConnectionFactory.php
ConnectionFactory.getMemcachedConnection
public function getMemcachedConnection(array $options = []) { $options = array_replace(['host' => 'localhost', 'port' => 11211], $options); if (null !== $cache = $this->getConnection('memcached', $options)) { return $cache; } if (!extension_loaded('memcached')) { throw new RuntimeException('The Memcached cache requires the Memcached extension.'); } $memcached = new \Memcached(); $memcached->addServer($options['host'], $options['port']); $memcached->getStats(); if (\Memcached::RES_SUCCESS !== $memcached->getResultCode()) { throw new RuntimeException(sprintf("Memcached instance with host '%s' and port '%s' is not reachable.", $options['host'], $options['port'])); } return $this->setConnection('memcached', $options, $memcached); }
php
public function getMemcachedConnection(array $options = []) { $options = array_replace(['host' => 'localhost', 'port' => 11211], $options); if (null !== $cache = $this->getConnection('memcached', $options)) { return $cache; } if (!extension_loaded('memcached')) { throw new RuntimeException('The Memcached cache requires the Memcached extension.'); } $memcached = new \Memcached(); $memcached->addServer($options['host'], $options['port']); $memcached->getStats(); if (\Memcached::RES_SUCCESS !== $memcached->getResultCode()) { throw new RuntimeException(sprintf("Memcached instance with host '%s' and port '%s' is not reachable.", $options['host'], $options['port'])); } return $this->setConnection('memcached', $options, $memcached); }
[ "public", "function", "getMemcachedConnection", "(", "array", "$", "options", "=", "[", "]", ")", "{", "$", "options", "=", "array_replace", "(", "[", "'host'", "=>", "'localhost'", ",", "'port'", "=>", "11211", "]", ",", "$", "options", ")", ";", "if", ...
Returns a Memcached connection. @param array $options Available options are 'host' and 'port' @return \Memcached @throws RuntimeException
[ "Returns", "a", "Memcached", "connection", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Cache/ConnectionFactory.php#L94-L114
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Report/ReportFactory.php
ReportFactory.createReport
public function createReport($table, $sbasId=null, $parms=null) { switch($table) { case self::CONNECTIONS: return (new ReportConnections( $this->findDbOr404($sbasId), $parms )) ->setAppKey($this->appKey) ; break; case self::DOWNLOADS: return (new ReportDownloads( $this->findDbOr404($sbasId), $parms )) ->setAppKey($this->appKey) ->setACL($this->acl) ; break; case self::RECORDS: return (new ReportRecords( $this->findDbOr404($sbasId), $parms )) ->setACL($this->acl) ; break; default: throw new \InvalidArgumentException(sprintf("unknown table type \"%s\"", $table)); break; } }
php
public function createReport($table, $sbasId=null, $parms=null) { switch($table) { case self::CONNECTIONS: return (new ReportConnections( $this->findDbOr404($sbasId), $parms )) ->setAppKey($this->appKey) ; break; case self::DOWNLOADS: return (new ReportDownloads( $this->findDbOr404($sbasId), $parms )) ->setAppKey($this->appKey) ->setACL($this->acl) ; break; case self::RECORDS: return (new ReportRecords( $this->findDbOr404($sbasId), $parms )) ->setACL($this->acl) ; break; default: throw new \InvalidArgumentException(sprintf("unknown table type \"%s\"", $table)); break; } }
[ "public", "function", "createReport", "(", "$", "table", ",", "$", "sbasId", "=", "null", ",", "$", "parms", "=", "null", ")", "{", "switch", "(", "$", "table", ")", "{", "case", "self", "::", "CONNECTIONS", ":", "return", "(", "new", "ReportConnection...
@param $table @param null $sbasId @param null $parms @return ReportConnections | ReportDownloads
[ "@param", "$table", "@param", "null", "$sbasId", "@param", "null", "$parms" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Report/ReportFactory.php#L54-L89
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Media/SubdefSubstituer.php
SubdefSubstituer.substitute
public function substitute(\record_adapter $record, $name, MediaInterface $media, $adapt = true) { if ($name == 'document') { $this->substituteDocument($record, $media, $adapt); return; } $this->substituteSubdef($record, $name, $media, $adapt); }
php
public function substitute(\record_adapter $record, $name, MediaInterface $media, $adapt = true) { if ($name == 'document') { $this->substituteDocument($record, $media, $adapt); return; } $this->substituteSubdef($record, $name, $media, $adapt); }
[ "public", "function", "substitute", "(", "\\", "record_adapter", "$", "record", ",", "$", "name", ",", "MediaInterface", "$", "media", ",", "$", "adapt", "=", "true", ")", "{", "if", "(", "$", "name", "==", "'document'", ")", "{", "$", "this", "->", ...
@param \record_adapter $record @param string $name @param MediaInterface $media @param bool $adapt @deprecated use {@link self::substituteDocument} or {@link self::substituteSubdef} instead
[ "@param", "\\", "record_adapter", "$record", "@param", "string", "$name", "@param", "MediaInterface", "$media", "@param", "bool", "$adapt" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Media/SubdefSubstituer.php#L46-L55
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Core/Provider/WorkerConfigurationServiceProvider.php
WorkerConfigurationServiceProvider.register
public function register(Application $app) { // Define the first defined queue as the worker queue $app['alchemy_worker.queue_name'] = $app->share(function (Application $app) { $queues = $app['alchemy_queues.queues']; reset($queues); return key($queues); }); $app['alchemy_queues.queues'] = $app->share(function (Application $app) { $defaultConfiguration = [ 'worker-queue' => [ 'registry' => 'alchemy_worker.queue_registry', 'host' => 'localhost', 'port' => 5672, 'user' => 'guest', 'vhost' => '/' ] ]; try { /** @var PropertyAccess $configuration */ $configuration = $app['conf']; $queueConfigurations = $configuration->get(['workers', 'queue'], $defaultConfiguration); $queueConfiguration = reset($queueConfigurations); $queueKey = key($queueConfigurations); if (! isset($queueConfiguration['name'])) { if (! is_string($queueKey)) { throw new \RuntimeException('Invalid queue configuration: configuration has no key or name.'); } $queueConfiguration['name'] = $queueKey; } $config = [ $queueConfiguration['name'] => $queueConfiguration ]; return $config; } catch (RuntimeException $exception) { return []; } }); }
php
public function register(Application $app) { // Define the first defined queue as the worker queue $app['alchemy_worker.queue_name'] = $app->share(function (Application $app) { $queues = $app['alchemy_queues.queues']; reset($queues); return key($queues); }); $app['alchemy_queues.queues'] = $app->share(function (Application $app) { $defaultConfiguration = [ 'worker-queue' => [ 'registry' => 'alchemy_worker.queue_registry', 'host' => 'localhost', 'port' => 5672, 'user' => 'guest', 'vhost' => '/' ] ]; try { /** @var PropertyAccess $configuration */ $configuration = $app['conf']; $queueConfigurations = $configuration->get(['workers', 'queue'], $defaultConfiguration); $queueConfiguration = reset($queueConfigurations); $queueKey = key($queueConfigurations); if (! isset($queueConfiguration['name'])) { if (! is_string($queueKey)) { throw new \RuntimeException('Invalid queue configuration: configuration has no key or name.'); } $queueConfiguration['name'] = $queueKey; } $config = [ $queueConfiguration['name'] => $queueConfiguration ]; return $config; } catch (RuntimeException $exception) { return []; } }); }
[ "public", "function", "register", "(", "Application", "$", "app", ")", "{", "// Define the first defined queue as the worker queue", "$", "app", "[", "'alchemy_worker.queue_name'", "]", "=", "$", "app", "->", "share", "(", "function", "(", "Application", "$", "app",...
Registers services on the given app. This method should only be used to configure services and parameters. It should not get services.
[ "Registers", "services", "on", "the", "given", "app", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Core/Provider/WorkerConfigurationServiceProvider.php#L21-L68
alchemy-fr/Phraseanet
lib/classes/patch/383alpha1a.php
patch_383alpha1a.apply
public function apply(base $appbox, Application $app) { if (!$this->hasSessionTable($app)) { return true; } // Remove deleted users sessions $sql = 'SELECT s.id FROM `Sessions` s INNER JOIN Users u ON (u.id = s.user_id) WHERE u.deleted = 1'; $stmt = $appbox->get_connection()->prepare($sql); $stmt->execute(); $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); foreach ($rows as $row) { if (null !== $session = $app['repo.sessions']->find($row['id'])) { $app['orm.em']->remove($session); } } // Remove API sessions $query = $app['orm.em']->createQuery('SELECT s FROM Phraseanet:Session s WHERE s.user_agent LIKE :guzzle'); $query->setParameter(':guzzle', 'Guzzle%'); foreach ($query->getResult() as $session) { $app['orm.em']->remove($session); } $app['orm.em']->flush(); return true; }
php
public function apply(base $appbox, Application $app) { if (!$this->hasSessionTable($app)) { return true; } // Remove deleted users sessions $sql = 'SELECT s.id FROM `Sessions` s INNER JOIN Users u ON (u.id = s.user_id) WHERE u.deleted = 1'; $stmt = $appbox->get_connection()->prepare($sql); $stmt->execute(); $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); foreach ($rows as $row) { if (null !== $session = $app['repo.sessions']->find($row['id'])) { $app['orm.em']->remove($session); } } // Remove API sessions $query = $app['orm.em']->createQuery('SELECT s FROM Phraseanet:Session s WHERE s.user_agent LIKE :guzzle'); $query->setParameter(':guzzle', 'Guzzle%'); foreach ($query->getResult() as $session) { $app['orm.em']->remove($session); } $app['orm.em']->flush(); return true; }
[ "public", "function", "apply", "(", "base", "$", "appbox", ",", "Application", "$", "app", ")", "{", "if", "(", "!", "$", "this", "->", "hasSessionTable", "(", "$", "app", ")", ")", "{", "return", "true", ";", "}", "// Remove deleted users sessions", "$"...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/383alpha1a.php#L50-L80
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Notification/Mail/MailInfoBridgeUploadFailed.php
MailInfoBridgeUploadFailed.getMessage
public function getMessage() { if (null === $this->adapter) { throw new LogicException('You must set an adapter before calling getMessage'); } if (null === $this->reason) { throw new LogicException('You must set a reason before calling getMessage'); } return $this->app->trans('An upload on %bridge_adapter% failed, the resaon is : %reason%', ['%bridge_adapter%' => $this->adapter, '%reason%' => $this->reason]); }
php
public function getMessage() { if (null === $this->adapter) { throw new LogicException('You must set an adapter before calling getMessage'); } if (null === $this->reason) { throw new LogicException('You must set a reason before calling getMessage'); } return $this->app->trans('An upload on %bridge_adapter% failed, the resaon is : %reason%', ['%bridge_adapter%' => $this->adapter, '%reason%' => $this->reason]); }
[ "public", "function", "getMessage", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "adapter", ")", "{", "throw", "new", "LogicException", "(", "'You must set an adapter before calling getMessage'", ")", ";", "}", "if", "(", "null", "===", "$", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Notification/Mail/MailInfoBridgeUploadFailed.php#L54-L64
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Model/Entities/LazaretFile.php
LazaretFile.getRecordsToSubstitute
public function getRecordsToSubstitute(Application $app, $includeReason = false) { $merged = []; /** @var LazaretCheck $check */ foreach($this->getChecks() as $check) { /** @var record_adapter $record */ $conflicts = $check->listConflicts($app); foreach ($conflicts as $record) { if($includeReason) { if (!array_key_exists($record->getRecordId(), $merged)) { $merged[$record->getRecordId()] = [ 'record' => $record, 'reasons' => [] ]; } $merged[$record->getRecordId()]['reasons'][$this->getCheckerName($check)] = $check->getReason($app['translator']); } else { $merged[$record->getRecordId()] = $record; } } } return $merged; }
php
public function getRecordsToSubstitute(Application $app, $includeReason = false) { $merged = []; /** @var LazaretCheck $check */ foreach($this->getChecks() as $check) { /** @var record_adapter $record */ $conflicts = $check->listConflicts($app); foreach ($conflicts as $record) { if($includeReason) { if (!array_key_exists($record->getRecordId(), $merged)) { $merged[$record->getRecordId()] = [ 'record' => $record, 'reasons' => [] ]; } $merged[$record->getRecordId()]['reasons'][$this->getCheckerName($check)] = $check->getReason($app['translator']); } else { $merged[$record->getRecordId()] = $record; } } } return $merged; }
[ "public", "function", "getRecordsToSubstitute", "(", "Application", "$", "app", ",", "$", "includeReason", "=", "false", ")", "{", "$", "merged", "=", "[", "]", ";", "/** @var LazaretCheck $check */", "foreach", "(", "$", "this", "->", "getChecks", "(", ")", ...
Get an array of records that can be substitued by the Lazaret file @return record_adapter[]
[ "Get", "an", "array", "of", "records", "that", "can", "be", "substitued", "by", "the", "Lazaret", "file" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Entities/LazaretFile.php#L451-L475
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Authentication/Phrasea/FailureManager.php
FailureManager.saveFailure
public function saveFailure($username, Request $request) { $this->removeOldFailures(); $failure = new AuthFailure(); $failure->setIp($request->getClientIp()); $failure->setUsername($username); $failure->setLocked(true); $this->em->persist($failure); $this->em->flush(); return $this; }
php
public function saveFailure($username, Request $request) { $this->removeOldFailures(); $failure = new AuthFailure(); $failure->setIp($request->getClientIp()); $failure->setUsername($username); $failure->setLocked(true); $this->em->persist($failure); $this->em->flush(); return $this; }
[ "public", "function", "saveFailure", "(", "$", "username", ",", "Request", "$", "request", ")", "{", "$", "this", "->", "removeOldFailures", "(", ")", ";", "$", "failure", "=", "new", "AuthFailure", "(", ")", ";", "$", "failure", "->", "setIp", "(", "$...
Saves an authentication failure @param string $username @param Request $request @return FailureManager
[ "Saves", "an", "authentication", "failure" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/Phrasea/FailureManager.php#L73-L86
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Authentication/Phrasea/FailureManager.php
FailureManager.checkFailures
public function checkFailures($username, Request $request) { $failures = $this->repository->findLockedFailuresMatching($username, $request->getClientIp()); if (0 === count($failures)) { return $this; } if ($this->trials < count($failures) && $this->captcha->isSetup()) { $response = $this->captcha->bind($request); if (!$response->isValid()) { throw new RequireCaptchaException('Too many failures, require captcha'); } foreach ($failures as $failure) { $failure->setLocked(false); } $this->em->flush($failures); } return $this; }
php
public function checkFailures($username, Request $request) { $failures = $this->repository->findLockedFailuresMatching($username, $request->getClientIp()); if (0 === count($failures)) { return $this; } if ($this->trials < count($failures) && $this->captcha->isSetup()) { $response = $this->captcha->bind($request); if (!$response->isValid()) { throw new RequireCaptchaException('Too many failures, require captcha'); } foreach ($failures as $failure) { $failure->setLocked(false); } $this->em->flush($failures); } return $this; }
[ "public", "function", "checkFailures", "(", "$", "username", ",", "Request", "$", "request", ")", "{", "$", "failures", "=", "$", "this", "->", "repository", "->", "findLockedFailuresMatching", "(", "$", "username", ",", "$", "request", "->", "getClientIp", ...
Checks a request for previous failures @param string $username @param Request $request @return FailureManager @throws RequireCaptchaException In case a captcha unlock is required
[ "Checks", "a", "request", "for", "previous", "failures" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/Phrasea/FailureManager.php#L98-L121
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Border/Checker/UUID.php
UUID.check
public function check(EntityManager $em, File $file) { $boolean = empty($file->getCollection()->get_databox()->getRecordRepository()->findByUuid($file->getUUID())); return new Response($boolean, $this); }
php
public function check(EntityManager $em, File $file) { $boolean = empty($file->getCollection()->get_databox()->getRecordRepository()->findByUuid($file->getUUID())); return new Response($boolean, $this); }
[ "public", "function", "check", "(", "EntityManager", "$", "em", ",", "File", "$", "file", ")", "{", "$", "boolean", "=", "empty", "(", "$", "file", "->", "getCollection", "(", ")", "->", "get_databox", "(", ")", "->", "getRecordRepository", "(", ")", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Border/Checker/UUID.php#L34-L39
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Authentication/Phrasea/NativeAuthentication.php
NativeAuthentication.getUsrId
public function getUsrId($username, $password, Request $request) { if (null === $user = $this->repository->findRealUserByLogin($username)) { return null; } if ($user->isSpecial()) { return null; } // check locked account if ($user->isMailLocked()) { throw new AccountLockedException('The account is locked', $user->getId()); } if (false === $user->isSaltedPassword()) { // we need a quick update and continue if ($this->oldEncoder->isPasswordValid($user->getPassword(), $password, $user->getNonce())) { $this->userManipulator->setPassword($user, $password); } } if (false === $this->encoder->isPasswordValid($user->getPassword(), $password, $user->getNonce())) { return null; } return $user->getId(); }
php
public function getUsrId($username, $password, Request $request) { if (null === $user = $this->repository->findRealUserByLogin($username)) { return null; } if ($user->isSpecial()) { return null; } // check locked account if ($user->isMailLocked()) { throw new AccountLockedException('The account is locked', $user->getId()); } if (false === $user->isSaltedPassword()) { // we need a quick update and continue if ($this->oldEncoder->isPasswordValid($user->getPassword(), $password, $user->getNonce())) { $this->userManipulator->setPassword($user, $password); } } if (false === $this->encoder->isPasswordValid($user->getPassword(), $password, $user->getNonce())) { return null; } return $user->getId(); }
[ "public", "function", "getUsrId", "(", "$", "username", ",", "$", "password", ",", "Request", "$", "request", ")", "{", "if", "(", "null", "===", "$", "user", "=", "$", "this", "->", "repository", "->", "findRealUserByLogin", "(", "$", "username", ")", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/Phrasea/NativeAuthentication.php#L41-L68
alchemy-fr/Phraseanet
lib/classes/patch/390alpha5a.php
patch_390alpha5a.apply
public function apply(base $appbox, Application $app) { $sql = 'DELETE FROM UserNotificationSettings'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $conn = $app->getApplicationBox()->get_connection(); $sql = 'SELECT * FROM usr_settings WHERE prop LIKE "notification_%"'; $stmt = $conn->prepare($sql); $stmt->execute(); $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); $n = 0; $em = $app['orm.em']; foreach ($rs as $row) { if (null === $user = $this->loadUser($app['orm.em'], $row['usr_id'])) { continue; } $userSetting = new UserNotificationSetting(); $userSetting->setName($row['prop']); $userSetting->setValue($row['value']); $userSetting->setUser($user); $em->persist($userSetting); $n++; if ($n % 200 === 0) { $em->flush(); $em->clear(); } } $em->flush(); $em->clear(); return true; }
php
public function apply(base $appbox, Application $app) { $sql = 'DELETE FROM UserNotificationSettings'; $stmt = $app->getApplicationBox()->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $conn = $app->getApplicationBox()->get_connection(); $sql = 'SELECT * FROM usr_settings WHERE prop LIKE "notification_%"'; $stmt = $conn->prepare($sql); $stmt->execute(); $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); $n = 0; $em = $app['orm.em']; foreach ($rs as $row) { if (null === $user = $this->loadUser($app['orm.em'], $row['usr_id'])) { continue; } $userSetting = new UserNotificationSetting(); $userSetting->setName($row['prop']); $userSetting->setValue($row['value']); $userSetting->setUser($user); $em->persist($userSetting); $n++; if ($n % 200 === 0) { $em->flush(); $em->clear(); } } $em->flush(); $em->clear(); return true; }
[ "public", "function", "apply", "(", "base", "$", "appbox", ",", "Application", "$", "app", ")", "{", "$", "sql", "=", "'DELETE FROM UserNotificationSettings'", ";", "$", "stmt", "=", "$", "app", "->", "getApplicationBox", "(", ")", "->", "get_connection", "(...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/390alpha5a.php#L58-L100
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.getSchedulerAction
public function getSchedulerAction(Request $request) { /** @var LiveInformation $information */ $information = $this->app['task-manager.live-information']; $data = $information->getManager(); return Result::create($request, [ 'scheduler' => [ 'configuration' => $data['configuration'], 'state' => $data['actual'], 'status' => $data['actual'], 'pid' => $data['process-id'], 'process-id' => $data['process-id'], 'updated_on' => (new \DateTime())->format(DATE_ATOM), ], ])->createResponse(); }
php
public function getSchedulerAction(Request $request) { /** @var LiveInformation $information */ $information = $this->app['task-manager.live-information']; $data = $information->getManager(); return Result::create($request, [ 'scheduler' => [ 'configuration' => $data['configuration'], 'state' => $data['actual'], 'status' => $data['actual'], 'pid' => $data['process-id'], 'process-id' => $data['process-id'], 'updated_on' => (new \DateTime())->format(DATE_ATOM), ], ])->createResponse(); }
[ "public", "function", "getSchedulerAction", "(", "Request", "$", "request", ")", "{", "/** @var LiveInformation $information */", "$", "information", "=", "$", "this", "->", "app", "[", "'task-manager.live-information'", "]", ";", "$", "data", "=", "$", "information...
Return an array of key-values information about scheduler @param Request $request @return Response
[ "Return", "an", "array", "of", "key", "-", "values", "information", "about", "scheduler" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L129-L145
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.getDataboxCollectionsAction
public function getDataboxCollectionsAction(Request $request, $databox_id) { $ret = [ "collections" => $this->listDataboxCollections($this->findDataboxById($databox_id)), ]; return Result::create($request, $ret)->createResponse(); }
php
public function getDataboxCollectionsAction(Request $request, $databox_id) { $ret = [ "collections" => $this->listDataboxCollections($this->findDataboxById($databox_id)), ]; return Result::create($request, $ret)->createResponse(); }
[ "public", "function", "getDataboxCollectionsAction", "(", "Request", "$", "request", ",", "$", "databox_id", ")", "{", "$", "ret", "=", "[", "\"collections\"", "=>", "$", "this", "->", "listDataboxCollections", "(", "$", "this", "->", "findDataboxById", "(", "...
Get a Response containing the collections of a \databox @param Request $request @param int $databox_id @return Response
[ "Get", "a", "Response", "containing", "the", "collections", "of", "a", "\\", "databox" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L476-L483
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.getDataboxStatusAction
public function getDataboxStatusAction(Request $request, $databox_id) { $ret = ["status" => $this->listDataboxStatus($this->findDataboxById($databox_id)->getStatusStructure())]; return Result::create($request, $ret)->createResponse(); }
php
public function getDataboxStatusAction(Request $request, $databox_id) { $ret = ["status" => $this->listDataboxStatus($this->findDataboxById($databox_id)->getStatusStructure())]; return Result::create($request, $ret)->createResponse(); }
[ "public", "function", "getDataboxStatusAction", "(", "Request", "$", "request", ",", "$", "databox_id", ")", "{", "$", "ret", "=", "[", "\"status\"", "=>", "$", "this", "->", "listDataboxStatus", "(", "$", "this", "->", "findDataboxById", "(", "$", "databox_...
Get a Response containing the status of a \databox @param Request $request @param int $databox_id @return Response
[ "Get", "a", "Response", "containing", "the", "status", "of", "a", "\\", "databox" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L528-L533
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.getDataboxTermsAction
public function getDataboxTermsAction(Request $request, $databox_id) { $ret = ["termsOfUse" => $this->listDataboxTerms($this->findDataboxById($databox_id))]; return Result::create($request, $ret)->createResponse(); }
php
public function getDataboxTermsAction(Request $request, $databox_id) { $ret = ["termsOfUse" => $this->listDataboxTerms($this->findDataboxById($databox_id))]; return Result::create($request, $ret)->createResponse(); }
[ "public", "function", "getDataboxTermsAction", "(", "Request", "$", "request", ",", "$", "databox_id", ")", "{", "$", "ret", "=", "[", "\"termsOfUse\"", "=>", "$", "this", "->", "listDataboxTerms", "(", "$", "this", "->", "findDataboxById", "(", "$", "databo...
Get a Response containing the terms of use of a \databox @param Request $request @param int $databox_id @return Response
[ "Get", "a", "Response", "containing", "the", "terms", "of", "use", "of", "a", "\\", "databox" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L613-L618
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.listDataboxTerms
private function listDataboxTerms(\databox $databox) { $ret = []; foreach ($databox->get_cgus() as $locale => $array_terms) { $ret[] = ['locale' => $locale, 'terms' => $array_terms['value']]; } return $ret; }
php
private function listDataboxTerms(\databox $databox) { $ret = []; foreach ($databox->get_cgus() as $locale => $array_terms) { $ret[] = ['locale' => $locale, 'terms' => $array_terms['value']]; } return $ret; }
[ "private", "function", "listDataboxTerms", "(", "\\", "databox", "$", "databox", ")", "{", "$", "ret", "=", "[", "]", ";", "foreach", "(", "$", "databox", "->", "get_cgus", "(", ")", "as", "$", "locale", "=>", "$", "array_terms", ")", "{", "$", "ret"...
Retrieve CGU's for the specified \databox @param \databox $databox @return array
[ "Retrieve", "CGU", "s", "for", "the", "specified", "\\", "databox" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L627-L635
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.searchAction
public function searchAction(Request $request) { $subdefTransformer = new SubdefTransformer($this->app['acl'], $this->getAuthenticatedUser(), new PermalinkTransformer()); $technicalDataTransformer = new TechnicalDataTransformer(); $recordTransformer = new RecordTransformer($subdefTransformer, $technicalDataTransformer); $storyTransformer = new StoryTransformer($subdefTransformer, $recordTransformer); $compositeTransformer = new V1SearchCompositeResultTransformer($recordTransformer, $storyTransformer); $searchTransformer = new V1SearchResultTransformer($compositeTransformer); $transformerResolver = new SearchResultTransformerResolver([ '' => $searchTransformer, 'results' => $compositeTransformer, 'results.stories' => $storyTransformer, 'results.stories.thumbnail' => $subdefTransformer, 'results.stories.metadatas' => new CallbackTransformer(), 'results.stories.caption' => new CallbackTransformer(), 'results.stories.records' => $recordTransformer, 'results.stories.records.thumbnail' => $subdefTransformer, 'results.stories.records.technical_informations' => $technicalDataTransformer, 'results.stories.records.subdefs' => $subdefTransformer, 'results.stories.records.metadata' => new CallbackTransformer(), 'results.stories.records.status' => new CallbackTransformer(), 'results.stories.records.caption' => new CallbackTransformer(), 'results.records' => $recordTransformer, 'results.records.thumbnail' => $subdefTransformer, 'results.records.technical_informations' => $technicalDataTransformer, 'results.records.subdefs' => $subdefTransformer, 'results.records.metadata' => new CallbackTransformer(), 'results.records.status' => new CallbackTransformer(), 'results.records.caption' => new CallbackTransformer(), ]); $includeResolver = new IncludeResolver($transformerResolver); $fractal = new \League\Fractal\Manager(); $fractal->setSerializer(new TraceableArraySerializer($this->app['dispatcher'])); $fractal->parseIncludes($this->resolveSearchIncludes($request)); $result = $this->doSearch($request); $searchView = $this->buildSearchView( $result, $includeResolver->resolve($fractal), $this->resolveSubdefUrlTTL($request) ); $ret = $fractal->createData(new Item($searchView, $searchTransformer))->toArray(); return Result::create($request, $ret)->createResponse(); }
php
public function searchAction(Request $request) { $subdefTransformer = new SubdefTransformer($this->app['acl'], $this->getAuthenticatedUser(), new PermalinkTransformer()); $technicalDataTransformer = new TechnicalDataTransformer(); $recordTransformer = new RecordTransformer($subdefTransformer, $technicalDataTransformer); $storyTransformer = new StoryTransformer($subdefTransformer, $recordTransformer); $compositeTransformer = new V1SearchCompositeResultTransformer($recordTransformer, $storyTransformer); $searchTransformer = new V1SearchResultTransformer($compositeTransformer); $transformerResolver = new SearchResultTransformerResolver([ '' => $searchTransformer, 'results' => $compositeTransformer, 'results.stories' => $storyTransformer, 'results.stories.thumbnail' => $subdefTransformer, 'results.stories.metadatas' => new CallbackTransformer(), 'results.stories.caption' => new CallbackTransformer(), 'results.stories.records' => $recordTransformer, 'results.stories.records.thumbnail' => $subdefTransformer, 'results.stories.records.technical_informations' => $technicalDataTransformer, 'results.stories.records.subdefs' => $subdefTransformer, 'results.stories.records.metadata' => new CallbackTransformer(), 'results.stories.records.status' => new CallbackTransformer(), 'results.stories.records.caption' => new CallbackTransformer(), 'results.records' => $recordTransformer, 'results.records.thumbnail' => $subdefTransformer, 'results.records.technical_informations' => $technicalDataTransformer, 'results.records.subdefs' => $subdefTransformer, 'results.records.metadata' => new CallbackTransformer(), 'results.records.status' => new CallbackTransformer(), 'results.records.caption' => new CallbackTransformer(), ]); $includeResolver = new IncludeResolver($transformerResolver); $fractal = new \League\Fractal\Manager(); $fractal->setSerializer(new TraceableArraySerializer($this->app['dispatcher'])); $fractal->parseIncludes($this->resolveSearchIncludes($request)); $result = $this->doSearch($request); $searchView = $this->buildSearchView( $result, $includeResolver->resolve($fractal), $this->resolveSubdefUrlTTL($request) ); $ret = $fractal->createData(new Item($searchView, $searchTransformer))->toArray(); return Result::create($request, $ret)->createResponse(); }
[ "public", "function", "searchAction", "(", "Request", "$", "request", ")", "{", "$", "subdefTransformer", "=", "new", "SubdefTransformer", "(", "$", "this", "->", "app", "[", "'acl'", "]", ",", "$", "this", "->", "getAuthenticatedUser", "(", ")", ",", "new...
Search for results @param Request $request @return Response
[ "Search", "for", "results" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L1165-L1213
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.searchRecordsAction
public function searchRecordsAction(Request $request) { $subdefTransformer = new SubdefTransformer($this->app['acl'], $this->getAuthenticatedUser(), new PermalinkTransformer()); $technicalDataTransformer = new TechnicalDataTransformer(); $recordTransformer = new RecordTransformer($subdefTransformer, $technicalDataTransformer); $searchTransformer = new V1SearchRecordsResultTransformer($recordTransformer); $transformerResolver = new SearchResultTransformerResolver([ '' => $searchTransformer, 'results' => $recordTransformer, 'results.thumbnail' => $subdefTransformer, 'results.technical_informations' => $technicalDataTransformer, 'results.subdefs' => $subdefTransformer, 'results.metadata' => new CallbackTransformer(), 'results.status' => new CallbackTransformer(), 'results.caption' => new CallbackTransformer(), ]); $includeResolver = new IncludeResolver($transformerResolver); $fractal = new \League\Fractal\Manager(); $fractal->setSerializer(new ArraySerializer()); $fractal->parseIncludes($this->resolveSearchRecordsIncludes($request)); $searchView = $this->buildSearchRecordsView( $this->doSearch($request), $includeResolver->resolve($fractal), $this->resolveSubdefUrlTTL($request) ); $ret = $fractal->createData(new Item($searchView, $searchTransformer))->toArray(); return Result::create($request, $ret)->createResponse(); }
php
public function searchRecordsAction(Request $request) { $subdefTransformer = new SubdefTransformer($this->app['acl'], $this->getAuthenticatedUser(), new PermalinkTransformer()); $technicalDataTransformer = new TechnicalDataTransformer(); $recordTransformer = new RecordTransformer($subdefTransformer, $technicalDataTransformer); $searchTransformer = new V1SearchRecordsResultTransformer($recordTransformer); $transformerResolver = new SearchResultTransformerResolver([ '' => $searchTransformer, 'results' => $recordTransformer, 'results.thumbnail' => $subdefTransformer, 'results.technical_informations' => $technicalDataTransformer, 'results.subdefs' => $subdefTransformer, 'results.metadata' => new CallbackTransformer(), 'results.status' => new CallbackTransformer(), 'results.caption' => new CallbackTransformer(), ]); $includeResolver = new IncludeResolver($transformerResolver); $fractal = new \League\Fractal\Manager(); $fractal->setSerializer(new ArraySerializer()); $fractal->parseIncludes($this->resolveSearchRecordsIncludes($request)); $searchView = $this->buildSearchRecordsView( $this->doSearch($request), $includeResolver->resolve($fractal), $this->resolveSubdefUrlTTL($request) ); $ret = $fractal->createData(new Item($searchView, $searchTransformer))->toArray(); return Result::create($request, $ret)->createResponse(); }
[ "public", "function", "searchRecordsAction", "(", "Request", "$", "request", ")", "{", "$", "subdefTransformer", "=", "new", "SubdefTransformer", "(", "$", "this", "->", "app", "[", "'acl'", "]", ",", "$", "this", "->", "getAuthenticatedUser", "(", ")", ",",...
Get a Response containing the results of a records search @deprecated in favor of search @param Request $request @return Response
[ "Get", "a", "Response", "containing", "the", "results", "of", "a", "records", "search" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L1224-L1256
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.resolveSearchIncludes
private function resolveSearchIncludes(Request $request) { $includes = [ 'results.stories.records' ]; if ($request->attributes->get('_extended', false)) { if ($request->get('search_type') != SearchEngineOptions::RECORD_STORY) { $includes = array_merge($includes, [ 'results.stories.records.subdefs', 'results.stories.records.metadata', 'results.stories.records.caption', 'results.stories.records.status' ]); } else { $includes = [ 'results.stories.caption' ]; } $includes = array_merge($includes, [ 'results.records.subdefs', 'results.records.metadata', 'results.records.caption', 'results.records.status' ]); } return $includes; }
php
private function resolveSearchIncludes(Request $request) { $includes = [ 'results.stories.records' ]; if ($request->attributes->get('_extended', false)) { if ($request->get('search_type') != SearchEngineOptions::RECORD_STORY) { $includes = array_merge($includes, [ 'results.stories.records.subdefs', 'results.stories.records.metadata', 'results.stories.records.caption', 'results.stories.records.status' ]); } else { $includes = [ 'results.stories.caption' ]; } $includes = array_merge($includes, [ 'results.records.subdefs', 'results.records.metadata', 'results.records.caption', 'results.records.status' ]); } return $includes; }
[ "private", "function", "resolveSearchIncludes", "(", "Request", "$", "request", ")", "{", "$", "includes", "=", "[", "'results.stories.records'", "]", ";", "if", "(", "$", "request", "->", "attributes", "->", "get", "(", "'_extended'", ",", "false", ")", ")"...
Returns requested includes @param Request $request @return string[]
[ "Returns", "requested", "includes" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L1485-L1513
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.listRecord
private function listRecord(Request $request, \record_adapter $record) { $technicalInformation = []; foreach ($record->get_technical_infos()->getValues() as $name => $value) { $technicalInformation[] = ['name' => $name, 'value' => $value]; } $data = [ 'databox_id' => $record->getDataboxId(), 'record_id' => $record->getRecordId(), 'mime_type' => $record->getMimeType(), 'title' => $record->get_title(), 'original_name' => $record->get_original_name(), 'updated_on' => $record->getUpdated()->format(DATE_ATOM), 'created_on' => $record->getCreated()->format(DATE_ATOM), 'collection_id' => $record->getCollectionId(), 'base_id' => $record->getBaseId(), 'sha256' => $record->getSha256(), 'thumbnail' => $this->listEmbeddableMedia($request, $record, $record->get_thumbnail()), 'technical_informations' => $technicalInformation, 'phrasea_type' => $record->getType(), 'uuid' => $record->getUuid(), ]; if ($request->attributes->get('_extended', false)) { $data = array_merge($data, [ 'subdefs' => $this->listRecordEmbeddableMedias($request, $record), 'metadata' => $this->listRecordMetadata($record), 'status' => $this->listRecordStatus($record), 'caption' => $this->listRecordCaption($record), ]); } return $data; }
php
private function listRecord(Request $request, \record_adapter $record) { $technicalInformation = []; foreach ($record->get_technical_infos()->getValues() as $name => $value) { $technicalInformation[] = ['name' => $name, 'value' => $value]; } $data = [ 'databox_id' => $record->getDataboxId(), 'record_id' => $record->getRecordId(), 'mime_type' => $record->getMimeType(), 'title' => $record->get_title(), 'original_name' => $record->get_original_name(), 'updated_on' => $record->getUpdated()->format(DATE_ATOM), 'created_on' => $record->getCreated()->format(DATE_ATOM), 'collection_id' => $record->getCollectionId(), 'base_id' => $record->getBaseId(), 'sha256' => $record->getSha256(), 'thumbnail' => $this->listEmbeddableMedia($request, $record, $record->get_thumbnail()), 'technical_informations' => $technicalInformation, 'phrasea_type' => $record->getType(), 'uuid' => $record->getUuid(), ]; if ($request->attributes->get('_extended', false)) { $data = array_merge($data, [ 'subdefs' => $this->listRecordEmbeddableMedias($request, $record), 'metadata' => $this->listRecordMetadata($record), 'status' => $this->listRecordStatus($record), 'caption' => $this->listRecordCaption($record), ]); } return $data; }
[ "private", "function", "listRecord", "(", "Request", "$", "request", ",", "\\", "record_adapter", "$", "record", ")", "{", "$", "technicalInformation", "=", "[", "]", ";", "foreach", "(", "$", "record", "->", "get_technical_infos", "(", ")", "->", "getValues...
Retrieve detailed information about one record @param Request $request @param \record_adapter $record @return array
[ "Retrieve", "detailed", "information", "about", "one", "record" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L1610-L1644
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.listStory
private function listStory(Request $request, \record_adapter $story) { if (!$story->isStory()) { return Result::createError($request, 404, 'Story not found')->createResponse(); } $caption = $story->get_caption(); $format = function (\caption_record $caption, $dcField) { $field = $caption->get_dc_field($dcField); if (!$field) { return null; } return $field->get_serialized_values(); }; return [ '@entity@' => self::OBJECT_TYPE_STORY, 'databox_id' => $story->getDataboxId(), 'story_id' => $story->getRecordId(), 'updated_on' => $story->getUpdated()->format(DATE_ATOM), 'created_on' => $story->getCreated()->format(DATE_ATOM), 'collection_id' => $story->getCollectionId(), 'base_id' => $story->getBaseId(), 'thumbnail' => $this->listEmbeddableMedia($request, $story, $story->get_thumbnail()), 'uuid' => $story->getUuid(), 'metadatas' => [ '@entity@' => self::OBJECT_TYPE_STORY_METADATA_BAG, 'dc:contributor' => $format($caption, \databox_Field_DCESAbstract::Contributor), 'dc:coverage' => $format($caption, \databox_Field_DCESAbstract::Coverage), 'dc:creator' => $format($caption, \databox_Field_DCESAbstract::Creator), 'dc:date' => $format($caption, \databox_Field_DCESAbstract::Date), 'dc:description' => $format($caption, \databox_Field_DCESAbstract::Description), 'dc:format' => $format($caption, \databox_Field_DCESAbstract::Format), 'dc:identifier' => $format($caption, \databox_Field_DCESAbstract::Identifier), 'dc:language' => $format($caption, \databox_Field_DCESAbstract::Language), 'dc:publisher' => $format($caption, \databox_Field_DCESAbstract::Publisher), 'dc:relation' => $format($caption, \databox_Field_DCESAbstract::Relation), 'dc:rights' => $format($caption, \databox_Field_DCESAbstract::Rights), 'dc:source' => $format($caption, \databox_Field_DCESAbstract::Source), 'dc:subject' => $format($caption, \databox_Field_DCESAbstract::Subject), 'dc:title' => $format($caption, \databox_Field_DCESAbstract::Title), 'dc:type' => $format($caption, \databox_Field_DCESAbstract::Type), ], 'records' => $this->listRecords($request, array_values($story->getChildren()->get_elements())), ]; }
php
private function listStory(Request $request, \record_adapter $story) { if (!$story->isStory()) { return Result::createError($request, 404, 'Story not found')->createResponse(); } $caption = $story->get_caption(); $format = function (\caption_record $caption, $dcField) { $field = $caption->get_dc_field($dcField); if (!$field) { return null; } return $field->get_serialized_values(); }; return [ '@entity@' => self::OBJECT_TYPE_STORY, 'databox_id' => $story->getDataboxId(), 'story_id' => $story->getRecordId(), 'updated_on' => $story->getUpdated()->format(DATE_ATOM), 'created_on' => $story->getCreated()->format(DATE_ATOM), 'collection_id' => $story->getCollectionId(), 'base_id' => $story->getBaseId(), 'thumbnail' => $this->listEmbeddableMedia($request, $story, $story->get_thumbnail()), 'uuid' => $story->getUuid(), 'metadatas' => [ '@entity@' => self::OBJECT_TYPE_STORY_METADATA_BAG, 'dc:contributor' => $format($caption, \databox_Field_DCESAbstract::Contributor), 'dc:coverage' => $format($caption, \databox_Field_DCESAbstract::Coverage), 'dc:creator' => $format($caption, \databox_Field_DCESAbstract::Creator), 'dc:date' => $format($caption, \databox_Field_DCESAbstract::Date), 'dc:description' => $format($caption, \databox_Field_DCESAbstract::Description), 'dc:format' => $format($caption, \databox_Field_DCESAbstract::Format), 'dc:identifier' => $format($caption, \databox_Field_DCESAbstract::Identifier), 'dc:language' => $format($caption, \databox_Field_DCESAbstract::Language), 'dc:publisher' => $format($caption, \databox_Field_DCESAbstract::Publisher), 'dc:relation' => $format($caption, \databox_Field_DCESAbstract::Relation), 'dc:rights' => $format($caption, \databox_Field_DCESAbstract::Rights), 'dc:source' => $format($caption, \databox_Field_DCESAbstract::Source), 'dc:subject' => $format($caption, \databox_Field_DCESAbstract::Subject), 'dc:title' => $format($caption, \databox_Field_DCESAbstract::Title), 'dc:type' => $format($caption, \databox_Field_DCESAbstract::Type), ], 'records' => $this->listRecords($request, array_values($story->getChildren()->get_elements())), ]; }
[ "private", "function", "listStory", "(", "Request", "$", "request", ",", "\\", "record_adapter", "$", "story", ")", "{", "if", "(", "!", "$", "story", "->", "isStory", "(", ")", ")", "{", "return", "Result", "::", "createError", "(", "$", "request", ",...
Retrieve detailed information about one story @param Request $request @param \record_adapter $story @return array @throws \Exception
[ "Retrieve", "detailed", "information", "about", "one", "story" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L1654-L1703
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.getRecordMetadataAction
public function getRecordMetadataAction(Request $request, $databox_id, $record_id) { $record = $this->findDataboxById($databox_id)->get_record($record_id); $ret = ["record_metadatas" => $this->listRecordMetadata($record)]; return Result::create($request, $ret)->createResponse(); }
php
public function getRecordMetadataAction(Request $request, $databox_id, $record_id) { $record = $this->findDataboxById($databox_id)->get_record($record_id); $ret = ["record_metadatas" => $this->listRecordMetadata($record)]; return Result::create($request, $ret)->createResponse(); }
[ "public", "function", "getRecordMetadataAction", "(", "Request", "$", "request", ",", "$", "databox_id", ",", "$", "record_id", ")", "{", "$", "record", "=", "$", "this", "->", "findDataboxById", "(", "$", "databox_id", ")", "->", "get_record", "(", "$", "...
Get a Response containing the record metadata @param Request $request @param int $databox_id @param int $record_id @return Response
[ "Get", "a", "Response", "containing", "the", "record", "metadata" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L1738-L1744
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.listRecordMetadata
private function listRecordMetadata(\record_adapter $record) { $includeBusiness = $this->getAclForUser()->can_see_business_fields($record->getDatabox()); return $this->listRecordCaptionFields($record->get_caption()->get_fields(null, $includeBusiness)); }
php
private function listRecordMetadata(\record_adapter $record) { $includeBusiness = $this->getAclForUser()->can_see_business_fields($record->getDatabox()); return $this->listRecordCaptionFields($record->get_caption()->get_fields(null, $includeBusiness)); }
[ "private", "function", "listRecordMetadata", "(", "\\", "record_adapter", "$", "record", ")", "{", "$", "includeBusiness", "=", "$", "this", "->", "getAclForUser", "(", ")", "->", "can_see_business_fields", "(", "$", "record", "->", "getDatabox", "(", ")", ")"...
List all fields of given record @param \record_adapter $record @return array
[ "List", "all", "fields", "of", "given", "record" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L1752-L1757
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.getRecordStatusAction
public function getRecordStatusAction(Request $request, $databox_id, $record_id) { $record = $this->findDataboxById($databox_id)->get_record($record_id); $ret = ["status" => $this->listRecordStatus($record)]; return Result::create($request, $ret)->createResponse(); }
php
public function getRecordStatusAction(Request $request, $databox_id, $record_id) { $record = $this->findDataboxById($databox_id)->get_record($record_id); $ret = ["status" => $this->listRecordStatus($record)]; return Result::create($request, $ret)->createResponse(); }
[ "public", "function", "getRecordStatusAction", "(", "Request", "$", "request", ",", "$", "databox_id", ",", "$", "record_id", ")", "{", "$", "record", "=", "$", "this", "->", "findDataboxById", "(", "$", "databox_id", ")", "->", "get_record", "(", "$", "re...
Get a Response containing the record status @param Request $request @param int $databox_id @param int $record_id @return Response
[ "Get", "a", "Response", "containing", "the", "record", "status" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L1803-L1810
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.listRecordStatus
private function listRecordStatus(\record_adapter $record) { $ret = []; foreach ($record->getStatusStructure() as $bit => $status) { $ret[] = [ 'bit' => $bit, 'state' => \databox_status::bitIsSet($record->getStatusBitField(), $bit), ]; } return $ret; }
php
private function listRecordStatus(\record_adapter $record) { $ret = []; foreach ($record->getStatusStructure() as $bit => $status) { $ret[] = [ 'bit' => $bit, 'state' => \databox_status::bitIsSet($record->getStatusBitField(), $bit), ]; } return $ret; }
[ "private", "function", "listRecordStatus", "(", "\\", "record_adapter", "$", "record", ")", "{", "$", "ret", "=", "[", "]", ";", "foreach", "(", "$", "record", "->", "getStatusStructure", "(", ")", "as", "$", "bit", "=>", "$", "status", ")", "{", "$", ...
Retrieve detailed information about one status @param \record_adapter $record @return array
[ "Retrieve", "detailed", "information", "about", "one", "status" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L1818-L1829
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.getRelatedRecordsAction
public function getRelatedRecordsAction(Request $request, $databox_id, $record_id) { $record = $this->findDataboxById($databox_id)->get_record($record_id); $baskets = array_map(function (Basket $basket) { return $this->listBasket($basket); }, (array) $record->get_container_baskets($this->app['orm.em'], $this->getAuthenticatedUser())); $stories = array_map(function (\record_adapter $story) use ($request) { return $this->listStory($request, $story); }, array_values($record->get_grouping_parents()->get_elements())); return Result::create($request, ["baskets" => $baskets, "stories" => $stories])->createResponse(); }
php
public function getRelatedRecordsAction(Request $request, $databox_id, $record_id) { $record = $this->findDataboxById($databox_id)->get_record($record_id); $baskets = array_map(function (Basket $basket) { return $this->listBasket($basket); }, (array) $record->get_container_baskets($this->app['orm.em'], $this->getAuthenticatedUser())); $stories = array_map(function (\record_adapter $story) use ($request) { return $this->listStory($request, $story); }, array_values($record->get_grouping_parents()->get_elements())); return Result::create($request, ["baskets" => $baskets, "stories" => $stories])->createResponse(); }
[ "public", "function", "getRelatedRecordsAction", "(", "Request", "$", "request", ",", "$", "databox_id", ",", "$", "record_id", ")", "{", "$", "record", "=", "$", "this", "->", "findDataboxById", "(", "$", "databox_id", ")", "->", "get_record", "(", "$", "...
Get a Response containing the baskets where the record is in @param Request $request @param int $databox_id @param int $record_id @return Response
[ "Get", "a", "Response", "containing", "the", "baskets", "where", "the", "record", "is", "in" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L1840-L1854
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.listBasket
private function listBasket(Basket $basket) { $ret = [ 'basket_id' => $basket->getId(), 'owner' => $this->listUser($basket->getUser()), 'created_on' => $basket->getCreated()->format(DATE_ATOM), 'description' => (string) $basket->getDescription(), 'name' => $basket->getName(), 'pusher_usr_id' => $basket->getPusher() ? $basket->getPusher()->getId() : null, 'pusher' => $basket->getPusher() ? $this->listUser($basket->getPusher()) : null, 'updated_on' => $basket->getUpdated()->format(DATE_ATOM), 'unread' => !$basket->isRead(), 'validation_basket' => !!$basket->getValidation(), ]; if ($basket->getValidation()) { $users = array_map(function (ValidationParticipant $participant) { $user = $participant->getUser(); return [ 'usr_id' => $user->getId(), 'usr_name' => $user->getDisplayName(), 'confirmed' => $participant->getIsConfirmed(), 'can_agree' => $participant->getCanAgree(), 'can_see_others' => $participant->getCanSeeOthers(), 'readonly' => $user->getId() != $this->getAuthenticatedUser()->getId(), 'user' => $this->listUser($user), ]; }, iterator_to_array($basket->getValidation()->getParticipants())); $expires_on_atom = NullableDateTime::format($basket->getValidation()->getExpires()); $ret = array_merge([ 'validation_users' => $users, 'expires_on' => $expires_on_atom, 'validation_infos' => $basket->getValidation() ->getValidationString($this->app, $this->getAuthenticatedUser()), 'validation_confirmed' => $basket->getValidation() ->getParticipant($this->getAuthenticatedUser()) ->getIsConfirmed(), 'validation_initiator' => $basket->getValidation() ->isInitiator($this->getAuthenticatedUser()), 'validation_initiator_user' => $this->listUser($basket->getValidation()->getInitiator()), ], $ret); } return $ret; }
php
private function listBasket(Basket $basket) { $ret = [ 'basket_id' => $basket->getId(), 'owner' => $this->listUser($basket->getUser()), 'created_on' => $basket->getCreated()->format(DATE_ATOM), 'description' => (string) $basket->getDescription(), 'name' => $basket->getName(), 'pusher_usr_id' => $basket->getPusher() ? $basket->getPusher()->getId() : null, 'pusher' => $basket->getPusher() ? $this->listUser($basket->getPusher()) : null, 'updated_on' => $basket->getUpdated()->format(DATE_ATOM), 'unread' => !$basket->isRead(), 'validation_basket' => !!$basket->getValidation(), ]; if ($basket->getValidation()) { $users = array_map(function (ValidationParticipant $participant) { $user = $participant->getUser(); return [ 'usr_id' => $user->getId(), 'usr_name' => $user->getDisplayName(), 'confirmed' => $participant->getIsConfirmed(), 'can_agree' => $participant->getCanAgree(), 'can_see_others' => $participant->getCanSeeOthers(), 'readonly' => $user->getId() != $this->getAuthenticatedUser()->getId(), 'user' => $this->listUser($user), ]; }, iterator_to_array($basket->getValidation()->getParticipants())); $expires_on_atom = NullableDateTime::format($basket->getValidation()->getExpires()); $ret = array_merge([ 'validation_users' => $users, 'expires_on' => $expires_on_atom, 'validation_infos' => $basket->getValidation() ->getValidationString($this->app, $this->getAuthenticatedUser()), 'validation_confirmed' => $basket->getValidation() ->getParticipant($this->getAuthenticatedUser()) ->getIsConfirmed(), 'validation_initiator' => $basket->getValidation() ->isInitiator($this->getAuthenticatedUser()), 'validation_initiator_user' => $this->listUser($basket->getValidation()->getInitiator()), ], $ret); } return $ret; }
[ "private", "function", "listBasket", "(", "Basket", "$", "basket", ")", "{", "$", "ret", "=", "[", "'basket_id'", "=>", "$", "basket", "->", "getId", "(", ")", ",", "'owner'", "=>", "$", "this", "->", "listUser", "(", "$", "basket", "->", "getUser", ...
Retrieve information about one basket @param Basket $basket @return array
[ "Retrieve", "information", "about", "one", "basket" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L1863-L1910
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.getRecordAction
public function getRecordAction(Request $request, $databox_id, $record_id) { try { $record = $this->findDataboxById($databox_id)->get_record($record_id); return Result::create($request, ['record' => $this->listRecord($request, $record)])->createResponse(); } catch (NotFoundHttpException $e) { return Result::createError($request, 404, $this->app->trans('Record Not Found'))->createResponse(); } catch (\Exception $e) { return $this->getBadRequestAction($request, $this->app->trans('An error occurred')); } }
php
public function getRecordAction(Request $request, $databox_id, $record_id) { try { $record = $this->findDataboxById($databox_id)->get_record($record_id); return Result::create($request, ['record' => $this->listRecord($request, $record)])->createResponse(); } catch (NotFoundHttpException $e) { return Result::createError($request, 404, $this->app->trans('Record Not Found'))->createResponse(); } catch (\Exception $e) { return $this->getBadRequestAction($request, $this->app->trans('An error occurred')); } }
[ "public", "function", "getRecordAction", "(", "Request", "$", "request", ",", "$", "databox_id", ",", "$", "record_id", ")", "{", "try", "{", "$", "record", "=", "$", "this", "->", "findDataboxById", "(", "$", "databox_id", ")", "->", "get_record", "(", ...
Return detailed information about one record @param Request $request @param int $databox_id @param int $record_id @return Response
[ "Return", "detailed", "information", "about", "one", "record" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L2025-L2036
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.setRecordCollectionAction
public function setRecordCollectionAction(Request $request, $databox_id, $record_id) { $databox = $this->findDataboxById($databox_id); $record = $databox->get_record($record_id); try { $collection = \collection::getByBaseId($this->app, $request->get('base_id')); $record->move_to_collection($collection, $this->getApplicationBox()); return Result::create($request, ["record" => $this->listRecord($request, $record)])->createResponse(); } catch (\Exception $e) { return $this->getBadRequestAction($request, $e->getMessage()); } }
php
public function setRecordCollectionAction(Request $request, $databox_id, $record_id) { $databox = $this->findDataboxById($databox_id); $record = $databox->get_record($record_id); try { $collection = \collection::getByBaseId($this->app, $request->get('base_id')); $record->move_to_collection($collection, $this->getApplicationBox()); return Result::create($request, ["record" => $this->listRecord($request, $record)])->createResponse(); } catch (\Exception $e) { return $this->getBadRequestAction($request, $e->getMessage()); } }
[ "public", "function", "setRecordCollectionAction", "(", "Request", "$", "request", ",", "$", "databox_id", ",", "$", "record_id", ")", "{", "$", "databox", "=", "$", "this", "->", "findDataboxById", "(", "$", "databox_id", ")", ";", "$", "record", "=", "$"...
Move a record to another collection @param Request $request @param int $databox_id @param int $record_id @return Response
[ "Move", "a", "record", "to", "another", "collection" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L2047-L2060
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.listBaskets
private function listBaskets() { /** @var BasketRepository $repo */ $repo = $this->app['repo.baskets']; return array_map(function (Basket $basket) { return $this->listBasket($basket); }, $repo->findActiveByUser($this->getAuthenticatedUser())); }
php
private function listBaskets() { /** @var BasketRepository $repo */ $repo = $this->app['repo.baskets']; return array_map(function (Basket $basket) { return $this->listBasket($basket); }, $repo->findActiveByUser($this->getAuthenticatedUser())); }
[ "private", "function", "listBaskets", "(", ")", "{", "/** @var BasketRepository $repo */", "$", "repo", "=", "$", "this", "->", "app", "[", "'repo.baskets'", "]", ";", "return", "array_map", "(", "function", "(", "Basket", "$", "basket", ")", "{", "return", ...
Return a baskets list * @return array
[ "Return", "a", "baskets", "list", "*" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L2079-L2087
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.createBasketAction
public function createBasketAction(Request $request) { $name = $request->get('name'); if (trim(strip_tags($name)) === '') { return $this->getBadRequestAction($request, 'Missing basket name parameter'); } $Basket = new Basket(); $Basket->setUser($this->getAuthenticatedUser()); $Basket->setName($name); /** @var EntityManager $em */ $em = $this->app['orm.em']; $em->persist($Basket); $em->flush(); return Result::create($request, ["basket" => $this->listBasket($Basket)])->createResponse(); }
php
public function createBasketAction(Request $request) { $name = $request->get('name'); if (trim(strip_tags($name)) === '') { return $this->getBadRequestAction($request, 'Missing basket name parameter'); } $Basket = new Basket(); $Basket->setUser($this->getAuthenticatedUser()); $Basket->setName($name); /** @var EntityManager $em */ $em = $this->app['orm.em']; $em->persist($Basket); $em->flush(); return Result::create($request, ["basket" => $this->listBasket($Basket)])->createResponse(); }
[ "public", "function", "createBasketAction", "(", "Request", "$", "request", ")", "{", "$", "name", "=", "$", "request", "->", "get", "(", "'name'", ")", ";", "if", "(", "trim", "(", "strip_tags", "(", "$", "name", ")", ")", "===", "''", ")", "{", "...
Create a new basket @param Request $request @return Response
[ "Create", "a", "new", "basket" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L2096-L2114
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.getBasketAction
public function getBasketAction(Request $request, Basket $basket) { $ret = [ "basket" => $this->listBasket($basket), "basket_elements" => $this->listBasketContent($request, $basket), ]; return Result::create($request, $ret)->createResponse(); }
php
public function getBasketAction(Request $request, Basket $basket) { $ret = [ "basket" => $this->listBasket($basket), "basket_elements" => $this->listBasketContent($request, $basket), ]; return Result::create($request, $ret)->createResponse(); }
[ "public", "function", "getBasketAction", "(", "Request", "$", "request", ",", "Basket", "$", "basket", ")", "{", "$", "ret", "=", "[", "\"basket\"", "=>", "$", "this", "->", "listBasket", "(", "$", "basket", ")", ",", "\"basket_elements\"", "=>", "$", "t...
Retrieve a basket @param Request $request @param Basket $basket @return Response
[ "Retrieve", "a", "basket" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L2124-L2132
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.listBasketContent
private function listBasketContent(Request $request, Basket $basket) { return array_map(function (BasketElement $element) use ($request) { return $this->listBasketElement($request, $element); }, iterator_to_array($basket->getElements())); }
php
private function listBasketContent(Request $request, Basket $basket) { return array_map(function (BasketElement $element) use ($request) { return $this->listBasketElement($request, $element); }, iterator_to_array($basket->getElements())); }
[ "private", "function", "listBasketContent", "(", "Request", "$", "request", ",", "Basket", "$", "basket", ")", "{", "return", "array_map", "(", "function", "(", "BasketElement", "$", "element", ")", "use", "(", "$", "request", ")", "{", "return", "$", "thi...
Retrieve elements of one basket @param Request $request @param Basket $basket @return array
[ "Retrieve", "elements", "of", "one", "basket" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L2141-L2146
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.listBasketElement
private function listBasketElement(Request $request, BasketElement $basket_element) { $ret = [ 'basket_element_id' => $basket_element->getId(), 'order' => $basket_element->getOrd(), 'record' => $this->listRecord($request, $basket_element->getRecord($this->app)), 'validation_item' => null != $basket_element->getBasket()->getValidation(), ]; if ($basket_element->getBasket()->getValidation()) { $choices = []; $agreement = null; $note = ''; /** @var ValidationData $validationData */ foreach ($basket_element->getValidationDatas() as $validationData) { $participant = $validationData->getParticipant(); $user = $participant->getUser(); $choices[] = [ 'validation_user' => [ 'usr_id' => $user->getId(), 'usr_name' => $user->getDisplayName(), 'confirmed' => $participant->getIsConfirmed(), 'can_agree' => $participant->getCanAgree(), 'can_see_others' => $participant->getCanSeeOthers(), 'readonly' => $user->getId() != $this->getAuthenticatedUser()->getId(), 'user' => $this->listUser($user), ], 'agreement' => $validationData->getAgreement(), 'updated_on' => $validationData->getUpdated()->format(DATE_ATOM), 'note' => null === $validationData->getNote() ? '' : $validationData->getNote(), ]; if ($user->getId() == $this->getAuthenticatedUser()->getId()) { $agreement = $validationData->getAgreement(); $note = null === $validationData->getNote() ? '' : $validationData->getNote(); } $ret['validation_choices'] = $choices; } $ret['agreement'] = $agreement; $ret['note'] = $note; } return $ret; }
php
private function listBasketElement(Request $request, BasketElement $basket_element) { $ret = [ 'basket_element_id' => $basket_element->getId(), 'order' => $basket_element->getOrd(), 'record' => $this->listRecord($request, $basket_element->getRecord($this->app)), 'validation_item' => null != $basket_element->getBasket()->getValidation(), ]; if ($basket_element->getBasket()->getValidation()) { $choices = []; $agreement = null; $note = ''; /** @var ValidationData $validationData */ foreach ($basket_element->getValidationDatas() as $validationData) { $participant = $validationData->getParticipant(); $user = $participant->getUser(); $choices[] = [ 'validation_user' => [ 'usr_id' => $user->getId(), 'usr_name' => $user->getDisplayName(), 'confirmed' => $participant->getIsConfirmed(), 'can_agree' => $participant->getCanAgree(), 'can_see_others' => $participant->getCanSeeOthers(), 'readonly' => $user->getId() != $this->getAuthenticatedUser()->getId(), 'user' => $this->listUser($user), ], 'agreement' => $validationData->getAgreement(), 'updated_on' => $validationData->getUpdated()->format(DATE_ATOM), 'note' => null === $validationData->getNote() ? '' : $validationData->getNote(), ]; if ($user->getId() == $this->getAuthenticatedUser()->getId()) { $agreement = $validationData->getAgreement(); $note = null === $validationData->getNote() ? '' : $validationData->getNote(); } $ret['validation_choices'] = $choices; } $ret['agreement'] = $agreement; $ret['note'] = $note; } return $ret; }
[ "private", "function", "listBasketElement", "(", "Request", "$", "request", ",", "BasketElement", "$", "basket_element", ")", "{", "$", "ret", "=", "[", "'basket_element_id'", "=>", "$", "basket_element", "->", "getId", "(", ")", ",", "'order'", "=>", "$", "...
Retrieve detailed information about a basket element @param Request $request @param BasketElement $basket_element @return array
[ "Retrieve", "detailed", "information", "about", "a", "basket", "element" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L2155-L2201
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.setBasketTitleAction
public function setBasketTitleAction(Request $request, Basket $basket) { $basket->setName($request->get('name')); /** @var EntityManager $em */ $em = $this->app['orm.em']; $em->persist($basket); $em->flush(); return Result::create($request, ["basket" => $this->listBasket($basket)])->createResponse(); }
php
public function setBasketTitleAction(Request $request, Basket $basket) { $basket->setName($request->get('name')); /** @var EntityManager $em */ $em = $this->app['orm.em']; $em->persist($basket); $em->flush(); return Result::create($request, ["basket" => $this->listBasket($basket)])->createResponse(); }
[ "public", "function", "setBasketTitleAction", "(", "Request", "$", "request", ",", "Basket", "$", "basket", ")", "{", "$", "basket", "->", "setName", "(", "$", "request", "->", "get", "(", "'name'", ")", ")", ";", "/** @var EntityManager $em */", "$", "em", ...
Change the name of one basket @param Request $request @param Basket $basket @return Response
[ "Change", "the", "name", "of", "one", "basket" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L2211-L2221
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.setBasketDescriptionAction
public function setBasketDescriptionAction(Request $request, Basket $basket) { $basket->setDescription($request->get('description')); /** @var EntityManager $em */ $em = $this->app['orm.em']; $em->persist($basket); $em->flush(); return Result::create($request, ["basket" => $this->listBasket($basket)])->createResponse(); }
php
public function setBasketDescriptionAction(Request $request, Basket $basket) { $basket->setDescription($request->get('description')); /** @var EntityManager $em */ $em = $this->app['orm.em']; $em->persist($basket); $em->flush(); return Result::create($request, ["basket" => $this->listBasket($basket)])->createResponse(); }
[ "public", "function", "setBasketDescriptionAction", "(", "Request", "$", "request", ",", "Basket", "$", "basket", ")", "{", "$", "basket", "->", "setDescription", "(", "$", "request", "->", "get", "(", "'description'", ")", ")", ";", "/** @var EntityManager $em ...
Change the description of one basket @param Request $request @param Basket $basket @return Response
[ "Change", "the", "description", "of", "one", "basket" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L2231-L2241
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Api/V1Controller.php
V1Controller.deleteBasketAction
public function deleteBasketAction(Request $request, Basket $basket) { /** @var EntityManager $em */ $em = $this->app['orm.em']; $em->remove($basket); $em->flush(); return $this->searchBasketsAction($request); }
php
public function deleteBasketAction(Request $request, Basket $basket) { /** @var EntityManager $em */ $em = $this->app['orm.em']; $em->remove($basket); $em->flush(); return $this->searchBasketsAction($request); }
[ "public", "function", "deleteBasketAction", "(", "Request", "$", "request", ",", "Basket", "$", "basket", ")", "{", "/** @var EntityManager $em */", "$", "em", "=", "$", "this", "->", "app", "[", "'orm.em'", "]", ";", "$", "em", "->", "remove", "(", "$", ...
Delete a basket @param Request $request @param Basket $basket @return array
[ "Delete", "a", "basket" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/V1Controller.php#L2251-L2259