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/Controller/Admin/DashboardController.php | DashboardController.addAdmins | public function addAdmins(Request $request)
{
$admins = $request->request->get('admins', []);
// Remove empty values
$admins = array_filter($admins);
if (!is_array($admins) || count($admins) === 0) {
$this->app->abort(400, '"admins" parameter must contains at least one value.');
}
/** @var Authenticator $authenticator */
$authenticator = $this->app->getAuthenticator();
if (!in_array($authenticator->getUser()->getId(), $admins)) {
$admins[] = $authenticator->getUser()->getId();
}
$userRepository = $this->getUserRepository();
$demotedAdmins = [];
foreach ($userRepository->findAdmins() as $admin) {
if (!in_array($admin->getId(), $admins)) {
$demotedAdmins[$admin->getId()] = $admin;
}
}
$userRepository->findBy(['id' => $admins]);
$admins = array_map(function ($usrId) use ($userRepository) {
if (null === $user = $userRepository->find($usrId)) {
throw new RuntimeException(sprintf('Invalid usrId %s provided.', $usrId));
}
return $user;
}, $admins);
/** @var UserManipulator $userManipulator */
$userManipulator = $this->app['manipulator.user'];
$userManipulator->demote($demotedAdmins);
$userManipulator->promote($admins);
/** @var ACLManipulator $aclManipulator */
$aclManipulator = $this->app['manipulator.acl'];
$aclManipulator->resetAdminRights($admins);
return $this->app->redirectPath('admin_dashboard');
} | php | public function addAdmins(Request $request)
{
$admins = $request->request->get('admins', []);
// Remove empty values
$admins = array_filter($admins);
if (!is_array($admins) || count($admins) === 0) {
$this->app->abort(400, '"admins" parameter must contains at least one value.');
}
/** @var Authenticator $authenticator */
$authenticator = $this->app->getAuthenticator();
if (!in_array($authenticator->getUser()->getId(), $admins)) {
$admins[] = $authenticator->getUser()->getId();
}
$userRepository = $this->getUserRepository();
$demotedAdmins = [];
foreach ($userRepository->findAdmins() as $admin) {
if (!in_array($admin->getId(), $admins)) {
$demotedAdmins[$admin->getId()] = $admin;
}
}
$userRepository->findBy(['id' => $admins]);
$admins = array_map(function ($usrId) use ($userRepository) {
if (null === $user = $userRepository->find($usrId)) {
throw new RuntimeException(sprintf('Invalid usrId %s provided.', $usrId));
}
return $user;
}, $admins);
/** @var UserManipulator $userManipulator */
$userManipulator = $this->app['manipulator.user'];
$userManipulator->demote($demotedAdmins);
$userManipulator->promote($admins);
/** @var ACLManipulator $aclManipulator */
$aclManipulator = $this->app['manipulator.acl'];
$aclManipulator->resetAdminRights($admins);
return $this->app->redirectPath('admin_dashboard');
} | [
"public",
"function",
"addAdmins",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"admins",
"=",
"$",
"request",
"->",
"request",
"->",
"get",
"(",
"'admins'",
",",
"[",
"]",
")",
";",
"// Remove empty values",
"$",
"admins",
"=",
"array_filter",
"(",
"$... | Grant to an user admin rights
@param Request $request
@return RedirectResponse | [
"Grant",
"to",
"an",
"user",
"admin",
"rights"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/DashboardController.php#L124-L170 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/SearchEngine/Elastic/Search/QueryCompiler.php | QueryCompiler.parse | public function parse($string, $postprocessing = true)
{
return $this->visitString($string, $this->createQueryVisitor(), $postprocessing);
} | php | public function parse($string, $postprocessing = true)
{
return $this->visitString($string, $this->createQueryVisitor(), $postprocessing);
} | [
"public",
"function",
"parse",
"(",
"$",
"string",
",",
"$",
"postprocessing",
"=",
"true",
")",
"{",
"return",
"$",
"this",
"->",
"visitString",
"(",
"$",
"string",
",",
"$",
"this",
"->",
"createQueryVisitor",
"(",
")",
",",
"$",
"postprocessing",
")",... | Creates a Query object from a string | [
"Creates",
"a",
"Query",
"object",
"from",
"a",
"string"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/Elastic/Search/QueryCompiler.php#L56-L59 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/SearchEngine/Elastic/Search/QueryCompiler.php | QueryCompiler.fixOperatorAssociativity | private function fixOperatorAssociativity(TreeNode &$root)
{
switch ($root->getChildrenNumber()) {
case 0:
// Leaf nodes can't be rotated, and have no childs
return;
case 2:
// We only want to rotate tree contained in the left associative
// subset of operators
$rootType = $root->getId();
if (!in_array($rootType, self::$leftAssociativeOperators)) {
break;
}
// Do not break operator precedence
$pivot = $root->getChild(1);
if ($pivot->getId() !== $rootType) {
break;
}
$this->leftRotateTree($root);
break;
}
// Recursively fix tree branches
$children = $root->getChildren();
foreach ($children as $index => $_) {
$this->fixOperatorAssociativity($children[$index]);
}
$root->setChildren($children);
} | php | private function fixOperatorAssociativity(TreeNode &$root)
{
switch ($root->getChildrenNumber()) {
case 0:
// Leaf nodes can't be rotated, and have no childs
return;
case 2:
// We only want to rotate tree contained in the left associative
// subset of operators
$rootType = $root->getId();
if (!in_array($rootType, self::$leftAssociativeOperators)) {
break;
}
// Do not break operator precedence
$pivot = $root->getChild(1);
if ($pivot->getId() !== $rootType) {
break;
}
$this->leftRotateTree($root);
break;
}
// Recursively fix tree branches
$children = $root->getChildren();
foreach ($children as $index => $_) {
$this->fixOperatorAssociativity($children[$index]);
}
$root->setChildren($children);
} | [
"private",
"function",
"fixOperatorAssociativity",
"(",
"TreeNode",
"&",
"$",
"root",
")",
"{",
"switch",
"(",
"$",
"root",
"->",
"getChildrenNumber",
"(",
")",
")",
"{",
"case",
"0",
":",
"// Leaf nodes can't be rotated, and have no childs",
"return",
";",
"case"... | Walks the tree to restore left-associativity of some operators
@param TreeNode $root AST root node | [
"Walks",
"the",
"tree",
"to",
"restore",
"left",
"-",
"associativity",
"of",
"some",
"operators"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/Elastic/Search/QueryCompiler.php#L94-L123 |
alchemy-fr/Phraseanet | lib/classes/patch/380alpha18a.php | patch_380alpha18a.apply | public function apply(base $appbox, Application $app)
{
$app['conf']->set(['binaries', 'recess_binary'], (new ExecutableFinder())->find('recess'));
return true;
} | php | public function apply(base $appbox, Application $app)
{
$app['conf']->set(['binaries', 'recess_binary'], (new ExecutableFinder())->find('recess'));
return true;
} | [
"public",
"function",
"apply",
"(",
"base",
"$",
"appbox",
",",
"Application",
"$",
"app",
")",
"{",
"$",
"app",
"[",
"'conf'",
"]",
"->",
"set",
"(",
"[",
"'binaries'",
",",
"'recess_binary'",
"]",
",",
"(",
"new",
"ExecutableFinder",
"(",
")",
")",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/380alpha18a.php#L50-L55 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Model/Entities/UsrListOwner.php | UsrListOwner.setRole | public function setRole($role)
{
if ( ! in_array($role, [self::ROLE_ADMIN, self::ROLE_EDITOR, self::ROLE_USER]))
throw new \Exception('Unknown role `' . $role . '`');
$this->role = $role;
return $this;
} | php | public function setRole($role)
{
if ( ! in_array($role, [self::ROLE_ADMIN, self::ROLE_EDITOR, self::ROLE_USER]))
throw new \Exception('Unknown role `' . $role . '`');
$this->role = $role;
return $this;
} | [
"public",
"function",
"setRole",
"(",
"$",
"role",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"role",
",",
"[",
"self",
"::",
"ROLE_ADMIN",
",",
"self",
"::",
"ROLE_EDITOR",
",",
"self",
"::",
"ROLE_USER",
"]",
")",
")",
"throw",
"new",
"\\",
... | Set role
@param string $role
@return UsrListOwner | [
"Set",
"role"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Entities/UsrListOwner.php#L101-L109 |
alchemy-fr/Phraseanet | lib/classes/patch/383alpha2a.php | patch_383alpha2a.apply | public function apply(base $appbox, Application $app)
{
// Clean validation sessions where initiator_id does not exist anymore
$sql = 'SELECT DISTINCT(v.id) AS validation_session_id FROM `ValidationSessions` v LEFT JOIN Users u ON (v.initiator_id = u.id) WHERE u.id IS NULL';
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$stmt->closeCursor();
foreach ($rows as $row) {
try {
$vsession = $app['orm.em']->createQuery('SELECT PARTIAL s.{id} FROM Phraseanet:ValidationSession s WHERE s.id = :id')
->setParameters(['id' => $row['validation_session_id']])
->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true)
->getSingleResult();
$app['orm.em']->remove($vsession);
} catch (NoResultException $e) {
}
}
$app['orm.em']->flush();
return true;
} | php | public function apply(base $appbox, Application $app)
{
// Clean validation sessions where initiator_id does not exist anymore
$sql = 'SELECT DISTINCT(v.id) AS validation_session_id FROM `ValidationSessions` v LEFT JOIN Users u ON (v.initiator_id = u.id) WHERE u.id IS NULL';
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$stmt->closeCursor();
foreach ($rows as $row) {
try {
$vsession = $app['orm.em']->createQuery('SELECT PARTIAL s.{id} FROM Phraseanet:ValidationSession s WHERE s.id = :id')
->setParameters(['id' => $row['validation_session_id']])
->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true)
->getSingleResult();
$app['orm.em']->remove($vsession);
} catch (NoResultException $e) {
}
}
$app['orm.em']->flush();
return true;
} | [
"public",
"function",
"apply",
"(",
"base",
"$",
"appbox",
",",
"Application",
"$",
"app",
")",
"{",
"// Clean validation sessions where initiator_id does not exist anymore",
"$",
"sql",
"=",
"'SELECT DISTINCT(v.id) AS validation_session_id FROM `ValidationSessions` v LEFT JOIN Use... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/383alpha2a.php#L58-L82 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Border/Attribute/Metadata.php | Metadata.loadFromString | public static function loadFromString(Application $app, $string)
{
if (!$metadata = @unserialize($string)) {
throw new \InvalidArgumentException('Unable to load metadata from string');
}
if (!$metadata instanceof ExiftoolMeta) {
throw new \InvalidArgumentException('Unable to load metadata from string');
}
return new static($metadata);
} | php | public static function loadFromString(Application $app, $string)
{
if (!$metadata = @unserialize($string)) {
throw new \InvalidArgumentException('Unable to load metadata from string');
}
if (!$metadata instanceof ExiftoolMeta) {
throw new \InvalidArgumentException('Unable to load metadata from string');
}
return new static($metadata);
} | [
"public",
"static",
"function",
"loadFromString",
"(",
"Application",
"$",
"app",
",",
"$",
"string",
")",
"{",
"if",
"(",
"!",
"$",
"metadata",
"=",
"@",
"unserialize",
"(",
"$",
"string",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
... | {@inheritdoc}
@return Metadata | [
"{",
"@inheritdoc",
"}"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Border/Attribute/Metadata.php#L76-L87 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/Upgrade39Tokens.php | Upgrade39Tokens.rollback | public function rollback(EntityManager $em, \appbox $appbox, Configuration $conf)
{
if ($this->tableExists($em, 'tokens_backup')) {
$em->getConnection()->executeUpdate('RENAME TABLE `tokens_backup` TO `tokens`');
}
} | php | public function rollback(EntityManager $em, \appbox $appbox, Configuration $conf)
{
if ($this->tableExists($em, 'tokens_backup')) {
$em->getConnection()->executeUpdate('RENAME TABLE `tokens_backup` TO `tokens`');
}
} | [
"public",
"function",
"rollback",
"(",
"EntityManager",
"$",
"em",
",",
"\\",
"appbox",
"$",
"appbox",
",",
"Configuration",
"$",
"conf",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"tableExists",
"(",
"$",
"em",
",",
"'tokens_backup'",
")",
")",
"{",
"$",... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/Upgrade39Tokens.php#L41-L46 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Border/Checker/AbstractChecker.php | AbstractChecker.restrictToDataboxes | public function restrictToDataboxes($databoxes)
{
if ($this->collections) {
throw new \LogicException('You can not restrict on databoxes and collections simultanously');
}
$this->databoxes = [];
foreach ($this->toIterator($databoxes) as $databox) {
if (!$databox instanceof \databox) {
throw new \InvalidArgumentException('Restrict to databoxes only accept databoxes as argument');
}
$this->databoxes[] = $databox;
}
return $this->databoxes;
} | php | public function restrictToDataboxes($databoxes)
{
if ($this->collections) {
throw new \LogicException('You can not restrict on databoxes and collections simultanously');
}
$this->databoxes = [];
foreach ($this->toIterator($databoxes) as $databox) {
if (!$databox instanceof \databox) {
throw new \InvalidArgumentException('Restrict to databoxes only accept databoxes as argument');
}
$this->databoxes[] = $databox;
}
return $this->databoxes;
} | [
"public",
"function",
"restrictToDataboxes",
"(",
"$",
"databoxes",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"collections",
")",
"{",
"throw",
"new",
"\\",
"LogicException",
"(",
"'You can not restrict on databoxes and collections simultanously'",
")",
";",
"}",
"$",... | Restrict the checker to a set of databoxes.
Warning, you can not restrict on both databoxes and collections
@param \databox[] $databoxes A databox or an array of databoxes
@return bool
@throws \LogicException If already restricted to collections
@throws \InvalidArgumentException In case invalid databoxes are provided | [
"Restrict",
"the",
"checker",
"to",
"a",
"set",
"of",
"databoxes",
".",
"Warning",
"you",
"can",
"not",
"restrict",
"on",
"both",
"databoxes",
"and",
"collections"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Border/Checker/AbstractChecker.php#L52-L68 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Border/Checker/AbstractChecker.php | AbstractChecker.restrictToCollections | public function restrictToCollections($collections)
{
if ($this->databoxes) {
throw new \LogicException('You can not restrict on databoxes and collections simultanously');
}
$this->collections = [];
foreach ($this->toIterator($collections) as $collection) {
if (!$collection instanceof \collection) {
throw new \InvalidArgumentException('Restrict to collections only accept collections as argument');
}
$this->collections[] = $collection;
}
return $this->collections;
} | php | public function restrictToCollections($collections)
{
if ($this->databoxes) {
throw new \LogicException('You can not restrict on databoxes and collections simultanously');
}
$this->collections = [];
foreach ($this->toIterator($collections) as $collection) {
if (!$collection instanceof \collection) {
throw new \InvalidArgumentException('Restrict to collections only accept collections as argument');
}
$this->collections[] = $collection;
}
return $this->collections;
} | [
"public",
"function",
"restrictToCollections",
"(",
"$",
"collections",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"databoxes",
")",
"{",
"throw",
"new",
"\\",
"LogicException",
"(",
"'You can not restrict on databoxes and collections simultanously'",
")",
";",
"}",
"$... | Restrict the checker to a set of collections.
Warning, you can not restrict on both databoxes and collections
@param \collection[] $collections
@return bool
@throws \LogicException If already restricted to databoxes
@throws \InvalidArgumentException In case invalid collections are provided | [
"Restrict",
"the",
"checker",
"to",
"a",
"set",
"of",
"collections",
".",
"Warning",
"you",
"can",
"not",
"restrict",
"on",
"both",
"databoxes",
"and",
"collections"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Border/Checker/AbstractChecker.php#L80-L96 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Border/Checker/AbstractChecker.php | AbstractChecker.isApplicable | public function isApplicable(File $file)
{
if (empty($this->databoxes) && empty($this->collections)) {
return true;
}
if (null === $file->getCollection()) {
return true;
}
$fileDatabox = $file->getCollection()->get_databox();
foreach ($this->databoxes as $databox) {
if ($databox->get_sbas_id() ===
$fileDatabox->get_sbas_id()) {
return true;
}
}
foreach ($this->collections as $collection) {
if ($collection->get_base_id() === $file->getCollection()->get_base_id()) {
return true;
}
}
return false;
} | php | public function isApplicable(File $file)
{
if (empty($this->databoxes) && empty($this->collections)) {
return true;
}
if (null === $file->getCollection()) {
return true;
}
$fileDatabox = $file->getCollection()->get_databox();
foreach ($this->databoxes as $databox) {
if ($databox->get_sbas_id() ===
$fileDatabox->get_sbas_id()) {
return true;
}
}
foreach ($this->collections as $collection) {
if ($collection->get_base_id() === $file->getCollection()->get_base_id()) {
return true;
}
}
return false;
} | [
"public",
"function",
"isApplicable",
"(",
"File",
"$",
"file",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"databoxes",
")",
"&&",
"empty",
"(",
"$",
"this",
"->",
"collections",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"nul... | Returns true if the checker should be executed against the current file
@param File $file A file to check
@return Boolean | [
"Returns",
"true",
"if",
"the",
"checker",
"should",
"be",
"executed",
"against",
"the",
"current",
"file"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Border/Checker/AbstractChecker.php#L105-L131 |
alchemy-fr/Phraseanet | lib/classes/databox/descriptionStructure.php | databox_descriptionStructure.get_element_by_name | public function get_element_by_name($name, $compareMode=self::SLUG_COMPARE)
{
if (null === $this->cache_name_id) {
$this->cache_name_id = [];
foreach ($this->elements as $id => $meta) {
$this->cache_name_id[$meta->get_name()] = $id;
}
}
if($compareMode == self::SLUG_COMPARE) {
$name = databox_field::generateName($name, $this->unicode);
}
return isset($this->cache_name_id[$name])
? $this->elements[$this->cache_name_id[$name]]
: null;
} | php | public function get_element_by_name($name, $compareMode=self::SLUG_COMPARE)
{
if (null === $this->cache_name_id) {
$this->cache_name_id = [];
foreach ($this->elements as $id => $meta) {
$this->cache_name_id[$meta->get_name()] = $id;
}
}
if($compareMode == self::SLUG_COMPARE) {
$name = databox_field::generateName($name, $this->unicode);
}
return isset($this->cache_name_id[$name])
? $this->elements[$this->cache_name_id[$name]]
: null;
} | [
"public",
"function",
"get_element_by_name",
"(",
"$",
"name",
",",
"$",
"compareMode",
"=",
"self",
"::",
"SLUG_COMPARE",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"cache_name_id",
")",
"{",
"$",
"this",
"->",
"cache_name_id",
"=",
"[",
"]"... | @param string $name
@param int $compareMode // use STRICT_COMPARE if the name already comes from phrasea (faster)
@return databox_field|null | [
"@param",
"string",
"$name",
"@param",
"int",
"$compareMode",
"//",
"use",
"STRICT_COMPARE",
"if",
"the",
"name",
"already",
"comes",
"from",
"phrasea",
"(",
"faster",
")"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/databox/descriptionStructure.php#L110-L127 |
alchemy-fr/Phraseanet | lib/classes/set/export.php | set_export.build_zip | public static function build_zip(Application $app, Token $token, array $list, $zipFile)
{
if (isset($list['complete']) && $list['complete'] === true) {
return $zipFile;
}
$files = $list['files'];
$list['complete'] = false;
$token->setData(serialize($list));
$app['manipulator.token']->update($token);
$toRemove = [];
$archiveFiles = [];
foreach ($files as $record) {
if (isset($record["subdefs"])) {
foreach ($record["subdefs"] as $o => $obj) {
$path = p4string::addEndSlash($obj["path"]) . $obj["file"];
if (is_file($path)) {
$name = $obj["folder"]
. $record["export_name"]
. $obj["ajout"]
. (isset($obj["exportExt"]) && trim($obj["exportExt"]) != '' ? '.' . $obj["exportExt"] : '');
$archiveFiles[$app['unicode']->remove_diacritics($name)] = $path;
if ($o == 'caption') {
if (!in_array(dirname($path), $toRemove)) {
$toRemove[] = dirname($path);
}
$toRemove[] = $path;
}
}
}
}
}
$app['zippy']->create($zipFile, $archiveFiles);
$list['complete'] = true;
$token->setData(serialize($list));
$app['manipulator.token']->update($token);
$app['filesystem']->remove($toRemove);
$app['filesystem']->chmod($zipFile, 0760);
return $zipFile;
} | php | public static function build_zip(Application $app, Token $token, array $list, $zipFile)
{
if (isset($list['complete']) && $list['complete'] === true) {
return $zipFile;
}
$files = $list['files'];
$list['complete'] = false;
$token->setData(serialize($list));
$app['manipulator.token']->update($token);
$toRemove = [];
$archiveFiles = [];
foreach ($files as $record) {
if (isset($record["subdefs"])) {
foreach ($record["subdefs"] as $o => $obj) {
$path = p4string::addEndSlash($obj["path"]) . $obj["file"];
if (is_file($path)) {
$name = $obj["folder"]
. $record["export_name"]
. $obj["ajout"]
. (isset($obj["exportExt"]) && trim($obj["exportExt"]) != '' ? '.' . $obj["exportExt"] : '');
$archiveFiles[$app['unicode']->remove_diacritics($name)] = $path;
if ($o == 'caption') {
if (!in_array(dirname($path), $toRemove)) {
$toRemove[] = dirname($path);
}
$toRemove[] = $path;
}
}
}
}
}
$app['zippy']->create($zipFile, $archiveFiles);
$list['complete'] = true;
$token->setData(serialize($list));
$app['manipulator.token']->update($token);
$app['filesystem']->remove($toRemove);
$app['filesystem']->chmod($zipFile, 0760);
return $zipFile;
} | [
"public",
"static",
"function",
"build_zip",
"(",
"Application",
"$",
"app",
",",
"Token",
"$",
"token",
",",
"array",
"$",
"list",
",",
"$",
"zipFile",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"list",
"[",
"'complete'",
"]",
")",
"&&",
"$",
"list",
... | @param Application $app
@param Token $token
@param array $list
@param string $zipFile
@return string | [
"@param",
"Application",
"$app",
"@param",
"Token",
"$token",
"@param",
"array",
"$list",
"@param",
"string",
"$zipFile"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/set/export.php#L674-L723 |
alchemy-fr/Phraseanet | lib/classes/set/export.php | set_export.log_download | public static function log_download(Application $app, array $list, $type, $anonymous = false, $comment = '')
{
$tmplog = [];
$files = $list['files'];
$event_name = in_array($type, [
Session_Logger::EVENT_EXPORTMAIL,
Session_Logger::EVENT_EXPORTDOWNLOAD,
]) ? $type : Session_Logger::EVENT_EXPORTDOWNLOAD;
foreach ($files as $record) {
foreach ($record["subdefs"] as $o => $obj) {
$sbas_id = phrasea::sbasFromBas($app, $record['base_id']);
$record_object = new record_adapter($app, $sbas_id, $record['record_id']);
$app['phraseanet.logger']($record_object->getDatabox())->log($record_object, $event_name, $o, $comment);
if ($o != "caption") {
$log["rid"] = $record_object->getRecordId();
$log["subdef"] = $o;
$log["poids"] = $obj["size"];
$log["shortXml"] = $app['serializer.caption']->serialize($record_object->get_caption(), CaptionSerializer::SERIALIZE_XML);
$tmplog[$record_object->getBaseId()][] = $log;
if (!$anonymous && $o == 'document' && null !== $app->getAuthenticatedUser()) {
$app->getAclForUser($app->getAuthenticatedUser())->remove_remaining($record_object->getBaseId());
}
}
unset($record_object);
}
}
$list_base = array_unique(array_keys($tmplog));
if (!$anonymous && null !== $app->getAuthenticatedUser()) {
$sql = "UPDATE basusr SET remain_dwnld = :remain_dl WHERE base_id = :base_id AND usr_id = :usr_id";
$stmt = $app->getApplicationBox()->get_connection()->prepare($sql);
foreach ($list_base as $base_id) {
if ($app->getAclForUser($app->getAuthenticatedUser())->is_restricted_download($base_id)) {
$params = [
':remain_dl' => $app->getAclForUser($app->getAuthenticatedUser())->remaining_download($base_id),
':base_id' => $base_id,
':usr_id' => $app->getAuthenticatedUser()->getId(),
];
$stmt->execute($params);
}
}
$stmt->closeCursor();
}
} | php | public static function log_download(Application $app, array $list, $type, $anonymous = false, $comment = '')
{
$tmplog = [];
$files = $list['files'];
$event_name = in_array($type, [
Session_Logger::EVENT_EXPORTMAIL,
Session_Logger::EVENT_EXPORTDOWNLOAD,
]) ? $type : Session_Logger::EVENT_EXPORTDOWNLOAD;
foreach ($files as $record) {
foreach ($record["subdefs"] as $o => $obj) {
$sbas_id = phrasea::sbasFromBas($app, $record['base_id']);
$record_object = new record_adapter($app, $sbas_id, $record['record_id']);
$app['phraseanet.logger']($record_object->getDatabox())->log($record_object, $event_name, $o, $comment);
if ($o != "caption") {
$log["rid"] = $record_object->getRecordId();
$log["subdef"] = $o;
$log["poids"] = $obj["size"];
$log["shortXml"] = $app['serializer.caption']->serialize($record_object->get_caption(), CaptionSerializer::SERIALIZE_XML);
$tmplog[$record_object->getBaseId()][] = $log;
if (!$anonymous && $o == 'document' && null !== $app->getAuthenticatedUser()) {
$app->getAclForUser($app->getAuthenticatedUser())->remove_remaining($record_object->getBaseId());
}
}
unset($record_object);
}
}
$list_base = array_unique(array_keys($tmplog));
if (!$anonymous && null !== $app->getAuthenticatedUser()) {
$sql = "UPDATE basusr SET remain_dwnld = :remain_dl WHERE base_id = :base_id AND usr_id = :usr_id";
$stmt = $app->getApplicationBox()->get_connection()->prepare($sql);
foreach ($list_base as $base_id) {
if ($app->getAclForUser($app->getAuthenticatedUser())->is_restricted_download($base_id)) {
$params = [
':remain_dl' => $app->getAclForUser($app->getAuthenticatedUser())->remaining_download($base_id),
':base_id' => $base_id,
':usr_id' => $app->getAuthenticatedUser()->getId(),
];
$stmt->execute($params);
}
}
$stmt->closeCursor();
}
} | [
"public",
"static",
"function",
"log_download",
"(",
"Application",
"$",
"app",
",",
"array",
"$",
"list",
",",
"$",
"type",
",",
"$",
"anonymous",
"=",
"false",
",",
"$",
"comment",
"=",
"''",
")",
"{",
"$",
"tmplog",
"=",
"[",
"]",
";",
"$",
"fil... | @todo a revoir le cas anonymous
@param Application $app
@param array $list
@param String $type
@param boolean $anonymous
@param string $comment
@return void | [
"@todo",
"a",
"revoir",
"le",
"cas",
"anonymous"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/set/export.php#L736-L790 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Command/Setup/H264ConfigurationDumper.php | H264ConfigurationDumper.doExecute | protected function doExecute(InputInterface $input, OutputInterface $output)
{
$output->writeln('');
if (!$this->container['phraseanet.h264-factory']->isH264Enabled()) {
$output->writeln('H264 pseudo streaming support is <error>disabled</error>');
$ret = 1;
} else {
$output->writeln('H264 pseudo streaming support is <info>enabled</info>');
$ret = 0;
}
try {
$configuration = $this->container['phraseanet.h264-factory']->createMode(true, true)->getVirtualHostConfiguration();
$output->writeln('H264 pseudo streaming configuration seems <info>OK</info>');
$output->writeln($configuration);
} catch (RuntimeException $e) {
$output->writeln('H264 pseudo streaming configuration seems <error>invalid</error>');
$ret = 1;
}
$output->writeln('');
return $ret;
} | php | protected function doExecute(InputInterface $input, OutputInterface $output)
{
$output->writeln('');
if (!$this->container['phraseanet.h264-factory']->isH264Enabled()) {
$output->writeln('H264 pseudo streaming support is <error>disabled</error>');
$ret = 1;
} else {
$output->writeln('H264 pseudo streaming support is <info>enabled</info>');
$ret = 0;
}
try {
$configuration = $this->container['phraseanet.h264-factory']->createMode(true, true)->getVirtualHostConfiguration();
$output->writeln('H264 pseudo streaming configuration seems <info>OK</info>');
$output->writeln($configuration);
} catch (RuntimeException $e) {
$output->writeln('H264 pseudo streaming configuration seems <error>invalid</error>');
$ret = 1;
}
$output->writeln('');
return $ret;
} | [
"protected",
"function",
"doExecute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"output",
"->",
"writeln",
"(",
"''",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"container",
"[",
"'phraseanet.h264-factory'",... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/Setup/H264ConfigurationDumper.php#L31-L55 |
alchemy-fr/Phraseanet | lib/classes/patch/370alpha7a.php | patch_370alpha7a.apply | public function apply(base $appbox, Application $app)
{
$conn = $appbox->get_connection();
try {
//get all old lazaret file & transform them to LazaretFile object
$sql = 'SELECT * FROM lazaret';
$stmt = $conn->prepare($sql);
$stmt->execute();
$rs = $stmt->fetchAll();
$stmt->closeCursor();
} catch (DBALException $e) {
// table not found
if ($e->getCode() == '42S02') {
}
return;
}
//order matters for foreign keys constraints
//truncate all altered tables
$this->truncateTable($app['orm.em'], 'Alchemy\\Phrasea\\Model\\Entities\\LazaretAttribute');
$this->truncateTable($app['orm.em'], 'Alchemy\\Phrasea\\Model\\Entities\\LazaretCheck');
$this->truncateTable($app['orm.em'], 'Alchemy\\Phrasea\\Model\\Entities\\LazaretFile');
$this->truncateTable($app['orm.em'], 'Alchemy\\Phrasea\\Model\\Entities\\LazaretSession');
$i = 0;
foreach ($rs as $row) {
$filePath = $app['tmp.lazaret.path'].'/'.$row['filepath'];
if (null === $user = $this->loadUser($app['orm.em'], $row['usr_id'])) {
continue;
}
if (file_exists($filePath)) {
$spec = new ImageSpec();
$spec->setResizeMode(ImageSpec::RESIZE_MODE_INBOUND_FIXEDRATIO);
$spec->setDimensions(375, 275);
$thumbPath = $app['tmp.lazaret.path'].'/'.sprintf("thumb_%s", $row['filepath']);
try {
$app['media-alchemyst']->turnInto($filePath, $thumbPath, $spec);
} catch (MediaAlchemystException $e) {
}
$media = $app->getMediaFromUri($filePath);
$collection = \collection::getByBaseId($app, $row['base_id']);
$borderFile = new \Alchemy\Phrasea\Border\File($app, $media, $collection);
$lazaretSession = new LazaretSession();
$lazaretSession->setUser($user);
$lazaretFile = new LazaretFile();
$lazaretFile->setBaseId($row['base_id']);
if (null === $row['uuid']) {
$uuid = $borderFile->getUUID(true);
$lazaretFile->setUuid($uuid);
} else {
$lazaretFile->setUuid($row['uuid']);
}
if (null === $row['sha256']) {
$sha256 = $media->getHash('sha256');
$lazaretFile->setSha256($sha256);
} else {
$lazaretFile->setSha256($row['sha256']);
}
$lazaretFile->setOriginalName($row['filename']);
$lazaretFile->setFilename($row['filepath']);
$lazaretFile->setThumbFilename(pathinfo($thumbPath), PATHINFO_BASENAME);
$lazaretFile->setCreated(new \DateTime($row['created_on']));
$lazaretFile->setSession($lazaretSession);
$app['orm.em']->persist($lazaretFile);
if (0 === ++$i % 100) {
$app['orm.em']->flush();
$app['orm.em']->clear();
}
}
}
$app['orm.em']->flush();
$app['orm.em']->clear();
$stmt->closeCursor();
return true;
} | php | public function apply(base $appbox, Application $app)
{
$conn = $appbox->get_connection();
try {
//get all old lazaret file & transform them to LazaretFile object
$sql = 'SELECT * FROM lazaret';
$stmt = $conn->prepare($sql);
$stmt->execute();
$rs = $stmt->fetchAll();
$stmt->closeCursor();
} catch (DBALException $e) {
// table not found
if ($e->getCode() == '42S02') {
}
return;
}
//order matters for foreign keys constraints
//truncate all altered tables
$this->truncateTable($app['orm.em'], 'Alchemy\\Phrasea\\Model\\Entities\\LazaretAttribute');
$this->truncateTable($app['orm.em'], 'Alchemy\\Phrasea\\Model\\Entities\\LazaretCheck');
$this->truncateTable($app['orm.em'], 'Alchemy\\Phrasea\\Model\\Entities\\LazaretFile');
$this->truncateTable($app['orm.em'], 'Alchemy\\Phrasea\\Model\\Entities\\LazaretSession');
$i = 0;
foreach ($rs as $row) {
$filePath = $app['tmp.lazaret.path'].'/'.$row['filepath'];
if (null === $user = $this->loadUser($app['orm.em'], $row['usr_id'])) {
continue;
}
if (file_exists($filePath)) {
$spec = new ImageSpec();
$spec->setResizeMode(ImageSpec::RESIZE_MODE_INBOUND_FIXEDRATIO);
$spec->setDimensions(375, 275);
$thumbPath = $app['tmp.lazaret.path'].'/'.sprintf("thumb_%s", $row['filepath']);
try {
$app['media-alchemyst']->turnInto($filePath, $thumbPath, $spec);
} catch (MediaAlchemystException $e) {
}
$media = $app->getMediaFromUri($filePath);
$collection = \collection::getByBaseId($app, $row['base_id']);
$borderFile = new \Alchemy\Phrasea\Border\File($app, $media, $collection);
$lazaretSession = new LazaretSession();
$lazaretSession->setUser($user);
$lazaretFile = new LazaretFile();
$lazaretFile->setBaseId($row['base_id']);
if (null === $row['uuid']) {
$uuid = $borderFile->getUUID(true);
$lazaretFile->setUuid($uuid);
} else {
$lazaretFile->setUuid($row['uuid']);
}
if (null === $row['sha256']) {
$sha256 = $media->getHash('sha256');
$lazaretFile->setSha256($sha256);
} else {
$lazaretFile->setSha256($row['sha256']);
}
$lazaretFile->setOriginalName($row['filename']);
$lazaretFile->setFilename($row['filepath']);
$lazaretFile->setThumbFilename(pathinfo($thumbPath), PATHINFO_BASENAME);
$lazaretFile->setCreated(new \DateTime($row['created_on']));
$lazaretFile->setSession($lazaretSession);
$app['orm.em']->persist($lazaretFile);
if (0 === ++$i % 100) {
$app['orm.em']->flush();
$app['orm.em']->clear();
}
}
}
$app['orm.em']->flush();
$app['orm.em']->clear();
$stmt->closeCursor();
return true;
} | [
"public",
"function",
"apply",
"(",
"base",
"$",
"appbox",
",",
"Application",
"$",
"app",
")",
"{",
"$",
"conn",
"=",
"$",
"appbox",
"->",
"get_connection",
"(",
")",
";",
"try",
"{",
"//get all old lazaret file & transform them to LazaretFile object",
"$",
"sq... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/370alpha7a.php#L62-L158 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Report/RootController.php | RootController.getDashboard | public function getDashboard(Request $request)
{
if ('json' === $request->getRequestFormat()) {
\Session_Logger::updateClientInfos($this->app, 4);
$dashboard = new \module_report_dashboard($this->app, $this->getAuthenticatedUser());
$dmin = $request->query->get('dmin');
$dmax = $request->query->get('dmax');
if ($dmin && $dmax) {
$dashboard->setDate($dmin, $dmax);
}
$dashboard->execute();
return $this->app->json(['html' => $this->render('report/ajax_dashboard_content_child.html.twig', [
'dashboard' => $dashboard
])]);
}
$granted = [];
$acl = $this->getAclForUser();
foreach ($acl->get_granted_base([\ACL::CANREPORT]) as $collection) {
$sbas_id = $collection->get_sbas_id();
if (!isset($granted[$sbas_id])) {
$granted[$sbas_id] = [
'id' => $sbas_id,
'name' => $collection->get_databox()->get_viewname(),
'collections' => [],
'metas' => []
];
foreach ($collection->get_databox()->get_meta_structure() as $meta) {
// skip the fields that can't be reported
if (!$meta->is_report() || ($meta->isBusiness() && !$acl->can_see_business_fields($collection->get_databox()))) {
continue;
}
$granted[$sbas_id]['metas'][] = $meta->get_name();
}
}
$granted[$sbas_id]['collections'][] = [
'id' => $collection->get_coll_id(),
'base_id' => $collection->get_base_id(),
'name' => $collection->get_name(),
];
}
$conf = $this->getConf();
return $this->render('report/report_layout_child.html.twig', [
'ajax_dash' => true,
'dashboard' => null,
'granted_bases' => $granted,
'home_title' => $conf->get(['registry', 'general', 'title']),
'module' => 'report',
'module_name' => 'Report',
'anonymous' => $conf->get(['registry', 'modules', 'anonymous-report']),
'g_anal' => $conf->get(['registry', 'general', 'analytics']),
'ajax' => false,
'ajax_chart' => false
]);
} | php | public function getDashboard(Request $request)
{
if ('json' === $request->getRequestFormat()) {
\Session_Logger::updateClientInfos($this->app, 4);
$dashboard = new \module_report_dashboard($this->app, $this->getAuthenticatedUser());
$dmin = $request->query->get('dmin');
$dmax = $request->query->get('dmax');
if ($dmin && $dmax) {
$dashboard->setDate($dmin, $dmax);
}
$dashboard->execute();
return $this->app->json(['html' => $this->render('report/ajax_dashboard_content_child.html.twig', [
'dashboard' => $dashboard
])]);
}
$granted = [];
$acl = $this->getAclForUser();
foreach ($acl->get_granted_base([\ACL::CANREPORT]) as $collection) {
$sbas_id = $collection->get_sbas_id();
if (!isset($granted[$sbas_id])) {
$granted[$sbas_id] = [
'id' => $sbas_id,
'name' => $collection->get_databox()->get_viewname(),
'collections' => [],
'metas' => []
];
foreach ($collection->get_databox()->get_meta_structure() as $meta) {
// skip the fields that can't be reported
if (!$meta->is_report() || ($meta->isBusiness() && !$acl->can_see_business_fields($collection->get_databox()))) {
continue;
}
$granted[$sbas_id]['metas'][] = $meta->get_name();
}
}
$granted[$sbas_id]['collections'][] = [
'id' => $collection->get_coll_id(),
'base_id' => $collection->get_base_id(),
'name' => $collection->get_name(),
];
}
$conf = $this->getConf();
return $this->render('report/report_layout_child.html.twig', [
'ajax_dash' => true,
'dashboard' => null,
'granted_bases' => $granted,
'home_title' => $conf->get(['registry', 'general', 'title']),
'module' => 'report',
'module_name' => 'Report',
'anonymous' => $conf->get(['registry', 'modules', 'anonymous-report']),
'g_anal' => $conf->get(['registry', 'general', 'analytics']),
'ajax' => false,
'ajax_chart' => false
]);
} | [
"public",
"function",
"getDashboard",
"(",
"Request",
"$",
"request",
")",
"{",
"if",
"(",
"'json'",
"===",
"$",
"request",
"->",
"getRequestFormat",
"(",
")",
")",
"{",
"\\",
"Session_Logger",
"::",
"updateClientInfos",
"(",
"$",
"this",
"->",
"app",
",",... | Display dashboard information
@param Request $request
@return JsonResponse | [
"Display",
"dashboard",
"information"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Report/RootController.php#L29-L92 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Command/BuildSubdefs.php | BuildSubdefs.getOptionAsArray | private function getOptionAsArray(InputInterface $input, $optionName, $option)
{
$ret = [];
foreach($input->getOption($optionName) as $v0) {
foreach(explode(',', $v0) as $v) {
$v = trim($v);
if($option & self::OPTION_ALL_VALUES || !in_array($v, $ret)) {
$ret[] = $v;
}
}
}
return $ret;
} | php | private function getOptionAsArray(InputInterface $input, $optionName, $option)
{
$ret = [];
foreach($input->getOption($optionName) as $v0) {
foreach(explode(',', $v0) as $v) {
$v = trim($v);
if($option & self::OPTION_ALL_VALUES || !in_array($v, $ret)) {
$ret[] = $v;
}
}
}
return $ret;
} | [
"private",
"function",
"getOptionAsArray",
"(",
"InputInterface",
"$",
"input",
",",
"$",
"optionName",
",",
"$",
"option",
")",
"{",
"$",
"ret",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"input",
"->",
"getOption",
"(",
"$",
"optionName",
")",
"as",
"$... | merge options so one can mix csv-option and/or multiple options
ex. with keepUnique = false : --opt=a,b --opt=c --opt=b ==> [a,b,c,b]
ex. with keepUnique = true : --opt=a,b --opt=c --opt=b ==> [a,b,c]
@param InputInterface $input
@param string $optionName
@param int $option
@return array | [
"merge",
"options",
"so",
"one",
"can",
"mix",
"csv",
"-",
"option",
"and",
"/",
"or",
"multiple",
"options",
"ex",
".",
"with",
"keepUnique",
"=",
"false",
":",
"--",
"opt",
"=",
"a",
"b",
"--",
"opt",
"=",
"c",
"--",
"opt",
"=",
"b",
"==",
">",... | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/BuildSubdefs.php#L177-L190 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Command/BuildSubdefs.php | BuildSubdefs.verbose | private function verbose($s)
{
if($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
$this->output->write($s);
}
} | php | private function verbose($s)
{
if($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
$this->output->write($s);
}
} | [
"private",
"function",
"verbose",
"(",
"$",
"s",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"output",
"->",
"getVerbosity",
"(",
")",
">=",
"OutputInterface",
"::",
"VERBOSITY_VERBOSE",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"write",
"(",
"$",
"s",
... | print a string if verbosity >= verbose (-v)
@param string $s | [
"print",
"a",
"string",
"if",
"verbosity",
">",
"=",
"verbose",
"(",
"-",
"v",
")"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/BuildSubdefs.php#L196-L201 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Command/BuildSubdefs.php | BuildSubdefs.sanitizeArgs | protected function sanitizeArgs(InputInterface $input, OutputInterface $output)
{
$argsOK = true;
// find the databox / collection by id or by name
$this->databox = null;
if(($d = $input->getOption('databox')) !== null) {
$d = trim($d);
foreach ($this->container->getDataboxes() as $db) {
if ($db->get_sbas_id() == (int)$d || $db->get_viewname() == $d || $db->get_dbname() == $d) {
$this->databox = $db;
$this->connection = $db->get_connection();
break;
}
}
if ($this->databox == null) {
$output->writeln(sprintf("<error>Unknown databox \"%s\"</error>", $input->getOption('databox')));
$argsOK = false;
}
}
else {
$output->writeln(sprintf("<error>Missing mandatory options --databox</error>"));
$argsOK = false;
}
// get options
$this->mode = $input->getOption('mode');
if($this->mode) {
if(!in_array($this->mode, array_keys($this->presets))) {
$output->writeln(sprintf("<error>invalid --mode \"%s\"<error>", $this->mode));
$argsOK = false;
}
else {
$explain = "";
foreach($this->presets[$this->mode] as $k=>$v) {
if($input->getOption($k) !== false && $input->getOption($k) !== null) {
$output->writeln(sprintf("<error>--mode=%s and --%s are mutually exclusive</error>", $this->mode, $k));
$argsOK = false;
}
else {
$input->setOption($k, $v);
}
$explain .= ' --' . $k . ($v===true ? '' : ('='.$v));
}
$output->writeln(sprintf("mode \"%s\" ==>%s", $this->mode, $explain));
}
}
$this->show_sql = $input->getOption('show_sql') ? true : false;
$this->dry = $input->getOption('dry') ? true : false;
$this->min_record_id = $input->getOption('min_record_id');
$this->max_record_id = $input->getOption('max_record_id');
$this->substituted_only = $input->getOption('substituted_only') ? true : false;
$this->with_substituted = $input->getOption('with_substituted') ? true : false;
$this->missing_only = $input->getOption('missing_only') ? true : false;
$this->prune = $input->getOption('prune') ? true : false;
$this->all = $input->getOption('all') ? true : false;
$this->scheduled = $input->getOption('scheduled') ? true : false;
$this->reverse = $input->getOption('reverse') ? true : false;
$this->reset_subdef_flag = $input->getOption('reset_subdef_flag') ? true : false;
$this->set_writemeta_flag = $input->getOption('set_writemeta_flag') ? true : false;
$this->maxrecs = (int)$input->getOption('maxrecs');
$this->maxduration = (int)$input->getOption('maxduration');
$this->ttl = (int)$input->getOption('ttl');
$types = $this->getOptionAsArray($input, 'record_type', self::OPTION_DISTINT_VALUES);
$names = $this->getOptionAsArray($input, 'name', self::OPTION_DISTINT_VALUES);
if ($this->with_substituted && $this->substituted_only) {
$output->writeln("<error>--substituted_only and --with_substituted are mutually exclusive<error>");
$argsOK = false;
}
if($this->prune && !empty($names)) {
$output->writeln("<error>--prune and --name are mutually exclusive<error>");
$argsOK = false;
}
$n = ($this->scheduled?1:0) + ($this->missing_only?1:0) + ($this->all?1:0);
if($n != 1) {
$output->writeln("<error>set one an only one option --scheduled, --missing_only, --all<error>");
$argsOK = false;
}
// validate types and subdefs
$this->subdefsTodoByType = [];
$this->subdefsByType = [];
if($this->databox !== null) {
/** @var SubdefGroup $sg */
foreach ($this->databox->get_subdef_structure() as $sg) {
if (empty($types) || in_array($sg->getName(), $types)) {
$all = [];
$todo = [];
/** @var databox_subdef $sd */
foreach ($sg as $sd) {
$all[] = $sd->get_name();
if (empty($names) || in_array($sd->get_name(), $names)) {
$todo[] = $sd->get_name();
}
}
asort($all);
$this->subdefsByType[$sg->getName()] = $all;
asort($todo);
$this->subdefsTodoByType[$sg->getName()] = $todo;
}
}
foreach ($types as $t) {
if (!array_key_exists($t, $this->subdefsTodoByType)) {
$output->writeln(sprintf("<error>unknown type \"%s\"</error>", $t));
$argsOK = false;
}
}
}
// validate partition
$this->partitionIndex = $this->partitionCount = null;
if( ($arg = $input->getOption('partition')) !== null) {
$arg = explode('/', $arg);
if(count($arg) == 2 && ($arg0 = (int)trim($arg[0]))>0 && ($arg1 = (int)trim($arg[1]))>1 && $arg0<=$arg1 ) {
$this->partitionIndex = $arg0;
$this->partitionCount = $arg1;
}
else {
$output->writeln(sprintf('<error>partition must be n/N</error>'));
$argsOK = false;
}
}
// warning about changing jeton when not working on all subdefs
if(!empty($names) && ($this->reset_subdef_flag || $this->set_writemeta_flag)) {
$output->writeln("<warning>changing record flag(s) but working on a subset of subdefs</warning>");
}
return $argsOK;
} | php | protected function sanitizeArgs(InputInterface $input, OutputInterface $output)
{
$argsOK = true;
// find the databox / collection by id or by name
$this->databox = null;
if(($d = $input->getOption('databox')) !== null) {
$d = trim($d);
foreach ($this->container->getDataboxes() as $db) {
if ($db->get_sbas_id() == (int)$d || $db->get_viewname() == $d || $db->get_dbname() == $d) {
$this->databox = $db;
$this->connection = $db->get_connection();
break;
}
}
if ($this->databox == null) {
$output->writeln(sprintf("<error>Unknown databox \"%s\"</error>", $input->getOption('databox')));
$argsOK = false;
}
}
else {
$output->writeln(sprintf("<error>Missing mandatory options --databox</error>"));
$argsOK = false;
}
// get options
$this->mode = $input->getOption('mode');
if($this->mode) {
if(!in_array($this->mode, array_keys($this->presets))) {
$output->writeln(sprintf("<error>invalid --mode \"%s\"<error>", $this->mode));
$argsOK = false;
}
else {
$explain = "";
foreach($this->presets[$this->mode] as $k=>$v) {
if($input->getOption($k) !== false && $input->getOption($k) !== null) {
$output->writeln(sprintf("<error>--mode=%s and --%s are mutually exclusive</error>", $this->mode, $k));
$argsOK = false;
}
else {
$input->setOption($k, $v);
}
$explain .= ' --' . $k . ($v===true ? '' : ('='.$v));
}
$output->writeln(sprintf("mode \"%s\" ==>%s", $this->mode, $explain));
}
}
$this->show_sql = $input->getOption('show_sql') ? true : false;
$this->dry = $input->getOption('dry') ? true : false;
$this->min_record_id = $input->getOption('min_record_id');
$this->max_record_id = $input->getOption('max_record_id');
$this->substituted_only = $input->getOption('substituted_only') ? true : false;
$this->with_substituted = $input->getOption('with_substituted') ? true : false;
$this->missing_only = $input->getOption('missing_only') ? true : false;
$this->prune = $input->getOption('prune') ? true : false;
$this->all = $input->getOption('all') ? true : false;
$this->scheduled = $input->getOption('scheduled') ? true : false;
$this->reverse = $input->getOption('reverse') ? true : false;
$this->reset_subdef_flag = $input->getOption('reset_subdef_flag') ? true : false;
$this->set_writemeta_flag = $input->getOption('set_writemeta_flag') ? true : false;
$this->maxrecs = (int)$input->getOption('maxrecs');
$this->maxduration = (int)$input->getOption('maxduration');
$this->ttl = (int)$input->getOption('ttl');
$types = $this->getOptionAsArray($input, 'record_type', self::OPTION_DISTINT_VALUES);
$names = $this->getOptionAsArray($input, 'name', self::OPTION_DISTINT_VALUES);
if ($this->with_substituted && $this->substituted_only) {
$output->writeln("<error>--substituted_only and --with_substituted are mutually exclusive<error>");
$argsOK = false;
}
if($this->prune && !empty($names)) {
$output->writeln("<error>--prune and --name are mutually exclusive<error>");
$argsOK = false;
}
$n = ($this->scheduled?1:0) + ($this->missing_only?1:0) + ($this->all?1:0);
if($n != 1) {
$output->writeln("<error>set one an only one option --scheduled, --missing_only, --all<error>");
$argsOK = false;
}
// validate types and subdefs
$this->subdefsTodoByType = [];
$this->subdefsByType = [];
if($this->databox !== null) {
/** @var SubdefGroup $sg */
foreach ($this->databox->get_subdef_structure() as $sg) {
if (empty($types) || in_array($sg->getName(), $types)) {
$all = [];
$todo = [];
/** @var databox_subdef $sd */
foreach ($sg as $sd) {
$all[] = $sd->get_name();
if (empty($names) || in_array($sd->get_name(), $names)) {
$todo[] = $sd->get_name();
}
}
asort($all);
$this->subdefsByType[$sg->getName()] = $all;
asort($todo);
$this->subdefsTodoByType[$sg->getName()] = $todo;
}
}
foreach ($types as $t) {
if (!array_key_exists($t, $this->subdefsTodoByType)) {
$output->writeln(sprintf("<error>unknown type \"%s\"</error>", $t));
$argsOK = false;
}
}
}
// validate partition
$this->partitionIndex = $this->partitionCount = null;
if( ($arg = $input->getOption('partition')) !== null) {
$arg = explode('/', $arg);
if(count($arg) == 2 && ($arg0 = (int)trim($arg[0]))>0 && ($arg1 = (int)trim($arg[1]))>1 && $arg0<=$arg1 ) {
$this->partitionIndex = $arg0;
$this->partitionCount = $arg1;
}
else {
$output->writeln(sprintf('<error>partition must be n/N</error>'));
$argsOK = false;
}
}
// warning about changing jeton when not working on all subdefs
if(!empty($names) && ($this->reset_subdef_flag || $this->set_writemeta_flag)) {
$output->writeln("<warning>changing record flag(s) but working on a subset of subdefs</warning>");
}
return $argsOK;
} | [
"protected",
"function",
"sanitizeArgs",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"argsOK",
"=",
"true",
";",
"// find the databox / collection by id or by name",
"$",
"this",
"->",
"databox",
"=",
"null",
";",
"if... | sanity check the cmd line options
@param InputInterface $input
@param OutputInterface $output
@return bool | [
"sanity",
"check",
"the",
"cmd",
"line",
"options"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/BuildSubdefs.php#L210-L346 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Command/BuildSubdefs.php | BuildSubdefs.doExecute | protected function doExecute(InputInterface $input, OutputInterface $output)
{
$time_start = new \DateTime();
if(!$this->sanitizeArgs($input, $output)) {
return -1;
}
$this->input = $input;
$this->output = $output;
$progress = null;
$sql = $this->getSQL();
if($this->show_sql) {
$this->output->writeln($sql);
}
$sqlCount = sprintf('SELECT COUNT(*) FROM (%s) AS c', $sql);
$totalRecords = (int)$this->connection->executeQuery($sqlCount)->fetchColumn();
$nRecordsDone = 0;
$again = true;
$stmt = $this->connection->executeQuery($sql);
while($again && ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) ) {
if($output->getVerbosity() < OutputInterface::VERBOSITY_VERBOSE && $progress === null) {
$progress = new ProgressBar($output, $totalRecords);
$progress->start();
$progress->display();
}
$recordChanged = false;
$type = $row['type'];
$msg = [];
$msg[] = sprintf(' record %s (%s) :', $row['record_id'], $type);
try {
$record = $this->databox->get_record($row['record_id']);
$subdefNamesToDo = array_flip($this->subdefsTodoByType[$type]); // do all subdefs ?
/** @var media_subdef $subdef */
$subdefsDeleted = [];
foreach ($record->get_subdefs() as $subdef) {
$name = $subdef->get_name();
if($name == "document") {
continue;
}
if(!in_array($name, $this->subdefsByType[$type])) {
// this existing subdef is unknown in structure
if($this->prune) {
if(!$this->dry) {
$subdef->delete();
}
$recordChanged = true;
$subdefsDeleted[] = $name;
$msg[] = sprintf(" \"%s\" pruned", $name);
}
continue;
}
if($this->missing_only) {
unset($subdefNamesToDo[$name]);
continue;
}
if($subdef->is_substituted()) {
if(!$this->with_substituted && !$this->substituted_only) {
unset($subdefNamesToDo[$name]);
continue;
}
}
else {
if($this->substituted_only) {
unset($subdefNamesToDo[$name]);
continue;
}
}
// here an existing subdef must be (re)done
if(isset($subdefNamesToDo[$name])) {
if (!$this->dry) {
$subdef->remove_file();
$subdef->set_substituted(false);
}
$recordChanged = true;
$msg[] = sprintf(" [\"%s\"] deleted", $name);
}
}
$subdefNamesToDo = array_keys($subdefNamesToDo);
if(!empty($subdefNamesToDo)) {
if(!$this->dry) {
/** @var SubdefGenerator $subdefGenerator */
$subdefGenerator = $this->container['subdef.generator'];
$subdefGenerator->generateSubdefs($record, $subdefNamesToDo);
}
$recordChanged = true;
$msg[] = sprintf(" [\"%s\"] built", implode('","', $subdefNamesToDo));
}
else {
// $msg .= " nothing to build";
}
unset($record);
if($this->reset_subdef_flag || $this->set_writemeta_flag) {
// subdef created, ask to rewrite metadata
$sql = 'UPDATE record'
. ' SET jeton=(jeton & ~(:flag_and)) | :flag_or'
. ' WHERE record_id=:record_id';
if($this->reset_subdef_flag) {
$msg[] = "jeton[\"make_subdef\"]=0";
}
if($this->set_writemeta_flag) {
$msg[] = "jeton[\"write_met_subdef\"]=1";
}
if(!$this->dry) {
$this->connection->executeUpdate($sql, [
':record_id' => $row['record_id'],
':flag_and' => ($this->reset_subdef_flag ? PhraseaTokens::MAKE_SUBDEF : 0),
':flag_or' => ($this->set_writemeta_flag ? PhraseaTokens::WRITE_META_SUBDEF : 0)
]);
}
$recordChanged = true;
}
if($recordChanged) {
$nRecordsDone++;
}
}
catch(\Exception $e) {
$output->write("failed\n");
}
if($progress) {
$progress->advance();
//$output->write(implode(' ', $msg));
}
else {
$output->writeln(implode("\n", $msg));
}
if($this->maxrecs > 0 && $nRecordsDone >= $this->maxrecs) {
if($progress) {
$output->writeln('');
}
$output->writeln(sprintf("Maximum number (%d >= %d) of records done, quit.", $nRecordsDone, $this->maxrecs));
$again = false;
}
$time_end = new \DateTime();
$dt = $time_end->getTimestamp() - $time_start->getTimestamp();
if($this->maxduration > 0 && $dt >= $this->maxduration && $nRecordsDone > 0) {
if($progress) {
$output->writeln('');
}
$output->writeln(sprintf("Maximum duration (%d >= %d) done, quit.", $dt, $this->maxduration));
$again = false;
}
}
unset($stmt);
if($progress) {
$output->writeln('');
}
if($nRecordsDone == 0) {
while($this->ttl > 0) {
sleep(1);
$this->ttl--;
}
}
return 0;
} | php | protected function doExecute(InputInterface $input, OutputInterface $output)
{
$time_start = new \DateTime();
if(!$this->sanitizeArgs($input, $output)) {
return -1;
}
$this->input = $input;
$this->output = $output;
$progress = null;
$sql = $this->getSQL();
if($this->show_sql) {
$this->output->writeln($sql);
}
$sqlCount = sprintf('SELECT COUNT(*) FROM (%s) AS c', $sql);
$totalRecords = (int)$this->connection->executeQuery($sqlCount)->fetchColumn();
$nRecordsDone = 0;
$again = true;
$stmt = $this->connection->executeQuery($sql);
while($again && ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) ) {
if($output->getVerbosity() < OutputInterface::VERBOSITY_VERBOSE && $progress === null) {
$progress = new ProgressBar($output, $totalRecords);
$progress->start();
$progress->display();
}
$recordChanged = false;
$type = $row['type'];
$msg = [];
$msg[] = sprintf(' record %s (%s) :', $row['record_id'], $type);
try {
$record = $this->databox->get_record($row['record_id']);
$subdefNamesToDo = array_flip($this->subdefsTodoByType[$type]); // do all subdefs ?
/** @var media_subdef $subdef */
$subdefsDeleted = [];
foreach ($record->get_subdefs() as $subdef) {
$name = $subdef->get_name();
if($name == "document") {
continue;
}
if(!in_array($name, $this->subdefsByType[$type])) {
// this existing subdef is unknown in structure
if($this->prune) {
if(!$this->dry) {
$subdef->delete();
}
$recordChanged = true;
$subdefsDeleted[] = $name;
$msg[] = sprintf(" \"%s\" pruned", $name);
}
continue;
}
if($this->missing_only) {
unset($subdefNamesToDo[$name]);
continue;
}
if($subdef->is_substituted()) {
if(!$this->with_substituted && !$this->substituted_only) {
unset($subdefNamesToDo[$name]);
continue;
}
}
else {
if($this->substituted_only) {
unset($subdefNamesToDo[$name]);
continue;
}
}
// here an existing subdef must be (re)done
if(isset($subdefNamesToDo[$name])) {
if (!$this->dry) {
$subdef->remove_file();
$subdef->set_substituted(false);
}
$recordChanged = true;
$msg[] = sprintf(" [\"%s\"] deleted", $name);
}
}
$subdefNamesToDo = array_keys($subdefNamesToDo);
if(!empty($subdefNamesToDo)) {
if(!$this->dry) {
/** @var SubdefGenerator $subdefGenerator */
$subdefGenerator = $this->container['subdef.generator'];
$subdefGenerator->generateSubdefs($record, $subdefNamesToDo);
}
$recordChanged = true;
$msg[] = sprintf(" [\"%s\"] built", implode('","', $subdefNamesToDo));
}
else {
// $msg .= " nothing to build";
}
unset($record);
if($this->reset_subdef_flag || $this->set_writemeta_flag) {
// subdef created, ask to rewrite metadata
$sql = 'UPDATE record'
. ' SET jeton=(jeton & ~(:flag_and)) | :flag_or'
. ' WHERE record_id=:record_id';
if($this->reset_subdef_flag) {
$msg[] = "jeton[\"make_subdef\"]=0";
}
if($this->set_writemeta_flag) {
$msg[] = "jeton[\"write_met_subdef\"]=1";
}
if(!$this->dry) {
$this->connection->executeUpdate($sql, [
':record_id' => $row['record_id'],
':flag_and' => ($this->reset_subdef_flag ? PhraseaTokens::MAKE_SUBDEF : 0),
':flag_or' => ($this->set_writemeta_flag ? PhraseaTokens::WRITE_META_SUBDEF : 0)
]);
}
$recordChanged = true;
}
if($recordChanged) {
$nRecordsDone++;
}
}
catch(\Exception $e) {
$output->write("failed\n");
}
if($progress) {
$progress->advance();
//$output->write(implode(' ', $msg));
}
else {
$output->writeln(implode("\n", $msg));
}
if($this->maxrecs > 0 && $nRecordsDone >= $this->maxrecs) {
if($progress) {
$output->writeln('');
}
$output->writeln(sprintf("Maximum number (%d >= %d) of records done, quit.", $nRecordsDone, $this->maxrecs));
$again = false;
}
$time_end = new \DateTime();
$dt = $time_end->getTimestamp() - $time_start->getTimestamp();
if($this->maxduration > 0 && $dt >= $this->maxduration && $nRecordsDone > 0) {
if($progress) {
$output->writeln('');
}
$output->writeln(sprintf("Maximum duration (%d >= %d) done, quit.", $dt, $this->maxduration));
$again = false;
}
}
unset($stmt);
if($progress) {
$output->writeln('');
}
if($nRecordsDone == 0) {
while($this->ttl > 0) {
sleep(1);
$this->ttl--;
}
}
return 0;
} | [
"protected",
"function",
"doExecute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"time_start",
"=",
"new",
"\\",
"DateTime",
"(",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"sanitizeArgs",
"(",
"$",
"inpu... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/BuildSubdefs.php#L351-L532 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Model/Repositories/OrderRepository.php | OrderRepository.listOrders | public function listOrders($baseIds, $offsetStart = 0, $perPage = 20, $sort = "created_on", $filters = [])
{
$qb = $this
->createQueryBuilder('o');
$this->performQuery($qb, $baseIds, $filters);
$qb->groupBy('o.id');
if ($sort === 'user') {
$qb->orderBy('o.user', 'ASC');
}
elseif ($sort === 'usage') {
$qb->orderBy('o.orderUsage', 'ASC');
}
else {
$qb->orderBy('o.createdOn', 'DESC');
}
$qb
->setFirstResult((int)$offsetStart)
->setMaxResults(max(10, (int)$perPage));
return $qb->getQuery()->getResult();
} | php | public function listOrders($baseIds, $offsetStart = 0, $perPage = 20, $sort = "created_on", $filters = [])
{
$qb = $this
->createQueryBuilder('o');
$this->performQuery($qb, $baseIds, $filters);
$qb->groupBy('o.id');
if ($sort === 'user') {
$qb->orderBy('o.user', 'ASC');
}
elseif ($sort === 'usage') {
$qb->orderBy('o.orderUsage', 'ASC');
}
else {
$qb->orderBy('o.createdOn', 'DESC');
}
$qb
->setFirstResult((int)$offsetStart)
->setMaxResults(max(10, (int)$perPage));
return $qb->getQuery()->getResult();
} | [
"public",
"function",
"listOrders",
"(",
"$",
"baseIds",
",",
"$",
"offsetStart",
"=",
"0",
",",
"$",
"perPage",
"=",
"20",
",",
"$",
"sort",
"=",
"\"created_on\"",
",",
"$",
"filters",
"=",
"[",
"]",
")",
"{",
"$",
"qb",
"=",
"$",
"this",
"->",
... | Returns an array of all the orders, starting at $offsetStart, limited to $perPage
@param array $baseIds
@param integer $offsetStart
@param integer $perPage
@param string $sort
@param ArrayCollection $filters
@return Order[] | [
"Returns",
"an",
"array",
"of",
"all",
"the",
"orders",
"starting",
"at",
"$offsetStart",
"limited",
"to",
"$perPage"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Repositories/OrderRepository.php#L41-L64 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Model/Repositories/OrderRepository.php | OrderRepository.countTotalOrders | public function countTotalOrders(array $baseIds = [], $filters = [])
{
$builder = $this->createQueryBuilder('o');
$builder->select($builder->expr()->countDistinct('o.id'));
$this->performQuery($builder, $baseIds, $filters);
return $builder->getQuery()->getSingleScalarResult();
} | php | public function countTotalOrders(array $baseIds = [], $filters = [])
{
$builder = $this->createQueryBuilder('o');
$builder->select($builder->expr()->countDistinct('o.id'));
$this->performQuery($builder, $baseIds, $filters);
return $builder->getQuery()->getSingleScalarResult();
} | [
"public",
"function",
"countTotalOrders",
"(",
"array",
"$",
"baseIds",
"=",
"[",
"]",
",",
"$",
"filters",
"=",
"[",
"]",
")",
"{",
"$",
"builder",
"=",
"$",
"this",
"->",
"createQueryBuilder",
"(",
"'o'",
")",
";",
"$",
"builder",
"->",
"select",
"... | Returns the total number of orders from an array of base_id and filters
@param array $baseIds
@param array $filters
@return int | [
"Returns",
"the",
"total",
"number",
"of",
"orders",
"from",
"an",
"array",
"of",
"base_id",
"and",
"filters"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Repositories/OrderRepository.php#L140-L147 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Model/Repositories/RegistrationRepository.php | RegistrationRepository.getUserRegistrations | public function getUserRegistrations(User $user, array $collections)
{
$qb = $this->createQueryBuilder('d');
$qb->where($qb->expr()->eq('d.user', ':user'));
$qb->setParameter(':user', $user->getId());
if (count($collections) > 0) {
$qb->andWhere('d.baseId IN (:bases)');
$qb->setParameter(':bases', array_map(function (\collection $collection) {
return $collection->get_base_id();
}, $collections));
}
$qb->orderBy('d.created', 'DESC');
return $qb->getQuery()->getResult();
} | php | public function getUserRegistrations(User $user, array $collections)
{
$qb = $this->createQueryBuilder('d');
$qb->where($qb->expr()->eq('d.user', ':user'));
$qb->setParameter(':user', $user->getId());
if (count($collections) > 0) {
$qb->andWhere('d.baseId IN (:bases)');
$qb->setParameter(':bases', array_map(function (\collection $collection) {
return $collection->get_base_id();
}, $collections));
}
$qb->orderBy('d.created', 'DESC');
return $qb->getQuery()->getResult();
} | [
"public",
"function",
"getUserRegistrations",
"(",
"User",
"$",
"user",
",",
"array",
"$",
"collections",
")",
"{",
"$",
"qb",
"=",
"$",
"this",
"->",
"createQueryBuilder",
"(",
"'d'",
")",
";",
"$",
"qb",
"->",
"where",
"(",
"$",
"qb",
"->",
"expr",
... | Displays registrations for user on provided collection.
@param User $user
@param \collection[] $collections
@return Registration[] | [
"Displays",
"registrations",
"for",
"user",
"on",
"provided",
"collection",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Repositories/RegistrationRepository.php#L34-L50 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Model/Repositories/RegistrationRepository.php | RegistrationRepository.getPendingRegistrations | public function getPendingRegistrations(array $collections)
{
$builder = $this->createQueryBuilder('r');
$builder->where('r.pending = 1');
if (!empty($collections)) {
$builder->andWhere('r.baseId IN (:bases)');
$builder->setParameter('bases', array_map(function (\collection $collection) {
return $collection->get_base_id();
}, $collections));
}
$builder->orderBy('r.created', 'DESC');
return $builder->getQuery()->getResult();
} | php | public function getPendingRegistrations(array $collections)
{
$builder = $this->createQueryBuilder('r');
$builder->where('r.pending = 1');
if (!empty($collections)) {
$builder->andWhere('r.baseId IN (:bases)');
$builder->setParameter('bases', array_map(function (\collection $collection) {
return $collection->get_base_id();
}, $collections));
}
$builder->orderBy('r.created', 'DESC');
return $builder->getQuery()->getResult();
} | [
"public",
"function",
"getPendingRegistrations",
"(",
"array",
"$",
"collections",
")",
"{",
"$",
"builder",
"=",
"$",
"this",
"->",
"createQueryBuilder",
"(",
"'r'",
")",
";",
"$",
"builder",
"->",
"where",
"(",
"'r.pending = 1'",
")",
";",
"if",
"(",
"!"... | Get Current pending registrations.
@param \collection[] $collections
@return Registration[] | [
"Get",
"Current",
"pending",
"registrations",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Repositories/RegistrationRepository.php#L58-L73 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Model/Repositories/RegistrationRepository.php | RegistrationRepository.getRegistrationsSummaryForUser | public function getRegistrationsSummaryForUser(User $user)
{
$data = [];
$rsm = $this->createResultSetMappingBuilder('d');
$rsm->addScalarResult('sbas_id','sbas_id');
$rsm->addScalarResult('base_id','base_id');
$rsm->addScalarResult('dbname','dbname');
$rsm->addScalarResult('time_limited', 'time_limited');
$rsm->addScalarResult('limited_from', 'limited_from');
$rsm->addScalarResult('limited_to', 'limited_to');
$rsm->addScalarResult('actif', 'actif');
$sql = "
SELECT dbname, sbas.sbas_id, time_limited,
UNIX_TIMESTAMP( limited_from ) AS limited_from,
UNIX_TIMESTAMP( limited_to ) AS limited_to,
bas.server_coll_id, Users.id, basusr.actif,
bas.base_id, " . $rsm->generateSelectClause(['d' => 'd',]) . "
FROM (Users, bas, sbas)
LEFT JOIN basusr ON ( Users.id = basusr.usr_id AND bas.base_id = basusr.base_id )
LEFT JOIN Registrations d ON ( d.user_id = Users.id AND bas.base_id = d.base_id )
WHERE basusr.actif = 1 AND bas.sbas_id = sbas.sbas_id
AND Users.id = ?";
$query = $this->_em->createNativeQuery($sql, $rsm);
$query->setParameter(1, $user->getId());
foreach ($query->getResult() as $row) {
$registrationEntity = $row[0];
$data[$row['sbas_id']][$row['base_id']] = [
'base-id' => $row['base_id'],
'db-name' => $row['dbname'],
'active' => (Boolean) $row['actif'],
'time-limited' => (Boolean) $row['time_limited'],
'in-time' => $row['time_limited'] && ! ($row['limited_from'] >= time() && $row['limited_to'] <= time()),
'registration' => $registrationEntity
];
}
return $data;
} | php | public function getRegistrationsSummaryForUser(User $user)
{
$data = [];
$rsm = $this->createResultSetMappingBuilder('d');
$rsm->addScalarResult('sbas_id','sbas_id');
$rsm->addScalarResult('base_id','base_id');
$rsm->addScalarResult('dbname','dbname');
$rsm->addScalarResult('time_limited', 'time_limited');
$rsm->addScalarResult('limited_from', 'limited_from');
$rsm->addScalarResult('limited_to', 'limited_to');
$rsm->addScalarResult('actif', 'actif');
$sql = "
SELECT dbname, sbas.sbas_id, time_limited,
UNIX_TIMESTAMP( limited_from ) AS limited_from,
UNIX_TIMESTAMP( limited_to ) AS limited_to,
bas.server_coll_id, Users.id, basusr.actif,
bas.base_id, " . $rsm->generateSelectClause(['d' => 'd',]) . "
FROM (Users, bas, sbas)
LEFT JOIN basusr ON ( Users.id = basusr.usr_id AND bas.base_id = basusr.base_id )
LEFT JOIN Registrations d ON ( d.user_id = Users.id AND bas.base_id = d.base_id )
WHERE basusr.actif = 1 AND bas.sbas_id = sbas.sbas_id
AND Users.id = ?";
$query = $this->_em->createNativeQuery($sql, $rsm);
$query->setParameter(1, $user->getId());
foreach ($query->getResult() as $row) {
$registrationEntity = $row[0];
$data[$row['sbas_id']][$row['base_id']] = [
'base-id' => $row['base_id'],
'db-name' => $row['dbname'],
'active' => (Boolean) $row['actif'],
'time-limited' => (Boolean) $row['time_limited'],
'in-time' => $row['time_limited'] && ! ($row['limited_from'] >= time() && $row['limited_to'] <= time()),
'registration' => $registrationEntity
];
}
return $data;
} | [
"public",
"function",
"getRegistrationsSummaryForUser",
"(",
"User",
"$",
"user",
")",
"{",
"$",
"data",
"=",
"[",
"]",
";",
"$",
"rsm",
"=",
"$",
"this",
"->",
"createResultSetMappingBuilder",
"(",
"'d'",
")",
";",
"$",
"rsm",
"->",
"addScalarResult",
"("... | Gets registration registrations for a user.
@param User $user
@return array | [
"Gets",
"registration",
"registrations",
"for",
"a",
"user",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Repositories/RegistrationRepository.php#L82-L122 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Command/Command.php | Command.execute | public function execute(InputInterface $input, OutputInterface $output)
{
if ($output->getVerbosity() >= OutputInterface::VERBOSITY_QUIET) {
switch ($output->getVerbosity()) {
default:
case OutputInterface::VERBOSITY_NORMAL:
$level = Logger::WARNING;
break;
case OutputInterface::VERBOSITY_VERBOSE:
$level = Logger::NOTICE;
break;
case OutputInterface::VERBOSITY_VERY_VERBOSE:
$level = Logger::INFO;
break;
case OutputInterface::VERBOSITY_DEBUG:
$level = Logger::DEBUG;
break;
}
$handler = new StreamHandler('php://stdout', $level);
$pushHandler = function (Logger $logger) use ($handler) {
return $logger->pushHandler($handler);
};
$this->container['monolog'] = $this->container->share(
$this->container->extend('monolog', $pushHandler)
);
$this->container['task-manager.logger'] = $this->container->share(
$this->container->extend('task-manager.logger', $pushHandler)
);
}
return $this->doExecute($input, $output);
} | php | public function execute(InputInterface $input, OutputInterface $output)
{
if ($output->getVerbosity() >= OutputInterface::VERBOSITY_QUIET) {
switch ($output->getVerbosity()) {
default:
case OutputInterface::VERBOSITY_NORMAL:
$level = Logger::WARNING;
break;
case OutputInterface::VERBOSITY_VERBOSE:
$level = Logger::NOTICE;
break;
case OutputInterface::VERBOSITY_VERY_VERBOSE:
$level = Logger::INFO;
break;
case OutputInterface::VERBOSITY_DEBUG:
$level = Logger::DEBUG;
break;
}
$handler = new StreamHandler('php://stdout', $level);
$pushHandler = function (Logger $logger) use ($handler) {
return $logger->pushHandler($handler);
};
$this->container['monolog'] = $this->container->share(
$this->container->extend('monolog', $pushHandler)
);
$this->container['task-manager.logger'] = $this->container->share(
$this->container->extend('task-manager.logger', $pushHandler)
);
}
return $this->doExecute($input, $output);
} | [
"public",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"if",
"(",
"$",
"output",
"->",
"getVerbosity",
"(",
")",
">=",
"OutputInterface",
"::",
"VERBOSITY_QUIET",
")",
"{",
"switch",
"(",
"$",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/Command.php#L31-L64 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Command/Command.php | Command.getService | public function getService($name)
{
return isset($this->container[$name]) ? $this->container[$name] : null;
} | php | public function getService($name)
{
return isset($this->container[$name]) ? $this->container[$name] : null;
} | [
"public",
"function",
"getService",
"(",
"$",
"name",
")",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"container",
"[",
"$",
"name",
"]",
")",
"?",
"$",
"this",
"->",
"container",
"[",
"$",
"name",
"]",
":",
"null",
";",
"}"
] | Returns a service contained in the application container or null if none
is found with that name.
This is a convenience method used to retrieve an element from the
Application container without having to assign the results of the
getContainer() method in every call.
@param string $name Name of the service
@see self::getContainer()
@return mixed | [
"Returns",
"a",
"service",
"contained",
"in",
"the",
"application",
"container",
"or",
"null",
"if",
"none",
"is",
"found",
"with",
"that",
"name",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/Command.php#L104-L107 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Command/Command.php | Command.getFormattedDuration | public function getFormattedDuration($seconds)
{
$duration = ceil($seconds) . ' seconds';
if ($duration > 60) {
$duration = round($duration / 60, 1) . ' minutes';
} elseif ($duration > 3600) {
$duration = round($duration / (60 * 60), 1) . ' hours';
} elseif ($duration > (24 * 60 * 60)) {
$duration = round($duration / (24 * 60 * 60), 1) . ' days';
}
return $duration;
} | php | public function getFormattedDuration($seconds)
{
$duration = ceil($seconds) . ' seconds';
if ($duration > 60) {
$duration = round($duration / 60, 1) . ' minutes';
} elseif ($duration > 3600) {
$duration = round($duration / (60 * 60), 1) . ' hours';
} elseif ($duration > (24 * 60 * 60)) {
$duration = round($duration / (24 * 60 * 60), 1) . ' days';
}
return $duration;
} | [
"public",
"function",
"getFormattedDuration",
"(",
"$",
"seconds",
")",
"{",
"$",
"duration",
"=",
"ceil",
"(",
"$",
"seconds",
")",
".",
"' seconds'",
";",
"if",
"(",
"$",
"duration",
">",
"60",
")",
"{",
"$",
"duration",
"=",
"round",
"(",
"$",
"du... | Format a duration in seconds to human readable
@param int $seconds the time to format
@return string | [
"Format",
"a",
"duration",
"in",
"seconds",
"to",
"human",
"readable"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/Command.php#L115-L128 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Notification/Mail/MailSuccessEmailUpdate.php | MailSuccessEmailUpdate.getMessage | public function getMessage()
{
return sprintf("%s\n%s\n%s",
$this->app->trans('Dear %user%,', ['%user%' => $this->receiver->getName()]),
$this->app->trans('Your contact email address has been updated'),
$this->message
);
} | php | public function getMessage()
{
return sprintf("%s\n%s\n%s",
$this->app->trans('Dear %user%,', ['%user%' => $this->receiver->getName()]),
$this->app->trans('Your contact email address has been updated'),
$this->message
);
} | [
"public",
"function",
"getMessage",
"(",
")",
"{",
"return",
"sprintf",
"(",
"\"%s\\n%s\\n%s\"",
",",
"$",
"this",
"->",
"app",
"->",
"trans",
"(",
"'Dear %user%,'",
",",
"[",
"'%user%'",
"=>",
"$",
"this",
"->",
"receiver",
"->",
"getName",
"(",
")",
"]... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Notification/Mail/MailSuccessEmailUpdate.php#L27-L34 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Model/Manipulator/ApiLogManipulator.php | ApiLogManipulator.setDetails | private function setDetails(ApiLog $log, Request $request, Response $response)
{
$chunks = explode('/', trim($request->getPathInfo(), '/'));
if (false === $response->isOk() || sizeof($chunks) === 0) {
return;
}
switch ($chunks[0]) {
case ApiLog::DATABOXES_RESOURCE :
$this->hydrateDataboxes($log, $chunks);
break;
case ApiLog::RECORDS_RESOURCE :
$this->hydrateRecords($log, $chunks);
break;
case ApiLog::BASKETS_RESOURCE :
$this->hydrateBaskets($log, $chunks);
break;
case ApiLog::FEEDS_RESOURCE :
$this->hydrateFeeds($log, $chunks);
break;
case ApiLog::QUARANTINE_RESOURCE :
$this->hydrateQuarantine($log, $chunks);
break;
case ApiLog::STORIES_RESOURCE :
$this->hydrateStories($log, $chunks);
break;
case ApiLog::MONITOR_RESOURCE :
$this->hydrateMonitor($log, $chunks);
break;
}
} | php | private function setDetails(ApiLog $log, Request $request, Response $response)
{
$chunks = explode('/', trim($request->getPathInfo(), '/'));
if (false === $response->isOk() || sizeof($chunks) === 0) {
return;
}
switch ($chunks[0]) {
case ApiLog::DATABOXES_RESOURCE :
$this->hydrateDataboxes($log, $chunks);
break;
case ApiLog::RECORDS_RESOURCE :
$this->hydrateRecords($log, $chunks);
break;
case ApiLog::BASKETS_RESOURCE :
$this->hydrateBaskets($log, $chunks);
break;
case ApiLog::FEEDS_RESOURCE :
$this->hydrateFeeds($log, $chunks);
break;
case ApiLog::QUARANTINE_RESOURCE :
$this->hydrateQuarantine($log, $chunks);
break;
case ApiLog::STORIES_RESOURCE :
$this->hydrateStories($log, $chunks);
break;
case ApiLog::MONITOR_RESOURCE :
$this->hydrateMonitor($log, $chunks);
break;
}
} | [
"private",
"function",
"setDetails",
"(",
"ApiLog",
"$",
"log",
",",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
")",
"{",
"$",
"chunks",
"=",
"explode",
"(",
"'/'",
",",
"trim",
"(",
"$",
"request",
"->",
"getPathInfo",
"(",
")",
",",... | Parses the requested route to fetch
- the resource (databox, basket, record etc ..)
- general action (list, add, search)
- the action (setstatus, setname etc..)
- the aspect (collections, related, content etc..)
@param ApiLog $log
@param Request $request
@param Response $response | [
"Parses",
"the",
"requested",
"route",
"to",
"fetch",
"-",
"the",
"resource",
"(",
"databox",
"basket",
"record",
"etc",
"..",
")",
"-",
"general",
"action",
"(",
"list",
"add",
"search",
")",
"-",
"the",
"action",
"(",
"setstatus",
"setname",
"etc",
"..... | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Manipulator/ApiLogManipulator.php#L75-L106 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Authentication/Authenticator.php | Authenticator.openAccount | public function openAccount(User $user)
{
$this->session->remove('usr_id');
$this->session->remove('session_id');
$session = new Session();
$session->setBrowserName($this->browser->getBrowser())
->setBrowserVersion($this->browser->getVersion())
->setPlatform($this->browser->getPlatform())
->setUserAgent($this->browser->getUserAgent())
->setUser($user);
$this->em->persist($session);
$this->em->flush();
$this->populateSession($session);
foreach ($this->app->getAclForUser($user)->get_granted_sbas() as $databox) {
\cache_databox::insertClient($this->app, $databox);
}
$this->reinitUser();
return $session;
} | php | public function openAccount(User $user)
{
$this->session->remove('usr_id');
$this->session->remove('session_id');
$session = new Session();
$session->setBrowserName($this->browser->getBrowser())
->setBrowserVersion($this->browser->getVersion())
->setPlatform($this->browser->getPlatform())
->setUserAgent($this->browser->getUserAgent())
->setUser($user);
$this->em->persist($session);
$this->em->flush();
$this->populateSession($session);
foreach ($this->app->getAclForUser($user)->get_granted_sbas() as $databox) {
\cache_databox::insertClient($this->app, $databox);
}
$this->reinitUser();
return $session;
} | [
"public",
"function",
"openAccount",
"(",
"User",
"$",
"user",
")",
"{",
"$",
"this",
"->",
"session",
"->",
"remove",
"(",
"'usr_id'",
")",
";",
"$",
"this",
"->",
"session",
"->",
"remove",
"(",
"'session_id'",
")",
";",
"$",
"session",
"=",
"new",
... | Open user session
@param User $user
@return Session
@throws \Exception_InternalServerError | [
"Open",
"user",
"session"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/Authenticator.php#L69-L92 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Authentication/Authenticator.php | Authenticator.closeAccount | public function closeAccount()
{
if (!$this->session->has('session_id')) {
throw new RuntimeException('No session to close.');
}
if (null !== $session = $this->app['repo.sessions']->find($this->session->get('session_id'))) {
$this->em->remove($session);
$this->em->flush();
}
$this->session->invalidate();
$this->reinitUser();
return $this;
} | php | public function closeAccount()
{
if (!$this->session->has('session_id')) {
throw new RuntimeException('No session to close.');
}
if (null !== $session = $this->app['repo.sessions']->find($this->session->get('session_id'))) {
$this->em->remove($session);
$this->em->flush();
}
$this->session->invalidate();
$this->reinitUser();
return $this;
} | [
"public",
"function",
"closeAccount",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"session",
"->",
"has",
"(",
"'session_id'",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'No session to close.'",
")",
";",
"}",
"if",
"(",
"null",
"!=="... | Closes user session | [
"Closes",
"user",
"session"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/Authenticator.php#L127-L142 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Authentication/Authenticator.php | Authenticator.isAuthenticated | public function isAuthenticated()
{
if (!$this->session->has('usr_id')) {
return false;
}
if ($this->session->has('session_id')) {
if (null !== $this->app['repo.sessions']->find($this->session->get('session_id'))) {
return true;
}
}
$this->session->invalidate();
$this->reinitUser();
return false;
} | php | public function isAuthenticated()
{
if (!$this->session->has('usr_id')) {
return false;
}
if ($this->session->has('session_id')) {
if (null !== $this->app['repo.sessions']->find($this->session->get('session_id'))) {
return true;
}
}
$this->session->invalidate();
$this->reinitUser();
return false;
} | [
"public",
"function",
"isAuthenticated",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"session",
"->",
"has",
"(",
"'usr_id'",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"session",
"->",
"has",
"(",
"'session_id'",... | Tell if current a session is open
@return boolean | [
"Tell",
"if",
"current",
"a",
"session",
"is",
"open"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/Authenticator.php#L160-L176 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Core/Profiler/TraceableCache.php | TraceableCache.fetch | public function fetch($id)
{
try {
$this->stopWatch->start('cache');
$value = $this->cache->fetch($id);
$this->stopWatch->stop('cache');
}
catch (\Exception $ex) {
$value = false;
}
$this->collect('fetch', $id, $value != false, $value);
return $value;
} | php | public function fetch($id)
{
try {
$this->stopWatch->start('cache');
$value = $this->cache->fetch($id);
$this->stopWatch->stop('cache');
}
catch (\Exception $ex) {
$value = false;
}
$this->collect('fetch', $id, $value != false, $value);
return $value;
} | [
"public",
"function",
"fetch",
"(",
"$",
"id",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"stopWatch",
"->",
"start",
"(",
"'cache'",
")",
";",
"$",
"value",
"=",
"$",
"this",
"->",
"cache",
"->",
"fetch",
"(",
"$",
"id",
")",
";",
"$",
"this",
"... | Fetches an entry from the cache.
@param string $id The id of the cache entry to fetch.
@return mixed The cached data or FALSE, if no cache entry exists for the given id. | [
"Fetches",
"an",
"entry",
"from",
"the",
"cache",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Core/Profiler/TraceableCache.php#L151-L165 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Core/Profiler/TraceableCache.php | TraceableCache.save | public function save($id, $data, $lifeTime = 0)
{
$this->collect('save', $id);
$this->stopWatch->start('cache');
$result = $this->cache->save($id, $data, $lifeTime);
$this->stopWatch->stop('cache');
return $result;
} | php | public function save($id, $data, $lifeTime = 0)
{
$this->collect('save', $id);
$this->stopWatch->start('cache');
$result = $this->cache->save($id, $data, $lifeTime);
$this->stopWatch->stop('cache');
return $result;
} | [
"public",
"function",
"save",
"(",
"$",
"id",
",",
"$",
"data",
",",
"$",
"lifeTime",
"=",
"0",
")",
"{",
"$",
"this",
"->",
"collect",
"(",
"'save'",
",",
"$",
"id",
")",
";",
"$",
"this",
"->",
"stopWatch",
"->",
"start",
"(",
"'cache'",
")",
... | Puts data into the cache.
If a cache entry with the given id already exists, its data will be replaced.
@param string $id The cache id.
@param mixed $data The cache entry/data.
@param int $lifeTime The lifetime in number of seconds for this cache entry.
If zero (the default), the entry never expires (although it may be deleted from the cache
to make place for other entries).
@return bool TRUE if the entry was successfully stored in the cache, FALSE otherwise. | [
"Puts",
"data",
"into",
"the",
"cache",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Core/Profiler/TraceableCache.php#L198-L207 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Core/Profiler/TraceableCache.php | TraceableCache.delete | public function delete($id)
{
$this->collect('delete', $id);
$this->stopWatch->start('cache');
$result = $this->cache->delete($id);
$this->stopWatch->stop('cache');
return $result;
} | php | public function delete($id)
{
$this->collect('delete', $id);
$this->stopWatch->start('cache');
$result = $this->cache->delete($id);
$this->stopWatch->stop('cache');
return $result;
} | [
"public",
"function",
"delete",
"(",
"$",
"id",
")",
"{",
"$",
"this",
"->",
"collect",
"(",
"'delete'",
",",
"$",
"id",
")",
";",
"$",
"this",
"->",
"stopWatch",
"->",
"start",
"(",
"'cache'",
")",
";",
"$",
"result",
"=",
"$",
"this",
"->",
"ca... | Deletes a cache entry.
@param string $id The cache id.
@return bool TRUE if the cache entry was successfully deleted, FALSE otherwise.
Deleting a non-existing entry is considered successful. | [
"Deletes",
"a",
"cache",
"entry",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Core/Profiler/TraceableCache.php#L217-L226 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Core/Profiler/TraceableCache.php | TraceableCache.getStats | public function getStats()
{
$this->stopWatch->start('cache');
$result = $this->cache->getStats();
$this->stopWatch->stop('cache');
return $result;
} | php | public function getStats()
{
$this->stopWatch->start('cache');
$result = $this->cache->getStats();
$this->stopWatch->stop('cache');
return $result;
} | [
"public",
"function",
"getStats",
"(",
")",
"{",
"$",
"this",
"->",
"stopWatch",
"->",
"start",
"(",
"'cache'",
")",
";",
"$",
"result",
"=",
"$",
"this",
"->",
"cache",
"->",
"getStats",
"(",
")",
";",
"$",
"this",
"->",
"stopWatch",
"->",
"stop",
... | Retrieves cached information from the data store.
The server's statistics array has the following values:
- <b>hits</b>
Number of keys that have been requested and found present.
- <b>misses</b>
Number of items that have been requested and not found.
- <b>uptime</b>
Time that the server is running.
- <b>memory_usage</b>
Memory used by this server to store items.
- <b>memory_available</b>
Memory allowed to use for storage.
@since 2.2
@return array|null An associative array with server's statistics if available, NULL otherwise. | [
"Retrieves",
"cached",
"information",
"from",
"the",
"data",
"store",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Core/Profiler/TraceableCache.php#L252-L259 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Core/Profiler/TraceableCache.php | TraceableCache.flushAll | public function flushAll()
{
$this->collect('flush-all', null);
$this->stopWatch->start('cache');
$this->cache->flushAll();
$this->stopWatch->stop('cache');
} | php | public function flushAll()
{
$this->collect('flush-all', null);
$this->stopWatch->start('cache');
$this->cache->flushAll();
$this->stopWatch->stop('cache');
} | [
"public",
"function",
"flushAll",
"(",
")",
"{",
"$",
"this",
"->",
"collect",
"(",
"'flush-all'",
",",
"null",
")",
";",
"$",
"this",
"->",
"stopWatch",
"->",
"start",
"(",
"'cache'",
")",
";",
"$",
"this",
"->",
"cache",
"->",
"flushAll",
"(",
")",... | Flushes all data contained in the adapter | [
"Flushes",
"all",
"data",
"contained",
"in",
"the",
"adapter"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Core/Profiler/TraceableCache.php#L275-L281 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Border/File.php | File.getUUID | public function getUUID($generate = false, $write = false)
{
if ($this->uuid && !$write) {
return $this->uuid;
}
$availableUUIDs = [
'XMP-exif:ImageUniqueID',
'SigmaRaw:ImageUniqueID',
'IPTC:UniqueDocumentID',
'ExifIFD:ImageUniqueID',
'Canon:ImageUniqueID',
'XMP-xmpMM:DocumentID',
];
if (!$this->uuid) {
$metadatas = $this->media->getMetadatas();
$uuid = null;
foreach ($availableUUIDs as $meta) {
if ($metadatas->containsKey($meta)) {
$candidate = $metadatas->get($meta)->getValue()->asString();
if(in_array($meta, self::$xmpTag)){
$candidate = self::sanitizeXmpUuid($candidate);
}
if (Uuid::isValid($candidate)) {
$uuid = $candidate;
break;
}
}
}
if (!$uuid && $generate) {
$uuid = Uuid::uuid4();
}
$this->uuid = $uuid;
}
if ($write) {
$value = new MonoValue($this->uuid);
$metadatas = new ExiftoolMetadataBag();
foreach ($availableUUIDs as $tagname) {
$metadatas->add(new Metadata(TagFactory::getFromRDFTagname($tagname), $value));
}
try {
$writer = $this->app['exiftool.writer'];
$writer->reset();
$writer->write($this->getFile()->getRealPath(), $metadatas);
} catch (PHPExiftoolException $e) {
// PHPExiftool throws exception on some files not supported
}
}
return $this->uuid;
} | php | public function getUUID($generate = false, $write = false)
{
if ($this->uuid && !$write) {
return $this->uuid;
}
$availableUUIDs = [
'XMP-exif:ImageUniqueID',
'SigmaRaw:ImageUniqueID',
'IPTC:UniqueDocumentID',
'ExifIFD:ImageUniqueID',
'Canon:ImageUniqueID',
'XMP-xmpMM:DocumentID',
];
if (!$this->uuid) {
$metadatas = $this->media->getMetadatas();
$uuid = null;
foreach ($availableUUIDs as $meta) {
if ($metadatas->containsKey($meta)) {
$candidate = $metadatas->get($meta)->getValue()->asString();
if(in_array($meta, self::$xmpTag)){
$candidate = self::sanitizeXmpUuid($candidate);
}
if (Uuid::isValid($candidate)) {
$uuid = $candidate;
break;
}
}
}
if (!$uuid && $generate) {
$uuid = Uuid::uuid4();
}
$this->uuid = $uuid;
}
if ($write) {
$value = new MonoValue($this->uuid);
$metadatas = new ExiftoolMetadataBag();
foreach ($availableUUIDs as $tagname) {
$metadatas->add(new Metadata(TagFactory::getFromRDFTagname($tagname), $value));
}
try {
$writer = $this->app['exiftool.writer'];
$writer->reset();
$writer->write($this->getFile()->getRealPath(), $metadatas);
} catch (PHPExiftoolException $e) {
// PHPExiftool throws exception on some files not supported
}
}
return $this->uuid;
} | [
"public",
"function",
"getUUID",
"(",
"$",
"generate",
"=",
"false",
",",
"$",
"write",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"uuid",
"&&",
"!",
"$",
"write",
")",
"{",
"return",
"$",
"this",
"->",
"uuid",
";",
"}",
"$",
"availabl... | Checks for UUID in metadatas
@todo Check if a file exists with the same checksum
@todo Check if an UUID is contained in the attributes, replace It if
necessary
@param boolean $generate if true, if no uuid found, a valid one is generated
@param boolean $write if true, writes uuid in all available metadatas
@return File | [
"Checks",
"for",
"UUID",
"in",
"metadatas"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Border/File.php#L94-L152 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Border/File.php | File.getSha256 | public function getSha256()
{
if (!$this->sha256) {
$this->sha256 = $this->media->getHash('sha256');
}
return $this->sha256;
} | php | public function getSha256()
{
if (!$this->sha256) {
$this->sha256 = $this->media->getHash('sha256');
}
return $this->sha256;
} | [
"public",
"function",
"getSha256",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"sha256",
")",
"{",
"$",
"this",
"->",
"sha256",
"=",
"$",
"this",
"->",
"media",
"->",
"getHash",
"(",
"'sha256'",
")",
";",
"}",
"return",
"$",
"this",
"->",
"... | Returns the sha256 checksum of the document
@return string | [
"Returns",
"the",
"sha256",
"checksum",
"of",
"the",
"document"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Border/File.php#L187-L194 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Border/File.php | File.getMD5 | public function getMD5()
{
if (!$this->md5) {
$this->md5 = $this->media->getHash('md5');
}
return $this->md5;
} | php | public function getMD5()
{
if (!$this->md5) {
$this->md5 = $this->media->getHash('md5');
}
return $this->md5;
} | [
"public",
"function",
"getMD5",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"md5",
")",
"{",
"$",
"this",
"->",
"md5",
"=",
"$",
"this",
"->",
"media",
"->",
"getHash",
"(",
"'md5'",
")",
";",
"}",
"return",
"$",
"this",
"->",
"md5",
";",... | Returns the md5 checksum of the document
@return string | [
"Returns",
"the",
"md5",
"checksum",
"of",
"the",
"document"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Border/File.php#L201-L208 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Border/File.php | File.buildFromPathfile | public static function buildFromPathfile($pathfile, \collection $collection, Application $app, $originalName = null)
{
try {
$media = $app->getMediaFromUri($pathfile);
} catch (FileNotFoundException $e) {
throw new \InvalidArgumentException(sprintf('Unable to build media file from non existant %s', $pathfile));
}
return new File($app, $media, $collection, $originalName);
} | php | public static function buildFromPathfile($pathfile, \collection $collection, Application $app, $originalName = null)
{
try {
$media = $app->getMediaFromUri($pathfile);
} catch (FileNotFoundException $e) {
throw new \InvalidArgumentException(sprintf('Unable to build media file from non existant %s', $pathfile));
}
return new File($app, $media, $collection, $originalName);
} | [
"public",
"static",
"function",
"buildFromPathfile",
"(",
"$",
"pathfile",
",",
"\\",
"collection",
"$",
"collection",
",",
"Application",
"$",
"app",
",",
"$",
"originalName",
"=",
"null",
")",
"{",
"try",
"{",
"$",
"media",
"=",
"$",
"app",
"->",
"getM... | Build the File package object
@param string $pathfile The path to the file
@param \collection $collection The destination collection
@param Application $app An application
@param string $originalName An optionnal original name (if
different from the $pathfile filename)
@throws \InvalidArgumentException
@return File | [
"Build",
"the",
"File",
"package",
"object"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Border/File.php#L285-L294 |
alchemy-fr/Phraseanet | lib/classes/record/adapter.php | record_adapter.get_duration | public function get_duration()
{
if (!$this->duration) {
$duration = $this->get_technical_infos(media_subdef::TC_DATA_DURATION);
$this->duration = $duration ? round($duration->getValue()) : false;
}
return $this->duration;
} | php | public function get_duration()
{
if (!$this->duration) {
$duration = $this->get_technical_infos(media_subdef::TC_DATA_DURATION);
$this->duration = $duration ? round($duration->getValue()) : false;
}
return $this->duration;
} | [
"public",
"function",
"get_duration",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"duration",
")",
"{",
"$",
"duration",
"=",
"$",
"this",
"->",
"get_technical_infos",
"(",
"media_subdef",
"::",
"TC_DATA_DURATION",
")",
";",
"$",
"this",
"->",
"dur... | Returns duration in seconds
@return int | [
"Returns",
"duration",
"in",
"seconds"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/record/adapter.php#L510-L518 |
alchemy-fr/Phraseanet | lib/classes/record/adapter.php | record_adapter.getSubdfefByDeviceAndMime | public function getSubdfefByDeviceAndMime($devices = null, $mimes = null)
{
$subdefNames = $subdefs = [];
$availableSubdefs = $this->get_subdefs();
if (isset($availableSubdefs['document'])) {
$mime_ok = !$mimes || in_array($availableSubdefs['document']->get_mime(), (array)$mimes, false);
$devices_ok = !$devices || array_intersect($availableSubdefs['document']->getDevices(), (array)$devices);
if ($mime_ok && $devices_ok) {
$subdefs['document'] = $availableSubdefs['document'];
}
}
$searchDevices = array_merge((array)$devices, (array)databox_subdef::DEVICE_ALL);
$type = $this->isStory() ? 'image' : $this->getType();
foreach ($this->getDatabox()->get_subdef_structure() as $group => $databoxSubdefs) {
if ($type != $group) {
continue;
}
foreach ($databoxSubdefs as $databoxSubdef) {
if ($devices && !array_intersect($databoxSubdef->getDevices(), $searchDevices)) {
continue;
}
array_push($subdefNames, $databoxSubdef->get_name());
}
}
foreach ($availableSubdefs as $subdef) {
if (!in_array($subdef->get_name(), $subdefNames)) {
continue;
}
if ($mimes && !in_array($subdef->get_mime(), (array)$mimes)) {
continue;
}
$subdefs[$subdef->get_name()] = $subdef;
}
return $subdefs;
} | php | public function getSubdfefByDeviceAndMime($devices = null, $mimes = null)
{
$subdefNames = $subdefs = [];
$availableSubdefs = $this->get_subdefs();
if (isset($availableSubdefs['document'])) {
$mime_ok = !$mimes || in_array($availableSubdefs['document']->get_mime(), (array)$mimes, false);
$devices_ok = !$devices || array_intersect($availableSubdefs['document']->getDevices(), (array)$devices);
if ($mime_ok && $devices_ok) {
$subdefs['document'] = $availableSubdefs['document'];
}
}
$searchDevices = array_merge((array)$devices, (array)databox_subdef::DEVICE_ALL);
$type = $this->isStory() ? 'image' : $this->getType();
foreach ($this->getDatabox()->get_subdef_structure() as $group => $databoxSubdefs) {
if ($type != $group) {
continue;
}
foreach ($databoxSubdefs as $databoxSubdef) {
if ($devices && !array_intersect($databoxSubdef->getDevices(), $searchDevices)) {
continue;
}
array_push($subdefNames, $databoxSubdef->get_name());
}
}
foreach ($availableSubdefs as $subdef) {
if (!in_array($subdef->get_name(), $subdefNames)) {
continue;
}
if ($mimes && !in_array($subdef->get_mime(), (array)$mimes)) {
continue;
}
$subdefs[$subdef->get_name()] = $subdef;
}
return $subdefs;
} | [
"public",
"function",
"getSubdfefByDeviceAndMime",
"(",
"$",
"devices",
"=",
"null",
",",
"$",
"mimes",
"=",
"null",
")",
"{",
"$",
"subdefNames",
"=",
"$",
"subdefs",
"=",
"[",
"]",
";",
"$",
"availableSubdefs",
"=",
"$",
"this",
"->",
"get_subdefs",
"(... | Returns an array of subdef matching
@param string|string[] $devices the matching device (see databox_subdef::DEVICE_*)
@param string|string[] $mimes the matching mime types
@return media_subdef[] | [
"Returns",
"an",
"array",
"of",
"subdef",
"matching"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/record/adapter.php#L622-L672 |
alchemy-fr/Phraseanet | lib/classes/record/adapter.php | record_adapter.get_technical_infos | public function get_technical_infos($data = '')
{
if (null === $this->technical_data) {
$sets = $this->app['service.technical_data']->fetchRecordsTechnicalData([$this]);
$this->setTechnicalDataSet(reset($sets));
}
if ($data) {
if (isset($this->technical_data[$data])) {
return $this->technical_data[$data];
} else {
return false;
}
}
return $this->technical_data;
} | php | public function get_technical_infos($data = '')
{
if (null === $this->technical_data) {
$sets = $this->app['service.technical_data']->fetchRecordsTechnicalData([$this]);
$this->setTechnicalDataSet(reset($sets));
}
if ($data) {
if (isset($this->technical_data[$data])) {
return $this->technical_data[$data];
} else {
return false;
}
}
return $this->technical_data;
} | [
"public",
"function",
"get_technical_infos",
"(",
"$",
"data",
"=",
"''",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"technical_data",
")",
"{",
"$",
"sets",
"=",
"$",
"this",
"->",
"app",
"[",
"'service.technical_data'",
"]",
"->",
"fetchRec... | Return a Technical data set or a specific technical data or false when not found
@param string $data
@return TechnicalDataSet|TechnicalData|false | [
"Return",
"a",
"Technical",
"data",
"set",
"or",
"a",
"specific",
"technical",
"data",
"or",
"false",
"when",
"not",
"found"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/record/adapter.php#L738-L755 |
alchemy-fr/Phraseanet | lib/classes/record/adapter.php | record_adapter.getPositionFromTechnicalInfos | public function getPositionFromTechnicalInfos()
{
$positionTechnicalField = [
media_subdef::TC_DATA_LATITUDE,
media_subdef::TC_DATA_LONGITUDE
];
$position = [];
foreach($positionTechnicalField as $field){
$fieldData = $this->get_technical_infos($field);
if($fieldData){
$position[$field] = $fieldData->getValue();
}
}
if(count($position) == 2){
return [
'isCoordComplete' => 1,
'latitude' => $position[media_subdef::TC_DATA_LATITUDE],
'longitude' => $position[media_subdef::TC_DATA_LONGITUDE]
];
}
return ['isCoordComplete' => 0, 'latitude' => 'false', 'longitude' => 'false'];
} | php | public function getPositionFromTechnicalInfos()
{
$positionTechnicalField = [
media_subdef::TC_DATA_LATITUDE,
media_subdef::TC_DATA_LONGITUDE
];
$position = [];
foreach($positionTechnicalField as $field){
$fieldData = $this->get_technical_infos($field);
if($fieldData){
$position[$field] = $fieldData->getValue();
}
}
if(count($position) == 2){
return [
'isCoordComplete' => 1,
'latitude' => $position[media_subdef::TC_DATA_LATITUDE],
'longitude' => $position[media_subdef::TC_DATA_LONGITUDE]
];
}
return ['isCoordComplete' => 0, 'latitude' => 'false', 'longitude' => 'false'];
} | [
"public",
"function",
"getPositionFromTechnicalInfos",
"(",
")",
"{",
"$",
"positionTechnicalField",
"=",
"[",
"media_subdef",
"::",
"TC_DATA_LATITUDE",
",",
"media_subdef",
"::",
"TC_DATA_LONGITUDE",
"]",
";",
"$",
"position",
"=",
"[",
"]",
";",
"foreach",
"(",
... | Return an array containing GPSPosition
@return array | [
"Return",
"an",
"array",
"containing",
"GPSPosition"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/record/adapter.php#L762-L787 |
alchemy-fr/Phraseanet | lib/classes/record/adapter.php | record_adapter.getTitle | public function getTitle($locale = null, Array $options = [])
{
$removeExtension = !!igorw\get_in($options, ['removeExtension'], false);
$cache = !$removeExtension;
if ($cache) {
try {
return $this->get_data_from_cache(self::CACHE_TITLE);
} catch (\Exception $e) {
}
}
$title = '';
$fields = $this->getDatabox()->get_meta_structure();
$fields_to_retrieve = [];
foreach ($fields as $field) {
if (in_array($field->get_thumbtitle(), ['1', $locale])) {
$fields_to_retrieve [] = $field->get_name();
}
}
if (count($fields_to_retrieve) > 0) {
$retrieved_fields = $this->get_caption()->get_highlight_fields($fields_to_retrieve);
$titles = [];
foreach ($retrieved_fields as $value) {
foreach ($value['values'] as $v) {
$titles[] = $v['value'];
}
}
$title = trim(implode(' - ', $titles));
}
if (trim($title) === '') {
$title = trim($this->get_original_name($removeExtension));
}
$title = $title != "" ? $title : $this->app->trans('reponses::document sans titre');
if ($cache) {
$this->set_data_to_cache(self::CACHE_TITLE, $title);
}
return $title;
} | php | public function getTitle($locale = null, Array $options = [])
{
$removeExtension = !!igorw\get_in($options, ['removeExtension'], false);
$cache = !$removeExtension;
if ($cache) {
try {
return $this->get_data_from_cache(self::CACHE_TITLE);
} catch (\Exception $e) {
}
}
$title = '';
$fields = $this->getDatabox()->get_meta_structure();
$fields_to_retrieve = [];
foreach ($fields as $field) {
if (in_array($field->get_thumbtitle(), ['1', $locale])) {
$fields_to_retrieve [] = $field->get_name();
}
}
if (count($fields_to_retrieve) > 0) {
$retrieved_fields = $this->get_caption()->get_highlight_fields($fields_to_retrieve);
$titles = [];
foreach ($retrieved_fields as $value) {
foreach ($value['values'] as $v) {
$titles[] = $v['value'];
}
}
$title = trim(implode(' - ', $titles));
}
if (trim($title) === '') {
$title = trim($this->get_original_name($removeExtension));
}
$title = $title != "" ? $title : $this->app->trans('reponses::document sans titre');
if ($cache) {
$this->set_data_to_cache(self::CACHE_TITLE, $title);
}
return $title;
} | [
"public",
"function",
"getTitle",
"(",
"$",
"locale",
"=",
"null",
",",
"Array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"removeExtension",
"=",
"!",
"!",
"igorw",
"\\",
"get_in",
"(",
"$",
"options",
",",
"[",
"'removeExtension'",
"]",
",",
"f... | get the title (concat "thumbtitle" fields which match locale, with "-")
fallback to the filename, possibly with extension removed
@param string $locale
@param $options[]
'removeExtension' : boolean
@return string | [
"get",
"the",
"title",
"(",
"concat",
"thumbtitle",
"fields",
"which",
"match",
"locale",
"with",
"-",
")",
"fallback",
"to",
"the",
"filename",
"possibly",
"with",
"extension",
"removed"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/record/adapter.php#L897-L945 |
alchemy-fr/Phraseanet | lib/classes/record/adapter.php | record_adapter.set_metadatas | public function set_metadatas(array $metadatas, $force_readonly = false)
{
$databox_descriptionStructure = $this->getDatabox()->get_meta_structure();
foreach ($metadatas as $param) {
if (!is_array($param)) {
throw new Exception_InvalidArgument('Invalid metadatas argument');
}
$db_field = $databox_descriptionStructure->get_element($param['meta_struct_id']);
if ($db_field->is_readonly() === true && !$force_readonly) {
continue;
}
$this->set_metadata($param, $this->getDatabox());
}
$xml = new DOMDocument();
$xml->loadXML($this->app['serializer.caption']->serialize($this->get_caption(), CaptionSerializer::SERIALIZE_XML, true));
$this->set_xml($xml);
unset($xml);
$this->write_metas();
$this->dispatch(RecordEvents::METADATA_CHANGED, new MetadataChangedEvent($this));
return $this;
} | php | public function set_metadatas(array $metadatas, $force_readonly = false)
{
$databox_descriptionStructure = $this->getDatabox()->get_meta_structure();
foreach ($metadatas as $param) {
if (!is_array($param)) {
throw new Exception_InvalidArgument('Invalid metadatas argument');
}
$db_field = $databox_descriptionStructure->get_element($param['meta_struct_id']);
if ($db_field->is_readonly() === true && !$force_readonly) {
continue;
}
$this->set_metadata($param, $this->getDatabox());
}
$xml = new DOMDocument();
$xml->loadXML($this->app['serializer.caption']->serialize($this->get_caption(), CaptionSerializer::SERIALIZE_XML, true));
$this->set_xml($xml);
unset($xml);
$this->write_metas();
$this->dispatch(RecordEvents::METADATA_CHANGED, new MetadataChangedEvent($this));
return $this;
} | [
"public",
"function",
"set_metadatas",
"(",
"array",
"$",
"metadatas",
",",
"$",
"force_readonly",
"=",
"false",
")",
"{",
"$",
"databox_descriptionStructure",
"=",
"$",
"this",
"->",
"getDatabox",
"(",
")",
"->",
"get_meta_structure",
"(",
")",
";",
"foreach"... | @todo move this function to caption_record
@param array $metadatas
@param boolean $force_readonly
@return record_adapter | [
"@todo",
"move",
"this",
"function",
"to",
"caption_record"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/record/adapter.php#L1084-L1112 |
alchemy-fr/Phraseanet | lib/classes/record/adapter.php | record_adapter.createFromFile | public static function createFromFile(File $file, Application $app)
{
$databox = $file->getCollection()->get_databox();
$sql = "INSERT INTO record"
. " (coll_id, record_id, parent_record_id, moddate, credate, type, sha256, uuid, originalname, mime)"
. " VALUES (:coll_id, null, :parent_record_id, NOW(), NOW(), :type, :sha256, :uuid, :originalname, :mime)";
$connection = $databox->get_connection();
$stmt = $connection->prepare($sql);
$stmt->execute([
':coll_id' => $file->getCollection()->get_coll_id(),
':parent_record_id' => 0,
':type' => $file->getType() ? $file->getType()->getType() : 'unknown',
':sha256' => $file->getMedia()->getHash('sha256'),
':uuid' => $file->getUUID(true),
':originalname' => $file->getOriginalName(),
':mime' => $file->getFile()->getMimeType(),
]);
$stmt->closeCursor();
$record_id = $connection->lastInsertId();
$record = new self($app, $databox->get_sbas_id(), $record_id);
try {
$log_id = $app['phraseanet.logger']($databox)->get_id();
$sql = "INSERT INTO log_docs (id, log_id, date, record_id, coll_id, action, final, comment)"
. " VALUES (null, :log_id, now(), :record_id, :coll_id, 'add', :final, '')";
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute([
':log_id' => $log_id,
':record_id' => $record_id,
':coll_id' => $file->getCollection()->get_coll_id(),
':final' => $file->getCollection()->get_coll_id(),
]);
$stmt->closeCursor();
} catch (\Exception $e) {
unset($e);
}
$filesystem = self::getFilesystem($app);
$pathhd = $filesystem->generateDataboxDocumentBasePath($databox);
$newname = $filesystem->generateDocumentFilename($record, $file->getFile());
$filesystem->copy($file->getFile()->getRealPath(), $pathhd . $newname);
$media = $app->getMediaFromUri($pathhd . $newname);
media_subdef::create($app, $record, 'document', $media);
$record->delete_data_from_cache(\record_adapter::CACHE_SUBDEFS);
$record->insertTechnicalDatas($app['mediavorus']);
$record->dispatch(RecordEvents::CREATED, new CreatedEvent($record));
return $record;
} | php | public static function createFromFile(File $file, Application $app)
{
$databox = $file->getCollection()->get_databox();
$sql = "INSERT INTO record"
. " (coll_id, record_id, parent_record_id, moddate, credate, type, sha256, uuid, originalname, mime)"
. " VALUES (:coll_id, null, :parent_record_id, NOW(), NOW(), :type, :sha256, :uuid, :originalname, :mime)";
$connection = $databox->get_connection();
$stmt = $connection->prepare($sql);
$stmt->execute([
':coll_id' => $file->getCollection()->get_coll_id(),
':parent_record_id' => 0,
':type' => $file->getType() ? $file->getType()->getType() : 'unknown',
':sha256' => $file->getMedia()->getHash('sha256'),
':uuid' => $file->getUUID(true),
':originalname' => $file->getOriginalName(),
':mime' => $file->getFile()->getMimeType(),
]);
$stmt->closeCursor();
$record_id = $connection->lastInsertId();
$record = new self($app, $databox->get_sbas_id(), $record_id);
try {
$log_id = $app['phraseanet.logger']($databox)->get_id();
$sql = "INSERT INTO log_docs (id, log_id, date, record_id, coll_id, action, final, comment)"
. " VALUES (null, :log_id, now(), :record_id, :coll_id, 'add', :final, '')";
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute([
':log_id' => $log_id,
':record_id' => $record_id,
':coll_id' => $file->getCollection()->get_coll_id(),
':final' => $file->getCollection()->get_coll_id(),
]);
$stmt->closeCursor();
} catch (\Exception $e) {
unset($e);
}
$filesystem = self::getFilesystem($app);
$pathhd = $filesystem->generateDataboxDocumentBasePath($databox);
$newname = $filesystem->generateDocumentFilename($record, $file->getFile());
$filesystem->copy($file->getFile()->getRealPath(), $pathhd . $newname);
$media = $app->getMediaFromUri($pathhd . $newname);
media_subdef::create($app, $record, 'document', $media);
$record->delete_data_from_cache(\record_adapter::CACHE_SUBDEFS);
$record->insertTechnicalDatas($app['mediavorus']);
$record->dispatch(RecordEvents::CREATED, new CreatedEvent($record));
return $record;
} | [
"public",
"static",
"function",
"createFromFile",
"(",
"File",
"$",
"file",
",",
"Application",
"$",
"app",
")",
"{",
"$",
"databox",
"=",
"$",
"file",
"->",
"getCollection",
"(",
")",
"->",
"get_databox",
"(",
")",
";",
"$",
"sql",
"=",
"\"INSERT INTO r... | @param File $file
@param Application $app
@return \record_adapter | [
"@param",
"File",
"$file",
"@param",
"Application",
"$app"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/record/adapter.php#L1240-L1301 |
alchemy-fr/Phraseanet | lib/classes/record/adapter.php | record_adapter.insertTechnicalDatas | public function insertTechnicalDatas(MediaVorus $mediavorus)
{
try {
$document = $this->get_subdef('document');
} catch (\Exception_Media_SubdefNotFound $e) {
return $this;
}
$connection = $this->getDataboxConnection();
$connection->executeUpdate('DELETE FROM technical_datas WHERE record_id = :record_id', [
':record_id' => $this->getRecordId(),
]);
$sqlValues = [];
foreach ($document->readTechnicalDatas($mediavorus) as $name => $value) {
if (is_null($value)) {
continue;
} elseif (is_bool($value)) {
if ($value) {
$value = 1;
} else {
$value = 0;
}
}
$sqlValues[] = [$this->getRecordId(), $name, $value];
}
if ($sqlValues) {
$connection->transactional(function (Connection $connection) use ($sqlValues) {
$statement = $connection->prepare('INSERT INTO technical_datas (record_id, name, value) VALUES (?, ?, ?)');
array_walk($sqlValues, [$statement, 'execute']);
});
}
$this->delete_data_from_cache(self::CACHE_TECHNICAL_DATA);
return $this;
} | php | public function insertTechnicalDatas(MediaVorus $mediavorus)
{
try {
$document = $this->get_subdef('document');
} catch (\Exception_Media_SubdefNotFound $e) {
return $this;
}
$connection = $this->getDataboxConnection();
$connection->executeUpdate('DELETE FROM technical_datas WHERE record_id = :record_id', [
':record_id' => $this->getRecordId(),
]);
$sqlValues = [];
foreach ($document->readTechnicalDatas($mediavorus) as $name => $value) {
if (is_null($value)) {
continue;
} elseif (is_bool($value)) {
if ($value) {
$value = 1;
} else {
$value = 0;
}
}
$sqlValues[] = [$this->getRecordId(), $name, $value];
}
if ($sqlValues) {
$connection->transactional(function (Connection $connection) use ($sqlValues) {
$statement = $connection->prepare('INSERT INTO technical_datas (record_id, name, value) VALUES (?, ?, ?)');
array_walk($sqlValues, [$statement, 'execute']);
});
}
$this->delete_data_from_cache(self::CACHE_TECHNICAL_DATA);
return $this;
} | [
"public",
"function",
"insertTechnicalDatas",
"(",
"MediaVorus",
"$",
"mediavorus",
")",
"{",
"try",
"{",
"$",
"document",
"=",
"$",
"this",
"->",
"get_subdef",
"(",
"'document'",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception_Media_SubdefNotFound",
"$",
"e",
... | Read technical datas an insert them
This method can be long to perform
@return record_adapter | [
"Read",
"technical",
"datas",
"an",
"insert",
"them",
"This",
"method",
"can",
"be",
"long",
"to",
"perform"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/record/adapter.php#L1309-L1347 |
alchemy-fr/Phraseanet | lib/classes/record/adapter.php | record_adapter.insertOrUpdateTechnicalDatas | public function insertOrUpdateTechnicalDatas($technicalDatas)
{
$technicalFields = media_subdef::getTechnicalFieldsList();
$sqlValues = null;
foreach($technicalDatas as $name => $value){
if(array_key_exists($name, $technicalFields)){
if(is_null($value)){
$value = 0;
}
$sqlValues[] = [$this->getRecordId(), $name, $value, $value];
}
}
if($sqlValues){
$connection = $this->getDataboxConnection();
$connection->transactional(function (Connection $connection) use ($sqlValues) {
$statement = $connection->prepare('INSERT INTO technical_datas (record_id, name, value) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE value = ?');
array_walk($sqlValues, [$statement, 'execute']);
});
$this->delete_data_from_cache(self::CACHE_TECHNICAL_DATA);
}
} | php | public function insertOrUpdateTechnicalDatas($technicalDatas)
{
$technicalFields = media_subdef::getTechnicalFieldsList();
$sqlValues = null;
foreach($technicalDatas as $name => $value){
if(array_key_exists($name, $technicalFields)){
if(is_null($value)){
$value = 0;
}
$sqlValues[] = [$this->getRecordId(), $name, $value, $value];
}
}
if($sqlValues){
$connection = $this->getDataboxConnection();
$connection->transactional(function (Connection $connection) use ($sqlValues) {
$statement = $connection->prepare('INSERT INTO technical_datas (record_id, name, value) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE value = ?');
array_walk($sqlValues, [$statement, 'execute']);
});
$this->delete_data_from_cache(self::CACHE_TECHNICAL_DATA);
}
} | [
"public",
"function",
"insertOrUpdateTechnicalDatas",
"(",
"$",
"technicalDatas",
")",
"{",
"$",
"technicalFields",
"=",
"media_subdef",
"::",
"getTechnicalFieldsList",
"(",
")",
";",
"$",
"sqlValues",
"=",
"null",
";",
"foreach",
"(",
"$",
"technicalDatas",
"as",... | Insert or update technical data
$technicalDatas an array of name => value
@param array $technicalDatas | [
"Insert",
"or",
"update",
"technical",
"data",
"$technicalDatas",
"an",
"array",
"of",
"name",
"=",
">",
"value"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/record/adapter.php#L1355-L1378 |
alchemy-fr/Phraseanet | lib/classes/record/adapter.php | record_adapter.get_record_by_uuid | public static function get_record_by_uuid(\databox $databox, $uuid, $record_id = null)
{
$records = $databox->getRecordRepository()->findByUuid($uuid);
if (!is_null($record_id)) {
$records = array_filter($records, function (record_adapter $record) use ($record_id) {
return $record->getRecordId() == $record_id;
});
}
return $records;
} | php | public static function get_record_by_uuid(\databox $databox, $uuid, $record_id = null)
{
$records = $databox->getRecordRepository()->findByUuid($uuid);
if (!is_null($record_id)) {
$records = array_filter($records, function (record_adapter $record) use ($record_id) {
return $record->getRecordId() == $record_id;
});
}
return $records;
} | [
"public",
"static",
"function",
"get_record_by_uuid",
"(",
"\\",
"databox",
"$",
"databox",
",",
"$",
"uuid",
",",
"$",
"record_id",
"=",
"null",
")",
"{",
"$",
"records",
"=",
"$",
"databox",
"->",
"getRecordRepository",
"(",
")",
"->",
"findByUuid",
"(",... | Search for a record on a databox by UUID
@param \databox $databox
@param string $uuid
@param int $record_id Restrict check on a record_id
@return record_adapter[]
@deprecated use {@link databox::getRecordRepository} instead. | [
"Search",
"for",
"a",
"record",
"on",
"a",
"databox",
"by",
"UUID"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/record/adapter.php#L1409-L1420 |
alchemy-fr/Phraseanet | lib/classes/record/adapter.php | record_adapter.get_records_by_originalname | public static function get_records_by_originalname(databox $databox, $original_name, $caseSensitive = false, $offset_start = 0, $how_many = 10)
{
$offset_start = max(0, (int)$offset_start);
$how_many = max(1, (int)$how_many);
$sql = sprintf(
'SELECT record_id FROM record WHERE originalname = :original_name COLLATE %s LIMIT %d, %d',
$caseSensitive ? 'utf8_bin' : 'utf8_unicode_ci',
$offset_start,
$how_many
);
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute([':original_name' => $original_name]);
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$records = [];
foreach ($rs as $row) {
$records[] = $databox->get_record($row['record_id']);
}
return $records;
} | php | public static function get_records_by_originalname(databox $databox, $original_name, $caseSensitive = false, $offset_start = 0, $how_many = 10)
{
$offset_start = max(0, (int)$offset_start);
$how_many = max(1, (int)$how_many);
$sql = sprintf(
'SELECT record_id FROM record WHERE originalname = :original_name COLLATE %s LIMIT %d, %d',
$caseSensitive ? 'utf8_bin' : 'utf8_unicode_ci',
$offset_start,
$how_many
);
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute([':original_name' => $original_name]);
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$records = [];
foreach ($rs as $row) {
$records[] = $databox->get_record($row['record_id']);
}
return $records;
} | [
"public",
"static",
"function",
"get_records_by_originalname",
"(",
"databox",
"$",
"databox",
",",
"$",
"original_name",
",",
"$",
"caseSensitive",
"=",
"false",
",",
"$",
"offset_start",
"=",
"0",
",",
"$",
"how_many",
"=",
"10",
")",
"{",
"$",
"offset_sta... | @param databox $databox
@param int $original_name
@param bool $caseSensitive
@param int $offset_start
@param int $how_many
@return record_adapter[] | [
"@param",
"databox",
"$databox",
"@param",
"int",
"$original_name",
"@param",
"bool",
"$caseSensitive",
"@param",
"int",
"$offset_start",
"@param",
"int",
"$how_many"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/record/adapter.php#L1651-L1674 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Report/Controller/ProdReportController.php | ProdReportController.connectionsAction | public function connectionsAction(Request $request, $sbasId)
{
if(!($extension = $request->get('format'))) {
$extension = 'csv';
}
if(!array_key_exists($extension, self::$mapFromExtension)) {
throw new \InvalidArgumentException(sprintf("bad format \"%s\" for report", $extension));
}
$this->extension = $extension;
/** @var ReportConnections $report */
$report = $this->reportFactory->createReport(
ReportFactory::CONNECTIONS,
$sbasId,
[
'dmin' => $request->get('dmin'),
'dmax' => $request->get('dmax'),
'group' => $request->get('group'),
'anonymize' => $this->anonymousReport,
]
);
$report->setFormat(self::$mapFromExtension[$this->extension]['format']);
$response = new StreamedResponse();
$this->setHeadersFromFormat($response, $report);
$response->setCallback(function() use($report) {
$report->render();
});
return $response;
} | php | public function connectionsAction(Request $request, $sbasId)
{
if(!($extension = $request->get('format'))) {
$extension = 'csv';
}
if(!array_key_exists($extension, self::$mapFromExtension)) {
throw new \InvalidArgumentException(sprintf("bad format \"%s\" for report", $extension));
}
$this->extension = $extension;
/** @var ReportConnections $report */
$report = $this->reportFactory->createReport(
ReportFactory::CONNECTIONS,
$sbasId,
[
'dmin' => $request->get('dmin'),
'dmax' => $request->get('dmax'),
'group' => $request->get('group'),
'anonymize' => $this->anonymousReport,
]
);
$report->setFormat(self::$mapFromExtension[$this->extension]['format']);
$response = new StreamedResponse();
$this->setHeadersFromFormat($response, $report);
$response->setCallback(function() use($report) {
$report->render();
});
return $response;
} | [
"public",
"function",
"connectionsAction",
"(",
"Request",
"$",
"request",
",",
"$",
"sbasId",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"extension",
"=",
"$",
"request",
"->",
"get",
"(",
"'format'",
")",
")",
")",
"{",
"$",
"extension",
"=",
"'csv'",
";"... | route prod/report/connections
@param Request $request
@param $sbasId
@return StreamedResponse | [
"route",
"prod",
"/",
"report",
"/",
"connections"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Report/Controller/ProdReportController.php#L80-L113 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Report/Controller/ProdReportController.php | ProdReportController.recordsAction | public function recordsAction(Request $request, $sbasId)
{
if(!($extension = $request->get('format'))) {
$extension = 'csv';
}
if(!array_key_exists($extension, self::$mapFromExtension)) {
throw new \InvalidArgumentException(sprintf("bad format \"%s\" for report", $extension));
}
$this->extension = $extension;
/** @var ReportRecords $report */
$report = $this->reportFactory->createReport(
ReportFactory::RECORDS,
$sbasId,
[
'dmin' => $request->get('dmin'),
'dmax' => $request->get('dmax'),
'group' => $request->get('group'),
'base' => $request->get('base'),
'meta' => $request->get('meta'),
]
);
$report->setFormat(self::$mapFromExtension[$this->extension]['format']);
set_time_limit(600);
$response = new StreamedResponse();
$this->setHeadersFromFormat($response, $report);
$response->setCallback(function() use($report) {
$report->render();
});
return $response;
} | php | public function recordsAction(Request $request, $sbasId)
{
if(!($extension = $request->get('format'))) {
$extension = 'csv';
}
if(!array_key_exists($extension, self::$mapFromExtension)) {
throw new \InvalidArgumentException(sprintf("bad format \"%s\" for report", $extension));
}
$this->extension = $extension;
/** @var ReportRecords $report */
$report = $this->reportFactory->createReport(
ReportFactory::RECORDS,
$sbasId,
[
'dmin' => $request->get('dmin'),
'dmax' => $request->get('dmax'),
'group' => $request->get('group'),
'base' => $request->get('base'),
'meta' => $request->get('meta'),
]
);
$report->setFormat(self::$mapFromExtension[$this->extension]['format']);
set_time_limit(600);
$response = new StreamedResponse();
$this->setHeadersFromFormat($response, $report);
$response->setCallback(function() use($report) {
$report->render();
});
return $response;
} | [
"public",
"function",
"recordsAction",
"(",
"Request",
"$",
"request",
",",
"$",
"sbasId",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"extension",
"=",
"$",
"request",
"->",
"get",
"(",
"'format'",
")",
")",
")",
"{",
"$",
"extension",
"=",
"'csv'",
";",
... | route prod/report/records
@param Request $request
@param $sbasId
@return StreamedResponse | [
"route",
"prod",
"/",
"report",
"/",
"records"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Report/Controller/ProdReportController.php#L165-L200 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Admin/CollectionController.php | CollectionController.getCollection | public function getCollection(Request $request, $bas_id)
{
$collection = \collection::getByBaseId($this->app, $bas_id);
$admins = [];
if ($this->getAclForUser()->has_right_on_base($bas_id, \ACL::COLL_MANAGE)) {
$query = $this->createUserQuery();
$admins = $query->on_base_ids([$bas_id])
->who_have_right([\ACL::ORDER_MASTER])
->include_templates(true)
->execute()
->get_results();
}
switch ($errorMsg = $request->query->get('error')) {
case 'file-error':
$errorMsg = $this->app->trans('Error while sending the file');
break;
case 'file-invalid':
$errorMsg = $this->app->trans('Invalid file format');
break;
case 'file-file-too-big':
$errorMsg = $this->app->trans('The file is too big');
break;
case 'collection-not-empty':
$errorMsg = $this->app->trans('Empty the collection before removing');
break;
}
return $this->render('admin/collection/collection.html.twig', [
'collection' => $collection,
'admins' => $admins,
'errorMsg' => $errorMsg,
'reloadTree' => $request->query->get('reload-tree') === '1'
]);
} | php | public function getCollection(Request $request, $bas_id)
{
$collection = \collection::getByBaseId($this->app, $bas_id);
$admins = [];
if ($this->getAclForUser()->has_right_on_base($bas_id, \ACL::COLL_MANAGE)) {
$query = $this->createUserQuery();
$admins = $query->on_base_ids([$bas_id])
->who_have_right([\ACL::ORDER_MASTER])
->include_templates(true)
->execute()
->get_results();
}
switch ($errorMsg = $request->query->get('error')) {
case 'file-error':
$errorMsg = $this->app->trans('Error while sending the file');
break;
case 'file-invalid':
$errorMsg = $this->app->trans('Invalid file format');
break;
case 'file-file-too-big':
$errorMsg = $this->app->trans('The file is too big');
break;
case 'collection-not-empty':
$errorMsg = $this->app->trans('Empty the collection before removing');
break;
}
return $this->render('admin/collection/collection.html.twig', [
'collection' => $collection,
'admins' => $admins,
'errorMsg' => $errorMsg,
'reloadTree' => $request->query->get('reload-tree') === '1'
]);
} | [
"public",
"function",
"getCollection",
"(",
"Request",
"$",
"request",
",",
"$",
"bas_id",
")",
"{",
"$",
"collection",
"=",
"\\",
"collection",
"::",
"getByBaseId",
"(",
"$",
"this",
"->",
"app",
",",
"$",
"bas_id",
")",
";",
"$",
"admins",
"=",
"[",
... | Display collection information page
@param Request $request The current request
@param integer $bas_id The collection base_id
@return Response | [
"Display",
"collection",
"information",
"page"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/CollectionController.php#L43-L79 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Admin/CollectionController.php | CollectionController.setOrderAdmins | public function setOrderAdmins(Request $request, $bas_id)
{
$admins = array_filter(
array_values($request->request->get('admins', [])),
function ($value) { return $value != false; }
);
if (false && count($admins) === 0) {
$this->app->abort(400, 'No admins provided.');
}
if (!is_array($admins)) {
$this->app->abort(400, 'Admins must be an array.');
}
$collection = $this->getApplicationBox()->get_collection($bas_id);
$collectionReference = $collection->getReference();
$this->collectionService->setOrderMasters($collectionReference, $admins);
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $bas_id,
'success' => 1,
]);
} | php | public function setOrderAdmins(Request $request, $bas_id)
{
$admins = array_filter(
array_values($request->request->get('admins', [])),
function ($value) { return $value != false; }
);
if (false && count($admins) === 0) {
$this->app->abort(400, 'No admins provided.');
}
if (!is_array($admins)) {
$this->app->abort(400, 'Admins must be an array.');
}
$collection = $this->getApplicationBox()->get_collection($bas_id);
$collectionReference = $collection->getReference();
$this->collectionService->setOrderMasters($collectionReference, $admins);
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $bas_id,
'success' => 1,
]);
} | [
"public",
"function",
"setOrderAdmins",
"(",
"Request",
"$",
"request",
",",
"$",
"bas_id",
")",
"{",
"$",
"admins",
"=",
"array_filter",
"(",
"array_values",
"(",
"$",
"request",
"->",
"request",
"->",
"get",
"(",
"'admins'",
",",
"[",
"]",
")",
")",
... | Set new admin to handle orders
@param Request $request The current request
@param integer $bas_id The collection base_id
@return Response
@throws \Doctrine\DBAL\ConnectionException
@throws \Exception | [
"Set",
"new",
"admin",
"to",
"handle",
"orders"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/CollectionController.php#L90-L114 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Admin/CollectionController.php | CollectionController.emptyCollection | public function emptyCollection(Request $request, $bas_id)
{
$success = false;
$msg = $this->app->trans('An error occurred');
$collection = \collection::getByBaseId($this->app, $bas_id);
try {
if ($collection->get_record_amount() <= 500) {
$collection->empty_collection(500);
$msg = $this->app->trans('Collection empty successful');
} else {
$this->app['manipulator.task']->createEmptyCollectionJob($collection);
$msg = $this->app->trans('A task has been creted, please run it to complete empty collection');
}
$success = true;
} catch (\Exception $e) {
}
if ('json' === $request->getRequestFormat()) {
return $this->app->json([
'success' => $success,
'msg' => $msg,
'bas_id' => $collection->get_base_id()
]);
}
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $collection->get_base_id(),
'success' => (int) $success,
]);
} | php | public function emptyCollection(Request $request, $bas_id)
{
$success = false;
$msg = $this->app->trans('An error occurred');
$collection = \collection::getByBaseId($this->app, $bas_id);
try {
if ($collection->get_record_amount() <= 500) {
$collection->empty_collection(500);
$msg = $this->app->trans('Collection empty successful');
} else {
$this->app['manipulator.task']->createEmptyCollectionJob($collection);
$msg = $this->app->trans('A task has been creted, please run it to complete empty collection');
}
$success = true;
} catch (\Exception $e) {
}
if ('json' === $request->getRequestFormat()) {
return $this->app->json([
'success' => $success,
'msg' => $msg,
'bas_id' => $collection->get_base_id()
]);
}
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $collection->get_base_id(),
'success' => (int) $success,
]);
} | [
"public",
"function",
"emptyCollection",
"(",
"Request",
"$",
"request",
",",
"$",
"bas_id",
")",
"{",
"$",
"success",
"=",
"false",
";",
"$",
"msg",
"=",
"$",
"this",
"->",
"app",
"->",
"trans",
"(",
"'An error occurred'",
")",
";",
"$",
"collection",
... | Empty a collection
@param Request $request The current request
@param integer $bas_id The collection base_id
@return Response | [
"Empty",
"a",
"collection"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/CollectionController.php#L123-L155 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Admin/CollectionController.php | CollectionController.deleteStamp | public function deleteStamp(Request $request, $bas_id)
{
$success = false;
$collection = \collection::getByBaseId($this->app, $bas_id);
try {
$this->app->getApplicationBox()->write_collection_pic(
$this->app['media-alchemyst'],
$this->app['filesystem'],
$collection,
null,
\collection::PIC_STAMP
);
$success = true;
} catch (\Exception $e) {
}
if ('json' === $request->getRequestFormat()) {
return $this->app->json([
'success' => $success,
'msg' => $success ? $this->app->trans('Successful removal') : $this->app->trans('An error occured'),
'bas_id' => $collection->get_base_id()
]);
}
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $collection->get_base_id(),
'success' => (int) $success,
]);
} | php | public function deleteStamp(Request $request, $bas_id)
{
$success = false;
$collection = \collection::getByBaseId($this->app, $bas_id);
try {
$this->app->getApplicationBox()->write_collection_pic(
$this->app['media-alchemyst'],
$this->app['filesystem'],
$collection,
null,
\collection::PIC_STAMP
);
$success = true;
} catch (\Exception $e) {
}
if ('json' === $request->getRequestFormat()) {
return $this->app->json([
'success' => $success,
'msg' => $success ? $this->app->trans('Successful removal') : $this->app->trans('An error occured'),
'bas_id' => $collection->get_base_id()
]);
}
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $collection->get_base_id(),
'success' => (int) $success,
]);
} | [
"public",
"function",
"deleteStamp",
"(",
"Request",
"$",
"request",
",",
"$",
"bas_id",
")",
"{",
"$",
"success",
"=",
"false",
";",
"$",
"collection",
"=",
"\\",
"collection",
"::",
"getByBaseId",
"(",
"$",
"this",
"->",
"app",
",",
"$",
"bas_id",
")... | Delete the collection stamp
@param Request $request The current request
@param integer $bas_id The collection base_id
@return Response | [
"Delete",
"the",
"collection",
"stamp"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/CollectionController.php#L164-L195 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Admin/CollectionController.php | CollectionController.setStamp | public function setStamp(Request $request, $bas_id)
{
if (null === $file = $request->files->get('newStamp')) {
$this->app->abort(400);
}
if ($file->getClientSize() > 1024 * 1024) {
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $bas_id,
'success' => 0,
'error' => 'file-too-big',
]);
}
if (!$file->isValid()) {
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $bas_id,
'success' => 0,
'error' => 'file-invalid',
]);
}
$collection = \collection::getByBaseId($this->app, $bas_id);
try {
$this->app->getApplicationBox()->write_collection_pic(
$this->app['media-alchemyst'],
$this->app['filesystem'],
$collection,
$file,
\collection::PIC_STAMP
);
$this->app['filesystem']->remove($file->getPathname());
} catch (\Exception $e) {
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $bas_id,
'success' => 0,
'error' => 'file-error',
]);
}
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $bas_id,
'success' => 1,
]);
} | php | public function setStamp(Request $request, $bas_id)
{
if (null === $file = $request->files->get('newStamp')) {
$this->app->abort(400);
}
if ($file->getClientSize() > 1024 * 1024) {
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $bas_id,
'success' => 0,
'error' => 'file-too-big',
]);
}
if (!$file->isValid()) {
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $bas_id,
'success' => 0,
'error' => 'file-invalid',
]);
}
$collection = \collection::getByBaseId($this->app, $bas_id);
try {
$this->app->getApplicationBox()->write_collection_pic(
$this->app['media-alchemyst'],
$this->app['filesystem'],
$collection,
$file,
\collection::PIC_STAMP
);
$this->app['filesystem']->remove($file->getPathname());
} catch (\Exception $e) {
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $bas_id,
'success' => 0,
'error' => 'file-error',
]);
}
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $bas_id,
'success' => 1,
]);
} | [
"public",
"function",
"setStamp",
"(",
"Request",
"$",
"request",
",",
"$",
"bas_id",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"file",
"=",
"$",
"request",
"->",
"files",
"->",
"get",
"(",
"'newStamp'",
")",
")",
"{",
"$",
"this",
"->",
"app",
"->"... | Set a collection stamp
@param Request $request The current request
@param integer $bas_id The collection base_id
@return Response | [
"Set",
"a",
"collection",
"stamp"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/CollectionController.php#L285-L331 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Admin/CollectionController.php | CollectionController.delete | public function delete(Request $request, $bas_id)
{
$success = false;
$msg = $this->app->trans('An error occured');
$collection = \collection::getByBaseId($this->app, $bas_id);
try {
if ($collection->get_record_amount() > 0) {
$msg = $this->app->trans('Empty the collection before removing');
} else {
$collection->unmount();
$collection->delete();
$success = true;
$msg = $this->app->trans('Successful removal');
}
} catch (\Exception $e) {
}
if ('json' === $request->getRequestFormat()) {
return $this->app->json([
'success' => $success,
'msg' => $msg
]);
}
if ($collection->get_record_amount() > 0) {
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $collection->get_sbas_id(),
'success' => 0,
'error' => 'collection-not-empty',
]);
}
if ($success) {
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $collection->get_sbas_id(),
'success' => 1,
'reload-tree' => 1,
]);
}
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $collection->get_sbas_id(),
'success' => 0,
]);
} | php | public function delete(Request $request, $bas_id)
{
$success = false;
$msg = $this->app->trans('An error occured');
$collection = \collection::getByBaseId($this->app, $bas_id);
try {
if ($collection->get_record_amount() > 0) {
$msg = $this->app->trans('Empty the collection before removing');
} else {
$collection->unmount();
$collection->delete();
$success = true;
$msg = $this->app->trans('Successful removal');
}
} catch (\Exception $e) {
}
if ('json' === $request->getRequestFormat()) {
return $this->app->json([
'success' => $success,
'msg' => $msg
]);
}
if ($collection->get_record_amount() > 0) {
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $collection->get_sbas_id(),
'success' => 0,
'error' => 'collection-not-empty',
]);
}
if ($success) {
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $collection->get_sbas_id(),
'success' => 1,
'reload-tree' => 1,
]);
}
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $collection->get_sbas_id(),
'success' => 0,
]);
} | [
"public",
"function",
"delete",
"(",
"Request",
"$",
"request",
",",
"$",
"bas_id",
")",
"{",
"$",
"success",
"=",
"false",
";",
"$",
"msg",
"=",
"$",
"this",
"->",
"app",
"->",
"trans",
"(",
"'An error occured'",
")",
";",
"$",
"collection",
"=",
"\... | Delete a Collection
@param Request $request The current request
@param integer $bas_id The collection base_id
@return Response | [
"Delete",
"a",
"Collection"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/CollectionController.php#L447-L493 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Admin/CollectionController.php | CollectionController.unmount | public function unmount(Request $request, $bas_id)
{
$success = false;
$collection = \collection::getByBaseId($this->app, $bas_id);
try {
$collection->unmount();
$success = true;
} catch (\Exception $e) {
}
if ('json' === $request->getRequestFormat()) {
$msg = $success
? $this->app->trans('The publication has been stopped')
: $this->app->trans('An error occured');
return $this->app->json([
'success' => $success,
'msg' => $msg,
]);
}
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $collection->get_sbas_id(),
'success' => (int) $success,
]);
} | php | public function unmount(Request $request, $bas_id)
{
$success = false;
$collection = \collection::getByBaseId($this->app, $bas_id);
try {
$collection->unmount();
$success = true;
} catch (\Exception $e) {
}
if ('json' === $request->getRequestFormat()) {
$msg = $success
? $this->app->trans('The publication has been stopped')
: $this->app->trans('An error occured');
return $this->app->json([
'success' => $success,
'msg' => $msg,
]);
}
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $collection->get_sbas_id(),
'success' => (int) $success,
]);
} | [
"public",
"function",
"unmount",
"(",
"Request",
"$",
"request",
",",
"$",
"bas_id",
")",
"{",
"$",
"success",
"=",
"false",
";",
"$",
"collection",
"=",
"\\",
"collection",
"::",
"getByBaseId",
"(",
"$",
"this",
"->",
"app",
",",
"$",
"bas_id",
")",
... | Unmount a collection from application box
@param Request $request The current request
@param integer $bas_id The collection base_id
@return Response | [
"Unmount",
"a",
"collection",
"from",
"application",
"box"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/CollectionController.php#L502-L529 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Admin/CollectionController.php | CollectionController.rename | public function rename(Request $request, $bas_id)
{
if (trim($name = $request->request->get('name')) === '') {
$this->app->abort(400, $this->app->trans('Missing name parameter'));
}
$success = false;
$collection = \collection::getByBaseId($this->app, $bas_id);
try {
$collection->set_name($name);
$success = true;
} catch (\Exception $e) {
}
if ('json' === $this->app['request']->getRequestFormat()) {
return $this->app->json([
'success' => $success,
'msg' => $success ? $this->app->trans('Successful update') : $this->app->trans('An error occured'),
]);
}
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $collection->get_base_id(),
'success' => (int) $success,
'reload-tree' => 1,
]);
} | php | public function rename(Request $request, $bas_id)
{
if (trim($name = $request->request->get('name')) === '') {
$this->app->abort(400, $this->app->trans('Missing name parameter'));
}
$success = false;
$collection = \collection::getByBaseId($this->app, $bas_id);
try {
$collection->set_name($name);
$success = true;
} catch (\Exception $e) {
}
if ('json' === $this->app['request']->getRequestFormat()) {
return $this->app->json([
'success' => $success,
'msg' => $success ? $this->app->trans('Successful update') : $this->app->trans('An error occured'),
]);
}
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $collection->get_base_id(),
'success' => (int) $success,
'reload-tree' => 1,
]);
} | [
"public",
"function",
"rename",
"(",
"Request",
"$",
"request",
",",
"$",
"bas_id",
")",
"{",
"if",
"(",
"trim",
"(",
"$",
"name",
"=",
"$",
"request",
"->",
"request",
"->",
"get",
"(",
"'name'",
")",
")",
"===",
"''",
")",
"{",
"$",
"this",
"->... | Rename a collection
@param Request $request The current request
@param integer $bas_id The collection base_id
@return Response | [
"Rename",
"a",
"collection"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/CollectionController.php#L538-L567 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Admin/CollectionController.php | CollectionController.setPublicationDisplay | public function setPublicationDisplay(Request $request, $bas_id)
{
if (null === $watermark = $request->request->get('pub_wm')) {
$this->app->abort(400, 'Missing public watermark setting');
}
$success = false;
$collection = \collection::getByBaseId($this->app, $bas_id);
try {
$collection->set_public_presentation($watermark);
$success = true;
} catch (\Exception $e) {
}
if ('json' === $request->getRequestFormat()) {
return $this->app->json([
'success' => $success,
'msg' => $success ? $this->app->trans('Successful update') : $this->app->trans('An error occured'),
]);
}
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $collection->get_sbas_id(),
'success' => (int) $success,
]);
} | php | public function setPublicationDisplay(Request $request, $bas_id)
{
if (null === $watermark = $request->request->get('pub_wm')) {
$this->app->abort(400, 'Missing public watermark setting');
}
$success = false;
$collection = \collection::getByBaseId($this->app, $bas_id);
try {
$collection->set_public_presentation($watermark);
$success = true;
} catch (\Exception $e) {
}
if ('json' === $request->getRequestFormat()) {
return $this->app->json([
'success' => $success,
'msg' => $success ? $this->app->trans('Successful update') : $this->app->trans('An error occured'),
]);
}
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $collection->get_sbas_id(),
'success' => (int) $success,
]);
} | [
"public",
"function",
"setPublicationDisplay",
"(",
"Request",
"$",
"request",
",",
"$",
"bas_id",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"watermark",
"=",
"$",
"request",
"->",
"request",
"->",
"get",
"(",
"'pub_wm'",
")",
")",
"{",
"$",
"this",
"->... | Set public presentation watermark
@param Request $request The current request
@param integer $bas_id The collection base_id
@return Response | [
"Set",
"public",
"presentation",
"watermark"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/CollectionController.php#L614-L642 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Admin/CollectionController.php | CollectionController.getSuggestedValues | public function getSuggestedValues($bas_id)
{
/** @var \databox $databox */
$databox = $this->app->findDataboxById(\phrasea::sbasFromBas($this->app, $bas_id));
$collection = \collection::getByBaseId($this->app, $bas_id);
$structFields = $suggestedValues = $basePrefs = [];
/** @var \databox_field $meta */
foreach ($databox->get_meta_structure() as $meta) {
if ($meta->is_readonly()) {
continue;
}
$structFields[$meta->get_name()] = $meta;
}
if ($sxe = simplexml_load_string($collection->get_prefs())) {
$z = $sxe->xpath('/baseprefs/sugestedValues');
if ($z && is_array($z)) {
$f = 0;
foreach ($z[0] as $ki => $vi) {
if ($vi && isset($structFields[$ki])) {
foreach ($vi->value as $oneValue) {
$suggestedValues[] = [
'key' => $ki,
'value' => $f,
'name' => (string) $oneValue
];
$f++;
}
}
}
}
$z = $sxe->xpath('/baseprefs');
if ($z && is_array($z)) {
/**
* @var string $ki
* @var \SimpleXMLElement $vi
*/
foreach ($z[0] as $ki => $vi) {
$pref = ['status' => null, 'xml' => null];
if ($ki == 'status') {
$pref['status'] = $vi;
} elseif ($ki != 'sugestedValues') {
$pref['xml'] = $vi->asXML();
}
$basePrefs[] = $pref;
}
}
}
return $this->render('admin/collection/suggested_value.html.twig', [
'collection' => $collection,
'databox' => $databox,
'suggestedValues' => $suggestedValues,
'structFields' => $structFields,
'basePrefs' => $basePrefs,
]);
} | php | public function getSuggestedValues($bas_id)
{
/** @var \databox $databox */
$databox = $this->app->findDataboxById(\phrasea::sbasFromBas($this->app, $bas_id));
$collection = \collection::getByBaseId($this->app, $bas_id);
$structFields = $suggestedValues = $basePrefs = [];
/** @var \databox_field $meta */
foreach ($databox->get_meta_structure() as $meta) {
if ($meta->is_readonly()) {
continue;
}
$structFields[$meta->get_name()] = $meta;
}
if ($sxe = simplexml_load_string($collection->get_prefs())) {
$z = $sxe->xpath('/baseprefs/sugestedValues');
if ($z && is_array($z)) {
$f = 0;
foreach ($z[0] as $ki => $vi) {
if ($vi && isset($structFields[$ki])) {
foreach ($vi->value as $oneValue) {
$suggestedValues[] = [
'key' => $ki,
'value' => $f,
'name' => (string) $oneValue
];
$f++;
}
}
}
}
$z = $sxe->xpath('/baseprefs');
if ($z && is_array($z)) {
/**
* @var string $ki
* @var \SimpleXMLElement $vi
*/
foreach ($z[0] as $ki => $vi) {
$pref = ['status' => null, 'xml' => null];
if ($ki == 'status') {
$pref['status'] = $vi;
} elseif ($ki != 'sugestedValues') {
$pref['xml'] = $vi->asXML();
}
$basePrefs[] = $pref;
}
}
}
return $this->render('admin/collection/suggested_value.html.twig', [
'collection' => $collection,
'databox' => $databox,
'suggestedValues' => $suggestedValues,
'structFields' => $structFields,
'basePrefs' => $basePrefs,
]);
} | [
"public",
"function",
"getSuggestedValues",
"(",
"$",
"bas_id",
")",
"{",
"/** @var \\databox $databox */",
"$",
"databox",
"=",
"$",
"this",
"->",
"app",
"->",
"findDataboxById",
"(",
"\\",
"phrasea",
"::",
"sbasFromBas",
"(",
"$",
"this",
"->",
"app",
",",
... | Display suggested values
@param integer $bas_id The collection base_id
@return string | [
"Display",
"suggested",
"values"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/CollectionController.php#L716-L777 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Admin/CollectionController.php | CollectionController.submitSuggestedValues | public function submitSuggestedValues(Request $request, $bas_id)
{
$success = false;
$collection = \collection::getByBaseId($this->app, $bas_id);
$prefs = $request->request->get('str');
try {
if ('' !== trim($prefs)) {
$domdoc = new \DOMDocument();
if (true === @$domdoc->loadXML($prefs)) {
$collection->set_prefs($domdoc);
$success = true;
}
}
} catch (\Exception $e) {
}
if ('json' === $request->getRequestFormat()) {
return $this->app->json([
'success' => $success,
'msg' => $success ? $this->app->trans('Successful update') : $this->app->trans('An error occured'),
'bas_id' => $collection->get_base_id(),
]);
}
return $this->app->redirectPath('admin_collection_display_suggested_values', [
'bas_id' => $collection->get_sbas_id(),
'success' => (int) $success,
]);
} | php | public function submitSuggestedValues(Request $request, $bas_id)
{
$success = false;
$collection = \collection::getByBaseId($this->app, $bas_id);
$prefs = $request->request->get('str');
try {
if ('' !== trim($prefs)) {
$domdoc = new \DOMDocument();
if (true === @$domdoc->loadXML($prefs)) {
$collection->set_prefs($domdoc);
$success = true;
}
}
} catch (\Exception $e) {
}
if ('json' === $request->getRequestFormat()) {
return $this->app->json([
'success' => $success,
'msg' => $success ? $this->app->trans('Successful update') : $this->app->trans('An error occured'),
'bas_id' => $collection->get_base_id(),
]);
}
return $this->app->redirectPath('admin_collection_display_suggested_values', [
'bas_id' => $collection->get_sbas_id(),
'success' => (int) $success,
]);
} | [
"public",
"function",
"submitSuggestedValues",
"(",
"Request",
"$",
"request",
",",
"$",
"bas_id",
")",
"{",
"$",
"success",
"=",
"false",
";",
"$",
"collection",
"=",
"\\",
"collection",
"::",
"getByBaseId",
"(",
"$",
"this",
"->",
"app",
",",
"$",
"bas... | Register suggested values
@param Request $request The current request
@param integer $bas_id The collection base_id
@return Response | [
"Register",
"suggested",
"values"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/CollectionController.php#L786-L817 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Admin/CollectionController.php | CollectionController.getDetails | public function getDetails($bas_id)
{
$collection = \collection::getByBaseId($this->app, $bas_id);
$out = ['total' => ['totobj' => 0, 'totsiz' => 0, 'mega' => '0', 'giga' => '0'], 'result' => []];
foreach ($collection->get_record_details() as $vrow) {
$last_k1 = $last_k2 = null;
$outRow = ['midobj' => 0, 'midsiz' => 0];
if ($vrow['amount'] > 0 || $last_k1 !== $vrow['coll_id']) {
if (extension_loaded('bcmath')) {
$outRow['midsiz'] = bcadd($outRow['midsiz'], $vrow['size'], 0);
} else {
$outRow['midsiz'] += $vrow['size'];
}
if ($last_k2 !== $vrow['name']) {
$outRow['name'] = $vrow['name'];
$last_k2 = $vrow['name'];
}
if (extension_loaded('bcmath')) {
$mega = bcdiv($vrow['size'], 1024 * 1024, 5);
} else {
$mega = $vrow['size'] / (1024 * 1024);
}
if (extension_loaded('bcmath')) {
$giga = bcdiv($vrow['size'], 1024 * 1024 * 1024, 5);
} else {
$giga = $vrow['size'] / (1024 * 1024 * 1024);
}
$outRow['mega'] = sprintf('%.2f', $mega);
$outRow['giga'] = sprintf('%.2f', $giga);
$outRow['amount'] = $vrow['amount'];
}
$out['total']['totobj'] += $outRow['amount'];
if (extension_loaded('bcmath')) {
$out['total']['totsiz'] = bcadd($out['total']['totsiz'], $outRow['midsiz'], 0);
} else {
$out['total']['totsiz'] += $outRow['midsiz'];
}
if (extension_loaded('bcmath')) {
$mega = bcdiv($outRow['midsiz'], 1024 * 1024, 5);
} else {
$mega = $outRow['midsiz'] / (1024 * 1024);
}
if (extension_loaded('bcmath')) {
$giga = bcdiv($outRow['midsiz'], 1024 * 1024 * 1024, 5);
} else {
$giga = $outRow['midsiz'] / (1024 * 1024 * 1024);
}
$outRow['mega_mid_size'] = sprintf('%.2f', $mega);
$outRow['giga_mid_size'] = sprintf('%.2f', $giga);
$out['result'][] = $outRow;
}
if (extension_loaded('bcmath')) {
$out['total']['mega'] = bcdiv($out['total']['totsiz'], 1024 * 1024, 5);
} else {
$out['total']['mega'] = $out['total']['totsiz'] / (1024 * 1024);
}
if (extension_loaded('bcmath')) {
$out['total']['giga'] = bcdiv($out['total']['totsiz'], 1024 * 1024 * 1024, 5);
} else {
$out['total']['giga'] = $out['total']['totsiz'] / (1024 * 1024 * 1024);
}
return $this->render('admin/collection/details.html.twig', [
'collection' => $collection,
'table' => $out,
]);
} | php | public function getDetails($bas_id)
{
$collection = \collection::getByBaseId($this->app, $bas_id);
$out = ['total' => ['totobj' => 0, 'totsiz' => 0, 'mega' => '0', 'giga' => '0'], 'result' => []];
foreach ($collection->get_record_details() as $vrow) {
$last_k1 = $last_k2 = null;
$outRow = ['midobj' => 0, 'midsiz' => 0];
if ($vrow['amount'] > 0 || $last_k1 !== $vrow['coll_id']) {
if (extension_loaded('bcmath')) {
$outRow['midsiz'] = bcadd($outRow['midsiz'], $vrow['size'], 0);
} else {
$outRow['midsiz'] += $vrow['size'];
}
if ($last_k2 !== $vrow['name']) {
$outRow['name'] = $vrow['name'];
$last_k2 = $vrow['name'];
}
if (extension_loaded('bcmath')) {
$mega = bcdiv($vrow['size'], 1024 * 1024, 5);
} else {
$mega = $vrow['size'] / (1024 * 1024);
}
if (extension_loaded('bcmath')) {
$giga = bcdiv($vrow['size'], 1024 * 1024 * 1024, 5);
} else {
$giga = $vrow['size'] / (1024 * 1024 * 1024);
}
$outRow['mega'] = sprintf('%.2f', $mega);
$outRow['giga'] = sprintf('%.2f', $giga);
$outRow['amount'] = $vrow['amount'];
}
$out['total']['totobj'] += $outRow['amount'];
if (extension_loaded('bcmath')) {
$out['total']['totsiz'] = bcadd($out['total']['totsiz'], $outRow['midsiz'], 0);
} else {
$out['total']['totsiz'] += $outRow['midsiz'];
}
if (extension_loaded('bcmath')) {
$mega = bcdiv($outRow['midsiz'], 1024 * 1024, 5);
} else {
$mega = $outRow['midsiz'] / (1024 * 1024);
}
if (extension_loaded('bcmath')) {
$giga = bcdiv($outRow['midsiz'], 1024 * 1024 * 1024, 5);
} else {
$giga = $outRow['midsiz'] / (1024 * 1024 * 1024);
}
$outRow['mega_mid_size'] = sprintf('%.2f', $mega);
$outRow['giga_mid_size'] = sprintf('%.2f', $giga);
$out['result'][] = $outRow;
}
if (extension_loaded('bcmath')) {
$out['total']['mega'] = bcdiv($out['total']['totsiz'], 1024 * 1024, 5);
} else {
$out['total']['mega'] = $out['total']['totsiz'] / (1024 * 1024);
}
if (extension_loaded('bcmath')) {
$out['total']['giga'] = bcdiv($out['total']['totsiz'], 1024 * 1024 * 1024, 5);
} else {
$out['total']['giga'] = $out['total']['totsiz'] / (1024 * 1024 * 1024);
}
return $this->render('admin/collection/details.html.twig', [
'collection' => $collection,
'table' => $out,
]);
} | [
"public",
"function",
"getDetails",
"(",
"$",
"bas_id",
")",
"{",
"$",
"collection",
"=",
"\\",
"collection",
"::",
"getByBaseId",
"(",
"$",
"this",
"->",
"app",
",",
"$",
"bas_id",
")",
";",
"$",
"out",
"=",
"[",
"'total'",
"=>",
"[",
"'totobj'",
"=... | Get document details in the requested collection
@param integer $bas_id The collection base_id
@return Response | [
"Get",
"document",
"details",
"in",
"the",
"requested",
"collection"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/CollectionController.php#L825-L907 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Setup/Version/Probe/Probe31.php | Probe31.isMigrable | public function isMigrable()
{
$oldFilesExist = is_file(__DIR__ . "/../../../../../../config/connexion.inc")
&& is_file(__DIR__ . "/../../../../../../config/_GV.php");
if ($oldFilesExist) {
if (!is_file(__DIR__ . "/../../../../../../config/config.yml")) {
return true;
}
// previous upgrade did not rename this file
rename(__DIR__ . "/../../../../../../config/_GV.php", __DIR__ . "/../../../../../../config/_GV.php.old");
return false;
}
return false;
} | php | public function isMigrable()
{
$oldFilesExist = is_file(__DIR__ . "/../../../../../../config/connexion.inc")
&& is_file(__DIR__ . "/../../../../../../config/_GV.php");
if ($oldFilesExist) {
if (!is_file(__DIR__ . "/../../../../../../config/config.yml")) {
return true;
}
// previous upgrade did not rename this file
rename(__DIR__ . "/../../../../../../config/_GV.php", __DIR__ . "/../../../../../../config/_GV.php.old");
return false;
}
return false;
} | [
"public",
"function",
"isMigrable",
"(",
")",
"{",
"$",
"oldFilesExist",
"=",
"is_file",
"(",
"__DIR__",
".",
"\"/../../../../../../config/connexion.inc\"",
")",
"&&",
"is_file",
"(",
"__DIR__",
".",
"\"/../../../../../../config/_GV.php\"",
")",
";",
"if",
"(",
"$",... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Setup/Version/Probe/Probe31.php#L29-L45 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Border/CustomExtensionGuesser.php | CustomExtensionGuesser.guess | public function guess($path)
{
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
if (isset($this->mapping[$extension])) {
return $this->mapping[$extension];
}
} | php | public function guess($path)
{
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
if (isset($this->mapping[$extension])) {
return $this->mapping[$extension];
}
} | [
"public",
"function",
"guess",
"(",
"$",
"path",
")",
"{",
"$",
"extension",
"=",
"strtolower",
"(",
"pathinfo",
"(",
"$",
"path",
",",
"PATHINFO_EXTENSION",
")",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"mapping",
"[",
"$",
"extension",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Border/CustomExtensionGuesser.php#L28-L35 |
alchemy-fr/Phraseanet | lib/classes/patch/320alpha6a.php | patch_320alpha6a.apply | public function apply(base $databox, Application $app)
{
$sql = 'UPDATE record r, subdef s
SET r.mime = s.mime
WHERE r.record_id = s.record_id
AND s.name="document"';
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = 'UPDATE subdef s, record r
SET s.updated_on = r.moddate, s.created_on = r.credate
WHERE s.record_id = r.record_id';
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = 'UPDATE subdef SET `name` = LOWER( `name` )';
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$dom = $databox->get_dom_structure();
$xpath = $databox->get_xpath_structure();
$nodes = $xpath->query('//record/subdefs/subdefgroup/subdef');
foreach ($nodes as $node) {
$name = mb_strtolower(trim($node->getAttribute('name')));
if ($name === '')
continue;
$node->setAttribute('name', $name);
}
$databox->saveStructure($dom);
return true;
} | php | public function apply(base $databox, Application $app)
{
$sql = 'UPDATE record r, subdef s
SET r.mime = s.mime
WHERE r.record_id = s.record_id
AND s.name="document"';
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = 'UPDATE subdef s, record r
SET s.updated_on = r.moddate, s.created_on = r.credate
WHERE s.record_id = r.record_id';
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = 'UPDATE subdef SET `name` = LOWER( `name` )';
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$dom = $databox->get_dom_structure();
$xpath = $databox->get_xpath_structure();
$nodes = $xpath->query('//record/subdefs/subdefgroup/subdef');
foreach ($nodes as $node) {
$name = mb_strtolower(trim($node->getAttribute('name')));
if ($name === '')
continue;
$node->setAttribute('name', $name);
}
$databox->saveStructure($dom);
return true;
} | [
"public",
"function",
"apply",
"(",
"base",
"$",
"databox",
",",
"Application",
"$",
"app",
")",
"{",
"$",
"sql",
"=",
"'UPDATE record r, subdef s\n SET r.mime = s.mime\n WHERE r.record_id = s.record_id\n AND s.name=\"document\"'",
";"... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/320alpha6a.php#L49-L86 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Setup/Version/Probe/Probe38.php | Probe38.isMigrable | public function isMigrable()
{
return is_file($this->app['root.path'] . "/config/config.yml")
&& is_file($this->app['root.path'] . "/config/services.yml")
&& is_file($this->app['root.path'] . "/config/connexions.yml");
} | php | public function isMigrable()
{
return is_file($this->app['root.path'] . "/config/config.yml")
&& is_file($this->app['root.path'] . "/config/services.yml")
&& is_file($this->app['root.path'] . "/config/connexions.yml");
} | [
"public",
"function",
"isMigrable",
"(",
")",
"{",
"return",
"is_file",
"(",
"$",
"this",
"->",
"app",
"[",
"'root.path'",
"]",
".",
"\"/config/config.yml\"",
")",
"&&",
"is_file",
"(",
"$",
"this",
"->",
"app",
"[",
"'root.path'",
"]",
".",
"\"/config/ser... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Setup/Version/Probe/Probe38.php#L29-L34 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Databox/ArrayCacheDataboxRepository.php | ArrayCacheDataboxRepository.mount | public function mount($host, $port, $user, $password, $dbname)
{
$this->clear();
return $this->repository->mount($host, $port, $user, $password, $dbname);
} | php | public function mount($host, $port, $user, $password, $dbname)
{
$this->clear();
return $this->repository->mount($host, $port, $user, $password, $dbname);
} | [
"public",
"function",
"mount",
"(",
"$",
"host",
",",
"$",
"port",
",",
"$",
"user",
",",
"$",
"password",
",",
"$",
"dbname",
")",
"{",
"$",
"this",
"->",
"clear",
"(",
")",
";",
"return",
"$",
"this",
"->",
"repository",
"->",
"mount",
"(",
"$"... | @param $host
@param $port
@param $user
@param $password
@param $dbname
@return \databox | [
"@param",
"$host",
"@param",
"$port",
"@param",
"$user",
"@param",
"$password",
"@param",
"$dbname"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Databox/ArrayCacheDataboxRepository.php#L94-L99 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Databox/ArrayCacheDataboxRepository.php | ArrayCacheDataboxRepository.load | private function load()
{
if (! $this->loaded) {
$this->databoxes = $this->repository->findAll();
$this->loaded = true;
}
} | php | private function load()
{
if (! $this->loaded) {
$this->databoxes = $this->repository->findAll();
$this->loaded = true;
}
} | [
"private",
"function",
"load",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"loaded",
")",
"{",
"$",
"this",
"->",
"databoxes",
"=",
"$",
"this",
"->",
"repository",
"->",
"findAll",
"(",
")",
";",
"$",
"this",
"->",
"loaded",
"=",
"true",
"... | Initializes the memory cache if needed. | [
"Initializes",
"the",
"memory",
"cache",
"if",
"needed",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Databox/ArrayCacheDataboxRepository.php#L120-L126 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Model/Entities/Session.php | Session.getModuleById | public function getModuleById($moduleId)
{
foreach ($this->getModules() as $module) {
if ($module->getModuleId() == $moduleId) {
return $module;
}
}
return null;
} | php | public function getModuleById($moduleId)
{
foreach ($this->getModules() as $module) {
if ($module->getModuleId() == $moduleId) {
return $module;
}
}
return null;
} | [
"public",
"function",
"getModuleById",
"(",
"$",
"moduleId",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getModules",
"(",
")",
"as",
"$",
"module",
")",
"{",
"if",
"(",
"$",
"module",
"->",
"getModuleId",
"(",
")",
"==",
"$",
"moduleId",
")",
"{",... | Get a module by its identifier
@param integer $moduleId
@return SessionModule|null | [
"Get",
"a",
"module",
"by",
"its",
"identifier"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Entities/Session.php#L431-L440 |
alchemy-fr/Phraseanet | lib/classes/collection.php | collection.isRegistrationEnabled | public function isRegistrationEnabled()
{
if (false === $xml = simplexml_load_string($this->get_prefs())) {
return false;
}
$element = $xml->xpath('/baseprefs/caninscript');
if (count($element) === 0) {
return $this->databox->isRegistrationEnabled();
}
foreach ($element as $caninscript) {
if (false !== (bool)(string)$caninscript) {
return true;
}
}
return false;
} | php | public function isRegistrationEnabled()
{
if (false === $xml = simplexml_load_string($this->get_prefs())) {
return false;
}
$element = $xml->xpath('/baseprefs/caninscript');
if (count($element) === 0) {
return $this->databox->isRegistrationEnabled();
}
foreach ($element as $caninscript) {
if (false !== (bool)(string)$caninscript) {
return true;
}
}
return false;
} | [
"public",
"function",
"isRegistrationEnabled",
"(",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"xml",
"=",
"simplexml_load_string",
"(",
"$",
"this",
"->",
"get_prefs",
"(",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"element",
"=",
"$",
"xml... | Tells whether registration is activated for provided collection or not.
@return boolean | [
"Tells",
"whether",
"registration",
"is",
"activated",
"for",
"provided",
"collection",
"or",
"not",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/collection.php#L774-L793 |
alchemy-fr/Phraseanet | lib/classes/collection.php | collection.getAutoregisterModel | public function getAutoregisterModel($email)
{
// try to match against the collection whitelist
if($this->isRegistrationEnabled()) {
if (($xml = @simplexml_load_string($this->get_prefs())) !== false) {
foreach ($xml->xpath('/baseprefs/registration/auto_register/email_whitelist/email') as $element) {
if (preg_match($element['pattern'], $email) === 1) {
return (string)$element['user_model'];
}
}
}
}
// no match ? try against the databox whitelist
return $this->get_databox()->getAutoregisterModel($email);
} | php | public function getAutoregisterModel($email)
{
// try to match against the collection whitelist
if($this->isRegistrationEnabled()) {
if (($xml = @simplexml_load_string($this->get_prefs())) !== false) {
foreach ($xml->xpath('/baseprefs/registration/auto_register/email_whitelist/email') as $element) {
if (preg_match($element['pattern'], $email) === 1) {
return (string)$element['user_model'];
}
}
}
}
// no match ? try against the databox whitelist
return $this->get_databox()->getAutoregisterModel($email);
} | [
"public",
"function",
"getAutoregisterModel",
"(",
"$",
"email",
")",
"{",
"// try to match against the collection whitelist",
"if",
"(",
"$",
"this",
"->",
"isRegistrationEnabled",
"(",
")",
")",
"{",
"if",
"(",
"(",
"$",
"xml",
"=",
"@",
"simplexml_load_string",... | matches a email against the auto-register whitelist
@param string $email
@return null|string the user-model to apply if the email matches | [
"matches",
"a",
"email",
"against",
"the",
"auto",
"-",
"register",
"whitelist"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/collection.php#L801-L816 |
alchemy-fr/Phraseanet | lib/classes/collection.php | collection.getTermsOfUse | public function getTermsOfUse()
{
if (false === $xml = simplexml_load_string($this->get_prefs())) {
return null;
}
foreach ($xml->xpath('/baseprefs/cgu') as $sbpcgu) {
return $sbpcgu->saveXML();
}
} | php | public function getTermsOfUse()
{
if (false === $xml = simplexml_load_string($this->get_prefs())) {
return null;
}
foreach ($xml->xpath('/baseprefs/cgu') as $sbpcgu) {
return $sbpcgu->saveXML();
}
} | [
"public",
"function",
"getTermsOfUse",
"(",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"xml",
"=",
"simplexml_load_string",
"(",
"$",
"this",
"->",
"get_prefs",
"(",
")",
")",
")",
"{",
"return",
"null",
";",
"}",
"foreach",
"(",
"$",
"xml",
"->",
"xp... | Gets terms of use.
@return null|string | [
"Gets",
"terms",
"of",
"use",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/collection.php#L823-L832 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Model/Entities/Basket.php | Basket.addElement | public function addElement(BasketElement $element)
{
$this->elements[] = $element;
$element->setBasket($this);
$element->setOrd(count($this->elements));
return $this;
} | php | public function addElement(BasketElement $element)
{
$this->elements[] = $element;
$element->setBasket($this);
$element->setOrd(count($this->elements));
return $this;
} | [
"public",
"function",
"addElement",
"(",
"BasketElement",
"$",
"element",
")",
"{",
"$",
"this",
"->",
"elements",
"[",
"]",
"=",
"$",
"element",
";",
"$",
"element",
"->",
"setBasket",
"(",
"$",
"this",
")",
";",
"$",
"element",
"->",
"setOrd",
"(",
... | Add element
@param BasketElement $element
@return Basket | [
"Add",
"element"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Entities/Basket.php#L322-L329 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Model/Entities/Basket.php | Basket.removeElement | public function removeElement(BasketElement $element)
{
if ($this->elements->removeElement($element)) {
$element->setBasket();
return true;
}
return false;
} | php | public function removeElement(BasketElement $element)
{
if ($this->elements->removeElement($element)) {
$element->setBasket();
return true;
}
return false;
} | [
"public",
"function",
"removeElement",
"(",
"BasketElement",
"$",
"element",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"elements",
"->",
"removeElement",
"(",
"$",
"element",
")",
")",
"{",
"$",
"element",
"->",
"setBasket",
"(",
")",
";",
"return",
"true"... | Remove element
@param BasketElement $element
@return bool | [
"Remove",
"element"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Entities/Basket.php#L337-L346 |
alchemy-fr/Phraseanet | lib/classes/patch/410alpha10a.php | patch_410alpha10a.apply | public function apply(base $databox, Application $app)
{
// create an api application for adobeCC
/** @var ApiApplicationRepository $repo */
$repo = $app['repo.api-applications'];
if(!$repo->findByClientId(\API_OAuth2_Application_AdobeCCPlugin::CLIENT_ID)) {
/** @var ApiApplicationManipulator $manipulator */
$manipulator = $app['manipulator.api-application'];
$application = $manipulator->create(
\API_OAuth2_Application_AdobeCCPlugin::CLIENT_NAME,
ApiApplication::DESKTOP_TYPE,
'',
'http://www.phraseanet.com',
null,
ApiApplication::NATIVE_APP_REDIRECT_URI
);
$application->setGrantPassword(true);
$application->setClientId(\API_OAuth2_Application_AdobeCCPlugin::CLIENT_ID);
$application->setClientSecret(\API_OAuth2_Application_AdobeCCPlugin::CLIENT_SECRET);
$manipulator->update($application);
}
return true;
} | php | public function apply(base $databox, Application $app)
{
// create an api application for adobeCC
/** @var ApiApplicationRepository $repo */
$repo = $app['repo.api-applications'];
if(!$repo->findByClientId(\API_OAuth2_Application_AdobeCCPlugin::CLIENT_ID)) {
/** @var ApiApplicationManipulator $manipulator */
$manipulator = $app['manipulator.api-application'];
$application = $manipulator->create(
\API_OAuth2_Application_AdobeCCPlugin::CLIENT_NAME,
ApiApplication::DESKTOP_TYPE,
'',
'http://www.phraseanet.com',
null,
ApiApplication::NATIVE_APP_REDIRECT_URI
);
$application->setGrantPassword(true);
$application->setClientId(\API_OAuth2_Application_AdobeCCPlugin::CLIENT_ID);
$application->setClientSecret(\API_OAuth2_Application_AdobeCCPlugin::CLIENT_SECRET);
$manipulator->update($application);
}
return true;
} | [
"public",
"function",
"apply",
"(",
"base",
"$",
"databox",
",",
"Application",
"$",
"app",
")",
"{",
"// create an api application for adobeCC",
"/** @var ApiApplicationRepository $repo */",
"$",
"repo",
"=",
"$",
"app",
"[",
"'repo.api-applications'",
"]",
";",
"if"... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/410alpha10a.php#L61-L87 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/SearchEngine/SearchEngineOptions.php | SearchEngineOptions.setLocale | public function setLocale($locale)
{
if ($locale && !preg_match('/[a-z]{2,3}/', $locale)) {
throw new \InvalidArgumentException('Locale must be a valid i18n code');
}
$this->i18n = $locale;
return $this;
} | php | public function setLocale($locale)
{
if ($locale && !preg_match('/[a-z]{2,3}/', $locale)) {
throw new \InvalidArgumentException('Locale must be a valid i18n code');
}
$this->i18n = $locale;
return $this;
} | [
"public",
"function",
"setLocale",
"(",
"$",
"locale",
")",
"{",
"if",
"(",
"$",
"locale",
"&&",
"!",
"preg_match",
"(",
"'/[a-z]{2,3}/'",
",",
"$",
"locale",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Locale must be a valid i18n c... | Defines locale code to use for query
@param string $locale An i18n locale code
@return $this | [
"Defines",
"locale",
"code",
"to",
"use",
"for",
"query"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/SearchEngineOptions.php#L117-L126 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/SearchEngine/SearchEngineOptions.php | SearchEngineOptions.setSearchType | public function setSearchType($search_type)
{
switch ($search_type) {
case self::RECORD_RECORD:
default:
$this->search_type = self::RECORD_RECORD;
break;
case self::RECORD_GROUPING:
case self::RECORD_STORY:
$this->search_type = self::RECORD_GROUPING;
break;
}
return $this;
} | php | public function setSearchType($search_type)
{
switch ($search_type) {
case self::RECORD_RECORD:
default:
$this->search_type = self::RECORD_RECORD;
break;
case self::RECORD_GROUPING:
case self::RECORD_STORY:
$this->search_type = self::RECORD_GROUPING;
break;
}
return $this;
} | [
"public",
"function",
"setSearchType",
"(",
"$",
"search_type",
")",
"{",
"switch",
"(",
"$",
"search_type",
")",
"{",
"case",
"self",
"::",
"RECORD_RECORD",
":",
"default",
":",
"$",
"this",
"->",
"search_type",
"=",
"self",
"::",
"RECORD_RECORD",
";",
"b... | Set document type to search for
@param int $search_type
@return $this | [
"Set",
"document",
"type",
"to",
"search",
"for"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/SearchEngineOptions.php#L236-L250 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/SearchEngine/SearchEngineOptions.php | SearchEngineOptions.fromRequest | public static function fromRequest(Application $app, Request $request)
{
/** @var Authenticator $authenticator */
$authenticator = $app->getAuthenticator();
$isAuthenticated = $authenticator->isAuthenticated();
$options = new static();
$options->collectionReferenceRepository = $app['repo.collection-references'];
$options->disallowBusinessFields();
$options->setLocale($app['locale']);
$options->setSearchType($request->get('search_type'));
$options->setRecordType($request->get('record_type'));
$options->setSort($request->get('sort'), $request->get('ord', SearchEngineOptions::SORT_MODE_DESC));
$options->setStemming((Boolean) $request->get('stemme'));
$min_date = $max_date = null;
if ($request->get('date_min')) {
$min_date = \DateTime::createFromFormat('Y/m/d H:i:s', $request->get('date_min') . ' 00:00:00');
}
if ($request->get('date_max')) {
$max_date = \DateTime::createFromFormat('Y/m/d H:i:s', $request->get('date_max') . ' 23:59:59');
}
$options->setMinDate($min_date);
$options->setMaxDate($max_date);
$status = is_array($request->get('status')) ? $request->get('status') : [];
$options->setStatus($status);
/** @var ACLProvider $aclProvider */
$aclProvider = $app['acl'];
$acl = $isAuthenticated ? $aclProvider->get($authenticator->getUser()) : null;
if ($acl) {
$searchableBaseIds = $acl->getSearchableBasesIds();
if (is_array($request->get('bases'))) {
$selected_bases = array_map(function($bid){return (int)$bid;}, $request->get('bases'));
$searchableBaseIds = array_values(array_intersect($searchableBaseIds, $selected_bases));
if (empty($searchableBaseIds)) {
throw new BadRequestHttpException('No collections match your criteria');
}
}
$options->onBasesIds($searchableBaseIds);
if ($acl->has_right(\ACL::CANMODIFRECORD)) {
/** @var int[] $bf */
$bf = array_filter($searchableBaseIds, function ($baseId) use ($acl) {
return $acl->has_right_on_base($baseId, \ACL::CANMODIFRECORD);
});
$options->allowBusinessFieldsOn($bf);
}
}
else {
$options->onBasesIds([]);
}
/** @var \databox[] $databoxes */
$databoxes = [];
foreach($options->getCollectionsReferencesByDatabox() as $sbid=>$refs) {
$databoxes[] = $app->findDataboxById($sbid);
}
$queryFields = is_array($request->get('fields')) ? $request->get('fields') : [];
if (empty($queryFields)) {
// Select all fields (business included)
foreach ($databoxes as $databox) {
foreach ($databox->get_meta_structure() as $field) {
$queryFields[] = $field->get_name();
}
}
}
$queryFields = array_unique($queryFields);
$queryDateFields = array_unique(explode('|', $request->get('date_field')));
$databoxFields = [];
$databoxDateFields = [];
foreach ($databoxes as $databox) {
$metaStructure = $databox->get_meta_structure();
foreach ($queryFields as $fieldName) {
try {
if( ($databoxField = $metaStructure->get_element_by_name($fieldName, databox_descriptionStructure::STRICT_COMPARE)) ) {
$databoxFields[] = $databoxField;
}
} catch (\Exception $e) {
// no-op
}
}
foreach ($queryDateFields as $fieldName) {
try {
if( ($databoxField = $metaStructure->get_element_by_name($fieldName, databox_descriptionStructure::STRICT_COMPARE)) ) {
$databoxDateFields[] = $databoxField;
}
} catch (\Exception $e) {
// no-op
}
}
}
$options->setFields($databoxFields);
$options->setDateFields($databoxDateFields);
return $options;
} | php | public static function fromRequest(Application $app, Request $request)
{
/** @var Authenticator $authenticator */
$authenticator = $app->getAuthenticator();
$isAuthenticated = $authenticator->isAuthenticated();
$options = new static();
$options->collectionReferenceRepository = $app['repo.collection-references'];
$options->disallowBusinessFields();
$options->setLocale($app['locale']);
$options->setSearchType($request->get('search_type'));
$options->setRecordType($request->get('record_type'));
$options->setSort($request->get('sort'), $request->get('ord', SearchEngineOptions::SORT_MODE_DESC));
$options->setStemming((Boolean) $request->get('stemme'));
$min_date = $max_date = null;
if ($request->get('date_min')) {
$min_date = \DateTime::createFromFormat('Y/m/d H:i:s', $request->get('date_min') . ' 00:00:00');
}
if ($request->get('date_max')) {
$max_date = \DateTime::createFromFormat('Y/m/d H:i:s', $request->get('date_max') . ' 23:59:59');
}
$options->setMinDate($min_date);
$options->setMaxDate($max_date);
$status = is_array($request->get('status')) ? $request->get('status') : [];
$options->setStatus($status);
/** @var ACLProvider $aclProvider */
$aclProvider = $app['acl'];
$acl = $isAuthenticated ? $aclProvider->get($authenticator->getUser()) : null;
if ($acl) {
$searchableBaseIds = $acl->getSearchableBasesIds();
if (is_array($request->get('bases'))) {
$selected_bases = array_map(function($bid){return (int)$bid;}, $request->get('bases'));
$searchableBaseIds = array_values(array_intersect($searchableBaseIds, $selected_bases));
if (empty($searchableBaseIds)) {
throw new BadRequestHttpException('No collections match your criteria');
}
}
$options->onBasesIds($searchableBaseIds);
if ($acl->has_right(\ACL::CANMODIFRECORD)) {
/** @var int[] $bf */
$bf = array_filter($searchableBaseIds, function ($baseId) use ($acl) {
return $acl->has_right_on_base($baseId, \ACL::CANMODIFRECORD);
});
$options->allowBusinessFieldsOn($bf);
}
}
else {
$options->onBasesIds([]);
}
/** @var \databox[] $databoxes */
$databoxes = [];
foreach($options->getCollectionsReferencesByDatabox() as $sbid=>$refs) {
$databoxes[] = $app->findDataboxById($sbid);
}
$queryFields = is_array($request->get('fields')) ? $request->get('fields') : [];
if (empty($queryFields)) {
// Select all fields (business included)
foreach ($databoxes as $databox) {
foreach ($databox->get_meta_structure() as $field) {
$queryFields[] = $field->get_name();
}
}
}
$queryFields = array_unique($queryFields);
$queryDateFields = array_unique(explode('|', $request->get('date_field')));
$databoxFields = [];
$databoxDateFields = [];
foreach ($databoxes as $databox) {
$metaStructure = $databox->get_meta_structure();
foreach ($queryFields as $fieldName) {
try {
if( ($databoxField = $metaStructure->get_element_by_name($fieldName, databox_descriptionStructure::STRICT_COMPARE)) ) {
$databoxFields[] = $databoxField;
}
} catch (\Exception $e) {
// no-op
}
}
foreach ($queryDateFields as $fieldName) {
try {
if( ($databoxField = $metaStructure->get_element_by_name($fieldName, databox_descriptionStructure::STRICT_COMPARE)) ) {
$databoxDateFields[] = $databoxField;
}
} catch (\Exception $e) {
// no-op
}
}
}
$options->setFields($databoxFields);
$options->setDateFields($databoxDateFields);
return $options;
} | [
"public",
"static",
"function",
"fromRequest",
"(",
"Application",
"$",
"app",
",",
"Request",
"$",
"request",
")",
"{",
"/** @var Authenticator $authenticator */",
"$",
"authenticator",
"=",
"$",
"app",
"->",
"getAuthenticator",
"(",
")",
";",
"$",
"isAuthenticat... | Creates options based on a Symfony Request object
@param Application $app
@param Request $request
@return static | [
"Creates",
"options",
"based",
"on",
"a",
"Symfony",
"Request",
"object"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/SearchEngineOptions.php#L440-L546 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Core/Provider/FtpServiceProvider.php | FtpServiceProvider.register | public function register(Application $app)
{
$app['phraseanet.ftp.client'] = $app->protect(
function ($host, $port = 21, $timeout = 90, $ssl = false, $proxy = false, $proxyport = false, $proxyuser = false, $proxypwd = false) {
return new \ftpclient($host, $port, $timeout, $ssl, $proxy, $proxyport, $proxyuser, $proxypwd);
}
);
} | php | public function register(Application $app)
{
$app['phraseanet.ftp.client'] = $app->protect(
function ($host, $port = 21, $timeout = 90, $ssl = false, $proxy = false, $proxyport = false, $proxyuser = false, $proxypwd = false) {
return new \ftpclient($host, $port, $timeout, $ssl, $proxy, $proxyport, $proxyuser, $proxypwd);
}
);
} | [
"public",
"function",
"register",
"(",
"Application",
"$",
"app",
")",
"{",
"$",
"app",
"[",
"'phraseanet.ftp.client'",
"]",
"=",
"$",
"app",
"->",
"protect",
"(",
"function",
"(",
"$",
"host",
",",
"$",
"port",
"=",
"21",
",",
"$",
"timeout",
"=",
"... | {@inheritDoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Core/Provider/FtpServiceProvider.php#L22-L29 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Plugin/Management/AssetsManager.php | AssetsManager.update | public function update(Manifest $manifest)
{
try {
$this->fs->mirror(
$this->pluginsDirectory . DIRECTORY_SEPARATOR . $manifest->getName() . DIRECTORY_SEPARATOR . 'public',
$this->rootPath . DIRECTORY_SEPARATOR . 'www' . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $manifest->getName()
);
} catch (IOException $e) {
throw new RuntimeException(
sprintf('Unable to copy assets for plugin %s', $manifest->getName()), $e->getCode(), $e
);
}
} | php | public function update(Manifest $manifest)
{
try {
$this->fs->mirror(
$this->pluginsDirectory . DIRECTORY_SEPARATOR . $manifest->getName() . DIRECTORY_SEPARATOR . 'public',
$this->rootPath . DIRECTORY_SEPARATOR . 'www' . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $manifest->getName()
);
} catch (IOException $e) {
throw new RuntimeException(
sprintf('Unable to copy assets for plugin %s', $manifest->getName()), $e->getCode(), $e
);
}
} | [
"public",
"function",
"update",
"(",
"Manifest",
"$",
"manifest",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"fs",
"->",
"mirror",
"(",
"$",
"this",
"->",
"pluginsDirectory",
".",
"DIRECTORY_SEPARATOR",
".",
"$",
"manifest",
"->",
"getName",
"(",
")",
".",... | Updates plugins assets so that they are available online.
@param Manifest $manifest
@throws RuntimeException | [
"Updates",
"plugins",
"assets",
"so",
"that",
"they",
"are",
"available",
"online",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Plugin/Management/AssetsManager.php#L42-L54 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Plugin/Management/AssetsManager.php | AssetsManager.remove | public function remove($name)
{
try {
$this->fs->remove($this->rootPath . DIRECTORY_SEPARATOR . 'www' . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $name);
} catch (IOException $e) {
throw new RuntimeException(
sprintf('Unable to remove assets for plugin %s', $name), $e->getCode(), $e
);
}
} | php | public function remove($name)
{
try {
$this->fs->remove($this->rootPath . DIRECTORY_SEPARATOR . 'www' . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $name);
} catch (IOException $e) {
throw new RuntimeException(
sprintf('Unable to remove assets for plugin %s', $name), $e->getCode(), $e
);
}
} | [
"public",
"function",
"remove",
"(",
"$",
"name",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"fs",
"->",
"remove",
"(",
"$",
"this",
"->",
"rootPath",
".",
"DIRECTORY_SEPARATOR",
".",
"'www'",
".",
"DIRECTORY_SEPARATOR",
".",
"'plugins'",
".",
"DIRECTORY_SEP... | Removes assets for the plugin named with the given name
@param string $name
@throws RuntimeException | [
"Removes",
"assets",
"for",
"the",
"plugin",
"named",
"with",
"the",
"given",
"name"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Plugin/Management/AssetsManager.php#L63-L72 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Model/Repositories/BasketRepository.php | BasketRepository.findActiveValidationByUser | public function findActiveValidationByUser(User $user, $sort = null)
{
$dql = 'SELECT b
FROM Phraseanet:Basket b
JOIN b.elements e
JOIN e.validation_datas v
JOIN b.validation s
JOIN s.participants p
WHERE b.user != ?1 AND p.user = ?2
AND (s.expires IS NULL OR s.expires > CURRENT_TIMESTAMP()) ';
if ($sort == 'date') {
$dql .= ' ORDER BY b.created DESC';
} elseif ($sort == 'name') {
$dql .= ' ORDER BY b.name ASC';
}
$query = $this->_em->createQuery($dql);
$query->setParameters([1 => $user->getId(), 2 => $user->getId()]);
return $query->getResult();
} | php | public function findActiveValidationByUser(User $user, $sort = null)
{
$dql = 'SELECT b
FROM Phraseanet:Basket b
JOIN b.elements e
JOIN e.validation_datas v
JOIN b.validation s
JOIN s.participants p
WHERE b.user != ?1 AND p.user = ?2
AND (s.expires IS NULL OR s.expires > CURRENT_TIMESTAMP()) ';
if ($sort == 'date') {
$dql .= ' ORDER BY b.created DESC';
} elseif ($sort == 'name') {
$dql .= ' ORDER BY b.name ASC';
}
$query = $this->_em->createQuery($dql);
$query->setParameters([1 => $user->getId(), 2 => $user->getId()]);
return $query->getResult();
} | [
"public",
"function",
"findActiveValidationByUser",
"(",
"User",
"$",
"user",
",",
"$",
"sort",
"=",
"null",
")",
"{",
"$",
"dql",
"=",
"'SELECT b\n FROM Phraseanet:Basket b\n JOIN b.elements e\n JOIN e.validation_datas v\n JOIN b.validat... | Returns all baskets that are in validation session not expired and
where a specified user is participant (not owner)
@param User $user
@return Basket[] | [
"Returns",
"all",
"baskets",
"that",
"are",
"in",
"validation",
"session",
"not",
"expired",
"and",
"where",
"a",
"specified",
"user",
"is",
"participant",
"(",
"not",
"owner",
")"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Repositories/BasketRepository.php#L121-L142 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Model/Repositories/BasketRepository.php | BasketRepository.findUserBasket | public function findUserBasket($basket_id, User $user, $requireOwner)
{
$dql = 'SELECT b
FROM Phraseanet:Basket b
LEFT JOIN b.elements e
WHERE b.id = :basket_id';
$query = $this->_em->createQuery($dql);
$query->setParameters(['basket_id' => $basket_id]);
$basket = $query->getOneOrNullResult();
if (null === $basket) {
throw new NotFoundHttpException($this->trans('Basket is not found'));
}
/* @var Basket $basket */
if ($basket->getUser()->getId() != $user->getId()) {
$participant = false;
if ($basket->getValidation() && !$requireOwner) {
try {
$basket->getValidation()->getParticipant($user);
$participant = true;
} catch (\Exception $e) {
}
}
if (!$participant) {
throw new AccessDeniedHttpException($this->trans('You have not access to this basket'));
}
}
return $basket;
} | php | public function findUserBasket($basket_id, User $user, $requireOwner)
{
$dql = 'SELECT b
FROM Phraseanet:Basket b
LEFT JOIN b.elements e
WHERE b.id = :basket_id';
$query = $this->_em->createQuery($dql);
$query->setParameters(['basket_id' => $basket_id]);
$basket = $query->getOneOrNullResult();
if (null === $basket) {
throw new NotFoundHttpException($this->trans('Basket is not found'));
}
/* @var Basket $basket */
if ($basket->getUser()->getId() != $user->getId()) {
$participant = false;
if ($basket->getValidation() && !$requireOwner) {
try {
$basket->getValidation()->getParticipant($user);
$participant = true;
} catch (\Exception $e) {
}
}
if (!$participant) {
throw new AccessDeniedHttpException($this->trans('You have not access to this basket'));
}
}
return $basket;
} | [
"public",
"function",
"findUserBasket",
"(",
"$",
"basket_id",
",",
"User",
"$",
"user",
",",
"$",
"requireOwner",
")",
"{",
"$",
"dql",
"=",
"'SELECT b\n FROM Phraseanet:Basket b\n LEFT JOIN b.elements e\n WHERE b.id = :basket_id'",
";",
"$",... | Find a basket specified by his basket_id and his owner
@throws NotFoundHttpException
@throws AccessDeniedHttpException
@param int $basket_id
@param User $user
@return Basket | [
"Find",
"a",
"basket",
"specified",
"by",
"his",
"basket_id",
"and",
"his",
"owner"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Repositories/BasketRepository.php#L153-L187 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Report/ControllerProvider/ProdReportControllerProvider.php | ProdReportControllerProvider.connect | public function connect(Application $app)
{
$controllers = $this->createAuthenticatedCollection($app);
$controllers
->match('/connections/{sbasId}/', 'controller.prod.report:connectionsAction')
->assert('sbasId', '\d+')
->bind('report2_connections')
->method('GET|POST')
;
$controllers
->match('/downloads/{sbasId}/', 'controller.prod.report:downloadsAction')
->assert('sbasId', '\d+')
->bind('report2_downloads')
->method('GET|POST')
;
$controllers
->match('/records/{sbasId}/', 'controller.prod.report:recordsAction')
->assert('sbasId', '\d+')
->bind('report2_records')
->method('GET|POST')
;
return $controllers;
} | php | public function connect(Application $app)
{
$controllers = $this->createAuthenticatedCollection($app);
$controllers
->match('/connections/{sbasId}/', 'controller.prod.report:connectionsAction')
->assert('sbasId', '\d+')
->bind('report2_connections')
->method('GET|POST')
;
$controllers
->match('/downloads/{sbasId}/', 'controller.prod.report:downloadsAction')
->assert('sbasId', '\d+')
->bind('report2_downloads')
->method('GET|POST')
;
$controllers
->match('/records/{sbasId}/', 'controller.prod.report:recordsAction')
->assert('sbasId', '\d+')
->bind('report2_records')
->method('GET|POST')
;
return $controllers;
} | [
"public",
"function",
"connect",
"(",
"Application",
"$",
"app",
")",
"{",
"$",
"controllers",
"=",
"$",
"this",
"->",
"createAuthenticatedCollection",
"(",
"$",
"app",
")",
";",
"$",
"controllers",
"->",
"match",
"(",
"'/connections/{sbasId}/'",
",",
"'contro... | {@inheritDoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Report/ControllerProvider/ProdReportControllerProvider.php#L58-L84 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Core/Middleware/SetupMiddlewareProvider.php | SetupMiddlewareProvider.register | public function register(Application $app)
{
Assertion::isInstanceOf($app, \Alchemy\Phrasea\Application::class);
$app['setup.validate-config'] = $app->protect(function (Request $request) use ($app) {
if (0 === strpos($request->getPathInfo(), '/setup')) {
if (!$app['phraseanet.configuration-tester']->isInstalled()) {
if (!$app['phraseanet.configuration-tester']->isBlank()) {
if ('setup_upgrade_instructions' !== $app['request']->attributes->get('_route')) {
return $app->redirectPath('setup_upgrade_instructions');
}
}
} elseif (!$app['phraseanet.configuration-tester']->isBlank()) {
return $app->redirectPath('homepage');
}
} else {
if (false === strpos($request->getPathInfo(), '/include/minify')) {
$app['firewall']->requireSetup();
}
}
});
} | php | public function register(Application $app)
{
Assertion::isInstanceOf($app, \Alchemy\Phrasea\Application::class);
$app['setup.validate-config'] = $app->protect(function (Request $request) use ($app) {
if (0 === strpos($request->getPathInfo(), '/setup')) {
if (!$app['phraseanet.configuration-tester']->isInstalled()) {
if (!$app['phraseanet.configuration-tester']->isBlank()) {
if ('setup_upgrade_instructions' !== $app['request']->attributes->get('_route')) {
return $app->redirectPath('setup_upgrade_instructions');
}
}
} elseif (!$app['phraseanet.configuration-tester']->isBlank()) {
return $app->redirectPath('homepage');
}
} else {
if (false === strpos($request->getPathInfo(), '/include/minify')) {
$app['firewall']->requireSetup();
}
}
});
} | [
"public",
"function",
"register",
"(",
"Application",
"$",
"app",
")",
"{",
"Assertion",
"::",
"isInstanceOf",
"(",
"$",
"app",
",",
"\\",
"Alchemy",
"\\",
"Phrasea",
"\\",
"Application",
"::",
"class",
")",
";",
"$",
"app",
"[",
"'setup.validate-config'",
... | Registers services on the given app.
This method should only be used to configure services and parameters.
It should not get services.
@param Application $app | [
"Registers",
"services",
"on",
"the",
"given",
"app",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Core/Middleware/SetupMiddlewareProvider.php#L19-L40 |
alchemy-fr/Phraseanet | lib/classes/patch/390alpha12a.php | patch_390alpha12a.apply | public function apply(base $appbox, Application $app)
{
foreach ($this->listPlugins($app) as $name => $plugin) {
$app['conf']->set(['plugins', $name, 'enabled'], true);
}
} | php | public function apply(base $appbox, Application $app)
{
foreach ($this->listPlugins($app) as $name => $plugin) {
$app['conf']->set(['plugins', $name, 'enabled'], true);
}
} | [
"public",
"function",
"apply",
"(",
"base",
"$",
"appbox",
",",
"Application",
"$",
"app",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"listPlugins",
"(",
"$",
"app",
")",
"as",
"$",
"name",
"=>",
"$",
"plugin",
")",
"{",
"$",
"app",
"[",
"'conf'"... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/390alpha12a.php#L52-L57 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Form/Constraint/NewEmailValidator.php | NewEmailValidator.validate | public function validate($value, Constraint $constraint)
{
if ($constraint->isAlreadyRegistered($value)) {
$this->context->addViolation($constraint->message);
}
} | php | public function validate($value, Constraint $constraint)
{
if ($constraint->isAlreadyRegistered($value)) {
$this->context->addViolation($constraint->message);
}
} | [
"public",
"function",
"validate",
"(",
"$",
"value",
",",
"Constraint",
"$",
"constraint",
")",
"{",
"if",
"(",
"$",
"constraint",
"->",
"isAlreadyRegistered",
"(",
"$",
"value",
")",
")",
"{",
"$",
"this",
"->",
"context",
"->",
"addViolation",
"(",
"$"... | {@inheritDoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Form/Constraint/NewEmailValidator.php#L22-L27 |
alchemy-fr/Phraseanet | lib/classes/patch/381alpha3a.php | patch_381alpha3a.apply | public function apply(base $appbox, Application $app)
{
$propSql = $propArgs = [];
$n = 0;
foreach ($app['settings']->getUsersSettings() as $prop => $value) {
if ('start_page_query' === $prop) {
continue;
}
$propSql[] = '(prop = :prop_'.$n.' AND value = :value_'.$n.')';
$propArgs[':prop_'.$n] = $prop;
$propArgs[':value_'.$n] = $value;
$n++;
}
$sql = "DELETE FROM usr_settings
WHERE 1 AND (".implode(' OR ', $propSql)." OR value IS NULL OR (value = 1 AND prop LIKE 'notification_%'))";
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute($propArgs);
$stmt->closeCursor();
return true;
} | php | public function apply(base $appbox, Application $app)
{
$propSql = $propArgs = [];
$n = 0;
foreach ($app['settings']->getUsersSettings() as $prop => $value) {
if ('start_page_query' === $prop) {
continue;
}
$propSql[] = '(prop = :prop_'.$n.' AND value = :value_'.$n.')';
$propArgs[':prop_'.$n] = $prop;
$propArgs[':value_'.$n] = $value;
$n++;
}
$sql = "DELETE FROM usr_settings
WHERE 1 AND (".implode(' OR ', $propSql)." OR value IS NULL OR (value = 1 AND prop LIKE 'notification_%'))";
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute($propArgs);
$stmt->closeCursor();
return true;
} | [
"public",
"function",
"apply",
"(",
"base",
"$",
"appbox",
",",
"Application",
"$",
"app",
")",
"{",
"$",
"propSql",
"=",
"$",
"propArgs",
"=",
"[",
"]",
";",
"$",
"n",
"=",
"0",
";",
"foreach",
"(",
"$",
"app",
"[",
"'settings'",
"]",
"->",
"get... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/381alpha3a.php#L49-L72 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/User/UserPreferenceController.php | UserPreferenceController.saveTemporaryPref | public function saveTemporaryPref(Request $request)
{
if (!$request->isXmlHttpRequest()) {
$this->app->abort(400);
}
$prop = $request->request->get('prop');
$value = $request->request->get('value');
$success = false;
$msg = $this->app->trans('Error while saving preference');
if (!is_null($prop) && !is_null($value)) {
$this->getSession()->set('phraseanet.' . $prop, $value);
$success = true;
$msg = $this->app->trans('Preference saved !');
}
return new JsonResponse(['success' => $success, 'message' => $msg]);
} | php | public function saveTemporaryPref(Request $request)
{
if (!$request->isXmlHttpRequest()) {
$this->app->abort(400);
}
$prop = $request->request->get('prop');
$value = $request->request->get('value');
$success = false;
$msg = $this->app->trans('Error while saving preference');
if (!is_null($prop) && !is_null($value)) {
$this->getSession()->set('phraseanet.' . $prop, $value);
$success = true;
$msg = $this->app->trans('Preference saved !');
}
return new JsonResponse(['success' => $success, 'message' => $msg]);
} | [
"public",
"function",
"saveTemporaryPref",
"(",
"Request",
"$",
"request",
")",
"{",
"if",
"(",
"!",
"$",
"request",
"->",
"isXmlHttpRequest",
"(",
")",
")",
"{",
"$",
"this",
"->",
"app",
"->",
"abort",
"(",
"400",
")",
";",
"}",
"$",
"prop",
"=",
... | Save temporary user preferences
@param Request $request
@return JsonResponse | [
"Save",
"temporary",
"user",
"preferences"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/User/UserPreferenceController.php#L26-L44 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/User/UserPreferenceController.php | UserPreferenceController.saveUserPref | public function saveUserPref(Request $request)
{
if (!$request->isXmlHttpRequest()) {
$this->app->abort(400);
}
$msg = $this->app->trans('Error while saving preference');
$prop = $request->request->get('prop');
$value = $request->request->get('value');
$success = false;
if (null !== $prop && null !== $value) {
$this->getUserManipulator()->setUserSetting($this->getAuthenticatedUser(), $prop, $value);
$success = true;
$msg = $this->app->trans('Preference saved !');
}
return new JsonResponse(['success' => $success, 'message' => $msg]);
} | php | public function saveUserPref(Request $request)
{
if (!$request->isXmlHttpRequest()) {
$this->app->abort(400);
}
$msg = $this->app->trans('Error while saving preference');
$prop = $request->request->get('prop');
$value = $request->request->get('value');
$success = false;
if (null !== $prop && null !== $value) {
$this->getUserManipulator()->setUserSetting($this->getAuthenticatedUser(), $prop, $value);
$success = true;
$msg = $this->app->trans('Preference saved !');
}
return new JsonResponse(['success' => $success, 'message' => $msg]);
} | [
"public",
"function",
"saveUserPref",
"(",
"Request",
"$",
"request",
")",
"{",
"if",
"(",
"!",
"$",
"request",
"->",
"isXmlHttpRequest",
"(",
")",
")",
"{",
"$",
"this",
"->",
"app",
"->",
"abort",
"(",
"400",
")",
";",
"}",
"$",
"msg",
"=",
"$",
... | Save user preferences
@param Request $request
@return JsonResponse | [
"Save",
"user",
"preferences"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/User/UserPreferenceController.php#L52-L70 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Record/RecordReferenceCollection.php | RecordReferenceCollection.fromListExtractor | public static function fromListExtractor($list, callable $extractor, callable $creator = null)
{
Assertion::isTraversable($list);
$references = [];
if (null === $creator) {
$creator = function ($data) {
return $data;
};
}
foreach ($list as $index => $item) {
$data = $extractor($item);
if (null === $data) {
continue;
}
$reference = $creator($data);
if ($reference instanceof RecordReferenceInterface) {
$references[$index] = $reference;
}
}
return new self($references);
} | php | public static function fromListExtractor($list, callable $extractor, callable $creator = null)
{
Assertion::isTraversable($list);
$references = [];
if (null === $creator) {
$creator = function ($data) {
return $data;
};
}
foreach ($list as $index => $item) {
$data = $extractor($item);
if (null === $data) {
continue;
}
$reference = $creator($data);
if ($reference instanceof RecordReferenceInterface) {
$references[$index] = $reference;
}
}
return new self($references);
} | [
"public",
"static",
"function",
"fromListExtractor",
"(",
"$",
"list",
",",
"callable",
"$",
"extractor",
",",
"callable",
"$",
"creator",
"=",
"null",
")",
"{",
"Assertion",
"::",
"isTraversable",
"(",
"$",
"list",
")",
";",
"$",
"references",
"=",
"[",
... | Append all RecordReferences extracted via call to extractor on each element
@param array|\Traversable $list List of elements to process
@param callable $extractor Extracts data from each element or return null if unavailable
@param callable $creator Creates Reference from extracted data. no-op when null
@return RecordReferenceCollection | [
"Append",
"all",
"RecordReferences",
"extracted",
"via",
"call",
"to",
"extractor",
"on",
"each",
"element"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Record/RecordReferenceCollection.php#L48-L75 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Model/Entities/Feed.php | Feed.isOwner | public function isOwner(User $user)
{
$owner = $this->getOwner();
if ($owner !== null && $user->getId() === $owner->getUser()->getId()) {
return true;
}
return false;
} | php | public function isOwner(User $user)
{
$owner = $this->getOwner();
if ($owner !== null && $user->getId() === $owner->getUser()->getId()) {
return true;
}
return false;
} | [
"public",
"function",
"isOwner",
"(",
"User",
"$",
"user",
")",
"{",
"$",
"owner",
"=",
"$",
"this",
"->",
"getOwner",
"(",
")",
";",
"if",
"(",
"$",
"owner",
"!==",
"null",
"&&",
"$",
"user",
"->",
"getId",
"(",
")",
"===",
"$",
"owner",
"->",
... | Returns a boolean indicating whether the given user is the owner of the feed.
@param User $user
@return boolean | [
"Returns",
"a",
"boolean",
"indicating",
"whether",
"the",
"given",
"user",
"is",
"the",
"owner",
"of",
"the",
"feed",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Entities/Feed.php#L285-L293 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Model/Entities/Feed.php | Feed.getCollection | public function getCollection(Application $app)
{
if ($this->getBaseId() !== null) {
return \collection::getByBaseId($app, $this->getBaseId());
}
} | php | public function getCollection(Application $app)
{
if ($this->getBaseId() !== null) {
return \collection::getByBaseId($app, $this->getBaseId());
}
} | [
"public",
"function",
"getCollection",
"(",
"Application",
"$",
"app",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"getBaseId",
"(",
")",
"!==",
"null",
")",
"{",
"return",
"\\",
"collection",
"::",
"getByBaseId",
"(",
"$",
"app",
",",
"$",
"this",
"->",
... | Returns the collection to which the feed belongs.
@param Application $app
@return \collection | [
"Returns",
"the",
"collection",
"to",
"which",
"the",
"feed",
"belongs",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Entities/Feed.php#L302-L307 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Model/Entities/Feed.php | Feed.setCollection | public function setCollection(\collection $collection = null)
{
if ($collection === null) {
$this->baseId = null;
return;
}
$this->baseId = $collection->get_base_id();
} | php | public function setCollection(\collection $collection = null)
{
if ($collection === null) {
$this->baseId = null;
return;
}
$this->baseId = $collection->get_base_id();
} | [
"public",
"function",
"setCollection",
"(",
"\\",
"collection",
"$",
"collection",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"collection",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"baseId",
"=",
"null",
";",
"return",
";",
"}",
"$",
"this",
"->",
"ba... | Sets the collection.
@param \collection $collection
@return void | [
"Sets",
"the",
"collection",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Entities/Feed.php#L316-L324 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.