repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/SearchEngine/Elastic/Structure/Field.php | Field.mergeWith | public function mergeWith(Field $other)
{
if (($name = $other->getName()) !== $this->name) {
throw new MergeException(sprintf("Fields have different names (%s vs %s)", $this->name, $name));
}
// Since mapping is merged between databoxes, two fields may
// have conflicting names. Indexing is the same for a given
// type so we reject only those with different types.
if (($type = $other->getType()) !== $this->type) {
throw new MergeException(sprintf("Field %s can't be merged, incompatible types (%s vs %s)", $name, $type, $this->type));
}
if ($other->isPrivate() !== $this->is_private) {
throw new MergeException(sprintf("Field %s can't be merged, could not mix private and public fields with same name", $name));
}
if ($other->isSearchable() !== $this->is_searchable) {
throw new MergeException(sprintf("Field %s can't be merged, incompatible searchablility", $name));
}
if ($other->getFacetValuesLimit() !== $this->facet) {
throw new MergeException(sprintf("Field %s can't be merged, incompatible facet eligibility", $name));
}
$thesaurus_roots = null;
if ($this->thesaurus_roots !== null || $other->thesaurus_roots !== null) {
$thesaurus_roots = array_merge(
(array) $this->thesaurus_roots,
(array) $other->thesaurus_roots
);
}
$used_by_collections = array_values(
array_unique(
array_merge(
$this->used_by_collections,
$other->used_by_collections
),
SORT_REGULAR
)
);
return $this->withOptions([
'thesaurus_roots' => $thesaurus_roots,
'used_by_collections' => $used_by_collections
]);
} | php | public function mergeWith(Field $other)
{
if (($name = $other->getName()) !== $this->name) {
throw new MergeException(sprintf("Fields have different names (%s vs %s)", $this->name, $name));
}
// Since mapping is merged between databoxes, two fields may
// have conflicting names. Indexing is the same for a given
// type so we reject only those with different types.
if (($type = $other->getType()) !== $this->type) {
throw new MergeException(sprintf("Field %s can't be merged, incompatible types (%s vs %s)", $name, $type, $this->type));
}
if ($other->isPrivate() !== $this->is_private) {
throw new MergeException(sprintf("Field %s can't be merged, could not mix private and public fields with same name", $name));
}
if ($other->isSearchable() !== $this->is_searchable) {
throw new MergeException(sprintf("Field %s can't be merged, incompatible searchablility", $name));
}
if ($other->getFacetValuesLimit() !== $this->facet) {
throw new MergeException(sprintf("Field %s can't be merged, incompatible facet eligibility", $name));
}
$thesaurus_roots = null;
if ($this->thesaurus_roots !== null || $other->thesaurus_roots !== null) {
$thesaurus_roots = array_merge(
(array) $this->thesaurus_roots,
(array) $other->thesaurus_roots
);
}
$used_by_collections = array_values(
array_unique(
array_merge(
$this->used_by_collections,
$other->used_by_collections
),
SORT_REGULAR
)
);
return $this->withOptions([
'thesaurus_roots' => $thesaurus_roots,
'used_by_collections' => $used_by_collections
]);
} | [
"public",
"function",
"mergeWith",
"(",
"Field",
"$",
"other",
")",
"{",
"if",
"(",
"(",
"$",
"name",
"=",
"$",
"other",
"->",
"getName",
"(",
")",
")",
"!==",
"$",
"this",
"->",
"name",
")",
"{",
"throw",
"new",
"MergeException",
"(",
"sprintf",
"... | Merge with another field, returning the new instance
@param Field $other
@return Field
@throws MergeException | [
"Merge",
"with",
"another",
"field",
"returning",
"the",
"new",
"instance"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/Elastic/Structure/Field.php#L200-L249 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Api/OAuth2Controller.php | OAuth2Controller.authorizeAction | public function authorizeAction(Request $request)
{
$context = new Context(Context::CONTEXT_OAUTH2_NATIVE);
$this->dispatch(PhraseaEvents::PRE_AUTHENTICATE, new PreAuthenticate($request, $context));
//Check for auth params, send error or redirect if not valid
$params = $this->oAuth2Adapter->getAuthorizationRequestParameters($request);
$appAuthorized = false;
$error = $request->get('error', '');
/** @var ApiApplicationRepository $appRepository */
$appRepository = $this->app['repo.api-applications'];
if (null === $client = $appRepository->findByClientId($params['client_id'])) {
throw new NotFoundHttpException(sprintf('Application with client id %s could not be found', $params['client_id']));
}
$this->oAuth2Adapter->setClient($client);
$actionAccept = $request->get("action_accept");
$actionLogin = $request->get("action_login");
$template = "api/auth/end_user_authorization.html.twig";
$custom_template = sprintf(
"%s/config/templates/web/api/auth/end_user_authorization/%s.html.twig"
, $this->app['root.path']
, $client->getId()
);
if (file_exists($custom_template)) {
$template = sprintf(
'api/auth/end_user_authorization/%s.html.twig'
, $client->getId()
);
}
if (!$this->getAuthenticator()->isAuthenticated()) {
if ($actionLogin !== null) {
try {
/** @var PasswordAuthenticationInterface $authentication */
$authentication = $this->app['auth.native'];
if (null === $usrId = $authentication->getUsrId($request->get("login"), $request->get("password"), $request)) {
$this->getSession()->getFlashBag()
->set('error', $this->app->trans('login::erreur: Erreur d\'authentification'));
return $this->app->redirectPath('oauth2_authorize', array_merge(array('error' => 'login'), $params));
}
} catch (RequireCaptchaException $e) {
return $this->app->redirectPath('oauth2_authorize', array_merge(array('error' => 'captcha'), $params));
} catch (AccountLockedException $e) {
return $this->app->redirectPath('oauth2_authorize', array_merge(array('error' => 'account-locked'), $params));
}
$user = $this->getUserRepository()->find($usrId);
$this->getAuthenticator()->openAccount($user);
$event = new PostAuthenticate($request, new Response(), $user, $context);
$this->dispatch(PhraseaEvents::POST_AUTHENTICATE, $event);
} else {
$r = new Response($this->render($template, array('error' => $error, "auth" => $this->oAuth2Adapter)));
$r->headers->set('Content-Type', 'text/html');
return $r;
}
}
$account = $this->oAuth2Adapter->updateAccount($this->getAuthenticatedUser());
//check if current client is already authorized by current user
$clients = $appRepository->findAuthorizedAppsByUser($this->getAuthenticatedUser());
foreach ($clients as $authClient) {
if ($client->getClientId() == $authClient->getClientId()) {
$appAuthorized = true;
break;
}
}
$params['account_id'] = $account->getId();
if (!$appAuthorized && $actionAccept === null) {
$params = [
"auth" => $this->oAuth2Adapter,
"error" => $error,
];
$r = new Response($this->render($template, $params));
$r->headers->set('Content-Type', 'text/html');
return $r;
} elseif (!$appAuthorized && $actionAccept !== null) {
$appAuthorized = (Boolean) $actionAccept;
if ($appAuthorized) {
$this->getApiAccountManipulator()
->authorizeAccess($account);
} else {
$this->getApiAccountManipulator()
->revokeAccess($account);
}
}
//if native app show template
if ($this->oAuth2Adapter->isNativeApp($params['redirect_uri'])) {
$params = $this->oAuth2Adapter->finishNativeClientAuthorization($appAuthorized, $params);
$r = new Response($this->render("api/auth/native_app_access_token.html.twig", $params));
$r->headers->set('Content-Type', 'text/html');
return $r;
}
$this->oAuth2Adapter->finishClientAuthorization($appAuthorized, $params);
// As OAuth2 library already outputs response content, we need to send an empty
// response to avoid breaking silex controller
return '';
} | php | public function authorizeAction(Request $request)
{
$context = new Context(Context::CONTEXT_OAUTH2_NATIVE);
$this->dispatch(PhraseaEvents::PRE_AUTHENTICATE, new PreAuthenticate($request, $context));
//Check for auth params, send error or redirect if not valid
$params = $this->oAuth2Adapter->getAuthorizationRequestParameters($request);
$appAuthorized = false;
$error = $request->get('error', '');
/** @var ApiApplicationRepository $appRepository */
$appRepository = $this->app['repo.api-applications'];
if (null === $client = $appRepository->findByClientId($params['client_id'])) {
throw new NotFoundHttpException(sprintf('Application with client id %s could not be found', $params['client_id']));
}
$this->oAuth2Adapter->setClient($client);
$actionAccept = $request->get("action_accept");
$actionLogin = $request->get("action_login");
$template = "api/auth/end_user_authorization.html.twig";
$custom_template = sprintf(
"%s/config/templates/web/api/auth/end_user_authorization/%s.html.twig"
, $this->app['root.path']
, $client->getId()
);
if (file_exists($custom_template)) {
$template = sprintf(
'api/auth/end_user_authorization/%s.html.twig'
, $client->getId()
);
}
if (!$this->getAuthenticator()->isAuthenticated()) {
if ($actionLogin !== null) {
try {
/** @var PasswordAuthenticationInterface $authentication */
$authentication = $this->app['auth.native'];
if (null === $usrId = $authentication->getUsrId($request->get("login"), $request->get("password"), $request)) {
$this->getSession()->getFlashBag()
->set('error', $this->app->trans('login::erreur: Erreur d\'authentification'));
return $this->app->redirectPath('oauth2_authorize', array_merge(array('error' => 'login'), $params));
}
} catch (RequireCaptchaException $e) {
return $this->app->redirectPath('oauth2_authorize', array_merge(array('error' => 'captcha'), $params));
} catch (AccountLockedException $e) {
return $this->app->redirectPath('oauth2_authorize', array_merge(array('error' => 'account-locked'), $params));
}
$user = $this->getUserRepository()->find($usrId);
$this->getAuthenticator()->openAccount($user);
$event = new PostAuthenticate($request, new Response(), $user, $context);
$this->dispatch(PhraseaEvents::POST_AUTHENTICATE, $event);
} else {
$r = new Response($this->render($template, array('error' => $error, "auth" => $this->oAuth2Adapter)));
$r->headers->set('Content-Type', 'text/html');
return $r;
}
}
$account = $this->oAuth2Adapter->updateAccount($this->getAuthenticatedUser());
//check if current client is already authorized by current user
$clients = $appRepository->findAuthorizedAppsByUser($this->getAuthenticatedUser());
foreach ($clients as $authClient) {
if ($client->getClientId() == $authClient->getClientId()) {
$appAuthorized = true;
break;
}
}
$params['account_id'] = $account->getId();
if (!$appAuthorized && $actionAccept === null) {
$params = [
"auth" => $this->oAuth2Adapter,
"error" => $error,
];
$r = new Response($this->render($template, $params));
$r->headers->set('Content-Type', 'text/html');
return $r;
} elseif (!$appAuthorized && $actionAccept !== null) {
$appAuthorized = (Boolean) $actionAccept;
if ($appAuthorized) {
$this->getApiAccountManipulator()
->authorizeAccess($account);
} else {
$this->getApiAccountManipulator()
->revokeAccess($account);
}
}
//if native app show template
if ($this->oAuth2Adapter->isNativeApp($params['redirect_uri'])) {
$params = $this->oAuth2Adapter->finishNativeClientAuthorization($appAuthorized, $params);
$r = new Response($this->render("api/auth/native_app_access_token.html.twig", $params));
$r->headers->set('Content-Type', 'text/html');
return $r;
}
$this->oAuth2Adapter->finishClientAuthorization($appAuthorized, $params);
// As OAuth2 library already outputs response content, we need to send an empty
// response to avoid breaking silex controller
return '';
} | [
"public",
"function",
"authorizeAction",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"context",
"=",
"new",
"Context",
"(",
"Context",
"::",
"CONTEXT_OAUTH2_NATIVE",
")",
";",
"$",
"this",
"->",
"dispatch",
"(",
"PhraseaEvents",
"::",
"PRE_AUTHENTICATE",
",... | AUTHORIZE ENDPOINT
Authorization endpoint - used to obtain authorization from the
resource owner via user-agent redirection.
@param Request $request
@return string|Response | [
"AUTHORIZE",
"ENDPOINT"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/OAuth2Controller.php#L59-L175 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Api/OAuth2Controller.php | OAuth2Controller.tokenAction | public function tokenAction(Request $request)
{
/** @var PropertyAccess $config */
$config = $this->app['conf'];
if ( ! $request->isSecure() && $config->get(['main', 'api_require_ssl'], true) == true) {
throw new HttpException(400, 'This route requires the use of the https scheme: ' . $config->get(['main', 'api_require_ssl']), null, ['content-type' => 'application/json']);
}
$this->oAuth2Adapter->grantAccessToken();
ob_flush();
flush();
// As OAuth2 library already outputs response content, we need to send an empty
// response to avoid breaking silex controller
return '';
} | php | public function tokenAction(Request $request)
{
/** @var PropertyAccess $config */
$config = $this->app['conf'];
if ( ! $request->isSecure() && $config->get(['main', 'api_require_ssl'], true) == true) {
throw new HttpException(400, 'This route requires the use of the https scheme: ' . $config->get(['main', 'api_require_ssl']), null, ['content-type' => 'application/json']);
}
$this->oAuth2Adapter->grantAccessToken();
ob_flush();
flush();
// As OAuth2 library already outputs response content, we need to send an empty
// response to avoid breaking silex controller
return '';
} | [
"public",
"function",
"tokenAction",
"(",
"Request",
"$",
"request",
")",
"{",
"/** @var PropertyAccess $config */",
"$",
"config",
"=",
"$",
"this",
"->",
"app",
"[",
"'conf'",
"]",
";",
"if",
"(",
"!",
"$",
"request",
"->",
"isSecure",
"(",
")",
"&&",
... | TOKEN ENDPOINT
Token endpoint - used to exchange an authorization grant for an access token.
@param Request $request
@return string | [
"TOKEN",
"ENDPOINT",
"Token",
"endpoint",
"-",
"used",
"to",
"exchange",
"an",
"authorization",
"grant",
"for",
"an",
"access",
"token",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Api/OAuth2Controller.php#L280-L296 |
alchemy-fr/Phraseanet | lib/classes/patch/390alpha15a.php | patch_390alpha15a.apply | public function apply(base $appbox, Application $app)
{
if (!$this->tableExists($app['orm.em'], 'tokens_backup')) {
return true;
}
$app['orm.em']->getConnection()->executeUpdate('
INSERT INTO Tokens
(
`value`, user_id, `type`, `data`,
created, updated, expiration
)
(
SELECT
tb.`value`, tb.usr_id, tb.`type`, tb.datas,
tb.created_on, tb.created_on, tb.expire_on
FROM tokens_backup tb
INNER JOIN Users u ON (u.id = tb.usr_id)
)');
return true;
} | php | public function apply(base $appbox, Application $app)
{
if (!$this->tableExists($app['orm.em'], 'tokens_backup')) {
return true;
}
$app['orm.em']->getConnection()->executeUpdate('
INSERT INTO Tokens
(
`value`, user_id, `type`, `data`,
created, updated, expiration
)
(
SELECT
tb.`value`, tb.usr_id, tb.`type`, tb.datas,
tb.created_on, tb.created_on, tb.expire_on
FROM tokens_backup tb
INNER JOIN Users u ON (u.id = tb.usr_id)
)');
return true;
} | [
"public",
"function",
"apply",
"(",
"base",
"$",
"appbox",
",",
"Application",
"$",
"app",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"tableExists",
"(",
"$",
"app",
"[",
"'orm.em'",
"]",
",",
"'tokens_backup'",
")",
")",
"{",
"return",
"true",
";"... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/390alpha15a.php#L57-L78 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Command/RescanTechnicalDatas.php | RescanTechnicalDatas.doExecute | protected function doExecute(InputInterface $input, OutputInterface $output)
{
$quantity = $this->computeQuantity();
$duration = $this->getFormattedDuration($quantity);
$dialog = $this->getHelperSet()->get('dialog');
do {
$continue = mb_strtolower($dialog->ask($output, sprintf('Estimated duration is %s, <question>continue ? (y/N)</question>', $duration), 'N'));
} while ( ! in_array($continue, ['y', 'n']));
if (strtolower($continue) !== 'y') {
$output->writeln('Aborting !');
return;
}
$start = microtime(true);
$n = 0;
foreach ($this->container->getDataboxes() as $databox) {
$sql = 'SELECT record_id FROM record WHERE parent_record_id = 0';
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute();
$rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$stmt->closeCursor();
foreach ($rs as $row) {
$record = $databox->get_record($row['record_id']);
$record->insertTechnicalDatas($this->getService('mediavorus'));
unset($record);
$output->write("\r" . $n . " records done");
$n ++;
}
}
$output->writeln("\n");
$stop = microtime(true);
$duration = $stop - $start;
$output->writeln(sprintf("process took %s, (%f rec/s.)", $this->getFormattedDuration($duration), round($quantity / $duration, 3)));
return;
} | php | protected function doExecute(InputInterface $input, OutputInterface $output)
{
$quantity = $this->computeQuantity();
$duration = $this->getFormattedDuration($quantity);
$dialog = $this->getHelperSet()->get('dialog');
do {
$continue = mb_strtolower($dialog->ask($output, sprintf('Estimated duration is %s, <question>continue ? (y/N)</question>', $duration), 'N'));
} while ( ! in_array($continue, ['y', 'n']));
if (strtolower($continue) !== 'y') {
$output->writeln('Aborting !');
return;
}
$start = microtime(true);
$n = 0;
foreach ($this->container->getDataboxes() as $databox) {
$sql = 'SELECT record_id FROM record WHERE parent_record_id = 0';
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute();
$rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$stmt->closeCursor();
foreach ($rs as $row) {
$record = $databox->get_record($row['record_id']);
$record->insertTechnicalDatas($this->getService('mediavorus'));
unset($record);
$output->write("\r" . $n . " records done");
$n ++;
}
}
$output->writeln("\n");
$stop = microtime(true);
$duration = $stop - $start;
$output->writeln(sprintf("process took %s, (%f rec/s.)", $this->getFormattedDuration($duration), round($quantity / $duration, 3)));
return;
} | [
"protected",
"function",
"doExecute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"quantity",
"=",
"$",
"this",
"->",
"computeQuantity",
"(",
")",
";",
"$",
"duration",
"=",
"$",
"this",
"->",
"getFormattedDurat... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/RescanTechnicalDatas.php#L42-L86 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Command/RescanTechnicalDatas.php | RescanTechnicalDatas.computeQuantity | protected function computeQuantity()
{
$n = 0;
foreach ($this->container->getDataboxes() as $databox) {
$n += $databox->get_record_amount();
}
return $n;
} | php | protected function computeQuantity()
{
$n = 0;
foreach ($this->container->getDataboxes() as $databox) {
$n += $databox->get_record_amount();
}
return $n;
} | [
"protected",
"function",
"computeQuantity",
"(",
")",
"{",
"$",
"n",
"=",
"0",
";",
"foreach",
"(",
"$",
"this",
"->",
"container",
"->",
"getDataboxes",
"(",
")",
"as",
"$",
"databox",
")",
"{",
"$",
"n",
"+=",
"$",
"databox",
"->",
"get_record_amount... | Return the total quantity of records to process
@return integer | [
"Return",
"the",
"total",
"quantity",
"of",
"records",
"to",
"process"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/RescanTechnicalDatas.php#L93-L102 |
alchemy-fr/Phraseanet | lib/classes/databox/status.php | databox_status.operation_mask | public static function operation_mask($stat1, $stat2)
{
$length = max(strlen($stat1), strlen($stat2));
$stat1 = str_pad($stat1, 32, '0', STR_PAD_LEFT);
$stat2 = str_pad($stat2, 32, '0', STR_PAD_LEFT);
$stat1_or = bindec(trim(str_replace("x", "0", $stat1)));
$stat1_and = bindec(trim(str_replace("x", "1", $stat1)));
$stat2_or = bindec(trim(str_replace("x", "0", $stat2)));
$stat2_and = bindec(trim(str_replace("x", "1", $stat2)));
$decbin = decbin((((0 | $stat1_or) & $stat1_and) | $stat2_or) & $stat2_and);
return str_pad($decbin, $length, '0', STR_PAD_LEFT);
} | php | public static function operation_mask($stat1, $stat2)
{
$length = max(strlen($stat1), strlen($stat2));
$stat1 = str_pad($stat1, 32, '0', STR_PAD_LEFT);
$stat2 = str_pad($stat2, 32, '0', STR_PAD_LEFT);
$stat1_or = bindec(trim(str_replace("x", "0", $stat1)));
$stat1_and = bindec(trim(str_replace("x", "1", $stat1)));
$stat2_or = bindec(trim(str_replace("x", "0", $stat2)));
$stat2_and = bindec(trim(str_replace("x", "1", $stat2)));
$decbin = decbin((((0 | $stat1_or) & $stat1_and) | $stat2_or) & $stat2_and);
return str_pad($decbin, $length, '0', STR_PAD_LEFT);
} | [
"public",
"static",
"function",
"operation_mask",
"(",
"$",
"stat1",
",",
"$",
"stat2",
")",
"{",
"$",
"length",
"=",
"max",
"(",
"strlen",
"(",
"$",
"stat1",
")",
",",
"strlen",
"(",
"$",
"stat2",
")",
")",
";",
"$",
"stat1",
"=",
"str_pad",
"(",
... | compute ((0 M s1) M s2) where M is the "mask" operator
nb : s1,s2 are binary mask strings as "01x0xx1xx0x", no other format (hex) supported
@param $stat1 a binary mask "010x1xx0.." STRING
@param $stat2 a binary mask "x100x1..." STRING
@return string | [
"compute",
"((",
"0",
"M",
"s1",
")",
"M",
"s2",
")",
"where",
"M",
"is",
"the",
"mask",
"operator",
"nb",
":",
"s1",
"s2",
"are",
"binary",
"mask",
"strings",
"as",
"01x0xx1xx0x",
"no",
"other",
"format",
"(",
"hex",
")",
"supported"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/databox/status.php#L165-L179 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Databox/DbalDataboxRepository.php | DbalDataboxRepository.mount | public function mount($host, $port, $user, $password, $dbname)
{
$query = 'INSERT INTO sbas (ord, host, port, dbname, sqlengine, user, pwd)
SELECT COALESCE(MAX(ord), 0) + 1 AS ord, :host AS host, :port AS port, :dbname AS dbname,
"MYSQL" AS sqlengine, :user AS user, :password AS pwd FROM sbas';
$statement = $this->connection->prepare($query);
$statement->execute([
':host' => $host,
':port' => $port,
':dbname' => $dbname,
':user' => $user,
':password' => $password
]);
$statement->closeCursor();
return $this->find((int) $this->connection->lastInsertId());
} | php | public function mount($host, $port, $user, $password, $dbname)
{
$query = 'INSERT INTO sbas (ord, host, port, dbname, sqlengine, user, pwd)
SELECT COALESCE(MAX(ord), 0) + 1 AS ord, :host AS host, :port AS port, :dbname AS dbname,
"MYSQL" AS sqlengine, :user AS user, :password AS pwd FROM sbas';
$statement = $this->connection->prepare($query);
$statement->execute([
':host' => $host,
':port' => $port,
':dbname' => $dbname,
':user' => $user,
':password' => $password
]);
$statement->closeCursor();
return $this->find((int) $this->connection->lastInsertId());
} | [
"public",
"function",
"mount",
"(",
"$",
"host",
",",
"$",
"port",
",",
"$",
"user",
",",
"$",
"password",
",",
"$",
"dbname",
")",
"{",
"$",
"query",
"=",
"'INSERT INTO sbas (ord, host, port, dbname, sqlengine, user, pwd)\n SELECT COALESCE(MAX(ord), 0) + 1... | @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/DbalDataboxRepository.php#L114-L132 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Databox/DbalDataboxRepository.php | DbalDataboxRepository.create | public function create($host, $port, $user, $password, $dbname)
{
$params = [
':host' => $host,
':port' => $port,
':user' => $user,
':password' => $password,
':dbname' => $dbname
];
$query = 'SELECT sbas_id FROM sbas
WHERE host = :host AND port = :port AND `user` = :user AND pwd = :password AND dbname = :dbname';
$statement = $this->connection->executeQuery($query, $params);
if ($row = $statement->fetch(\PDO::FETCH_ASSOC)) {
return $this->find((int) $row['sbas_id']);
}
$query = 'INSERT INTO sbas (ord, host, port, dbname, sqlengine, user, pwd)
SELECT COALESCE(MAX(ord), 0) + 1 AS ord, :host AS host, :port AS port, :dbname AS dbname,
"MYSQL" AS sqlengine, :user AS user, :password AS pwd FROM sbas';
$stmt = $this->connection->prepare($query);
$stmt->execute($params);
$stmt->closeCursor();
return $this->find((int) $this->connection->lastInsertId());
} | php | public function create($host, $port, $user, $password, $dbname)
{
$params = [
':host' => $host,
':port' => $port,
':user' => $user,
':password' => $password,
':dbname' => $dbname
];
$query = 'SELECT sbas_id FROM sbas
WHERE host = :host AND port = :port AND `user` = :user AND pwd = :password AND dbname = :dbname';
$statement = $this->connection->executeQuery($query, $params);
if ($row = $statement->fetch(\PDO::FETCH_ASSOC)) {
return $this->find((int) $row['sbas_id']);
}
$query = 'INSERT INTO sbas (ord, host, port, dbname, sqlengine, user, pwd)
SELECT COALESCE(MAX(ord), 0) + 1 AS ord, :host AS host, :port AS port, :dbname AS dbname,
"MYSQL" AS sqlengine, :user AS user, :password AS pwd FROM sbas';
$stmt = $this->connection->prepare($query);
$stmt->execute($params);
$stmt->closeCursor();
return $this->find((int) $this->connection->lastInsertId());
} | [
"public",
"function",
"create",
"(",
"$",
"host",
",",
"$",
"port",
",",
"$",
"user",
",",
"$",
"password",
",",
"$",
"dbname",
")",
"{",
"$",
"params",
"=",
"[",
"':host'",
"=>",
"$",
"host",
",",
"':port'",
"=>",
"$",
"port",
",",
"':user'",
"=... | @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/DbalDataboxRepository.php#L143-L172 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Core/Provider/TwigServiceProvider.php | TwigServiceProvider.register | public function register(Application $app)
{
$app['twig'] = $app->share($app->extend('twig', function (\Twig_Environment $twig, $app) {
$twig->setCache($app['cache.path'] . '/twig');
$paths = [];
if (file_exists($app['plugin.path'] . '/twig-paths.php')) {
$paths = require $app['plugin.path'] . '/twig-paths.php';
}
if ($app['browser']->isTablet() || $app['browser']->isMobile()) {
$paths[] = $app['root.path'] . '/config/templates/mobile';
$paths[] = $app['root.path'] . '/templates/mobile';
$paths['phraseanet'] = $app['root.path'] . '/config/templates/mobile';
$paths['phraseanet'] = $app['root.path'] . '/templates/mobile';
}
$paths[] = $app['root.path'] . '/config/templates/web';
$paths[] = $app['root.path'] . '/templates/web';
$paths['phraseanet'] = $app['root.path'] . '/config/templates/web';
$paths['phraseanet'] = $app['root.path'] . '/templates/web';
foreach ($paths as $namespace => $path) {
if (!is_int($namespace)) {
$app['twig.loader.filesystem']->addPath($path, $namespace);
} else {
$app['twig.loader.filesystem']->addPath($path);
}
}
$twig->addGlobal('current_date', new \DateTime());
$this->registerExtensions($twig, $app);
$this->registerFilters($twig, $app);
return $twig;
}));
} | php | public function register(Application $app)
{
$app['twig'] = $app->share($app->extend('twig', function (\Twig_Environment $twig, $app) {
$twig->setCache($app['cache.path'] . '/twig');
$paths = [];
if (file_exists($app['plugin.path'] . '/twig-paths.php')) {
$paths = require $app['plugin.path'] . '/twig-paths.php';
}
if ($app['browser']->isTablet() || $app['browser']->isMobile()) {
$paths[] = $app['root.path'] . '/config/templates/mobile';
$paths[] = $app['root.path'] . '/templates/mobile';
$paths['phraseanet'] = $app['root.path'] . '/config/templates/mobile';
$paths['phraseanet'] = $app['root.path'] . '/templates/mobile';
}
$paths[] = $app['root.path'] . '/config/templates/web';
$paths[] = $app['root.path'] . '/templates/web';
$paths['phraseanet'] = $app['root.path'] . '/config/templates/web';
$paths['phraseanet'] = $app['root.path'] . '/templates/web';
foreach ($paths as $namespace => $path) {
if (!is_int($namespace)) {
$app['twig.loader.filesystem']->addPath($path, $namespace);
} else {
$app['twig.loader.filesystem']->addPath($path);
}
}
$twig->addGlobal('current_date', new \DateTime());
$this->registerExtensions($twig, $app);
$this->registerFilters($twig, $app);
return $twig;
}));
} | [
"public",
"function",
"register",
"(",
"Application",
"$",
"app",
")",
"{",
"$",
"app",
"[",
"'twig'",
"]",
"=",
"$",
"app",
"->",
"share",
"(",
"$",
"app",
"->",
"extend",
"(",
"'twig'",
",",
"function",
"(",
"\\",
"Twig_Environment",
"$",
"twig",
"... | Registers services on the given app.
This method should only be used to configure services and parameters.
It should not get services. | [
"Registers",
"services",
"on",
"the",
"given",
"app",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Core/Provider/TwigServiceProvider.php#L31-L69 |
alchemy-fr/Phraseanet | lib/classes/patch/360alpha2b.php | patch_360alpha2b.apply | public function apply(base $databox, Application $app)
{
Assertion::isInstanceOf($databox, databox::class);
/** @var databox $databox */
/**
* Fail if upgrade has previously failed, no problem
*/
try {
$sql = "ALTER TABLE `metadatas`
ADD `updated` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT '1',
ADD INDEX ( `updated` )";
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = 'UPDATE metadatas SET updated = "0"
WHERE meta_struct_id IN
(
SELECT id
FROM metadatas_structure
WHERE multi = "1"
)';
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
} catch (DBALException $e) {
}
try {
$sql = 'ALTER TABLE `metadatas` DROP INDEX `unique`';
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
} catch (DBALException $e) {
}
$sql = 'SELECT m . *
FROM metadatas_structure s, metadatas m
WHERE m.meta_struct_id = s.id
AND s.multi = "1" AND updated="0"';
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute();
$rowCount = $stmt->rowCount();
$stmt->closeCursor();
$n = 0;
$perPage = 1000;
while ($n < $rowCount) {
$sql = 'SELECT m . *
FROM metadatas_structure s, metadatas m
WHERE m.meta_struct_id = s.id
AND s.multi = "1" LIMIT ' . $n . ', ' . $perPage;
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute();
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$databox->get_connection()->beginTransaction();
$sql = 'INSERT INTO metadatas(id, record_id, meta_struct_id, value)
VALUES (null, :record_id, :meta_struct_id, :value)';
$stmt = $databox->get_connection()->prepare($sql);
$databox_fields = $databox->get_meta_structure();
foreach ($rs as $row) {
$meta_struct_id = $row['meta_struct_id'];
$databox_field = $databox_fields->get_element($meta_struct_id);
$values = \caption_field::get_multi_values($row['value'], $databox_field->get_separator());
foreach ($values as $value) {
$params = [
':record_id' => $row['record_id'],
':meta_struct_id' => $row['meta_struct_id'],
':value' => $value,
];
$stmt->execute($params);
}
}
$stmt->closeCursor();
$sql = 'DELETE FROM metadatas WHERE id = :id';
$stmt = $databox->get_connection()->prepare($sql);
foreach ($rs as $row) {
$params = [':id' => $row['id']];
$stmt->execute($params);
}
$stmt->closeCursor();
$databox->get_connection()->commit();
$n+= $perPage;
}
/**
* Remove the extra column
*/
try {
$sql = "ALTER TABLE `metadatas` DROP `updated`";
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
} catch (\Exception $e) {
}
return true;
} | php | public function apply(base $databox, Application $app)
{
Assertion::isInstanceOf($databox, databox::class);
/** @var databox $databox */
/**
* Fail if upgrade has previously failed, no problem
*/
try {
$sql = "ALTER TABLE `metadatas`
ADD `updated` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT '1',
ADD INDEX ( `updated` )";
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = 'UPDATE metadatas SET updated = "0"
WHERE meta_struct_id IN
(
SELECT id
FROM metadatas_structure
WHERE multi = "1"
)';
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
} catch (DBALException $e) {
}
try {
$sql = 'ALTER TABLE `metadatas` DROP INDEX `unique`';
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
} catch (DBALException $e) {
}
$sql = 'SELECT m . *
FROM metadatas_structure s, metadatas m
WHERE m.meta_struct_id = s.id
AND s.multi = "1" AND updated="0"';
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute();
$rowCount = $stmt->rowCount();
$stmt->closeCursor();
$n = 0;
$perPage = 1000;
while ($n < $rowCount) {
$sql = 'SELECT m . *
FROM metadatas_structure s, metadatas m
WHERE m.meta_struct_id = s.id
AND s.multi = "1" LIMIT ' . $n . ', ' . $perPage;
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute();
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$databox->get_connection()->beginTransaction();
$sql = 'INSERT INTO metadatas(id, record_id, meta_struct_id, value)
VALUES (null, :record_id, :meta_struct_id, :value)';
$stmt = $databox->get_connection()->prepare($sql);
$databox_fields = $databox->get_meta_structure();
foreach ($rs as $row) {
$meta_struct_id = $row['meta_struct_id'];
$databox_field = $databox_fields->get_element($meta_struct_id);
$values = \caption_field::get_multi_values($row['value'], $databox_field->get_separator());
foreach ($values as $value) {
$params = [
':record_id' => $row['record_id'],
':meta_struct_id' => $row['meta_struct_id'],
':value' => $value,
];
$stmt->execute($params);
}
}
$stmt->closeCursor();
$sql = 'DELETE FROM metadatas WHERE id = :id';
$stmt = $databox->get_connection()->prepare($sql);
foreach ($rs as $row) {
$params = [':id' => $row['id']];
$stmt->execute($params);
}
$stmt->closeCursor();
$databox->get_connection()->commit();
$n+= $perPage;
}
/**
* Remove the extra column
*/
try {
$sql = "ALTER TABLE `metadatas` DROP `updated`";
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
} catch (\Exception $e) {
}
return true;
} | [
"public",
"function",
"apply",
"(",
"base",
"$",
"databox",
",",
"Application",
"$",
"app",
")",
"{",
"Assertion",
"::",
"isInstanceOf",
"(",
"$",
"databox",
",",
"databox",
"::",
"class",
")",
";",
"/** @var databox $databox */",
"/**\n * Fail if upgrade ... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/360alpha2b.php#L51-L169 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Command/UpgradeDBDatas.php | UpgradeDBDatas.doExecute | protected function doExecute(InputInterface $input, OutputInterface $output)
{
$this->generateUpgradesFromOption($input);
if (! $this->upgrades) {
throw new \Exception('No upgrade available');
}
$time = 30;
foreach ($this->upgrades as $version) {
$time += $version->getTimeEstimation();
}
$question = sprintf("This process is estimated to %s", $this->getFormattedDuration($time));
$dialog = $this->getHelperSet()->get('dialog');
do {
$continue = strtolower($dialog->ask($output, $question . '<question>Continue ? (Y/n)</question>', 'Y'));
} while ( ! in_array($continue, ['y', 'n']));
if (strtolower($continue) !== 'y') {
$output->writeln('Aborting !');
return;
}
foreach ($this->upgrades as $version) {
$version->execute($input, $output);
}
return;
} | php | protected function doExecute(InputInterface $input, OutputInterface $output)
{
$this->generateUpgradesFromOption($input);
if (! $this->upgrades) {
throw new \Exception('No upgrade available');
}
$time = 30;
foreach ($this->upgrades as $version) {
$time += $version->getTimeEstimation();
}
$question = sprintf("This process is estimated to %s", $this->getFormattedDuration($time));
$dialog = $this->getHelperSet()->get('dialog');
do {
$continue = strtolower($dialog->ask($output, $question . '<question>Continue ? (Y/n)</question>', 'Y'));
} while ( ! in_array($continue, ['y', 'n']));
if (strtolower($continue) !== 'y') {
$output->writeln('Aborting !');
return;
}
foreach ($this->upgrades as $version) {
$version->execute($input, $output);
}
return;
} | [
"protected",
"function",
"doExecute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"this",
"->",
"generateUpgradesFromOption",
"(",
"$",
"input",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"upgrades",
")",
"{... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/UpgradeDBDatas.php#L108-L141 |
alchemy-fr/Phraseanet | lib/classes/eventsmanager/notify/order.php | eventsmanager_notify_order.is_available | public function is_available(User $user)
{
return $this->app->getAclForUser($user)->has_right(\ACL::ORDER_MASTER);
} | php | public function is_available(User $user)
{
return $this->app->getAclForUser($user)->has_right(\ACL::ORDER_MASTER);
} | [
"public",
"function",
"is_available",
"(",
"User",
"$",
"user",
")",
"{",
"return",
"$",
"this",
"->",
"app",
"->",
"getAclForUser",
"(",
"$",
"user",
")",
"->",
"has_right",
"(",
"\\",
"ACL",
"::",
"ORDER_MASTER",
")",
";",
"}"
] | @param integer $usr_id The id of the user to check
@return boolean | [
"@param",
"integer",
"$usr_id",
"The",
"id",
"of",
"the",
"user",
"to",
"check"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/eventsmanager/notify/order.php#L76-L79 |
alchemy-fr/Phraseanet | lib/classes/patch/400alpha3a.php | patch_400alpha3a.apply | public function apply(base $databox, Application $app)
{
/** @var PropertyAccess $registry */
$registry = $app['conf'];
$registry->remove(['registry', 'classic']);
return true;
} | php | public function apply(base $databox, Application $app)
{
/** @var PropertyAccess $registry */
$registry = $app['conf'];
$registry->remove(['registry', 'classic']);
return true;
} | [
"public",
"function",
"apply",
"(",
"base",
"$",
"databox",
",",
"Application",
"$",
"app",
")",
"{",
"/** @var PropertyAccess $registry */",
"$",
"registry",
"=",
"$",
"app",
"[",
"'conf'",
"]",
";",
"$",
"registry",
"->",
"remove",
"(",
"[",
"'registry'",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/400alpha3a.php#L58-L66 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Core/Provider/ConfigurationServiceProvider.php | ConfigurationServiceProvider.boot | public function boot(SilexApplication $app)
{
$app['dispatcher'] = $app->share(
$app->extend('dispatcher', function ($dispatcher, SilexApplication $app) {
$dispatcher->addSubscriber(new ConfigurationLoaderSubscriber($app['configuration.store']));
$dispatcher->addSubscriber(new TrustedProxySubscriber($app['configuration.store']));
return $dispatcher;
})
);
} | php | public function boot(SilexApplication $app)
{
$app['dispatcher'] = $app->share(
$app->extend('dispatcher', function ($dispatcher, SilexApplication $app) {
$dispatcher->addSubscriber(new ConfigurationLoaderSubscriber($app['configuration.store']));
$dispatcher->addSubscriber(new TrustedProxySubscriber($app['configuration.store']));
return $dispatcher;
})
);
} | [
"public",
"function",
"boot",
"(",
"SilexApplication",
"$",
"app",
")",
"{",
"$",
"app",
"[",
"'dispatcher'",
"]",
"=",
"$",
"app",
"->",
"share",
"(",
"$",
"app",
"->",
"extend",
"(",
"'dispatcher'",
",",
"function",
"(",
"$",
"dispatcher",
",",
"Sile... | {@inheritDoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Core/Provider/ConfigurationServiceProvider.php#L85-L95 |
alchemy-fr/Phraseanet | lib/classes/patch/390alpha14a.php | patch_390alpha14a.apply | public function apply(base $appbox, Application $app)
{
$app['conf']->remove(['main', 'api-timers']);
if ($this->tableHasField($app['orm.em'], 'api_logs', 'api_log_ressource')) {
$sql = "ALTER TABLE api_logs CHANGE api_log_ressource api_log_resource varchar(64)";
$app->getApplicationBox()->get_connection()->executeUpdate($sql);
}
return true;
} | php | public function apply(base $appbox, Application $app)
{
$app['conf']->remove(['main', 'api-timers']);
if ($this->tableHasField($app['orm.em'], 'api_logs', 'api_log_ressource')) {
$sql = "ALTER TABLE api_logs CHANGE api_log_ressource api_log_resource varchar(64)";
$app->getApplicationBox()->get_connection()->executeUpdate($sql);
}
return true;
} | [
"public",
"function",
"apply",
"(",
"base",
"$",
"appbox",
",",
"Application",
"$",
"app",
")",
"{",
"$",
"app",
"[",
"'conf'",
"]",
"->",
"remove",
"(",
"[",
"'main'",
",",
"'api-timers'",
"]",
")",
";",
"if",
"(",
"$",
"this",
"->",
"tableHasField"... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/390alpha14a.php#L49-L59 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Authentication/SuggestionFinder.php | SuggestionFinder.find | public function find(Token $token)
{
$infos = $token->getIdentity();
if ($infos->has(Identity::PROPERTY_EMAIL)) {
return $this->repository->findByEmail($infos->get(Identity::PROPERTY_EMAIL));
}
return null;
} | php | public function find(Token $token)
{
$infos = $token->getIdentity();
if ($infos->has(Identity::PROPERTY_EMAIL)) {
return $this->repository->findByEmail($infos->get(Identity::PROPERTY_EMAIL));
}
return null;
} | [
"public",
"function",
"find",
"(",
"Token",
"$",
"token",
")",
"{",
"$",
"infos",
"=",
"$",
"token",
"->",
"getIdentity",
"(",
")",
";",
"if",
"(",
"$",
"infos",
"->",
"has",
"(",
"Identity",
"::",
"PROPERTY_EMAIL",
")",
")",
"{",
"return",
"$",
"t... | Find a matching user given a token
@param Token $token
@return null|User
@throws NotAuthenticatedException In case the token is not authenticated. | [
"Find",
"a",
"matching",
"user",
"given",
"a",
"token"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/SuggestionFinder.php#L38-L47 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/TaskManager/Job/WriteMetadataJob.php | WriteMetadataJob.doJob | protected function doJob(JobData $jobData)
{
$settings = simplexml_load_string($jobData->getTask()->getSettings());
$clearDoc = (bool) (string) $settings->cleardoc;
$MWG = (bool) (string) $settings->mwg;
foreach ($jobData->getApplication()->getDataboxes() as $databox) {
$connection = $databox->get_connection();
$statement = $connection->prepare('SELECT record_id, coll_id, jeton FROM record WHERE (jeton & :token > 0)');
$statement->execute(['token' => PhraseaTokens::WRITE_META]);
$rs = $statement->fetchAll(\PDO::FETCH_ASSOC);
$statement->closeCursor();
foreach ($rs as $row) {
$record_id = $row['record_id'];
$token = $row['jeton'];
$record = $databox->get_record($record_id);
$type = $record->getType();
$subdefs = [];
foreach ($record->get_subdefs() as $name => $subdef) {
$write_document = (($token & PhraseaTokens::WRITE_META_DOC) && $name == 'document');
$write_subdef = (($token & PhraseaTokens::WRITE_META_SUBDEF) && $this->isSubdefMetadataUpdateRequired($databox, $type, $name));
if (($write_document || $write_subdef) && $subdef->is_physically_present()) {
$subdefs[$name] = $subdef->getRealPath();
}
}
$metadata = new Metadata\MetadataBag();
if ($record->getUuid()) {
$metadata->add(
new Metadata\Metadata(
new Tag\XMPExif\ImageUniqueID(),
new Value\Mono($record->getUuid())
)
);
$metadata->add(
new Metadata\Metadata(
new Tag\ExifIFD\ImageUniqueID(),
new Value\Mono($record->getUuid())
)
);
$metadata->add(
new Metadata\Metadata(
new Tag\IPTC\UniqueDocumentID(),
new Value\Mono($record->getUuid())
)
);
}
$caption = $record->get_caption();
foreach($databox->get_meta_structure() as $fieldStructure) {
$tagName = $fieldStructure->get_tag()->getTagname();
$fieldName = $fieldStructure->get_name();
// skip fields with no src
if($tagName == '') {
continue;
}
// check exiftool known tags to skip Phraseanet:tf-*
try {
TagFactory::getFromRDFTagname($tagName);
} catch (TagUnknown $e) {
continue;
}
try {
$field = $caption->get_field($fieldName);
$fieldValues = $field->get_values();
if ($fieldStructure->is_multi()) {
$values = array();
foreach ($fieldValues as $value) {
$values[] = $value->getValue();
}
$value = new Value\Multi($values);
} else {
$fieldValue = array_pop($fieldValues);
$value = $fieldValue->getValue();
$value = new Value\Mono($value);
}
} catch(\Exception $e) {
// the field is not set in the record, erase it
if ($fieldStructure->is_multi()) {
$value = new Value\Multi(array(''));
}
else {
$value = new Value\Mono('');
}
}
$metadata->add(
new Metadata\Metadata($fieldStructure->get_tag(), $value)
);
}
$writer = $this->getMetadataWriter($jobData->getApplication());
$writer->reset();
if($MWG) {
$writer->setModule(ExifWriter::MODULE_MWG, true);
}
foreach ($subdefs as $name => $file) {
$writer->erase($name != 'document' || $clearDoc, true);
try {
$writer->write($file, $metadata);
$this->log('info',sprintf('meta written for sbasid=%1$d - recordid=%2$d (%3$s)', $databox->get_sbas_id(), $record_id, $name));
} catch (PHPExiftoolException $e) {
$this->log('error',sprintf('meta NOT written for sbasid=%1$d - recordid=%2$d (%3$s) because "%s"', $databox->get_sbas_id(), $record_id, $name, $e->getMessage()));
}
}
$statement = $connection->prepare('UPDATE record SET jeton=jeton & ~:token WHERE record_id = :record_id');
$statement->execute([
'record_id' => $record_id,
'token' => PhraseaTokens::WRITE_META,
]);
$statement->closeCursor();
}
}
} | php | protected function doJob(JobData $jobData)
{
$settings = simplexml_load_string($jobData->getTask()->getSettings());
$clearDoc = (bool) (string) $settings->cleardoc;
$MWG = (bool) (string) $settings->mwg;
foreach ($jobData->getApplication()->getDataboxes() as $databox) {
$connection = $databox->get_connection();
$statement = $connection->prepare('SELECT record_id, coll_id, jeton FROM record WHERE (jeton & :token > 0)');
$statement->execute(['token' => PhraseaTokens::WRITE_META]);
$rs = $statement->fetchAll(\PDO::FETCH_ASSOC);
$statement->closeCursor();
foreach ($rs as $row) {
$record_id = $row['record_id'];
$token = $row['jeton'];
$record = $databox->get_record($record_id);
$type = $record->getType();
$subdefs = [];
foreach ($record->get_subdefs() as $name => $subdef) {
$write_document = (($token & PhraseaTokens::WRITE_META_DOC) && $name == 'document');
$write_subdef = (($token & PhraseaTokens::WRITE_META_SUBDEF) && $this->isSubdefMetadataUpdateRequired($databox, $type, $name));
if (($write_document || $write_subdef) && $subdef->is_physically_present()) {
$subdefs[$name] = $subdef->getRealPath();
}
}
$metadata = new Metadata\MetadataBag();
if ($record->getUuid()) {
$metadata->add(
new Metadata\Metadata(
new Tag\XMPExif\ImageUniqueID(),
new Value\Mono($record->getUuid())
)
);
$metadata->add(
new Metadata\Metadata(
new Tag\ExifIFD\ImageUniqueID(),
new Value\Mono($record->getUuid())
)
);
$metadata->add(
new Metadata\Metadata(
new Tag\IPTC\UniqueDocumentID(),
new Value\Mono($record->getUuid())
)
);
}
$caption = $record->get_caption();
foreach($databox->get_meta_structure() as $fieldStructure) {
$tagName = $fieldStructure->get_tag()->getTagname();
$fieldName = $fieldStructure->get_name();
// skip fields with no src
if($tagName == '') {
continue;
}
// check exiftool known tags to skip Phraseanet:tf-*
try {
TagFactory::getFromRDFTagname($tagName);
} catch (TagUnknown $e) {
continue;
}
try {
$field = $caption->get_field($fieldName);
$fieldValues = $field->get_values();
if ($fieldStructure->is_multi()) {
$values = array();
foreach ($fieldValues as $value) {
$values[] = $value->getValue();
}
$value = new Value\Multi($values);
} else {
$fieldValue = array_pop($fieldValues);
$value = $fieldValue->getValue();
$value = new Value\Mono($value);
}
} catch(\Exception $e) {
// the field is not set in the record, erase it
if ($fieldStructure->is_multi()) {
$value = new Value\Multi(array(''));
}
else {
$value = new Value\Mono('');
}
}
$metadata->add(
new Metadata\Metadata($fieldStructure->get_tag(), $value)
);
}
$writer = $this->getMetadataWriter($jobData->getApplication());
$writer->reset();
if($MWG) {
$writer->setModule(ExifWriter::MODULE_MWG, true);
}
foreach ($subdefs as $name => $file) {
$writer->erase($name != 'document' || $clearDoc, true);
try {
$writer->write($file, $metadata);
$this->log('info',sprintf('meta written for sbasid=%1$d - recordid=%2$d (%3$s)', $databox->get_sbas_id(), $record_id, $name));
} catch (PHPExiftoolException $e) {
$this->log('error',sprintf('meta NOT written for sbasid=%1$d - recordid=%2$d (%3$s) because "%s"', $databox->get_sbas_id(), $record_id, $name, $e->getMessage()));
}
}
$statement = $connection->prepare('UPDATE record SET jeton=jeton & ~:token WHERE record_id = :record_id');
$statement->execute([
'record_id' => $record_id,
'token' => PhraseaTokens::WRITE_META,
]);
$statement->closeCursor();
}
}
} | [
"protected",
"function",
"doJob",
"(",
"JobData",
"$",
"jobData",
")",
"{",
"$",
"settings",
"=",
"simplexml_load_string",
"(",
"$",
"jobData",
"->",
"getTask",
"(",
")",
"->",
"getSettings",
"(",
")",
")",
";",
"$",
"clearDoc",
"=",
"(",
"bool",
")",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/TaskManager/Job/WriteMetadataJob.php#L63-L193 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/TaskManager/Job/FtpJob.php | FtpJob.doJob | protected function doJob(JobData $data)
{
$app = $data->getApplication();
$this->removeDeadExports($app);
$exports = $this->retrieveExports($app);
foreach ($exports as $export) {
$this->doExport($app, $data->getTask(), $export);
}
} | php | protected function doJob(JobData $data)
{
$app = $data->getApplication();
$this->removeDeadExports($app);
$exports = $this->retrieveExports($app);
foreach ($exports as $export) {
$this->doExport($app, $data->getTask(), $export);
}
} | [
"protected",
"function",
"doJob",
"(",
"JobData",
"$",
"data",
")",
"{",
"$",
"app",
"=",
"$",
"data",
"->",
"getApplication",
"(",
")",
";",
"$",
"this",
"->",
"removeDeadExports",
"(",
"$",
"app",
")",
";",
"$",
"exports",
"=",
"$",
"this",
"->",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/TaskManager/Job/FtpJob.php#L67-L77 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Command/Setup/H264MappingGenerator.php | H264MappingGenerator.doExecute | protected function doExecute(InputInterface $input, OutputInterface $output)
{
$extractor = new DataboxPathExtractor($this->container->getApplicationBox());
$paths = $extractor->extractPaths();
foreach ($paths as $path) {
$this->container['filesystem']->mkdir($path);
}
$type = strtolower($input->getArgument('type'));
$enabled = $input->getOption('enabled');
$factory = new H264Factory($this->container['monolog'], true, $type, $this->computeMapping($paths));
$mode = $factory->createMode(true);
$currentConf = isset($this->container['phraseanet.configuration']['h264-pseudo-streaming']) ? $this->container['phraseanet.configuration']['h264-pseudo-streaming'] : [];
$currentMapping = (isset($currentConf['mapping']) && is_array($currentConf['mapping'])) ? $currentConf['mapping'] : [];
$conf = [
'enabled' => $enabled,
'type' => $type,
'mapping' => $mode->getMapping(),
];
if ($input->getOption('write')) {
$output->write("Writing configuration ...");
$this->container['phraseanet.configuration']['h264-pseudo-streaming'] = $conf;
$output->writeln(" <info>OK</info>");
$output->writeln("");
$output->write("It is now strongly recommended to use <info>h264-pseudo-streaming:dump-configuration</info> command to upgrade your virtual-host");
} else {
$output->writeln("Configuration will <info>not</info> be written, use <info>--write</info> option to write it");
$output->writeln("");
$output->writeln(Yaml::dump(['h264-pseudo-streaming' => $conf], 4));
}
return 0;
} | php | protected function doExecute(InputInterface $input, OutputInterface $output)
{
$extractor = new DataboxPathExtractor($this->container->getApplicationBox());
$paths = $extractor->extractPaths();
foreach ($paths as $path) {
$this->container['filesystem']->mkdir($path);
}
$type = strtolower($input->getArgument('type'));
$enabled = $input->getOption('enabled');
$factory = new H264Factory($this->container['monolog'], true, $type, $this->computeMapping($paths));
$mode = $factory->createMode(true);
$currentConf = isset($this->container['phraseanet.configuration']['h264-pseudo-streaming']) ? $this->container['phraseanet.configuration']['h264-pseudo-streaming'] : [];
$currentMapping = (isset($currentConf['mapping']) && is_array($currentConf['mapping'])) ? $currentConf['mapping'] : [];
$conf = [
'enabled' => $enabled,
'type' => $type,
'mapping' => $mode->getMapping(),
];
if ($input->getOption('write')) {
$output->write("Writing configuration ...");
$this->container['phraseanet.configuration']['h264-pseudo-streaming'] = $conf;
$output->writeln(" <info>OK</info>");
$output->writeln("");
$output->write("It is now strongly recommended to use <info>h264-pseudo-streaming:dump-configuration</info> command to upgrade your virtual-host");
} else {
$output->writeln("Configuration will <info>not</info> be written, use <info>--write</info> option to write it");
$output->writeln("");
$output->writeln(Yaml::dump(['h264-pseudo-streaming' => $conf], 4));
}
return 0;
} | [
"protected",
"function",
"doExecute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"extractor",
"=",
"new",
"DataboxPathExtractor",
"(",
"$",
"this",
"->",
"container",
"->",
"getApplicationBox",
"(",
")",
")",
";"... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/Setup/H264MappingGenerator.php#L38-L74 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Prod/TOUController.php | TOUController.denyTermsOfUse | public function denyTermsOfUse($sbas_id)
{
try {
$databox = $this->findDataboxById((int) $sbas_id);
$this->getAclForUser()->revoke_access_from_bases(
array_keys($this->getAclForUser()->get_granted_base([], [$databox->get_sbas_id()]))
);
$this->getAclForUser()->revoke_unused_sbas_rights();
$this->getAuthenticator()->closeAccount();
$ret = ['success' => true, 'message' => ''];
} catch (\Exception $exception) {
$ret = ['success' => false, 'message' => $exception->getMessage()];
}
return $this->app->json($ret);
} | php | public function denyTermsOfUse($sbas_id)
{
try {
$databox = $this->findDataboxById((int) $sbas_id);
$this->getAclForUser()->revoke_access_from_bases(
array_keys($this->getAclForUser()->get_granted_base([], [$databox->get_sbas_id()]))
);
$this->getAclForUser()->revoke_unused_sbas_rights();
$this->getAuthenticator()->closeAccount();
$ret = ['success' => true, 'message' => ''];
} catch (\Exception $exception) {
$ret = ['success' => false, 'message' => $exception->getMessage()];
}
return $this->app->json($ret);
} | [
"public",
"function",
"denyTermsOfUse",
"(",
"$",
"sbas_id",
")",
"{",
"try",
"{",
"$",
"databox",
"=",
"$",
"this",
"->",
"findDataboxById",
"(",
"(",
"int",
")",
"$",
"sbas_id",
")",
";",
"$",
"this",
"->",
"getAclForUser",
"(",
")",
"->",
"revoke_ac... | Deny database terms of use
@param integer $sbas_id
@return Response | [
"Deny",
"database",
"terms",
"of",
"use"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Prod/TOUController.php#L25-L43 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Prod/TOUController.php | TOUController.displayTermsOfUse | public function displayTermsOfUse(Request $request)
{
$toDisplay = $request->query->get('to_display', []);
$data = [];
foreach ($this->getApplicationBox()->get_databoxes() as $databox) {
if (count($toDisplay) > 0 && !in_array($databox->get_sbas_id(), $toDisplay)) {
continue;
}
$cgus = $databox->get_cgus();
if (!isset($cgus[$this->app['locale']])) {
continue;
}
$data[$databox->get_label($this->app['locale'])] = $cgus[$this->app['locale']]['value'];
}
return $this->renderResponse('/prod/TOU.html.twig', [
'TOUs' => $data,
'local_title' => $this->app->trans('Terms of use'),
]);
} | php | public function displayTermsOfUse(Request $request)
{
$toDisplay = $request->query->get('to_display', []);
$data = [];
foreach ($this->getApplicationBox()->get_databoxes() as $databox) {
if (count($toDisplay) > 0 && !in_array($databox->get_sbas_id(), $toDisplay)) {
continue;
}
$cgus = $databox->get_cgus();
if (!isset($cgus[$this->app['locale']])) {
continue;
}
$data[$databox->get_label($this->app['locale'])] = $cgus[$this->app['locale']]['value'];
}
return $this->renderResponse('/prod/TOU.html.twig', [
'TOUs' => $data,
'local_title' => $this->app->trans('Terms of use'),
]);
} | [
"public",
"function",
"displayTermsOfUse",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"toDisplay",
"=",
"$",
"request",
"->",
"query",
"->",
"get",
"(",
"'to_display'",
",",
"[",
"]",
")",
";",
"$",
"data",
"=",
"[",
"]",
";",
"foreach",
"(",
"$"... | Display database terms of use
@param Request $request
@return Response | [
"Display",
"database",
"terms",
"of",
"use"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Prod/TOUController.php#L51-L74 |
alchemy-fr/Phraseanet | lib/classes/patch/390alpha21a.php | patch_390alpha21a.apply | public function apply(base $appbox, Application $app)
{
$main = $app['conf']->get(['main']);
if (isset($main['static-file'])) {
unset($main['static-file']);
}
$app['conf']->set(['main'], $main);
return true;
} | php | public function apply(base $appbox, Application $app)
{
$main = $app['conf']->get(['main']);
if (isset($main['static-file'])) {
unset($main['static-file']);
}
$app['conf']->set(['main'], $main);
return true;
} | [
"public",
"function",
"apply",
"(",
"base",
"$",
"appbox",
",",
"Application",
"$",
"app",
")",
"{",
"$",
"main",
"=",
"$",
"app",
"[",
"'conf'",
"]",
"->",
"get",
"(",
"[",
"'main'",
"]",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"main",
"[",
"'... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/390alpha21a.php#L49-L58 |
alchemy-fr/Phraseanet | lib/classes/patch/370alpha5a.php | patch_370alpha5a.apply | public function apply(base $databox, Application $app)
{
$sql = 'SELECT id, src FROM metadatas_structure';
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute();
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$update = [];
foreach ($rs as $row) {
$src = str_replace(
['/rdf:RDF/rdf:Description/PHRASEANET:', '/rdf:RDF/rdf:Description/'], ['Phraseanet:', ''], $row['src']
);
$update[] = ['id' => $row['id'], 'src' => $src];
}
$sql = 'UPDATE metadatas_structure SET src = :src WHERE id = :id';
$stmt = $databox->get_connection()->prepare($sql);
foreach ($update as $row) {
$stmt->execute([':src' => $row['src'], ':id' => $row['id']]);
}
$stmt->closeCursor();
return true;
} | php | public function apply(base $databox, Application $app)
{
$sql = 'SELECT id, src FROM metadatas_structure';
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute();
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$update = [];
foreach ($rs as $row) {
$src = str_replace(
['/rdf:RDF/rdf:Description/PHRASEANET:', '/rdf:RDF/rdf:Description/'], ['Phraseanet:', ''], $row['src']
);
$update[] = ['id' => $row['id'], 'src' => $src];
}
$sql = 'UPDATE metadatas_structure SET src = :src WHERE id = :id';
$stmt = $databox->get_connection()->prepare($sql);
foreach ($update as $row) {
$stmt->execute([':src' => $row['src'], ':id' => $row['id']]);
}
$stmt->closeCursor();
return true;
} | [
"public",
"function",
"apply",
"(",
"base",
"$",
"databox",
",",
"Application",
"$",
"app",
")",
"{",
"$",
"sql",
"=",
"'SELECT id, src FROM metadatas_structure'",
";",
"$",
"stmt",
"=",
"$",
"databox",
"->",
"get_connection",
"(",
")",
"->",
"prepare",
"(",... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/370alpha5a.php#L49-L76 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Core/Event/Subscriber/SessionManagerSubscriber.php | SessionManagerSubscriber.checkSessionActivity | public function checkSessionActivity(GetResponseEvent $event)
{
$request = $event->getRequest();
if ($request->request->has('oauth_token')
|| $request->query->has('oauth_token')
|| $request->query->has('LOG')
|| null === $moduleId = $this->getModuleId($request->getPathInfo())
) {
return;
}
if ($this->isAdminJsPolledRoute($moduleId, $request)) {
return;
}
if ($moduleId === self::$modulesIds['prod'] && $this->isFlashUploadRequest($request)) {
return;
}
// if we are already disconnected (ex. from another window), quit immediately
if (!($this->app->getAuthenticator()->isAuthenticated())) {
$this->setDisconnectResponse($event);
return;
}
/** @var Session $session */
$session = $this->app['repo.sessions']->find($this->app['session']->get('session_id'));
$idle = 0;
if (isset($this->app['phraseanet.configuration']['session']['idle'])) {
$idle = (int)$this->app['phraseanet.configuration']['session']['idle'];
}
$now = new \DateTime();
if ($idle > 0 && $now->getTimestamp() > $session->getUpdated()->getTimestamp() + $idle) {
// we must disconnect due to idle time
$this->app->getAuthenticator()->closeAccount();
$this->setDisconnectResponse($event);
return;
}
$entityManager = $this->app['orm.em'];
$module = $this->addOrUpdateSessionModule($session, $moduleId, $now);
$entityManager->persist($module);
$entityManager->persist($session);
$entityManager->flush();
} | php | public function checkSessionActivity(GetResponseEvent $event)
{
$request = $event->getRequest();
if ($request->request->has('oauth_token')
|| $request->query->has('oauth_token')
|| $request->query->has('LOG')
|| null === $moduleId = $this->getModuleId($request->getPathInfo())
) {
return;
}
if ($this->isAdminJsPolledRoute($moduleId, $request)) {
return;
}
if ($moduleId === self::$modulesIds['prod'] && $this->isFlashUploadRequest($request)) {
return;
}
// if we are already disconnected (ex. from another window), quit immediately
if (!($this->app->getAuthenticator()->isAuthenticated())) {
$this->setDisconnectResponse($event);
return;
}
/** @var Session $session */
$session = $this->app['repo.sessions']->find($this->app['session']->get('session_id'));
$idle = 0;
if (isset($this->app['phraseanet.configuration']['session']['idle'])) {
$idle = (int)$this->app['phraseanet.configuration']['session']['idle'];
}
$now = new \DateTime();
if ($idle > 0 && $now->getTimestamp() > $session->getUpdated()->getTimestamp() + $idle) {
// we must disconnect due to idle time
$this->app->getAuthenticator()->closeAccount();
$this->setDisconnectResponse($event);
return;
}
$entityManager = $this->app['orm.em'];
$module = $this->addOrUpdateSessionModule($session, $moduleId, $now);
$entityManager->persist($module);
$entityManager->persist($session);
$entityManager->flush();
} | [
"public",
"function",
"checkSessionActivity",
"(",
"GetResponseEvent",
"$",
"event",
")",
"{",
"$",
"request",
"=",
"$",
"event",
"->",
"getRequest",
"(",
")",
";",
"if",
"(",
"$",
"request",
"->",
"request",
"->",
"has",
"(",
"'oauth_token'",
")",
"||",
... | log real human activity on application, to keep session alive
@param GetResponseEvent $event | [
"log",
"real",
"human",
"activity",
"on",
"application",
"to",
"keep",
"session",
"alive"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Core/Event/Subscriber/SessionManagerSubscriber.php#L69-L122 |
alchemy-fr/Phraseanet | lib/classes/patch/361alpha1a.php | patch_361alpha1a.apply | public function apply(base $appbox, Application $app)
{
$conn = $appbox->get_connection();
$sql = 'SELECT sbas_id, record_id, id FROM BasketElements';
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
foreach ($result as $row) {
$sbas_id = (int) $row['sbas_id'];
try {
$connbas = $app->findDataboxById($sbas_id)->get_connection();
$connbas->connect();
} catch (\Exception $e) {
$conn->exec('DELETE FROM ValidationDatas WHERE basket_element_id = ' . $row['id']);
$conn->exec('DELETE FROM BasketElements WHERE id = ' . $row['id']);
continue;
}
$sql = 'SELECT record_id FROM record WHERE record_id = :record_id';
$stmt = $connbas->prepare($sql);
$stmt->execute([':record_id' => $row['record_id']]);
$rowCount = $stmt->rowCount();
$stmt->closeCursor();
if ($rowCount == 0) {
$conn->exec('DELETE FROM ValidationDatas WHERE basket_element_id = ' . $row['id']);
$conn->exec('DELETE FROM BasketElements WHERE id = ' . $row['id']);
}
}
$dql = "SELECT b FROM Phraseanet:Basket b WHERE b.description != ''";
$n = 0;
$perPage = 100;
$query = $app['orm.em']->createQuery($dql)
->setFirstResult($n)
->setMaxResults($perPage);
$paginator = new Paginator($query, true);
$count = count($paginator);
while ($n < $count) {
$query = $app['orm.em']->createQuery($dql)
->setFirstResult($n)
->setMaxResults($perPage);
$paginator = new Paginator($query, true);
foreach ($paginator as $basket) {
$htmlDesc = $basket->getDescription();
$description = trim(strip_tags(str_replace("<br />", "\n", $htmlDesc)));
if ($htmlDesc == $description) {
continue;
}
$basket->setDescription($description);
}
$n += $perPage;
$app['orm.em']->flush();
}
$app['orm.em']->flush();
return true;
} | php | public function apply(base $appbox, Application $app)
{
$conn = $appbox->get_connection();
$sql = 'SELECT sbas_id, record_id, id FROM BasketElements';
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
foreach ($result as $row) {
$sbas_id = (int) $row['sbas_id'];
try {
$connbas = $app->findDataboxById($sbas_id)->get_connection();
$connbas->connect();
} catch (\Exception $e) {
$conn->exec('DELETE FROM ValidationDatas WHERE basket_element_id = ' . $row['id']);
$conn->exec('DELETE FROM BasketElements WHERE id = ' . $row['id']);
continue;
}
$sql = 'SELECT record_id FROM record WHERE record_id = :record_id';
$stmt = $connbas->prepare($sql);
$stmt->execute([':record_id' => $row['record_id']]);
$rowCount = $stmt->rowCount();
$stmt->closeCursor();
if ($rowCount == 0) {
$conn->exec('DELETE FROM ValidationDatas WHERE basket_element_id = ' . $row['id']);
$conn->exec('DELETE FROM BasketElements WHERE id = ' . $row['id']);
}
}
$dql = "SELECT b FROM Phraseanet:Basket b WHERE b.description != ''";
$n = 0;
$perPage = 100;
$query = $app['orm.em']->createQuery($dql)
->setFirstResult($n)
->setMaxResults($perPage);
$paginator = new Paginator($query, true);
$count = count($paginator);
while ($n < $count) {
$query = $app['orm.em']->createQuery($dql)
->setFirstResult($n)
->setMaxResults($perPage);
$paginator = new Paginator($query, true);
foreach ($paginator as $basket) {
$htmlDesc = $basket->getDescription();
$description = trim(strip_tags(str_replace("<br />", "\n", $htmlDesc)));
if ($htmlDesc == $description) {
continue;
}
$basket->setDescription($description);
}
$n += $perPage;
$app['orm.em']->flush();
}
$app['orm.em']->flush();
return true;
} | [
"public",
"function",
"apply",
"(",
"base",
"$",
"appbox",
",",
"Application",
"$",
"app",
")",
"{",
"$",
"conn",
"=",
"$",
"appbox",
"->",
"get_connection",
"(",
")",
";",
"$",
"sql",
"=",
"'SELECT sbas_id, record_id, id FROM BasketElements'",
";",
"$",
"st... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/361alpha1a.php#L58-L131 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Authentication/AccountCreator.php | AccountCreator.create | public function create(Application $app, $id, $email = null, array $templates = [])
{
if (!$this->enabled) {
throw new RuntimeException('Account creator is disabled');
}
$login = $id;
$n = 1;
if (null !== $email && null !== $app['repo.users']->findByEmail($email)) {
throw new InvalidArgumentException('Provided email already exist in account base.');
}
while (null !== $app['repo.users']->findByLogin($login)) {
$login = $id . '#' . $n;
$n++;
}
$user = $app['manipulator.user']->createUser($login, $this->random->generateString(128), $email);
$base_ids = [];
foreach ($this->appbox->get_databoxes() as $databox) {
foreach ($databox->get_collections() as $collection) {
$base_ids[] = $collection->get_base_id();
}
}
foreach (array_merge($this->templates, $templates) as $template) {
$app->getAclForUser($user)->apply_model($template, $base_ids);
}
return $user;
} | php | public function create(Application $app, $id, $email = null, array $templates = [])
{
if (!$this->enabled) {
throw new RuntimeException('Account creator is disabled');
}
$login = $id;
$n = 1;
if (null !== $email && null !== $app['repo.users']->findByEmail($email)) {
throw new InvalidArgumentException('Provided email already exist in account base.');
}
while (null !== $app['repo.users']->findByLogin($login)) {
$login = $id . '#' . $n;
$n++;
}
$user = $app['manipulator.user']->createUser($login, $this->random->generateString(128), $email);
$base_ids = [];
foreach ($this->appbox->get_databoxes() as $databox) {
foreach ($databox->get_collections() as $collection) {
$base_ids[] = $collection->get_base_id();
}
}
foreach (array_merge($this->templates, $templates) as $template) {
$app->getAclForUser($user)->apply_model($template, $base_ids);
}
return $user;
} | [
"public",
"function",
"create",
"(",
"Application",
"$",
"app",
",",
"$",
"id",
",",
"$",
"email",
"=",
"null",
",",
"array",
"$",
"templates",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"enabled",
")",
"{",
"throw",
"new",
"Runt... | Creates an account
@param Application $app The application
@param string $id The base for user login
@param string $email The email
@param array $templates Some extra templates to apply with the ones of this creator
@return User
@throws RuntimeException In case the AccountCreator is disabled
@throws InvalidArgumentException In case a user with the same email already exists | [
"Creates",
"an",
"account"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/AccountCreator.php#L66-L98 |
alchemy-fr/Phraseanet | lib/classes/patch/360alpha1a.php | patch_360alpha1a.apply | public function apply(base $appbox, Application $app)
{
$tables = ['StoryWZ', 'ValidationDatas', 'ValidationParticipants', 'ValidationSessions', 'BasketElements', 'Baskets'];
foreach ($tables as $table) {
$sql = 'DELETE FROM ' . $table;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
}
$stories = [];
$sql = <<<SQL
SELECT
sbas_id,
rid as record_id,
usr_id
FROM ssel
WHERE temporaryType = "1"
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$rs_s = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$current = [];
foreach ($rs_s as $row_story) {
$serial = $row_story['sbas_id'] . '_' . $row_story['usr_id'] . '_' . $row_story['record_id'];
if (isset($current[$serial])) {
$stories[] = $row_story;
}
$current[$serial] = $serial;
}
$sql = <<<SQL
DELETE FROM ssel
WHERE temporaryType="1"
AND record_id = :record_id
AND usr_id = :usr_id
AND sbas_id = :sbas_id
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
foreach ($stories as $row) {
$params = [
':usr_id' => $row['usr_id'],
':sbas_id' => $row['sbas_id'],
':record_id' => $row['record_id']
];
$stmt->execute($params);
}
$stmt->closeCursor();
$sql = <<<SQL
INSERT INTO StoryWZ (
SELECT
null as id,
usr_id as user_id,
sbas_id,
rid as record_id,
date as created
FROM ssel
INNER JOIN Users ON usr_id = Users.id
WHERE temporaryType = "1"
)
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = <<<SQL
INSERT INTO Baskets (
SELECT
ssel_id as id,
usr_id as user_id,
pushFrom as pusher_id,
name,
descript as description,
1 as is_read,
0 as archived,
date as created,
updater as updated
FROM ssel
INNER JOIN Users a ON ssel.usr_id = a.id
INNER JOIN Users b ON ssel.pushFrom = b.id
WHERE temporaryType = "0"
)
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = <<<SQL
SELECT ssel_id
FROM ssel
WHERE temporaryType = "0"
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$sselcont_ids = [];
foreach ($rs as $row) {
$sql = <<<SQL
SELECT
c.sselcont_id,
c.record_id,
b.sbas_id
FROM sselcont c
INNER JOIN bas b ON (b.base_id = c.base_id)
INNER JOIN ssel s ON (s.ssel_id = c.ssel_id)
INNER JOIN Baskets ba ON (ba.id = s.ssel_id)
WHERE s.temporaryType = "0"
AND c.ssel_id = :ssel_id
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute([':ssel_id' => $row['ssel_id']]);
$rs_be = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$current = [];
foreach ($rs_be as $row_sselcont) {
$serial = $row_sselcont['sbas_id'] . '_' . $row_sselcont['record_id'];
if (isset($current[$serial])) {
$sselcont_ids[] = $row_sselcont['sselcont_id'];
}
$current[$serial] = $serial;
}
}
$sql = <<<SQL
DELETE FROM sselcont
WHERE sselcont_id = :sselcont_id
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
foreach ($sselcont_ids as $sselcont_id) {
$stmt->execute([':sselcont_id' => $sselcont_id]);
}
$stmt->closeCursor();
$sql = <<<SQL
INSERT INTO BasketElements (
SELECT
sselcont_id as id,
c.ssel_id as basket_id,
record_id,
b.sbas_id,
c.ord,
s.date as created,
s.updater as updated
FROM sselcont c
INNER JOIN ssel s ON (s.ssel_id = c.ssel_id)
INNER JOIN Baskets a ON (a.id = s.ssel_id)
INNER JOIN bas b ON (b.base_id = c.base_id)
WHERE s.temporaryType = "0"
)
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = <<<SQL
UPDATE Baskets
SET pusher_id = NULL
WHERE pusher_id = 0
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = <<<SQL
INSERT INTO ValidationSessions (
SELECT null as id,
v.usr_id as initiator_id,
v.ssel_id as basket_id,
v.created_on as created,
v.updated_on as updated,
v.expires_on as expires
FROM validate v
INNER JOIN Baskets b ON (b.id = v.ssel_id)
INNER JOIN Users u ON (u.id = v.usr_id)
)
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = <<<SQL
INSERT INTO ValidationParticipants (
SELECT
v.id AS id,
v.usr_id AS user_id,
1 AS is_aware,
confirmed AS is_confirmed,
1 AS can_agree,
can_see_others,
last_reminder AS reminded,
vs.`id` AS validation_session_id
FROM validate v
INNER JOIN Baskets b ON (b.id = v.ssel_id)
INNER JOIN ValidationSessions vs ON (vs.basket_id = b.id)
INNER JOIN Users u ON (u.id = v.usr_id)
)
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = <<<SQL
SELECT
p.user_id,
s.basket_id,
p.id as participant_id
FROM ValidationParticipants p
INNER JOIN ValidationSessions s ON (s.id = p.validation_session_id)
INNER JOIN Users u ON (u.id = p.user_id)
INNER JOIN Baskets b ON (b.id = s.basket_id)
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$sql = <<<SQL
INSERT INTO ValidationDatas (
SELECT
d.id ,
:participant_id AS participant_id,
d.sselcont_id AS basket_element_id,
d.agreement,
d.note, d.updated_on AS updated
FROM validate v
INNER JOIN validate_datas d ON (v.id = d.validate_id)
INNER JOIN Baskets b ON (v.ssel_id = b.id)
INNER JOIN BasketElements be ON (be.id = d.sselcont_id)
AND v.usr_id = :usr_id AND v.ssel_id = :basket_id
)
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
foreach ($rs as $row) {
$params = [
':participant_id' => $row['participant_id'],
':basket_id' => $row['basket_id'],
':usr_id' => $row['user_id'],
];
$stmt->execute($params);
}
$stmt->closeCursor();
$sql = <<<SQL
UPDATE ValidationDatas
SET agreement = NULL
WHERE agreement = "0"
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = <<<SQL
UPDATE ValidationDatas
SET agreement = "0"
WHERE agreement = "-1"
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
return true;
} | php | public function apply(base $appbox, Application $app)
{
$tables = ['StoryWZ', 'ValidationDatas', 'ValidationParticipants', 'ValidationSessions', 'BasketElements', 'Baskets'];
foreach ($tables as $table) {
$sql = 'DELETE FROM ' . $table;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
}
$stories = [];
$sql = <<<SQL
SELECT
sbas_id,
rid as record_id,
usr_id
FROM ssel
WHERE temporaryType = "1"
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$rs_s = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$current = [];
foreach ($rs_s as $row_story) {
$serial = $row_story['sbas_id'] . '_' . $row_story['usr_id'] . '_' . $row_story['record_id'];
if (isset($current[$serial])) {
$stories[] = $row_story;
}
$current[$serial] = $serial;
}
$sql = <<<SQL
DELETE FROM ssel
WHERE temporaryType="1"
AND record_id = :record_id
AND usr_id = :usr_id
AND sbas_id = :sbas_id
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
foreach ($stories as $row) {
$params = [
':usr_id' => $row['usr_id'],
':sbas_id' => $row['sbas_id'],
':record_id' => $row['record_id']
];
$stmt->execute($params);
}
$stmt->closeCursor();
$sql = <<<SQL
INSERT INTO StoryWZ (
SELECT
null as id,
usr_id as user_id,
sbas_id,
rid as record_id,
date as created
FROM ssel
INNER JOIN Users ON usr_id = Users.id
WHERE temporaryType = "1"
)
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = <<<SQL
INSERT INTO Baskets (
SELECT
ssel_id as id,
usr_id as user_id,
pushFrom as pusher_id,
name,
descript as description,
1 as is_read,
0 as archived,
date as created,
updater as updated
FROM ssel
INNER JOIN Users a ON ssel.usr_id = a.id
INNER JOIN Users b ON ssel.pushFrom = b.id
WHERE temporaryType = "0"
)
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = <<<SQL
SELECT ssel_id
FROM ssel
WHERE temporaryType = "0"
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$sselcont_ids = [];
foreach ($rs as $row) {
$sql = <<<SQL
SELECT
c.sselcont_id,
c.record_id,
b.sbas_id
FROM sselcont c
INNER JOIN bas b ON (b.base_id = c.base_id)
INNER JOIN ssel s ON (s.ssel_id = c.ssel_id)
INNER JOIN Baskets ba ON (ba.id = s.ssel_id)
WHERE s.temporaryType = "0"
AND c.ssel_id = :ssel_id
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute([':ssel_id' => $row['ssel_id']]);
$rs_be = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$current = [];
foreach ($rs_be as $row_sselcont) {
$serial = $row_sselcont['sbas_id'] . '_' . $row_sselcont['record_id'];
if (isset($current[$serial])) {
$sselcont_ids[] = $row_sselcont['sselcont_id'];
}
$current[$serial] = $serial;
}
}
$sql = <<<SQL
DELETE FROM sselcont
WHERE sselcont_id = :sselcont_id
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
foreach ($sselcont_ids as $sselcont_id) {
$stmt->execute([':sselcont_id' => $sselcont_id]);
}
$stmt->closeCursor();
$sql = <<<SQL
INSERT INTO BasketElements (
SELECT
sselcont_id as id,
c.ssel_id as basket_id,
record_id,
b.sbas_id,
c.ord,
s.date as created,
s.updater as updated
FROM sselcont c
INNER JOIN ssel s ON (s.ssel_id = c.ssel_id)
INNER JOIN Baskets a ON (a.id = s.ssel_id)
INNER JOIN bas b ON (b.base_id = c.base_id)
WHERE s.temporaryType = "0"
)
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = <<<SQL
UPDATE Baskets
SET pusher_id = NULL
WHERE pusher_id = 0
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = <<<SQL
INSERT INTO ValidationSessions (
SELECT null as id,
v.usr_id as initiator_id,
v.ssel_id as basket_id,
v.created_on as created,
v.updated_on as updated,
v.expires_on as expires
FROM validate v
INNER JOIN Baskets b ON (b.id = v.ssel_id)
INNER JOIN Users u ON (u.id = v.usr_id)
)
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = <<<SQL
INSERT INTO ValidationParticipants (
SELECT
v.id AS id,
v.usr_id AS user_id,
1 AS is_aware,
confirmed AS is_confirmed,
1 AS can_agree,
can_see_others,
last_reminder AS reminded,
vs.`id` AS validation_session_id
FROM validate v
INNER JOIN Baskets b ON (b.id = v.ssel_id)
INNER JOIN ValidationSessions vs ON (vs.basket_id = b.id)
INNER JOIN Users u ON (u.id = v.usr_id)
)
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = <<<SQL
SELECT
p.user_id,
s.basket_id,
p.id as participant_id
FROM ValidationParticipants p
INNER JOIN ValidationSessions s ON (s.id = p.validation_session_id)
INNER JOIN Users u ON (u.id = p.user_id)
INNER JOIN Baskets b ON (b.id = s.basket_id)
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$sql = <<<SQL
INSERT INTO ValidationDatas (
SELECT
d.id ,
:participant_id AS participant_id,
d.sselcont_id AS basket_element_id,
d.agreement,
d.note, d.updated_on AS updated
FROM validate v
INNER JOIN validate_datas d ON (v.id = d.validate_id)
INNER JOIN Baskets b ON (v.ssel_id = b.id)
INNER JOIN BasketElements be ON (be.id = d.sselcont_id)
AND v.usr_id = :usr_id AND v.ssel_id = :basket_id
)
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
foreach ($rs as $row) {
$params = [
':participant_id' => $row['participant_id'],
':basket_id' => $row['basket_id'],
':usr_id' => $row['user_id'],
];
$stmt->execute($params);
}
$stmt->closeCursor();
$sql = <<<SQL
UPDATE ValidationDatas
SET agreement = NULL
WHERE agreement = "0"
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = <<<SQL
UPDATE ValidationDatas
SET agreement = "0"
WHERE agreement = "-1"
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
return true;
} | [
"public",
"function",
"apply",
"(",
"base",
"$",
"appbox",
",",
"Application",
"$",
"app",
")",
"{",
"$",
"tables",
"=",
"[",
"'StoryWZ'",
",",
"'ValidationDatas'",
",",
"'ValidationParticipants'",
",",
"'ValidationSessions'",
",",
"'BasketElements'",
",",
"'Bas... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/360alpha1a.php#L57-L352 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Border/Attribute/MetaField.php | MetaField.asString | public function asString()
{
return serialize([
'id' => $this->databox_field->get_id(),
'sbas_id' => $this->databox_field->get_databox()->get_sbas_id(),
'value' => $this->value
]);
} | php | public function asString()
{
return serialize([
'id' => $this->databox_field->get_id(),
'sbas_id' => $this->databox_field->get_databox()->get_sbas_id(),
'value' => $this->value
]);
} | [
"public",
"function",
"asString",
"(",
")",
"{",
"return",
"serialize",
"(",
"[",
"'id'",
"=>",
"$",
"this",
"->",
"databox_field",
"->",
"get_id",
"(",
")",
",",
"'sbas_id'",
"=>",
"$",
"this",
"->",
"databox_field",
"->",
"get_databox",
"(",
")",
"->",... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Border/Attribute/MetaField.php#L77-L84 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Border/Attribute/MetaField.php | MetaField.loadFromString | public static function loadFromString(Application $app, $string)
{
$data = @unserialize($string);
if (!is_array($data) || !isset($data['sbas_id']) || !isset($data['id']) || !isset($data['value'])) {
throw new \InvalidArgumentException('Unable to load metadata from string');
}
try {
$field = $app->findDataboxById($data['sbas_id'])->get_meta_structure()->get_element($data['id']);
return new static($field, $data['value']);
} catch (\Exception $exception) {
throw new \InvalidArgumentException('Field does not exist anymore', 0, $exception);
}
} | php | public static function loadFromString(Application $app, $string)
{
$data = @unserialize($string);
if (!is_array($data) || !isset($data['sbas_id']) || !isset($data['id']) || !isset($data['value'])) {
throw new \InvalidArgumentException('Unable to load metadata from string');
}
try {
$field = $app->findDataboxById($data['sbas_id'])->get_meta_structure()->get_element($data['id']);
return new static($field, $data['value']);
} catch (\Exception $exception) {
throw new \InvalidArgumentException('Field does not exist anymore', 0, $exception);
}
} | [
"public",
"static",
"function",
"loadFromString",
"(",
"Application",
"$",
"app",
",",
"$",
"string",
")",
"{",
"$",
"data",
"=",
"@",
"unserialize",
"(",
"$",
"string",
")",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"data",
")",
"||",
"!",
"isset",... | {@inheritdoc}
@return MetaField | [
"{",
"@inheritdoc",
"}"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Border/Attribute/MetaField.php#L91-L106 |
alchemy-fr/Phraseanet | lib/classes/patch/380alpha2b.php | patch_380alpha2b.apply | public function apply(base $appbox, Application $app)
{
$sql = "SHOW TABLE STATUS LIKE 'cache'";
$stmt = $app->getApplicationBox()->get_connection()->prepare($sql);
$stmt->execute();
$row = $stmt->fetch(\PDO::FETCH_ASSOC);
$stmt->closeCursor();
if ($row['Auto_increment']) {
$sql = sprintf('ALTER TABLE Sessions AUTO_INCREMENT = %d', $row['Auto_increment']);
$app->getApplicationBox()->get_connection()->exec($sql);
}
return true;
} | php | public function apply(base $appbox, Application $app)
{
$sql = "SHOW TABLE STATUS LIKE 'cache'";
$stmt = $app->getApplicationBox()->get_connection()->prepare($sql);
$stmt->execute();
$row = $stmt->fetch(\PDO::FETCH_ASSOC);
$stmt->closeCursor();
if ($row['Auto_increment']) {
$sql = sprintf('ALTER TABLE Sessions AUTO_INCREMENT = %d', $row['Auto_increment']);
$app->getApplicationBox()->get_connection()->exec($sql);
}
return true;
} | [
"public",
"function",
"apply",
"(",
"base",
"$",
"appbox",
",",
"Application",
"$",
"app",
")",
"{",
"$",
"sql",
"=",
"\"SHOW TABLE STATUS LIKE 'cache'\"",
";",
"$",
"stmt",
"=",
"$",
"app",
"->",
"getApplicationBox",
"(",
")",
"->",
"get_connection",
"(",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/380alpha2b.php#L49-L63 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/TaskManager/Job/FtpPullJob.php | FtpPullJob.doJob | protected function doJob(JobData $data)
{
$app = $data->getApplication();
$settings = simplexml_load_string($data->getTask()->getSettings());
$proxy = (string) $settings->proxy;
$proxyport = (string) $settings->proxyport;
$localPath = (string) $settings->localpath;
$ftpPath = (string) $settings->ftppath;
$host = (string) $settings->host;
$port = (string) $settings->port;
$user = (string) $settings->user;
$password = (string) $settings->password;
$ssl = (Boolean) (string) $settings->ssl;
$passive = (Boolean) (string) $settings->passive;
foreach ([
'localpath' => $localPath,
'host' => $host,
'port' => $host,
'user' => $user,
'password' => $password,
'ftppath' => $ftpPath,
] as $name => $value) {
if (trim($value) === '') {
// maybe throw an exception to consider the job as failing ?
$this->log('error', sprintf('setting `%s` must be set', $name));
throw new RuntimeException(sprintf('`%s` setting is empty', $name));
}
}
$app['filesystem']->mkdir($localPath, 0750);
if (!is_dir($localPath)) {
$this->log('error', sprintf('`%s` does not exists', $localPath));
throw new RuntimeException(sprintf('`%s` does not exists', $localPath));
}
if (!is_writeable($localPath)) {
$this->log('error', sprintf('`%s` is not writeable', $localPath));
throw new RuntimeException(sprintf('`%s` is not writeable', $localPath));
}
$ftp = $app['phraseanet.ftp.client']($host, $port, 90, $ssl, $proxy, $proxyport);
$ftp->login($user, $password);
$ftp->passive($passive);
$ftp->chdir($ftpPath);
$list_1 = $ftp->list_directory(true);
$done = 0;
$this->log('debug', "attente de 25sec pour avoir les fichiers froids...");
$this->pause(25);
if (!$this->isStarted()) {
$ftp->close();
$this->log('debug', "Stopping");
return;
}
$list_2 = $ftp->list_directory(true);
foreach ($list_1 as $filepath => $timestamp) {
$done++;
if (!isset($list_2[$filepath])) {
$this->log('debug', "le fichier $filepath a disparu...\n");
continue;
}
if ($list_2[$filepath] !== $timestamp) {
$this->log('debug', "le fichier $filepath a ete modifie depuis le dernier passage...");
continue;
}
$finalpath = \p4string::addEndSlash($localPath) . ($filepath[0] == '/' ? mb_substr($filepath, 1) : $filepath);
$this->log('debug', "Rappatriement de $filepath vers $finalpath\n");
if (file_exists($finalpath)) {
$this->log('debug', "Un fichier du meme nom ($finalpath) existe deja, skipping");
continue;
}
$this->log('debug', "Create ".dirname($finalpath)."");
$app['filesystem']->mkdir(dirname($finalpath), 0750);
$this->log('debug', "Get $filepath to $finalpath");
$ftp->get($finalpath, $filepath);
$this->log('debug', "Remove $filepath");
$ftp->delete($filepath);
}
$ftp->close();
} | php | protected function doJob(JobData $data)
{
$app = $data->getApplication();
$settings = simplexml_load_string($data->getTask()->getSettings());
$proxy = (string) $settings->proxy;
$proxyport = (string) $settings->proxyport;
$localPath = (string) $settings->localpath;
$ftpPath = (string) $settings->ftppath;
$host = (string) $settings->host;
$port = (string) $settings->port;
$user = (string) $settings->user;
$password = (string) $settings->password;
$ssl = (Boolean) (string) $settings->ssl;
$passive = (Boolean) (string) $settings->passive;
foreach ([
'localpath' => $localPath,
'host' => $host,
'port' => $host,
'user' => $user,
'password' => $password,
'ftppath' => $ftpPath,
] as $name => $value) {
if (trim($value) === '') {
// maybe throw an exception to consider the job as failing ?
$this->log('error', sprintf('setting `%s` must be set', $name));
throw new RuntimeException(sprintf('`%s` setting is empty', $name));
}
}
$app['filesystem']->mkdir($localPath, 0750);
if (!is_dir($localPath)) {
$this->log('error', sprintf('`%s` does not exists', $localPath));
throw new RuntimeException(sprintf('`%s` does not exists', $localPath));
}
if (!is_writeable($localPath)) {
$this->log('error', sprintf('`%s` is not writeable', $localPath));
throw new RuntimeException(sprintf('`%s` is not writeable', $localPath));
}
$ftp = $app['phraseanet.ftp.client']($host, $port, 90, $ssl, $proxy, $proxyport);
$ftp->login($user, $password);
$ftp->passive($passive);
$ftp->chdir($ftpPath);
$list_1 = $ftp->list_directory(true);
$done = 0;
$this->log('debug', "attente de 25sec pour avoir les fichiers froids...");
$this->pause(25);
if (!$this->isStarted()) {
$ftp->close();
$this->log('debug', "Stopping");
return;
}
$list_2 = $ftp->list_directory(true);
foreach ($list_1 as $filepath => $timestamp) {
$done++;
if (!isset($list_2[$filepath])) {
$this->log('debug', "le fichier $filepath a disparu...\n");
continue;
}
if ($list_2[$filepath] !== $timestamp) {
$this->log('debug', "le fichier $filepath a ete modifie depuis le dernier passage...");
continue;
}
$finalpath = \p4string::addEndSlash($localPath) . ($filepath[0] == '/' ? mb_substr($filepath, 1) : $filepath);
$this->log('debug', "Rappatriement de $filepath vers $finalpath\n");
if (file_exists($finalpath)) {
$this->log('debug', "Un fichier du meme nom ($finalpath) existe deja, skipping");
continue;
}
$this->log('debug', "Create ".dirname($finalpath)."");
$app['filesystem']->mkdir(dirname($finalpath), 0750);
$this->log('debug', "Get $filepath to $finalpath");
$ftp->get($finalpath, $filepath);
$this->log('debug', "Remove $filepath");
$ftp->delete($filepath);
}
$ftp->close();
} | [
"protected",
"function",
"doJob",
"(",
"JobData",
"$",
"data",
")",
"{",
"$",
"app",
"=",
"$",
"data",
"->",
"getApplication",
"(",
")",
";",
"$",
"settings",
"=",
"simplexml_load_string",
"(",
"$",
"data",
"->",
"getTask",
"(",
")",
"->",
"getSettings",... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/TaskManager/Job/FtpPullJob.php#L54-L143 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/SearchEngine/Elastic/Structure/GlobalStructure.php | GlobalStructure.createFromDataboxes | public static function createFromDataboxes(array $databoxes, $what = self::WITH_EVERYTHING)
{
$fields = [];
$flags = [];
foreach ($databoxes as $databox) {
if($what & self::STRUCTURE_WITH_FIELDS) {
foreach ($databox->get_meta_structure() as $fieldStructure) {
$fields[] = Field::createFromLegacyField($fieldStructure, $what);
}
}
if($what & self::STRUCTURE_WITH_FLAGS) {
foreach ($databox->getStatusStructure() as $status) {
$flags[] = Flag::createFromLegacyStatus($status);
}
}
}
return new self($fields, $flags, MetadataHelper::createTags());
} | php | public static function createFromDataboxes(array $databoxes, $what = self::WITH_EVERYTHING)
{
$fields = [];
$flags = [];
foreach ($databoxes as $databox) {
if($what & self::STRUCTURE_WITH_FIELDS) {
foreach ($databox->get_meta_structure() as $fieldStructure) {
$fields[] = Field::createFromLegacyField($fieldStructure, $what);
}
}
if($what & self::STRUCTURE_WITH_FLAGS) {
foreach ($databox->getStatusStructure() as $status) {
$flags[] = Flag::createFromLegacyStatus($status);
}
}
}
return new self($fields, $flags, MetadataHelper::createTags());
} | [
"public",
"static",
"function",
"createFromDataboxes",
"(",
"array",
"$",
"databoxes",
",",
"$",
"what",
"=",
"self",
"::",
"WITH_EVERYTHING",
")",
"{",
"$",
"fields",
"=",
"[",
"]",
";",
"$",
"flags",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"databoxe... | @param \databox[] $databoxes
@param int $what bitmask of what should be included in this structure, in fields, ...
@return GlobalStructure | [
"@param",
"\\",
"databox",
"[]",
"$databoxes",
"@param",
"int",
"$what",
"bitmask",
"of",
"what",
"should",
"be",
"included",
"in",
"this",
"structure",
"in",
"fields",
"..."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/Elastic/Structure/GlobalStructure.php#L53-L73 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/SearchEngine/Elastic/Structure/GlobalStructure.php | GlobalStructure.getCollectionsUsedByPrivateFields | public function getCollectionsUsedByPrivateFields()
{
$map = [];
foreach ($this->private as $name => $field) {
$map[$name] = $field->getDependantCollections();
}
return $map;
} | php | public function getCollectionsUsedByPrivateFields()
{
$map = [];
foreach ($this->private as $name => $field) {
$map[$name] = $field->getDependantCollections();
}
return $map;
} | [
"public",
"function",
"getCollectionsUsedByPrivateFields",
"(",
")",
"{",
"$",
"map",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"private",
"as",
"$",
"name",
"=>",
"$",
"field",
")",
"{",
"$",
"map",
"[",
"$",
"name",
"]",
"=",
"$",
"f... | Returns an array of collections indexed by field name.
[
"FieldName" => [1, 4, 5],
"OtherFieldName" => [4],
] | [
"Returns",
"an",
"array",
"of",
"collections",
"indexed",
"by",
"field",
"name",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/Elastic/Structure/GlobalStructure.php#L273-L282 |
alchemy-fr/Phraseanet | lib/classes/patch/390alpha6a.php | patch_390alpha6a.apply | public function apply(base $appbox, Application $app)
{
$sql = 'DELETE FROM FtpExports';
$stmt = $app->getApplicationBox()->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = 'DELETE FROM FtpExportElements';
$stmt = $app->getApplicationBox()->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$conn = $app->getApplicationBox()->get_connection();
$em = $app['orm.em'];
$em->getEventManager()->removeEventSubscriber(new TimestampableListener());
$sql = 'SELECT `id`, `crash`, `nbretry`, `mail`, `addr`, `ssl`,
`login`, `pwd`, `passif`,
`destfolder`, `sendermail`, `text_mail_sender`,
`text_mail_receiver`, `usr_id`, `date`, `foldertocreate`,
`logfile`
FROM ftp_export';
$stmt = $conn->prepare($sql);
$stmt->execute();
$rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$stmt->closeCursor();
$sql = 'SELECT base_id, record_id, subdef, filename, folder, error, done, businessfields
FROM ftp_export_elements
WHERE ftp_export_id = :export_id';
$stmt = $conn->prepare($sql);
$n = 0;
foreach ($rs as $row) {
if (null === $user = $this->loadUser($app['orm.em'], $row['usr_id'])) {
continue;
}
$export = new FtpExport();
$export
->setAddr($row['addr'])
->setCrash($row['crash'])
->setNbretry($row['nbretry'])
->setMail($row['mail'])
->setSsl($row['ssl'])
->setLogin($row['login'])
->setPwd($row['pwd'])
->setPassif($row['passif'])
->setDestfolder($row['destfolder'])
->setSendermail($row['sendermail'])
->setTextMailReceiver($row['text_mail_sender'])
->setTextMailSender($row['text_mail_receiver'])
->setUser($user)
->setCreated(new \DateTime($row['date']))
->setUpdated(new \DateTime($row['date']))
->setFoldertocreate($row['foldertocreate'])
->setLogfile($row['logfile']);
$em->persist($export);
$stmt->execute(['export_id' => $row['id']]);
$rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
foreach ($rs as $element_row) {
$element = new FtpExportElement();
$element->setBaseId($element_row['base_id'])
->setRecordId($element_row['record_id'])
->setBusinessfields($element_row['businessfields'])
->setCreated(new \DateTime($row['date']))
->setUpdated(new \DateTime($row['date']))
->setDone(!!$element_row['done'])
->setError(!!$element_row['error'])
->setFilename($element_row['filename'])
->setFolder($element_row['folder'])
->setSubdef($element_row['subdef'])
->setExport($export);
$export->addElement($element);
$em->persist($element);
}
$n++;
if ($n % 200 === 0) {
$em->flush();
$em->clear();
}
}
$stmt->closeCursor();
$em->flush();
$em->clear();
$em->getEventManager()->addEventSubscriber(new TimestampableListener());
return true;
} | php | public function apply(base $appbox, Application $app)
{
$sql = 'DELETE FROM FtpExports';
$stmt = $app->getApplicationBox()->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = 'DELETE FROM FtpExportElements';
$stmt = $app->getApplicationBox()->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$conn = $app->getApplicationBox()->get_connection();
$em = $app['orm.em'];
$em->getEventManager()->removeEventSubscriber(new TimestampableListener());
$sql = 'SELECT `id`, `crash`, `nbretry`, `mail`, `addr`, `ssl`,
`login`, `pwd`, `passif`,
`destfolder`, `sendermail`, `text_mail_sender`,
`text_mail_receiver`, `usr_id`, `date`, `foldertocreate`,
`logfile`
FROM ftp_export';
$stmt = $conn->prepare($sql);
$stmt->execute();
$rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$stmt->closeCursor();
$sql = 'SELECT base_id, record_id, subdef, filename, folder, error, done, businessfields
FROM ftp_export_elements
WHERE ftp_export_id = :export_id';
$stmt = $conn->prepare($sql);
$n = 0;
foreach ($rs as $row) {
if (null === $user = $this->loadUser($app['orm.em'], $row['usr_id'])) {
continue;
}
$export = new FtpExport();
$export
->setAddr($row['addr'])
->setCrash($row['crash'])
->setNbretry($row['nbretry'])
->setMail($row['mail'])
->setSsl($row['ssl'])
->setLogin($row['login'])
->setPwd($row['pwd'])
->setPassif($row['passif'])
->setDestfolder($row['destfolder'])
->setSendermail($row['sendermail'])
->setTextMailReceiver($row['text_mail_sender'])
->setTextMailSender($row['text_mail_receiver'])
->setUser($user)
->setCreated(new \DateTime($row['date']))
->setUpdated(new \DateTime($row['date']))
->setFoldertocreate($row['foldertocreate'])
->setLogfile($row['logfile']);
$em->persist($export);
$stmt->execute(['export_id' => $row['id']]);
$rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
foreach ($rs as $element_row) {
$element = new FtpExportElement();
$element->setBaseId($element_row['base_id'])
->setRecordId($element_row['record_id'])
->setBusinessfields($element_row['businessfields'])
->setCreated(new \DateTime($row['date']))
->setUpdated(new \DateTime($row['date']))
->setDone(!!$element_row['done'])
->setError(!!$element_row['error'])
->setFilename($element_row['filename'])
->setFolder($element_row['folder'])
->setSubdef($element_row['subdef'])
->setExport($export);
$export->addElement($element);
$em->persist($element);
}
$n++;
if ($n % 200 === 0) {
$em->flush();
$em->clear();
}
}
$stmt->closeCursor();
$em->flush();
$em->clear();
$em->getEventManager()->addEventSubscriber(new TimestampableListener());
return true;
} | [
"public",
"function",
"apply",
"(",
"base",
"$",
"appbox",
",",
"Application",
"$",
"app",
")",
"{",
"$",
"sql",
"=",
"'DELETE FROM FtpExports'",
";",
"$",
"stmt",
"=",
"$",
"app",
"->",
"getApplicationBox",
"(",
")",
"->",
"get_connection",
"(",
")",
"-... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/390alpha6a.php#L60-L159 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Core/Configuration/Configuration.php | Configuration.offsetSet | public function offsetSet($offset, $value)
{
$conf = $this->getConfig();
$conf[$offset] = $value;
$this->setConfig($conf);
} | php | public function offsetSet($offset, $value)
{
$conf = $this->getConfig();
$conf[$offset] = $value;
$this->setConfig($conf);
} | [
"public",
"function",
"offsetSet",
"(",
"$",
"offset",
",",
"$",
"value",
")",
"{",
"$",
"conf",
"=",
"$",
"this",
"->",
"getConfig",
"(",
")",
";",
"$",
"conf",
"[",
"$",
"offset",
"]",
"=",
"$",
"value",
";",
"$",
"this",
"->",
"setConfig",
"("... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Core/Configuration/Configuration.php#L58-L64 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Core/Configuration/Configuration.php | Configuration.offsetUnset | public function offsetUnset($offset)
{
$conf = $this->getConfig();
unset($conf[$offset]);
$this->setConfig($conf);
} | php | public function offsetUnset($offset)
{
$conf = $this->getConfig();
unset($conf[$offset]);
$this->setConfig($conf);
} | [
"public",
"function",
"offsetUnset",
"(",
"$",
"offset",
")",
"{",
"$",
"conf",
"=",
"$",
"this",
"->",
"getConfig",
"(",
")",
";",
"unset",
"(",
"$",
"conf",
"[",
"$",
"offset",
"]",
")",
";",
"$",
"this",
"->",
"setConfig",
"(",
"$",
"conf",
")... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Core/Configuration/Configuration.php#L79-L85 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Core/Configuration/Configuration.php | Configuration.setDefault | public function setDefault($name)
{
$defaultConfig = $this->loadDefaultConfiguration();
if (!isset($defaultConfig[$name])) {
throw new InvalidArgumentException(sprintf('%s is not a valid config name', $name));
}
$newConfig = $this->doSetDefault($this->getConfig(), $defaultConfig, func_get_args());
return $this->setConfig($newConfig);
} | php | public function setDefault($name)
{
$defaultConfig = $this->loadDefaultConfiguration();
if (!isset($defaultConfig[$name])) {
throw new InvalidArgumentException(sprintf('%s is not a valid config name', $name));
}
$newConfig = $this->doSetDefault($this->getConfig(), $defaultConfig, func_get_args());
return $this->setConfig($newConfig);
} | [
"public",
"function",
"setDefault",
"(",
"$",
"name",
")",
"{",
"$",
"defaultConfig",
"=",
"$",
"this",
"->",
"loadDefaultConfiguration",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"defaultConfig",
"[",
"$",
"name",
"]",
")",
")",
"{",
"throw",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Core/Configuration/Configuration.php#L90-L101 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Core/Configuration/Configuration.php | Configuration.getConfig | public function getConfig()
{
if (null !== $this->cache) {
return $this->cache;
}
if (!is_file($this->compiled) || ($this->isAutoReload() && !$this->isConfigFresh())) {
if (!$this->isSetup()) {
throw new RuntimeException('Configuration is not set up');
}
$this->writeCacheConfig($this->compiler->compile(
$this->parser->parse($this->loadFile($this->config))
));
}
return $this->cache = require $this->compiled;
} | php | public function getConfig()
{
if (null !== $this->cache) {
return $this->cache;
}
if (!is_file($this->compiled) || ($this->isAutoReload() && !$this->isConfigFresh())) {
if (!$this->isSetup()) {
throw new RuntimeException('Configuration is not set up');
}
$this->writeCacheConfig($this->compiler->compile(
$this->parser->parse($this->loadFile($this->config))
));
}
return $this->cache = require $this->compiled;
} | [
"public",
"function",
"getConfig",
"(",
")",
"{",
"if",
"(",
"null",
"!==",
"$",
"this",
"->",
"cache",
")",
"{",
"return",
"$",
"this",
"->",
"cache",
";",
"}",
"if",
"(",
"!",
"is_file",
"(",
"$",
"this",
"->",
"compiled",
")",
"||",
"(",
"$",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Core/Configuration/Configuration.php#L123-L139 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Core/Configuration/Configuration.php | Configuration.setConfig | public function setConfig(array $config)
{
$this->cache = $config;
$this->dumpFile($this->config, $this->parser->dump($config, 7), 0660);
$this->writeCacheConfig($this->compiler->compile($config));
return $this;
} | php | public function setConfig(array $config)
{
$this->cache = $config;
$this->dumpFile($this->config, $this->parser->dump($config, 7), 0660);
$this->writeCacheConfig($this->compiler->compile($config));
return $this;
} | [
"public",
"function",
"setConfig",
"(",
"array",
"$",
"config",
")",
"{",
"$",
"this",
"->",
"cache",
"=",
"$",
"config",
";",
"$",
"this",
"->",
"dumpFile",
"(",
"$",
"this",
"->",
"config",
",",
"$",
"this",
"->",
"parser",
"->",
"dump",
"(",
"$"... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Core/Configuration/Configuration.php#L144-L151 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Core/Configuration/Configuration.php | Configuration.compileAndWrite | public function compileAndWrite()
{
$this->cache = null;
$this->writeCacheConfig($this->compiler->compile(
$this->parser->parse($this->loadFile($this->config))
));
return $this;
} | php | public function compileAndWrite()
{
$this->cache = null;
$this->writeCacheConfig($this->compiler->compile(
$this->parser->parse($this->loadFile($this->config))
));
return $this;
} | [
"public",
"function",
"compileAndWrite",
"(",
")",
"{",
"$",
"this",
"->",
"cache",
"=",
"null",
";",
"$",
"this",
"->",
"writeCacheConfig",
"(",
"$",
"this",
"->",
"compiler",
"->",
"compile",
"(",
"$",
"this",
"->",
"parser",
"->",
"parse",
"(",
"$",... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Core/Configuration/Configuration.php#L156-L164 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Core/Configuration/Configuration.php | Configuration.delete | public function delete()
{
$this->cache = null;
foreach ([
$this->config,
$this->compiled,
] as $file) {
$this->eraseFile($file);
}
} | php | public function delete()
{
$this->cache = null;
foreach ([
$this->config,
$this->compiled,
] as $file) {
$this->eraseFile($file);
}
} | [
"public",
"function",
"delete",
"(",
")",
"{",
"$",
"this",
"->",
"cache",
"=",
"null",
";",
"foreach",
"(",
"[",
"$",
"this",
"->",
"config",
",",
"$",
"this",
"->",
"compiled",
",",
"]",
"as",
"$",
"file",
")",
"{",
"$",
"this",
"->",
"eraseFil... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Core/Configuration/Configuration.php#L169-L178 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Core/Configuration/Configuration.php | Configuration.initialize | public function initialize()
{
$this->delete();
$this->dumpFile($this->config, $this->loadFile(__DIR__ . static::CONFIG_REF), 0660);
// force rewrite
$this->getConfig();
return $this;
} | php | public function initialize()
{
$this->delete();
$this->dumpFile($this->config, $this->loadFile(__DIR__ . static::CONFIG_REF), 0660);
// force rewrite
$this->getConfig();
return $this;
} | [
"public",
"function",
"initialize",
"(",
")",
"{",
"$",
"this",
"->",
"delete",
"(",
")",
";",
"$",
"this",
"->",
"dumpFile",
"(",
"$",
"this",
"->",
"config",
",",
"$",
"this",
"->",
"loadFile",
"(",
"__DIR__",
".",
"static",
"::",
"CONFIG_REF",
")"... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Core/Configuration/Configuration.php#L183-L192 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Feed/Link/AggregateLinkGenerator.php | AggregateLinkGenerator.generatePublic | public function generatePublic(FeedInterface $aggregate, $format, $page = null)
{
if (!$this->supports($aggregate)) {
throw new InvalidArgumentException('AggregateLinkGenerator only support aggregate feeds.');
}
switch ($format) {
case self::FORMAT_ATOM:
$params = ['format' => 'atom'];
if (null !== $page) {
$params['page'] = $page;
}
return new FeedLink(
$this->generator->generate('feed_public_aggregated', $params, UrlGenerator::ABSOLUTE_URL),
sprintf('%s - %s', $aggregate->getTitle(), 'Atom'),
'application/atom+xml'
);
case self::FORMAT_RSS:
$params = ['format' => 'rss'];
if (null !== $page) {
$params['page'] = $page;
}
return new FeedLink(
$this->generator->generate('feed_public_aggregated', $params, UrlGenerator::ABSOLUTE_URL),
sprintf('%s - %s', $aggregate->getTitle(), 'RSS'),
'application/rss+xml'
);
default:
throw new InvalidArgumentException(sprintf('Format %s is not recognized.', $format));
}
} | php | public function generatePublic(FeedInterface $aggregate, $format, $page = null)
{
if (!$this->supports($aggregate)) {
throw new InvalidArgumentException('AggregateLinkGenerator only support aggregate feeds.');
}
switch ($format) {
case self::FORMAT_ATOM:
$params = ['format' => 'atom'];
if (null !== $page) {
$params['page'] = $page;
}
return new FeedLink(
$this->generator->generate('feed_public_aggregated', $params, UrlGenerator::ABSOLUTE_URL),
sprintf('%s - %s', $aggregate->getTitle(), 'Atom'),
'application/atom+xml'
);
case self::FORMAT_RSS:
$params = ['format' => 'rss'];
if (null !== $page) {
$params['page'] = $page;
}
return new FeedLink(
$this->generator->generate('feed_public_aggregated', $params, UrlGenerator::ABSOLUTE_URL),
sprintf('%s - %s', $aggregate->getTitle(), 'RSS'),
'application/rss+xml'
);
default:
throw new InvalidArgumentException(sprintf('Format %s is not recognized.', $format));
}
} | [
"public",
"function",
"generatePublic",
"(",
"FeedInterface",
"$",
"aggregate",
",",
"$",
"format",
",",
"$",
"page",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"supports",
"(",
"$",
"aggregate",
")",
")",
"{",
"throw",
"new",
"InvalidAr... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Feed/Link/AggregateLinkGenerator.php#L99-L131 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Root/SessionController.php | SessionController.getNotifications | public function getNotifications(Request $request)
{
if (!$request->isXmlHttpRequest()) {
$this->app->abort(400);
}
$ret = [
'status' => 'unknown',
'message' => '',
'notifications' => false,
'changed' => []
];
$authenticator = $this->getAuthenticator();
if ($authenticator->isAuthenticated()) {
$usr_id = $authenticator->getUser()->getId();
if ($usr_id != $request->request->get('usr')) { // I logged with another user
$ret['status'] = 'disconnected';
return $this->app->json($ret);
}
} else {
$ret['status'] = 'disconnected';
return $this->app->json($ret);
}
try {
$this->getApplicationBox()->get_connection();
} catch (\Exception $e) {
return $this->app->json($ret);
}
if (1 > $moduleId = (int) $request->request->get('module')) {
$ret['message'] = 'Missing or Invalid `module` parameter';
return $this->app->json($ret);
}
$ret['status'] = 'ok';
$ret['notifications'] = $this->render('prod/notifications.html.twig', [
'notifications' => $this->getEventsManager()->get_notifications()
]);
$baskets = $this->getBasketRepository()->findUnreadActiveByUser($authenticator->getUser());
foreach ($baskets as $basket) {
$ret['changed'][] = $basket->getId();
}
if (in_array($this->getSession()->get('phraseanet.message'), ['1', null])) {
if ($this->app['phraseanet.configuration']['main']['maintenance']) {
$ret['message'] .= $this->app->trans('The application is going down for maintenance, please logout.');
}
if ($this->getConf()->get(['registry', 'maintenance', 'enabled'], false)) {
$ret['message'] .= strip_tags($this->getConf()->get(['registry', 'maintenance', 'message']));
}
}
return $this->app->json($ret);
} | php | public function getNotifications(Request $request)
{
if (!$request->isXmlHttpRequest()) {
$this->app->abort(400);
}
$ret = [
'status' => 'unknown',
'message' => '',
'notifications' => false,
'changed' => []
];
$authenticator = $this->getAuthenticator();
if ($authenticator->isAuthenticated()) {
$usr_id = $authenticator->getUser()->getId();
if ($usr_id != $request->request->get('usr')) { // I logged with another user
$ret['status'] = 'disconnected';
return $this->app->json($ret);
}
} else {
$ret['status'] = 'disconnected';
return $this->app->json($ret);
}
try {
$this->getApplicationBox()->get_connection();
} catch (\Exception $e) {
return $this->app->json($ret);
}
if (1 > $moduleId = (int) $request->request->get('module')) {
$ret['message'] = 'Missing or Invalid `module` parameter';
return $this->app->json($ret);
}
$ret['status'] = 'ok';
$ret['notifications'] = $this->render('prod/notifications.html.twig', [
'notifications' => $this->getEventsManager()->get_notifications()
]);
$baskets = $this->getBasketRepository()->findUnreadActiveByUser($authenticator->getUser());
foreach ($baskets as $basket) {
$ret['changed'][] = $basket->getId();
}
if (in_array($this->getSession()->get('phraseanet.message'), ['1', null])) {
if ($this->app['phraseanet.configuration']['main']['maintenance']) {
$ret['message'] .= $this->app->trans('The application is going down for maintenance, please logout.');
}
if ($this->getConf()->get(['registry', 'maintenance', 'enabled'], false)) {
$ret['message'] .= strip_tags($this->getConf()->get(['registry', 'maintenance', 'message']));
}
}
return $this->app->json($ret);
} | [
"public",
"function",
"getNotifications",
"(",
"Request",
"$",
"request",
")",
"{",
"if",
"(",
"!",
"$",
"request",
"->",
"isXmlHttpRequest",
"(",
")",
")",
"{",
"$",
"this",
"->",
"app",
"->",
"abort",
"(",
"400",
")",
";",
"}",
"$",
"ret",
"=",
"... | Check things to notify
@param Request $request
@return JsonResponse | [
"Check",
"things",
"to",
"notify"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Root/SessionController.php#L32-L94 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Root/SessionController.php | SessionController.updateSession | public function updateSession(Request $request)
{
if (!$request->isXmlHttpRequest()) {
$this->app->abort(400);
}
$ret = [
'status' => 'unknown',
'message' => '',
'notifications' => false,
'changed' => []
];
$authenticator = $this->getAuthenticator();
if ($authenticator->isAuthenticated()) {
$usr_id = $authenticator->getUser()->getId();
if ($usr_id != $request->request->get('usr')) { // I logged with another user
$ret['status'] = 'disconnected';
return $this->app->json($ret);
}
} else {
$ret['status'] = 'disconnected';
return $this->app->json($ret);
}
try {
$this->getApplicationBox()->get_connection();
} catch (\Exception $e) {
return $this->app->json($ret);
}
if (1 > $moduleId = (int) $request->request->get('module')) {
$ret['message'] = 'Missing or Invalid `module` parameter';
return $this->app->json($ret);
}
/** @var \Alchemy\Phrasea\Model\Entities\Session $session */
$session = $this->getSessionRepository()->find($this->getSession()->get('session_id'));
$session->setUpdated(new \DateTime());
$manager = $this->getEntityManager();
if (!$session->hasModuleId($moduleId)) {
$module = new SessionModule();
$module->setModuleId($moduleId);
$module->setSession($session);
$manager->persist($module);
} else {
$manager->persist($session->getModuleById($moduleId)->setUpdated(new \DateTime()));
}
$manager->persist($session);
$manager->flush();
$ret['status'] = 'ok';
$ret['notifications'] = $this->render('prod/notifications.html.twig', [
'notifications' => $this->getEventsManager()->get_notifications()
]);
$baskets = $this->getBasketRepository()->findUnreadActiveByUser($authenticator->getUser());
foreach ($baskets as $basket) {
$ret['changed'][] = $basket->getId();
}
if (in_array($this->getSession()->get('phraseanet.message'), ['1', null])) {
$conf = $this->getConf();
if ($conf->get(['main', 'maintenance'])) {
$ret['message'] .= $this->app->trans('The application is going down for maintenance, please logout.');
}
if ($conf->get(['registry', 'maintenance', 'enabled'])) {
$ret['message'] .= strip_tags($conf->get(['registry', 'maintenance', 'message']));
}
}
return $this->app->json($ret);
} | php | public function updateSession(Request $request)
{
if (!$request->isXmlHttpRequest()) {
$this->app->abort(400);
}
$ret = [
'status' => 'unknown',
'message' => '',
'notifications' => false,
'changed' => []
];
$authenticator = $this->getAuthenticator();
if ($authenticator->isAuthenticated()) {
$usr_id = $authenticator->getUser()->getId();
if ($usr_id != $request->request->get('usr')) { // I logged with another user
$ret['status'] = 'disconnected';
return $this->app->json($ret);
}
} else {
$ret['status'] = 'disconnected';
return $this->app->json($ret);
}
try {
$this->getApplicationBox()->get_connection();
} catch (\Exception $e) {
return $this->app->json($ret);
}
if (1 > $moduleId = (int) $request->request->get('module')) {
$ret['message'] = 'Missing or Invalid `module` parameter';
return $this->app->json($ret);
}
/** @var \Alchemy\Phrasea\Model\Entities\Session $session */
$session = $this->getSessionRepository()->find($this->getSession()->get('session_id'));
$session->setUpdated(new \DateTime());
$manager = $this->getEntityManager();
if (!$session->hasModuleId($moduleId)) {
$module = new SessionModule();
$module->setModuleId($moduleId);
$module->setSession($session);
$manager->persist($module);
} else {
$manager->persist($session->getModuleById($moduleId)->setUpdated(new \DateTime()));
}
$manager->persist($session);
$manager->flush();
$ret['status'] = 'ok';
$ret['notifications'] = $this->render('prod/notifications.html.twig', [
'notifications' => $this->getEventsManager()->get_notifications()
]);
$baskets = $this->getBasketRepository()->findUnreadActiveByUser($authenticator->getUser());
foreach ($baskets as $basket) {
$ret['changed'][] = $basket->getId();
}
if (in_array($this->getSession()->get('phraseanet.message'), ['1', null])) {
$conf = $this->getConf();
if ($conf->get(['main', 'maintenance'])) {
$ret['message'] .= $this->app->trans('The application is going down for maintenance, please logout.');
}
if ($conf->get(['registry', 'maintenance', 'enabled'])) {
$ret['message'] .= strip_tags($conf->get(['registry', 'maintenance', 'message']));
}
}
return $this->app->json($ret);
} | [
"public",
"function",
"updateSession",
"(",
"Request",
"$",
"request",
")",
"{",
"if",
"(",
"!",
"$",
"request",
"->",
"isXmlHttpRequest",
"(",
")",
")",
"{",
"$",
"this",
"->",
"app",
"->",
"abort",
"(",
"400",
")",
";",
"}",
"$",
"ret",
"=",
"[",... | Check session state
@param Request $request
@return JsonResponse | [
"Check",
"session",
"state"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Root/SessionController.php#L102-L182 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Root/SessionController.php | SessionController.deleteSession | public function deleteSession(Request $request, $id)
{
$session = $this->getSessionRepository()->find($id);
if (null === $session) {
$this->app->abort(404, 'Unknown session');
}
if (null === $session->getUser()) {
$this->app->abort(403, 'Unauthorized');
}
if ($session->getUser()->getId() !== $this->getAuthenticatedUser()->getId()) {
$this->app->abort(403, 'Unauthorized');
}
$manager = $this->getEntityManager();
$manager->remove($session);
$manager->flush();
if ($request->isXmlHttpRequest()) {
return $this->app->json([
'success' => true,
'session_id' => $id
]);
}
return $this->app->redirectPath('account_sessions');
} | php | public function deleteSession(Request $request, $id)
{
$session = $this->getSessionRepository()->find($id);
if (null === $session) {
$this->app->abort(404, 'Unknown session');
}
if (null === $session->getUser()) {
$this->app->abort(403, 'Unauthorized');
}
if ($session->getUser()->getId() !== $this->getAuthenticatedUser()->getId()) {
$this->app->abort(403, 'Unauthorized');
}
$manager = $this->getEntityManager();
$manager->remove($session);
$manager->flush();
if ($request->isXmlHttpRequest()) {
return $this->app->json([
'success' => true,
'session_id' => $id
]);
}
return $this->app->redirectPath('account_sessions');
} | [
"public",
"function",
"deleteSession",
"(",
"Request",
"$",
"request",
",",
"$",
"id",
")",
"{",
"$",
"session",
"=",
"$",
"this",
"->",
"getSessionRepository",
"(",
")",
"->",
"find",
"(",
"$",
"id",
")",
";",
"if",
"(",
"null",
"===",
"$",
"session... | Deletes identified session
@param Request $request
@param integer $id
@return JsonResponse|RedirectResponse | [
"Deletes",
"identified",
"session"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Root/SessionController.php#L191-L219 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Utilities/CachedTranslator.php | CachedTranslator.loadCatalogue | protected function loadCatalogue($locale)
{
if (isset($this->catalogues[$locale])) {
return;
}
if (is_callable($this->options['cache_dir'])) {
$cache_dir = call_user_func($this->options['cache_dir'], $this->app);
} else {
$cache_dir = $this->options['cache_dir'];
}
if (null === $cache_dir) {
return parent::loadCatalogue($locale);
}
$cache = new ConfigCache($cache_dir.'/catalogue.'.$locale.'.php', $this->options['debug']);
if (!$cache->isFresh()) {
parent::loadCatalogue($locale);
$fallbackContent = '';
$current = '';
foreach ($this->computeFallbackLocales($locale) as $fallback) {
$fallbackSuffix = ucfirst(str_replace('-', '_', $fallback));
$fallbackContent .= sprintf(<<<EOF
\$catalogue%s = new MessageCatalogue('%s', %s);
\$catalogue%s->addFallbackCatalogue(\$catalogue%s);
EOF
,
$fallbackSuffix,
$fallback,
var_export($this->catalogues[$fallback]->all(), true),
ucfirst(str_replace('-', '_', $current)),
$fallbackSuffix
);
$current = $fallback;
}
$content = sprintf(<<<EOF
<?php
use Symfony\Component\Translation\MessageCatalogue;
\$catalogue = new MessageCatalogue('%s', %s);
%s
return \$catalogue;
EOF
,
$locale,
var_export($this->catalogues[$locale]->all(), true),
$fallbackContent
);
$cache->write($content, $this->catalogues[$locale]->getResources());
return;
}
$this->catalogues[$locale] = include $cache;
} | php | protected function loadCatalogue($locale)
{
if (isset($this->catalogues[$locale])) {
return;
}
if (is_callable($this->options['cache_dir'])) {
$cache_dir = call_user_func($this->options['cache_dir'], $this->app);
} else {
$cache_dir = $this->options['cache_dir'];
}
if (null === $cache_dir) {
return parent::loadCatalogue($locale);
}
$cache = new ConfigCache($cache_dir.'/catalogue.'.$locale.'.php', $this->options['debug']);
if (!$cache->isFresh()) {
parent::loadCatalogue($locale);
$fallbackContent = '';
$current = '';
foreach ($this->computeFallbackLocales($locale) as $fallback) {
$fallbackSuffix = ucfirst(str_replace('-', '_', $fallback));
$fallbackContent .= sprintf(<<<EOF
\$catalogue%s = new MessageCatalogue('%s', %s);
\$catalogue%s->addFallbackCatalogue(\$catalogue%s);
EOF
,
$fallbackSuffix,
$fallback,
var_export($this->catalogues[$fallback]->all(), true),
ucfirst(str_replace('-', '_', $current)),
$fallbackSuffix
);
$current = $fallback;
}
$content = sprintf(<<<EOF
<?php
use Symfony\Component\Translation\MessageCatalogue;
\$catalogue = new MessageCatalogue('%s', %s);
%s
return \$catalogue;
EOF
,
$locale,
var_export($this->catalogues[$locale]->all(), true),
$fallbackContent
);
$cache->write($content, $this->catalogues[$locale]->getResources());
return;
}
$this->catalogues[$locale] = include $cache;
} | [
"protected",
"function",
"loadCatalogue",
"(",
"$",
"locale",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"catalogues",
"[",
"$",
"locale",
"]",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"is_callable",
"(",
"$",
"this",
"->",
"options",... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Utilities/CachedTranslator.php#L42-L106 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Root/LoginController.php | LoginController.sendConfirmMail | public function sendConfirmMail(Request $request)
{
if (null === $usrId = $request->query->get('usr_id')) {
$this->app->abort(400, 'Missing usr_id parameter.');
}
$user = $this->getUserRepository()->find((int) $usrId);
if (!$user instanceof User) {
$this->app->addFlash('error', $this->app->trans('Invalid link.'));
return $this->app->redirectPath('homepage');
}
try {
$this->sendAccountUnlockEmail($user, $request);
$this->app->addFlash('success', $this->app->trans('login::notification: demande de confirmation par mail envoyee'));
} catch (InvalidArgumentException $e) {
// todo, log this failure
$this->app->addFlash('error', $this->app->trans('Unable to send your account unlock email.'));
}
return $this->app->redirectPath('homepage');
} | php | public function sendConfirmMail(Request $request)
{
if (null === $usrId = $request->query->get('usr_id')) {
$this->app->abort(400, 'Missing usr_id parameter.');
}
$user = $this->getUserRepository()->find((int) $usrId);
if (!$user instanceof User) {
$this->app->addFlash('error', $this->app->trans('Invalid link.'));
return $this->app->redirectPath('homepage');
}
try {
$this->sendAccountUnlockEmail($user, $request);
$this->app->addFlash('success', $this->app->trans('login::notification: demande de confirmation par mail envoyee'));
} catch (InvalidArgumentException $e) {
// todo, log this failure
$this->app->addFlash('error', $this->app->trans('Unable to send your account unlock email.'));
}
return $this->app->redirectPath('homepage');
} | [
"public",
"function",
"sendConfirmMail",
"(",
"Request",
"$",
"request",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"usrId",
"=",
"$",
"request",
"->",
"query",
"->",
"get",
"(",
"'usr_id'",
")",
")",
"{",
"$",
"this",
"->",
"app",
"->",
"abort",
"(",
... | Send a confirmation mail after register
@param Request $request The current request
@return RedirectResponse | [
"Send",
"a",
"confirmation",
"mail",
"after",
"register"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Root/LoginController.php#L295-L317 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Root/LoginController.php | LoginController.registerConfirm | public function registerConfirm(Request $request)
{
if (null === $code = $request->query->get('code')) {
$this->app->addFlash('error', $this->app->trans('Invalid unlock link.'));
return $this->app->redirectPath('homepage');
}
if (null === $token = $this->getTokenRepository()->findValidToken($code)) {
$this->app->addFlash('error', $this->app->trans('Invalid unlock link.'));
return $this->app->redirectPath('homepage');
}
$user = $token->getUser();
if (!$user->isMailLocked()) {
$this->app->addFlash('info', $this->app->trans('Account is already unlocked, you can login.'));
return $this->app->redirectPath('homepage');
}
$tokenManipulator = $this->getTokenManipulator();
$tokenManipulator->delete($token);
$user->setMailLocked(false);
try {
$receiver = Receiver::fromUser($user);
} catch (InvalidArgumentException $e) {
$this->app->addFlash('success', $this->app->trans('Account has been unlocked, you can now login.'));
return $this->app->redirectPath('homepage');
}
$tokenManipulator->delete($token);
if (count($this->getAclForUser($user)->get_granted_base()) > 0) {
$mail = MailSuccessEmailConfirmationRegistered::create($this->app, $receiver);
$this->deliver($mail);
$this->app->addFlash('success', $this->app->trans('Account has been unlocked, you can now login.'));
} else {
$mail = MailSuccessEmailConfirmationUnregistered::create($this->app, $receiver);
$this->deliver($mail);
$this->app->addFlash('info', $this->app->trans('Account has been unlocked, you still have to wait for admin approval.'));
}
return $this->app->redirectPath('homepage');
} | php | public function registerConfirm(Request $request)
{
if (null === $code = $request->query->get('code')) {
$this->app->addFlash('error', $this->app->trans('Invalid unlock link.'));
return $this->app->redirectPath('homepage');
}
if (null === $token = $this->getTokenRepository()->findValidToken($code)) {
$this->app->addFlash('error', $this->app->trans('Invalid unlock link.'));
return $this->app->redirectPath('homepage');
}
$user = $token->getUser();
if (!$user->isMailLocked()) {
$this->app->addFlash('info', $this->app->trans('Account is already unlocked, you can login.'));
return $this->app->redirectPath('homepage');
}
$tokenManipulator = $this->getTokenManipulator();
$tokenManipulator->delete($token);
$user->setMailLocked(false);
try {
$receiver = Receiver::fromUser($user);
} catch (InvalidArgumentException $e) {
$this->app->addFlash('success', $this->app->trans('Account has been unlocked, you can now login.'));
return $this->app->redirectPath('homepage');
}
$tokenManipulator->delete($token);
if (count($this->getAclForUser($user)->get_granted_base()) > 0) {
$mail = MailSuccessEmailConfirmationRegistered::create($this->app, $receiver);
$this->deliver($mail);
$this->app->addFlash('success', $this->app->trans('Account has been unlocked, you can now login.'));
} else {
$mail = MailSuccessEmailConfirmationUnregistered::create($this->app, $receiver);
$this->deliver($mail);
$this->app->addFlash('info', $this->app->trans('Account has been unlocked, you still have to wait for admin approval.'));
}
return $this->app->redirectPath('homepage');
} | [
"public",
"function",
"registerConfirm",
"(",
"Request",
"$",
"request",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"code",
"=",
"$",
"request",
"->",
"query",
"->",
"get",
"(",
"'code'",
")",
")",
"{",
"$",
"this",
"->",
"app",
"->",
"addFlash",
"(",
... | Validation of email address
@param Request $request The current request
@return RedirectResponse | [
"Validation",
"of",
"email",
"address"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Root/LoginController.php#L332-L381 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Root/LoginController.php | LoginController.forgotPassword | public function forgotPassword(Request $request)
{
$form = $this->app->form(new PhraseaForgotPasswordForm());
$service = $this->getRecoveryService();
try {
if ('POST' === $request->getMethod()) {
$form->handleRequest($request);
if ($form->isValid()) {
$data = $form->getData();
try {
$service->requestPasswordResetToken($data['email'], true);
}
catch (InvalidArgumentException $ex) {
/** @Ignore */
$message = $this->app->trans($ex->getMessage());
throw new FormProcessingException($message, 0, $ex);
}
$this->app->addFlash('info', $this->app->trans('phraseanet:: Un email vient de vous etre envoye'));
return $this->app->redirectPath('login_forgot_password');
}
}
} catch (FormProcessingException $e) {
$this->app->addFlash('error', $e->getMessage());
}
return $this->render('login/forgot-password.html.twig', array_merge(
$this->getDefaultTemplateVariables($request),
[ 'form' => $form->createView() ]
));
} | php | public function forgotPassword(Request $request)
{
$form = $this->app->form(new PhraseaForgotPasswordForm());
$service = $this->getRecoveryService();
try {
if ('POST' === $request->getMethod()) {
$form->handleRequest($request);
if ($form->isValid()) {
$data = $form->getData();
try {
$service->requestPasswordResetToken($data['email'], true);
}
catch (InvalidArgumentException $ex) {
/** @Ignore */
$message = $this->app->trans($ex->getMessage());
throw new FormProcessingException($message, 0, $ex);
}
$this->app->addFlash('info', $this->app->trans('phraseanet:: Un email vient de vous etre envoye'));
return $this->app->redirectPath('login_forgot_password');
}
}
} catch (FormProcessingException $e) {
$this->app->addFlash('error', $e->getMessage());
}
return $this->render('login/forgot-password.html.twig', array_merge(
$this->getDefaultTemplateVariables($request),
[ 'form' => $form->createView() ]
));
} | [
"public",
"function",
"forgotPassword",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"form",
"=",
"$",
"this",
"->",
"app",
"->",
"form",
"(",
"new",
"PhraseaForgotPasswordForm",
"(",
")",
")",
";",
"$",
"service",
"=",
"$",
"this",
"->",
"getRecoveryS... | Submit the new password
@param Request $request The current request
@return RedirectResponse | [
"Submit",
"the",
"new",
"password"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Root/LoginController.php#L414-L448 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Root/LoginController.php | LoginController.displayRegisterForm | public function displayRegisterForm(Request $request)
{
if (!$this->getRegistrationManager()->isRegistrationEnabled()) {
$this->app->abort(404, 'Registration is disabled');
}
if (0 < count($this->getAuthenticationProviders())) {
return $this->render('login/register.html.twig', $this->getDefaultTemplateVariables($request));
} else {
return $this->app->redirectPath('login_register_classic');
}
} | php | public function displayRegisterForm(Request $request)
{
if (!$this->getRegistrationManager()->isRegistrationEnabled()) {
$this->app->abort(404, 'Registration is disabled');
}
if (0 < count($this->getAuthenticationProviders())) {
return $this->render('login/register.html.twig', $this->getDefaultTemplateVariables($request));
} else {
return $this->app->redirectPath('login_register_classic');
}
} | [
"public",
"function",
"displayRegisterForm",
"(",
"Request",
"$",
"request",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"getRegistrationManager",
"(",
")",
"->",
"isRegistrationEnabled",
"(",
")",
")",
"{",
"$",
"this",
"->",
"app",
"->",
"abort",
"(",
... | Get the register form
@param Request $request The current request
@return Response | [
"Get",
"the",
"register",
"form"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Root/LoginController.php#L456-L467 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Root/LoginController.php | LoginController.logout | public function logout(Request $request)
{
$this->dispatch(PhraseaEvents::LOGOUT, new LogoutEvent($this->app));
$this->getAuthenticator()->closeAccount();
$this->app->addFlash('info', $this->app->trans('Vous etes maintenant deconnecte. A bientot.'));
$response = $this->app->redirectPath('homepage', [
'redirect' => $request->query->get("redirect")
]);
$response->headers->clearCookie('persistent');
$response->headers->clearCookie('last_act');
return $response;
} | php | public function logout(Request $request)
{
$this->dispatch(PhraseaEvents::LOGOUT, new LogoutEvent($this->app));
$this->getAuthenticator()->closeAccount();
$this->app->addFlash('info', $this->app->trans('Vous etes maintenant deconnecte. A bientot.'));
$response = $this->app->redirectPath('homepage', [
'redirect' => $request->query->get("redirect")
]);
$response->headers->clearCookie('persistent');
$response->headers->clearCookie('last_act');
return $response;
} | [
"public",
"function",
"logout",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"this",
"->",
"dispatch",
"(",
"PhraseaEvents",
"::",
"LOGOUT",
",",
"new",
"LogoutEvent",
"(",
"$",
"this",
"->",
"app",
")",
")",
";",
"$",
"this",
"->",
"getAuthenticator",... | Logout from Phraseanet
@param Request $request The current request
@return RedirectResponse | [
"Logout",
"from",
"Phraseanet"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Root/LoginController.php#L475-L490 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Root/LoginController.php | LoginController.login | public function login(Request $request)
{
try {
$this->getApplicationBox()->get_connection();
} catch (\Exception $e) {
$this->app->addFlash('error', $this->app->trans('login::erreur: No available connection - Please contact sys-admin'));
}
$feeds = $this->getFeedRepository()->findBy(['public' => true], ['updatedOn' => 'DESC']);
$form = $this->app->form(new PhraseaAuthenticationForm($this->app));
$form->setData([
'redirect' => $request->query->get('redirect')
]);
return $this->render('login/index.html.twig', array_merge(
$this->getDefaultTemplateVariables($request),
[
'feeds' => $feeds,
'form' => $form->createView(),
]));
} | php | public function login(Request $request)
{
try {
$this->getApplicationBox()->get_connection();
} catch (\Exception $e) {
$this->app->addFlash('error', $this->app->trans('login::erreur: No available connection - Please contact sys-admin'));
}
$feeds = $this->getFeedRepository()->findBy(['public' => true], ['updatedOn' => 'DESC']);
$form = $this->app->form(new PhraseaAuthenticationForm($this->app));
$form->setData([
'redirect' => $request->query->get('redirect')
]);
return $this->render('login/index.html.twig', array_merge(
$this->getDefaultTemplateVariables($request),
[
'feeds' => $feeds,
'form' => $form->createView(),
]));
} | [
"public",
"function",
"login",
"(",
"Request",
"$",
"request",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"getApplicationBox",
"(",
")",
"->",
"get_connection",
"(",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"$",
"this",
"->",... | Login into Phraseanet
@param Request $request The current request
@return Response | [
"Login",
"into",
"Phraseanet"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Root/LoginController.php#L498-L519 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Root/LoginController.php | LoginController.authenticate | public function authenticate(Request $request)
{
$form = $this->app->form(new PhraseaAuthenticationForm($this->app));
$redirector = function (array $params = []) {
return $this->app->redirectPath('homepage', $params);
};
try {
return $this->doAuthentication($request, $form, $redirector);
} catch (AuthenticationException $e) {
return $e->getResponse();
}
} | php | public function authenticate(Request $request)
{
$form = $this->app->form(new PhraseaAuthenticationForm($this->app));
$redirector = function (array $params = []) {
return $this->app->redirectPath('homepage', $params);
};
try {
return $this->doAuthentication($request, $form, $redirector);
} catch (AuthenticationException $e) {
return $e->getResponse();
}
} | [
"public",
"function",
"authenticate",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"form",
"=",
"$",
"this",
"->",
"app",
"->",
"form",
"(",
"new",
"PhraseaAuthenticationForm",
"(",
"$",
"this",
"->",
"app",
")",
")",
";",
"$",
"redirector",
"=",
"fu... | Authenticate to phraseanet
@param Request $request The current request
@return RedirectResponse | [
"Authenticate",
"to",
"phraseanet"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Root/LoginController.php#L527-L539 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Root/LoginController.php | LoginController.postAuthProcess | public function postAuthProcess(Request $request, User $user)
{
$date = new \DateTime('+' . (int) $this->getConf()->get(['registry', 'actions', 'validation-reminder-days']) . ' days');
$manager = $this->getEntityManager();
foreach ($this->getValidationParticipantRepository()->findNotConfirmedAndNotRemindedParticipantsByExpireDate($date) as $participant) {
$validationSession = $participant->getSession();
$basket = $validationSession->getBasket();
if (null === $token = $this->getTokenRepository()->findValidationToken($basket, $participant->getUser())) {
continue;
}
$url = $this->app->url('lightbox_validation', ['basket' => $basket->getId(), 'LOG' => $token->getValue()]);
$this->dispatch(PhraseaEvents::VALIDATION_REMINDER, new ValidationEvent($participant, $basket, $url));
$participant->setReminded(new \DateTime('now'));
$manager->persist($participant);
}
$manager->flush();
$session = $this->getAuthenticator()->openAccount($user);
if ($user->getLocale() != $this->app['locale']) {
$user->setLocale($this->app['locale']);
}
$width = $height = null;
if ($request->cookies->has('screen')) {
$data = array_filter((explode('x', $request->cookies->get('screen', ''))));
if (count($data) === 2) {
$width = $data[0];
$height = $data[1];
}
}
$session->setIpAddress($request->getClientIp())
->setScreenHeight($height)
->setScreenWidth($width);
$manager->persist($session);
$manager->flush();
return $session;
} | php | public function postAuthProcess(Request $request, User $user)
{
$date = new \DateTime('+' . (int) $this->getConf()->get(['registry', 'actions', 'validation-reminder-days']) . ' days');
$manager = $this->getEntityManager();
foreach ($this->getValidationParticipantRepository()->findNotConfirmedAndNotRemindedParticipantsByExpireDate($date) as $participant) {
$validationSession = $participant->getSession();
$basket = $validationSession->getBasket();
if (null === $token = $this->getTokenRepository()->findValidationToken($basket, $participant->getUser())) {
continue;
}
$url = $this->app->url('lightbox_validation', ['basket' => $basket->getId(), 'LOG' => $token->getValue()]);
$this->dispatch(PhraseaEvents::VALIDATION_REMINDER, new ValidationEvent($participant, $basket, $url));
$participant->setReminded(new \DateTime('now'));
$manager->persist($participant);
}
$manager->flush();
$session = $this->getAuthenticator()->openAccount($user);
if ($user->getLocale() != $this->app['locale']) {
$user->setLocale($this->app['locale']);
}
$width = $height = null;
if ($request->cookies->has('screen')) {
$data = array_filter((explode('x', $request->cookies->get('screen', ''))));
if (count($data) === 2) {
$width = $data[0];
$height = $data[1];
}
}
$session->setIpAddress($request->getClientIp())
->setScreenHeight($height)
->setScreenWidth($width);
$manager->persist($session);
$manager->flush();
return $session;
} | [
"public",
"function",
"postAuthProcess",
"(",
"Request",
"$",
"request",
",",
"User",
"$",
"user",
")",
"{",
"$",
"date",
"=",
"new",
"\\",
"DateTime",
"(",
"'+'",
".",
"(",
"int",
")",
"$",
"this",
"->",
"getConf",
"(",
")",
"->",
"get",
"(",
"[",... | move this in an event | [
"move",
"this",
"in",
"an",
"event"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Root/LoginController.php#L593-L637 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Model/Types/BinaryString.php | BinaryString.getSQLDeclaration | public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
if ($platform->getName() === 'mysql') {
/** @var MySqlPlatform $platform */
return $platform->getVarcharTypeDeclarationSQL($fieldDeclaration)
// . " CHARACTER SET utf8"
. " " . $platform->getColumnCollationDeclarationSQL('utf8_bin')
. " COMMENT '(DC2Type:binary_string)'"
;
}
return $platform->getVarcharTypeDeclarationSQL($fieldDeclaration);
} | php | public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
if ($platform->getName() === 'mysql') {
/** @var MySqlPlatform $platform */
return $platform->getVarcharTypeDeclarationSQL($fieldDeclaration)
// . " CHARACTER SET utf8"
. " " . $platform->getColumnCollationDeclarationSQL('utf8_bin')
. " COMMENT '(DC2Type:binary_string)'"
;
}
return $platform->getVarcharTypeDeclarationSQL($fieldDeclaration);
} | [
"public",
"function",
"getSQLDeclaration",
"(",
"array",
"$",
"fieldDeclaration",
",",
"AbstractPlatform",
"$",
"platform",
")",
"{",
"if",
"(",
"$",
"platform",
"->",
"getName",
"(",
")",
"===",
"'mysql'",
")",
"{",
"/** @var MySqlPlatform $platform */",
"return"... | {@inheritdoc}
@see: https://blog.vandenbrand.org/2015/06/25/creating-a-custom-doctrine-dbal-type-the-right-way/
about the reason of the COMMENT in the column | [
"{",
"@inheritdoc",
"}"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Types/BinaryString.php#L33-L45 |
alchemy-fr/Phraseanet | lib/classes/patch/381alpha2a.php | patch_381alpha2a.apply | public function apply(base $appbox, Application $app)
{
$sql = 'SELECT `value` FROM `registry` WHERE `key` = "GV_i18n_service"';
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$row = $stmt->fetch(\PDO::FETCH_ASSOC);
$stmt->closeCursor();
if (null !== $row && false !== strpos($row['value'], 'localization.webservice.alchemyasp.com')) {
$sql = 'UPDATE `registry` SET `value` = "http://geonames.alchemyasp.com/" WHERE `key` = "GV_i18n_service"';
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
}
return true;
} | php | public function apply(base $appbox, Application $app)
{
$sql = 'SELECT `value` FROM `registry` WHERE `key` = "GV_i18n_service"';
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$row = $stmt->fetch(\PDO::FETCH_ASSOC);
$stmt->closeCursor();
if (null !== $row && false !== strpos($row['value'], 'localization.webservice.alchemyasp.com')) {
$sql = 'UPDATE `registry` SET `value` = "http://geonames.alchemyasp.com/" WHERE `key` = "GV_i18n_service"';
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
}
return true;
} | [
"public",
"function",
"apply",
"(",
"base",
"$",
"appbox",
",",
"Application",
"$",
"app",
")",
"{",
"$",
"sql",
"=",
"'SELECT `value` FROM `registry` WHERE `key` = \"GV_i18n_service\"'",
";",
"$",
"stmt",
"=",
"$",
"appbox",
"->",
"get_connection",
"(",
")",
"-... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/381alpha2a.php#L49-L65 |
alchemy-fr/Phraseanet | lib/classes/patch/380alpha6a.php | patch_380alpha6a.apply | public function apply(base $appbox, Application $app)
{
$app['configuration.store']->setDefault('registration-fields');
$app['configuration.store']->setDefault('authentication');
return true;
} | php | public function apply(base $appbox, Application $app)
{
$app['configuration.store']->setDefault('registration-fields');
$app['configuration.store']->setDefault('authentication');
return true;
} | [
"public",
"function",
"apply",
"(",
"base",
"$",
"appbox",
",",
"Application",
"$",
"app",
")",
"{",
"$",
"app",
"[",
"'configuration.store'",
"]",
"->",
"setDefault",
"(",
"'registration-fields'",
")",
";",
"$",
"app",
"[",
"'configuration.store'",
"]",
"->... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/380alpha6a.php#L49-L55 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/TaskManager/Log/AbstractLogFile.php | AbstractLogFile.getContent | public function getContent($version = '')
{
$path = $this->getPath($version);
if (is_file($path)) {
return file_get_contents($this->getPath($version));
}
return '';
} | php | public function getContent($version = '')
{
$path = $this->getPath($version);
if (is_file($path)) {
return file_get_contents($this->getPath($version));
}
return '';
} | [
"public",
"function",
"getContent",
"(",
"$",
"version",
"=",
"''",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"getPath",
"(",
"$",
"version",
")",
";",
"if",
"(",
"is_file",
"(",
"$",
"path",
")",
")",
"{",
"return",
"file_get_contents",
"(",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/TaskManager/Log/AbstractLogFile.php#L37-L45 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/TaskManager/Log/AbstractLogFile.php | AbstractLogFile.getContentStream | public function getContentStream($version = '')
{
$path = $this->getPath($version);
return function () use ($path) {
$handle = fopen($path, 'r');
while (!feof($handle)) {
echo fread($handle, 4096);
ob_flush();flush();
}
fclose($handle);
};
} | php | public function getContentStream($version = '')
{
$path = $this->getPath($version);
return function () use ($path) {
$handle = fopen($path, 'r');
while (!feof($handle)) {
echo fread($handle, 4096);
ob_flush();flush();
}
fclose($handle);
};
} | [
"public",
"function",
"getContentStream",
"(",
"$",
"version",
"=",
"''",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"getPath",
"(",
"$",
"version",
")",
";",
"return",
"function",
"(",
")",
"use",
"(",
"$",
"path",
")",
"{",
"$",
"handle",
"="... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/TaskManager/Log/AbstractLogFile.php#L50-L62 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/TaskManager/Log/AbstractLogFile.php | AbstractLogFile.clear | public function clear($version = '')
{
file_put_contents($this->getPath($version), sprintf("[%s] File cleared\n", date(\DateTime::ATOM)));
} | php | public function clear($version = '')
{
file_put_contents($this->getPath($version), sprintf("[%s] File cleared\n", date(\DateTime::ATOM)));
} | [
"public",
"function",
"clear",
"(",
"$",
"version",
"=",
"''",
")",
"{",
"file_put_contents",
"(",
"$",
"this",
"->",
"getPath",
"(",
"$",
"version",
")",
",",
"sprintf",
"(",
"\"[%s] File cleared\\n\"",
",",
"date",
"(",
"\\",
"DateTime",
"::",
"ATOM",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/TaskManager/Log/AbstractLogFile.php#L67-L70 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Prod/UploadController.php | UploadController.upload | public function upload(Request $request)
{
$data = [
'success' => false,
'code' => null,
'message' => '',
'element' => '',
'reasons' => [],
'id' => '',
];
if (null === $request->files->get('files')) {
throw new BadRequestHttpException('Missing file parameter');
}
if (count($request->files->get('files')) > 1) {
throw new BadRequestHttpException('Upload is limited to 1 file per request');
}
$base_id = $request->request->get('base_id');
if (!$base_id) {
throw new BadRequestHttpException('Missing base_id parameter');
}
if (!$this->getAclForUser()->has_right_on_base($base_id, \ACL::CANADDRECORD)) {
throw new AccessDeniedHttpException('User is not allowed to add record on this collection');
}
/** @var UploadedFile $file */
$file = current($request->files->get('files'));
if (!$file->isValid()) {
throw new BadRequestHttpException('Uploaded file is invalid');
}
if ($file->getClientOriginalName() === "blob" && $file->getClientMimeType() === "application/json") {
// a "upload by url" was done, we receive a tiny json that contains url.
$json = json_decode(file_get_contents($file->getRealPath()), true);
$url = $json['url'];
$pi = pathinfo($url); // filename, extension
$tempfile = $this->getTemporaryFilesystem()->createTemporaryFile('download_', null, $pi['extension']);
try {
$guzzle = new Guzzle($url);
$res = $guzzle->get("", [], ['save_to' => $tempfile])->send();
}
catch (\Exception $e) {
throw new BadRequestHttpException(sprintf('Error "%s" downloading "%s"', $e->getMessage(), $url));
}
if($res->getStatusCode() !== 200) {
throw new BadRequestHttpException(sprintf('Error %s downloading "%s"', $res->getStatusCode(), $url));
}
$uploadedFilename = $renamedFilename = $tempfile;
$originalName = $pi['filename'] . '.' . $pi['extension'];
} else {
// Add file extension, so mediavorus can guess file type for octet-stream file
$uploadedFilename = $file->getRealPath();
$renamedFilename = null;
if(!empty($this->app['conf']->get(['main', 'storage', 'tmp_files']))) {
$tmpStorage = \p4string::addEndSlash($this->app['conf']->get(['main', 'storage', 'tmp_files'])).'upload/';
if(!is_dir($tmpStorage)){
$this->getFilesystem()->mkdir($tmpStorage);
}
$renamedFilename = $tmpStorage. pathinfo($file->getRealPath(), PATHINFO_FILENAME) .'.' . pathinfo($file->getClientOriginalName(), PATHINFO_EXTENSION);
} else {
$renamedFilename = $file->getRealPath() . '.' . pathinfo($file->getClientOriginalName(), PATHINFO_EXTENSION);
}
$this->getFilesystem()->rename($uploadedFilename, $renamedFilename);
$originalName = $file->getClientOriginalName();
}
try {
$media = $this->app->getMediaFromUri($renamedFilename);
$collection = \collection::getByBaseId($this->app, $base_id);
$lazaretSession = new LazaretSession();
$lazaretSession->setUser($this->getAuthenticatedUser());
$this->getEntityManager()->persist($lazaretSession);
$packageFile = new File($this->app, $media, $collection, $originalName);
$postStatus = $request->request->get('status');
if (isset($postStatus[$collection->get_base_id()]) && is_array($postStatus[$collection->get_base_id()])) {
$postStatus = $postStatus[$collection->get_base_id()];
$status = '';
foreach (range(0, 31) as $i) {
$status .= isset($postStatus[$i]) ? ($postStatus[$i] ? '1' : '0') : '0';
}
$packageFile->addAttribute(new Status($this->app, strrev($status)));
}
$forceBehavior = $request->request->get('forceAction');
$reasons = [];
$elementCreated = null;
$callback = function ($element, Visa $visa) use (&$reasons, &$elementCreated) {
foreach ($visa->getResponses() as $response) {
if (!$response->isOk()) {
$reasons[] = $response->getMessage($this->app['translator']);
}
}
$elementCreated = $element;
};
$code = $this->getBorderManager()->process( $lazaretSession, $packageFile, $callback, $forceBehavior);
if($renamedFilename !== $uploadedFilename) {
$this->getFilesystem()->rename($renamedFilename, $uploadedFilename);
}
if (!!$forceBehavior) {
$reasons = [];
}
if ($elementCreated instanceof \record_adapter) {
$id = $elementCreated->getId();
$element = 'record';
$message = $this->app->trans('The record was successfully created');
$this->dispatch(PhraseaEvents::RECORD_UPLOAD, new RecordEdit($elementCreated));
// try to create thumbnail from data URI
if ('' !== $b64Image = $request->request->get('b64_image', '')) {
try {
$dataUri = Parser::parse($b64Image);
$fileName = $this->getTemporaryFilesystem()->createTemporaryFile('base_64_thumb', null, "png");
file_put_contents($fileName, $dataUri->getData());
$media = $this->app->getMediaFromUri($fileName);
$this->getSubDefinitionSubstituer()->substituteSubdef($elementCreated, 'thumbnail', $media);
$this->getDataboxLogger($elementCreated->getDatabox())
->log($elementCreated, \Session_Logger::EVENT_SUBSTITUTE, 'thumbnail', '');
unset($media);
$this->getTemporaryFilesystem()->clean('base_64_thumb');
} catch (DataUriException $e) {
}
}
} else {
/** @var LazaretFile $elementCreated */
$this->dispatch(PhraseaEvents::LAZARET_CREATE, new LazaretEvent($elementCreated));
$id = $elementCreated->getId();
$element = 'lazaret';
$message = $this->app->trans('The file was moved to the quarantine');
}
$data = [
'success' => true,
'code' => $code,
'message' => $message,
'element' => $element,
'reasons' => $reasons,
'id' => $id,
];
} catch (\Exception $e) {
$data['message'] = $this->app->trans('Unable to add file to Phraseanet');
}
$response = $this->app->json($data);
// IE 7 and 8 does not correctly handle json response in file API
// lets send them an html content-type header
$response->headers->set('Content-type', 'text/html');
return $response;
} | php | public function upload(Request $request)
{
$data = [
'success' => false,
'code' => null,
'message' => '',
'element' => '',
'reasons' => [],
'id' => '',
];
if (null === $request->files->get('files')) {
throw new BadRequestHttpException('Missing file parameter');
}
if (count($request->files->get('files')) > 1) {
throw new BadRequestHttpException('Upload is limited to 1 file per request');
}
$base_id = $request->request->get('base_id');
if (!$base_id) {
throw new BadRequestHttpException('Missing base_id parameter');
}
if (!$this->getAclForUser()->has_right_on_base($base_id, \ACL::CANADDRECORD)) {
throw new AccessDeniedHttpException('User is not allowed to add record on this collection');
}
/** @var UploadedFile $file */
$file = current($request->files->get('files'));
if (!$file->isValid()) {
throw new BadRequestHttpException('Uploaded file is invalid');
}
if ($file->getClientOriginalName() === "blob" && $file->getClientMimeType() === "application/json") {
// a "upload by url" was done, we receive a tiny json that contains url.
$json = json_decode(file_get_contents($file->getRealPath()), true);
$url = $json['url'];
$pi = pathinfo($url); // filename, extension
$tempfile = $this->getTemporaryFilesystem()->createTemporaryFile('download_', null, $pi['extension']);
try {
$guzzle = new Guzzle($url);
$res = $guzzle->get("", [], ['save_to' => $tempfile])->send();
}
catch (\Exception $e) {
throw new BadRequestHttpException(sprintf('Error "%s" downloading "%s"', $e->getMessage(), $url));
}
if($res->getStatusCode() !== 200) {
throw new BadRequestHttpException(sprintf('Error %s downloading "%s"', $res->getStatusCode(), $url));
}
$uploadedFilename = $renamedFilename = $tempfile;
$originalName = $pi['filename'] . '.' . $pi['extension'];
} else {
// Add file extension, so mediavorus can guess file type for octet-stream file
$uploadedFilename = $file->getRealPath();
$renamedFilename = null;
if(!empty($this->app['conf']->get(['main', 'storage', 'tmp_files']))) {
$tmpStorage = \p4string::addEndSlash($this->app['conf']->get(['main', 'storage', 'tmp_files'])).'upload/';
if(!is_dir($tmpStorage)){
$this->getFilesystem()->mkdir($tmpStorage);
}
$renamedFilename = $tmpStorage. pathinfo($file->getRealPath(), PATHINFO_FILENAME) .'.' . pathinfo($file->getClientOriginalName(), PATHINFO_EXTENSION);
} else {
$renamedFilename = $file->getRealPath() . '.' . pathinfo($file->getClientOriginalName(), PATHINFO_EXTENSION);
}
$this->getFilesystem()->rename($uploadedFilename, $renamedFilename);
$originalName = $file->getClientOriginalName();
}
try {
$media = $this->app->getMediaFromUri($renamedFilename);
$collection = \collection::getByBaseId($this->app, $base_id);
$lazaretSession = new LazaretSession();
$lazaretSession->setUser($this->getAuthenticatedUser());
$this->getEntityManager()->persist($lazaretSession);
$packageFile = new File($this->app, $media, $collection, $originalName);
$postStatus = $request->request->get('status');
if (isset($postStatus[$collection->get_base_id()]) && is_array($postStatus[$collection->get_base_id()])) {
$postStatus = $postStatus[$collection->get_base_id()];
$status = '';
foreach (range(0, 31) as $i) {
$status .= isset($postStatus[$i]) ? ($postStatus[$i] ? '1' : '0') : '0';
}
$packageFile->addAttribute(new Status($this->app, strrev($status)));
}
$forceBehavior = $request->request->get('forceAction');
$reasons = [];
$elementCreated = null;
$callback = function ($element, Visa $visa) use (&$reasons, &$elementCreated) {
foreach ($visa->getResponses() as $response) {
if (!$response->isOk()) {
$reasons[] = $response->getMessage($this->app['translator']);
}
}
$elementCreated = $element;
};
$code = $this->getBorderManager()->process( $lazaretSession, $packageFile, $callback, $forceBehavior);
if($renamedFilename !== $uploadedFilename) {
$this->getFilesystem()->rename($renamedFilename, $uploadedFilename);
}
if (!!$forceBehavior) {
$reasons = [];
}
if ($elementCreated instanceof \record_adapter) {
$id = $elementCreated->getId();
$element = 'record';
$message = $this->app->trans('The record was successfully created');
$this->dispatch(PhraseaEvents::RECORD_UPLOAD, new RecordEdit($elementCreated));
// try to create thumbnail from data URI
if ('' !== $b64Image = $request->request->get('b64_image', '')) {
try {
$dataUri = Parser::parse($b64Image);
$fileName = $this->getTemporaryFilesystem()->createTemporaryFile('base_64_thumb', null, "png");
file_put_contents($fileName, $dataUri->getData());
$media = $this->app->getMediaFromUri($fileName);
$this->getSubDefinitionSubstituer()->substituteSubdef($elementCreated, 'thumbnail', $media);
$this->getDataboxLogger($elementCreated->getDatabox())
->log($elementCreated, \Session_Logger::EVENT_SUBSTITUTE, 'thumbnail', '');
unset($media);
$this->getTemporaryFilesystem()->clean('base_64_thumb');
} catch (DataUriException $e) {
}
}
} else {
/** @var LazaretFile $elementCreated */
$this->dispatch(PhraseaEvents::LAZARET_CREATE, new LazaretEvent($elementCreated));
$id = $elementCreated->getId();
$element = 'lazaret';
$message = $this->app->trans('The file was moved to the quarantine');
}
$data = [
'success' => true,
'code' => $code,
'message' => $message,
'element' => $element,
'reasons' => $reasons,
'id' => $id,
];
} catch (\Exception $e) {
$data['message'] = $this->app->trans('Unable to add file to Phraseanet');
}
$response = $this->app->json($data);
// IE 7 and 8 does not correctly handle json response in file API
// lets send them an html content-type header
$response->headers->set('Content-type', 'text/html');
return $response;
} | [
"public",
"function",
"upload",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"data",
"=",
"[",
"'success'",
"=>",
"false",
",",
"'code'",
"=>",
"null",
",",
"'message'",
"=>",
"''",
",",
"'element'",
"=>",
"''",
",",
"'reasons'",
"=>",
"[",
"]",
",... | Upload processus
@param Request $request The current request
parameters : 'bas_id' int (mandatory) : The id of the destination collection
'status' array (optional) : The status to set to new uploaded files
'attributes' array (optional) : Attributes id's to attach to the uploaded files
'forceBehavior' int (optional) : Force upload behavior
- 0 Force record
- 1 Force lazaret
@return Response | [
"Upload",
"processus"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Prod/UploadController.php#L118-L303 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Prod/UploadController.php | UploadController.getGrantedCollections | private function getGrantedCollections(\ACL $acl)
{
$collections = [];
foreach ($acl->get_granted_sbas() as $databox) {
$sbasId = $databox->get_sbas_id();
foreach ($acl->get_granted_base([\ACL::CANADDRECORD], [$sbasId]) as $collection) {
$databox = $collection->get_databox();
if (!isset($collections[$sbasId])) {
$collections[$databox->get_sbas_id()] = [
'databox' => $databox,
'databox_collections' => []
];
}
$collections[$databox->get_sbas_id()]['databox_collections'][] = $collection;
/** @var DisplaySettingService $settings */
$settings = $this->app['settings'];
$userOrderSetting = $settings->getUserSetting($this->app->getAuthenticatedUser(), 'order_collection_by');
// a temporary array to sort the collections
$aName = [];
list($ukey, $uorder) = ["order", SORT_ASC]; // default ORDER_BY_ADMIN
switch ($userOrderSetting) {
case $settings::ORDER_ALPHA_ASC :
list($ukey, $uorder) = ["name", SORT_ASC];
break;
case $settings::ORDER_ALPHA_DESC :
list($ukey, $uorder) = ["name", SORT_DESC];
break;
}
foreach ($collections[$databox->get_sbas_id()]['databox_collections'] as $key => $row) {
if ($ukey == "order") {
$aName[$key] = $row->get_ord();
}
else {
$aName[$key] = $row->get_name();
}
}
// sort the collections
array_multisort($aName, $uorder, SORT_REGULAR, $collections[$databox->get_sbas_id()]['databox_collections']);
}
}
return $collections;
} | php | private function getGrantedCollections(\ACL $acl)
{
$collections = [];
foreach ($acl->get_granted_sbas() as $databox) {
$sbasId = $databox->get_sbas_id();
foreach ($acl->get_granted_base([\ACL::CANADDRECORD], [$sbasId]) as $collection) {
$databox = $collection->get_databox();
if (!isset($collections[$sbasId])) {
$collections[$databox->get_sbas_id()] = [
'databox' => $databox,
'databox_collections' => []
];
}
$collections[$databox->get_sbas_id()]['databox_collections'][] = $collection;
/** @var DisplaySettingService $settings */
$settings = $this->app['settings'];
$userOrderSetting = $settings->getUserSetting($this->app->getAuthenticatedUser(), 'order_collection_by');
// a temporary array to sort the collections
$aName = [];
list($ukey, $uorder) = ["order", SORT_ASC]; // default ORDER_BY_ADMIN
switch ($userOrderSetting) {
case $settings::ORDER_ALPHA_ASC :
list($ukey, $uorder) = ["name", SORT_ASC];
break;
case $settings::ORDER_ALPHA_DESC :
list($ukey, $uorder) = ["name", SORT_DESC];
break;
}
foreach ($collections[$databox->get_sbas_id()]['databox_collections'] as $key => $row) {
if ($ukey == "order") {
$aName[$key] = $row->get_ord();
}
else {
$aName[$key] = $row->get_name();
}
}
// sort the collections
array_multisort($aName, $uorder, SORT_REGULAR, $collections[$databox->get_sbas_id()]['databox_collections']);
}
}
return $collections;
} | [
"private",
"function",
"getGrantedCollections",
"(",
"\\",
"ACL",
"$",
"acl",
")",
"{",
"$",
"collections",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"acl",
"->",
"get_granted_sbas",
"(",
")",
"as",
"$",
"databox",
")",
"{",
"$",
"sbasId",
"=",
"$",
"... | Get current user's granted collections where he can upload
@param \ACL $acl The user's ACL.
@return array | [
"Get",
"current",
"user",
"s",
"granted",
"collections",
"where",
"he",
"can",
"upload"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Prod/UploadController.php#L312-L355 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Prod/UploadController.php | UploadController.getUploadMaxFileSize | private function getUploadMaxFileSize()
{
$postMaxSize = trim(ini_get('post_max_size'));
if ('' === $postMaxSize) {
$postMaxSize = PHP_INT_MAX;
}
switch (strtolower(substr($postMaxSize, -1))) {
/** @noinspection PhpMissingBreakStatementInspection */
case 'g':
$postMaxSize *= 1024;
/** @noinspection PhpMissingBreakStatementInspection */
case 'm':
$postMaxSize *= 1024;
case 'k':
$postMaxSize *= 1024;
}
return min(UploadedFile::getMaxFilesize(), (int) $postMaxSize);
} | php | private function getUploadMaxFileSize()
{
$postMaxSize = trim(ini_get('post_max_size'));
if ('' === $postMaxSize) {
$postMaxSize = PHP_INT_MAX;
}
switch (strtolower(substr($postMaxSize, -1))) {
/** @noinspection PhpMissingBreakStatementInspection */
case 'g':
$postMaxSize *= 1024;
/** @noinspection PhpMissingBreakStatementInspection */
case 'm':
$postMaxSize *= 1024;
case 'k':
$postMaxSize *= 1024;
}
return min(UploadedFile::getMaxFilesize(), (int) $postMaxSize);
} | [
"private",
"function",
"getUploadMaxFileSize",
"(",
")",
"{",
"$",
"postMaxSize",
"=",
"trim",
"(",
"ini_get",
"(",
"'post_max_size'",
")",
")",
";",
"if",
"(",
"''",
"===",
"$",
"postMaxSize",
")",
"{",
"$",
"postMaxSize",
"=",
"PHP_INT_MAX",
";",
"}",
... | Get POST max file size
@return integer | [
"Get",
"POST",
"max",
"file",
"size"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Prod/UploadController.php#L362-L382 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Cache/ArrayCache.php | ArrayCache.get | public function get($id)
{
if (!$this->contains($id)) {
throw new Exception(sprintf('Unable to find key %s', $id));
}
return $this->fetch($id);
} | php | public function get($id)
{
if (!$this->contains($id)) {
throw new Exception(sprintf('Unable to find key %s', $id));
}
return $this->fetch($id);
} | [
"public",
"function",
"get",
"(",
"$",
"id",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"contains",
"(",
"$",
"id",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"sprintf",
"(",
"'Unable to find key %s'",
",",
"$",
"id",
")",
")",
";",
"}",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Cache/ArrayCache.php#L46-L53 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Command/BuildMissingSubdefs.php | BuildMissingSubdefs.doExecute | protected function doExecute(InputInterface $input, OutputInterface $output)
{
$start = microtime(true);
$progressBar = new ProgressBar($output);
$generatedSubdefs = 0;
foreach ($this->container->getDataboxes() as $databox) {
$sql = 'SELECT record_id FROM record WHERE parent_record_id = 0';
$result = $databox->get_connection()->executeQuery($sql)->fetchAll(\PDO::FETCH_ASSOC);
$progressBar->start(count($result));
foreach ($result as $row) {
$record = $databox->get_record($row['record_id']);
$generatedSubdefs += $this->generateRecordMissingSubdefs($record);
$progressBar->advance();
}
$progressBar->finish();
}
$this->container['monolog']->addInfo($generatedSubdefs . " subdefs done");
$stop = microtime(true);
$duration = $stop - $start;
$this->container['monolog']->addInfo(sprintf("process took %s, (%f sd/s.)", $this->getFormattedDuration($duration), round($generatedSubdefs / $duration, 3)));
$progressBar->finish();
} | php | protected function doExecute(InputInterface $input, OutputInterface $output)
{
$start = microtime(true);
$progressBar = new ProgressBar($output);
$generatedSubdefs = 0;
foreach ($this->container->getDataboxes() as $databox) {
$sql = 'SELECT record_id FROM record WHERE parent_record_id = 0';
$result = $databox->get_connection()->executeQuery($sql)->fetchAll(\PDO::FETCH_ASSOC);
$progressBar->start(count($result));
foreach ($result as $row) {
$record = $databox->get_record($row['record_id']);
$generatedSubdefs += $this->generateRecordMissingSubdefs($record);
$progressBar->advance();
}
$progressBar->finish();
}
$this->container['monolog']->addInfo($generatedSubdefs . " subdefs done");
$stop = microtime(true);
$duration = $stop - $start;
$this->container['monolog']->addInfo(sprintf("process took %s, (%f sd/s.)", $this->getFormattedDuration($duration), round($generatedSubdefs / $duration, 3)));
$progressBar->finish();
} | [
"protected",
"function",
"doExecute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"start",
"=",
"microtime",
"(",
"true",
")",
";",
"$",
"progressBar",
"=",
"new",
"ProgressBar",
"(",
"$",
"output",
")",
";",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/BuildMissingSubdefs.php#L33-L61 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Command/BuildMissingSubdefs.php | BuildMissingSubdefs.generateRecordMissingSubdefs | protected function generateRecordMissingSubdefs(\record_adapter $record)
{
$wanted_subdefs = $record->get_missing_subdefs();
if (!empty($wanted_subdefs)) {
$this->getSubdefGenerator()->generateSubdefs($record, $wanted_subdefs);
foreach ($wanted_subdefs as $subdef) {
$this->container['monolog']->addInfo("generate " . $subdef . " for record " . $record->getRecordId());
}
}
return count($wanted_subdefs);
} | php | protected function generateRecordMissingSubdefs(\record_adapter $record)
{
$wanted_subdefs = $record->get_missing_subdefs();
if (!empty($wanted_subdefs)) {
$this->getSubdefGenerator()->generateSubdefs($record, $wanted_subdefs);
foreach ($wanted_subdefs as $subdef) {
$this->container['monolog']->addInfo("generate " . $subdef . " for record " . $record->getRecordId());
}
}
return count($wanted_subdefs);
} | [
"protected",
"function",
"generateRecordMissingSubdefs",
"(",
"\\",
"record_adapter",
"$",
"record",
")",
"{",
"$",
"wanted_subdefs",
"=",
"$",
"record",
"->",
"get_missing_subdefs",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"wanted_subdefs",
")",
")",... | Generate subdef generation and return number of subdef
@param \record_adapter $record
@return int | [
"Generate",
"subdef",
"generation",
"and",
"return",
"number",
"of",
"subdef"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/BuildMissingSubdefs.php#L68-L81 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/Upgrade39Users.php | Upgrade39Users.apply | public function apply(EntityManager $em, \appbox $appbox, Configuration $conf)
{
// Sanitize usr table
$this->sanitizeUsrTable($em);
// Creates User schema
$version = $conf->getVersion('20131118000009');
if (false === $version->isMigrated()) {
$version->execute('up');
}
$version = $conf->getVersion('20131118000007');
if (false === $version->isMigrated()) {
$version->execute('up');
}
$this->alterTablesUp($em);
try {
$em->getConnection()->beginTransaction();
$em->getConnection()->query('SET FOREIGN_KEY_CHECKS=0');
// Creates user entities
$this->updateUsers($em);
$this->updateFtpSettings($em);
// Creates user model references
$this->updateTemplateOwner($em);
$this->updateLastAppliedModels($em);
$this->cleanForeignKeyReferences($em);
$em->getConnection()->query('SET FOREIGN_KEY_CHECKS=1');
$em->getConnection()->commit();
$this->renameTable($em, 'up');
} catch (\Exception $e) {
$em->getConnection()->rollback();
$em->close();
throw $e;
}
} | php | public function apply(EntityManager $em, \appbox $appbox, Configuration $conf)
{
// Sanitize usr table
$this->sanitizeUsrTable($em);
// Creates User schema
$version = $conf->getVersion('20131118000009');
if (false === $version->isMigrated()) {
$version->execute('up');
}
$version = $conf->getVersion('20131118000007');
if (false === $version->isMigrated()) {
$version->execute('up');
}
$this->alterTablesUp($em);
try {
$em->getConnection()->beginTransaction();
$em->getConnection()->query('SET FOREIGN_KEY_CHECKS=0');
// Creates user entities
$this->updateUsers($em);
$this->updateFtpSettings($em);
// Creates user model references
$this->updateTemplateOwner($em);
$this->updateLastAppliedModels($em);
$this->cleanForeignKeyReferences($em);
$em->getConnection()->query('SET FOREIGN_KEY_CHECKS=1');
$em->getConnection()->commit();
$this->renameTable($em, 'up');
} catch (\Exception $e) {
$em->getConnection()->rollback();
$em->close();
throw $e;
}
} | [
"public",
"function",
"apply",
"(",
"EntityManager",
"$",
"em",
",",
"\\",
"appbox",
"$",
"appbox",
",",
"Configuration",
"$",
"conf",
")",
"{",
"// Sanitize usr table",
"$",
"this",
"->",
"sanitizeUsrTable",
"(",
"$",
"em",
")",
";",
"// Creates User schema",... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/Upgrade39Users.php#L29-L62 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/Upgrade39Users.php | Upgrade39Users.rollback | public function rollback(EntityManager $em, \appbox $appbox, Configuration $conf)
{
// truncate created tables
$this->emptyTables($em);
// rollback schema
$this->alterTablesDown($em);
$version = $conf->getVersion('20131118000007');
if ($version->isMigrated()) {
$version->execute('down');
}
$version = $conf->getVersion('20131118000009');
if ($version->isMigrated()) {
$version->execute('down');
}
} | php | public function rollback(EntityManager $em, \appbox $appbox, Configuration $conf)
{
// truncate created tables
$this->emptyTables($em);
// rollback schema
$this->alterTablesDown($em);
$version = $conf->getVersion('20131118000007');
if ($version->isMigrated()) {
$version->execute('down');
}
$version = $conf->getVersion('20131118000009');
if ($version->isMigrated()) {
$version->execute('down');
}
} | [
"public",
"function",
"rollback",
"(",
"EntityManager",
"$",
"em",
",",
"\\",
"appbox",
"$",
"appbox",
",",
"Configuration",
"$",
"conf",
")",
"{",
"// truncate created tables",
"$",
"this",
"->",
"emptyTables",
"(",
"$",
"em",
")",
";",
"// rollback schema",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/Upgrade39Users.php#L75-L89 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/Upgrade39Users.php | Upgrade39Users.tableExists | private function tableExists(EntityManager $em, $table)
{
return (Boolean) $em->createNativeQuery(
'SHOW TABLE STATUS WHERE Name = :table', (new ResultSetMapping())->addScalarResult('Name', 'Name')
)->setParameter(':table', $table)->getOneOrNullResult();
} | php | private function tableExists(EntityManager $em, $table)
{
return (Boolean) $em->createNativeQuery(
'SHOW TABLE STATUS WHERE Name = :table', (new ResultSetMapping())->addScalarResult('Name', 'Name')
)->setParameter(':table', $table)->getOneOrNullResult();
} | [
"private",
"function",
"tableExists",
"(",
"EntityManager",
"$",
"em",
",",
"$",
"table",
")",
"{",
"return",
"(",
"Boolean",
")",
"$",
"em",
"->",
"createNativeQuery",
"(",
"'SHOW TABLE STATUS WHERE Name = :table'",
",",
"(",
"new",
"ResultSetMapping",
"(",
")"... | Checks whether the table exists or not.
@param $tableName
@return boolean | [
"Checks",
"whether",
"the",
"table",
"exists",
"or",
"not",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/Upgrade39Users.php#L149-L154 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/Upgrade39Users.php | Upgrade39Users.sanitizeUsrTable | private function sanitizeUsrTable($em)
{
$rs = $em->createNativeQuery(
"SHOW FIELDS FROM usr WHERE Field = 'usr_login';",
(new ResultSetMapping())->addScalarResult('Type', 'Type')
)->getSingleResult();
if (0 !== strpos(strtolower($rs['Type']), 'varbinary')) {
return;
}
// As 'usr_login' field type is varbinary it can contain any charset (utf8 or latin1).
// Compare usr_login to usr_login converted to utf8>utf32>utf8 will detect broken char for latin1 encoded string.
// Detected 'usr_login' fields must be updated using CONVERT(CAST(usr_login AS CHAR CHARACTER SET latin1) USING utf8)
$rs = $em->createNativeQuery(
'SELECT t.usr_id, t.login_utf8 FROM (
SELECT usr_id,
usr_login AS login_unknown_charset,
CONVERT(CAST(usr_login AS CHAR CHARACTER SET latin1) USING utf8) login_utf8,
CONVERT(CONVERT(CAST(usr_login AS CHAR CHARACTER SET utf8) USING utf32) USING utf8) AS login_utf8_utf32_utf8
FROM usr
) AS t
WHERE t.login_utf8_utf32_utf8 != t.login_unknown_charset',
(new ResultSetMapping())
->addScalarResult('usr_id', 'usr_id')
->addScalarResult('login_utf8', 'login_utf8')
)->getResult();
foreach ($rs as $row) {
$em->getConnection()->executeUpdate(sprintf('UPDATE usr SET usr_login="%s" WHERE usr_id=%d', $row['login_utf8'], $row['usr_id']));
}
foreach ([
// drop index
"ALTER TABLE usr DROP INDEX usr_login;",
// change field type
"ALTER TABLE usr MODIFY usr_login VARCHAR(128) CHARACTER SET utf8 COLLATE utf8_bin;",
// recreate index
"CREATE UNIQUE INDEX usr_login ON usr (usr_login);"
] as $sql) {
$em->getConnection()->executeUpdate($sql);
}
} | php | private function sanitizeUsrTable($em)
{
$rs = $em->createNativeQuery(
"SHOW FIELDS FROM usr WHERE Field = 'usr_login';",
(new ResultSetMapping())->addScalarResult('Type', 'Type')
)->getSingleResult();
if (0 !== strpos(strtolower($rs['Type']), 'varbinary')) {
return;
}
// As 'usr_login' field type is varbinary it can contain any charset (utf8 or latin1).
// Compare usr_login to usr_login converted to utf8>utf32>utf8 will detect broken char for latin1 encoded string.
// Detected 'usr_login' fields must be updated using CONVERT(CAST(usr_login AS CHAR CHARACTER SET latin1) USING utf8)
$rs = $em->createNativeQuery(
'SELECT t.usr_id, t.login_utf8 FROM (
SELECT usr_id,
usr_login AS login_unknown_charset,
CONVERT(CAST(usr_login AS CHAR CHARACTER SET latin1) USING utf8) login_utf8,
CONVERT(CONVERT(CAST(usr_login AS CHAR CHARACTER SET utf8) USING utf32) USING utf8) AS login_utf8_utf32_utf8
FROM usr
) AS t
WHERE t.login_utf8_utf32_utf8 != t.login_unknown_charset',
(new ResultSetMapping())
->addScalarResult('usr_id', 'usr_id')
->addScalarResult('login_utf8', 'login_utf8')
)->getResult();
foreach ($rs as $row) {
$em->getConnection()->executeUpdate(sprintf('UPDATE usr SET usr_login="%s" WHERE usr_id=%d', $row['login_utf8'], $row['usr_id']));
}
foreach ([
// drop index
"ALTER TABLE usr DROP INDEX usr_login;",
// change field type
"ALTER TABLE usr MODIFY usr_login VARCHAR(128) CHARACTER SET utf8 COLLATE utf8_bin;",
// recreate index
"CREATE UNIQUE INDEX usr_login ON usr (usr_login);"
] as $sql) {
$em->getConnection()->executeUpdate($sql);
}
} | [
"private",
"function",
"sanitizeUsrTable",
"(",
"$",
"em",
")",
"{",
"$",
"rs",
"=",
"$",
"em",
"->",
"createNativeQuery",
"(",
"\"SHOW FIELDS FROM usr WHERE Field = 'usr_login';\"",
",",
"(",
"new",
"ResultSetMapping",
"(",
")",
")",
"->",
"addScalarResult",
"(",... | Fix character set in usr table.
@param $em | [
"Fix",
"character",
"set",
"in",
"usr",
"table",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/Upgrade39Users.php#L161-L203 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/Upgrade39Users.php | Upgrade39Users.emptyTables | private function emptyTables(EntityManager $em)
{
$meta = $em->getClassMetadata('Alchemy\Phrasea\Model\Entities\User');
$connection = $em->getConnection();
$dbPlatform = $connection->getDatabasePlatform();
if ($connection->getSchemaManager()->tablesExist([ $meta->getTableName() ])) {
$connection->beginTransaction();
try {
$connection->query('SET FOREIGN_KEY_CHECKS=0');
$connection->executeUpdate($dbPlatform->getTruncateTableSql($meta->getTableName()));
$connection->query('SET FOREIGN_KEY_CHECKS=1');
$connection->commit();
} catch (\Exception $e) {
$connection->rollback();
throw $e;
}
}
} | php | private function emptyTables(EntityManager $em)
{
$meta = $em->getClassMetadata('Alchemy\Phrasea\Model\Entities\User');
$connection = $em->getConnection();
$dbPlatform = $connection->getDatabasePlatform();
if ($connection->getSchemaManager()->tablesExist([ $meta->getTableName() ])) {
$connection->beginTransaction();
try {
$connection->query('SET FOREIGN_KEY_CHECKS=0');
$connection->executeUpdate($dbPlatform->getTruncateTableSql($meta->getTableName()));
$connection->query('SET FOREIGN_KEY_CHECKS=1');
$connection->commit();
} catch (\Exception $e) {
$connection->rollback();
throw $e;
}
}
} | [
"private",
"function",
"emptyTables",
"(",
"EntityManager",
"$",
"em",
")",
"{",
"$",
"meta",
"=",
"$",
"em",
"->",
"getClassMetadata",
"(",
"'Alchemy\\Phrasea\\Model\\Entities\\User'",
")",
";",
"$",
"connection",
"=",
"$",
"em",
"->",
"getConnection",
"(",
"... | Empty User & migration table.
@param EntityManager $em | [
"Empty",
"User",
"&",
"migration",
"table",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/Upgrade39Users.php#L295-L314 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/Upgrade39Users.php | Upgrade39Users.hasField | private function hasField(EntityManager $em, $fieldName)
{
return (Boolean) $em->createNativeQuery(
"SHOW FIELDS FROM usr WHERE Field = :field",
(new ResultSetMapping())->addScalarResult('Field', 'Field')
)->setParameter(':field', $fieldName)->getOneOrNullResult();
} | php | private function hasField(EntityManager $em, $fieldName)
{
return (Boolean) $em->createNativeQuery(
"SHOW FIELDS FROM usr WHERE Field = :field",
(new ResultSetMapping())->addScalarResult('Field', 'Field')
)->setParameter(':field', $fieldName)->getOneOrNullResult();
} | [
"private",
"function",
"hasField",
"(",
"EntityManager",
"$",
"em",
",",
"$",
"fieldName",
")",
"{",
"return",
"(",
"Boolean",
")",
"$",
"em",
"->",
"createNativeQuery",
"(",
"\"SHOW FIELDS FROM usr WHERE Field = :field\"",
",",
"(",
"new",
"ResultSetMapping",
"("... | Check whether the usr table has a nonce column or not.
@param EntityManager $em
@return boolean | [
"Check",
"whether",
"the",
"usr",
"table",
"has",
"a",
"nonce",
"column",
"or",
"not",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/Upgrade39Users.php#L323-L329 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/Upgrade39Users.php | Upgrade39Users.updateUsers | private function updateUsers(EntityManager $em)
{
$em->getConnection()->executeUpdate(
'INSERT INTO Users
(
id, activity, address, admin,
can_change_ftp_profil, can_change_profil, city, company,
country, email, fax, first_name,
geoname_id, guest, job, last_connection,
last_name, ldap_created, locale, login,
mail_locked, last_model, mail_notifications, nonce,
password, push_list, request_notifications, salted_password,
gender, phone, timezone, zip_code,
created, updated, deleted
)
(
SELECT
usr_id, activite, adresse, create_db,
canchgftpprofil, canchgprofil, ville, societe,
pays, usr_mail, fax, usr_prenom,
geonameid, invite, fonction, last_conn,
usr_nom, ldap_created, locale, usr_login,
mail_locked, NULL AS lastModel, mail_notifications, '.($this->hasField($em, 'nonce') ? 'nonce' : 'NULL AS nonce').',
usr_password, push_list, request_notifications, '.($this->hasField($em, 'salted_password') ? 'salted_password' : '0 AS salted_password').',
usr_sexe, tel, timezone, cpostal,
usr_creationdate, usr_modificationdate, 0
FROM usr
)'
);
$em->getConnection()->executeUpdate('UPDATE Users SET geoname_id=NULL WHERE geoname_id=0');
$em->getConnection()->executeUpdate(
'UPDATE Users SET locale=NULL WHERE locale NOT IN (:locales)',
['locales' => array_keys(Application::getAvailableLanguages())],
['locales' => Connection::PARAM_STR_ARRAY]
);
$em->getConnection()->executeUpdate('UPDATE Users SET deleted=1, login=SUBSTRING(login, 11) WHERE login LIKE "(#deleted_%"');
} | php | private function updateUsers(EntityManager $em)
{
$em->getConnection()->executeUpdate(
'INSERT INTO Users
(
id, activity, address, admin,
can_change_ftp_profil, can_change_profil, city, company,
country, email, fax, first_name,
geoname_id, guest, job, last_connection,
last_name, ldap_created, locale, login,
mail_locked, last_model, mail_notifications, nonce,
password, push_list, request_notifications, salted_password,
gender, phone, timezone, zip_code,
created, updated, deleted
)
(
SELECT
usr_id, activite, adresse, create_db,
canchgftpprofil, canchgprofil, ville, societe,
pays, usr_mail, fax, usr_prenom,
geonameid, invite, fonction, last_conn,
usr_nom, ldap_created, locale, usr_login,
mail_locked, NULL AS lastModel, mail_notifications, '.($this->hasField($em, 'nonce') ? 'nonce' : 'NULL AS nonce').',
usr_password, push_list, request_notifications, '.($this->hasField($em, 'salted_password') ? 'salted_password' : '0 AS salted_password').',
usr_sexe, tel, timezone, cpostal,
usr_creationdate, usr_modificationdate, 0
FROM usr
)'
);
$em->getConnection()->executeUpdate('UPDATE Users SET geoname_id=NULL WHERE geoname_id=0');
$em->getConnection()->executeUpdate(
'UPDATE Users SET locale=NULL WHERE locale NOT IN (:locales)',
['locales' => array_keys(Application::getAvailableLanguages())],
['locales' => Connection::PARAM_STR_ARRAY]
);
$em->getConnection()->executeUpdate('UPDATE Users SET deleted=1, login=SUBSTRING(login, 11) WHERE login LIKE "(#deleted_%"');
} | [
"private",
"function",
"updateUsers",
"(",
"EntityManager",
"$",
"em",
")",
"{",
"$",
"em",
"->",
"getConnection",
"(",
")",
"->",
"executeUpdate",
"(",
"'INSERT INTO Users\n (\n id, activity, address, adm... | Sets user entity from usr table. | [
"Sets",
"user",
"entity",
"from",
"usr",
"table",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/Upgrade39Users.php#L334-L371 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/Upgrade39Users.php | Upgrade39Users.updateTemplateOwner | private function updateTemplateOwner(EntityManager $em)
{
$em->getConnection()->executeUpdate('
UPDATE Users
INNER JOIN usr ON (
usr.usr_id = Users.id
AND usr.model_of IS NOT NULL
AND usr.model_of>0
)
SET Users.model_of = usr.model_of
');
$em->getConnection()->executeUpdate('
DELETE from Users
WHERE id IN (
SELECT id FROM (
SELECT templates.id
FROM Users users, Users templates
WHERE templates.model_of = users.id AND (users.deleted = 1 OR users.model_of IS NOT NULL)
) as temporaryTable
)
');
$em->getConnection()->executeUpdate('
DELETE from Users
WHERE id IN (
SELECT id FROM (
SELECT templates.id
FROM Users templates
WHERE templates.model_of NOT IN (SELECT id FROM Users)
) as temporaryTable
)
');
$em->getConnection()->executeUpdate(' DELETE from Users WHERE deleted = 1 AND model_of IS NOT NULL');
} | php | private function updateTemplateOwner(EntityManager $em)
{
$em->getConnection()->executeUpdate('
UPDATE Users
INNER JOIN usr ON (
usr.usr_id = Users.id
AND usr.model_of IS NOT NULL
AND usr.model_of>0
)
SET Users.model_of = usr.model_of
');
$em->getConnection()->executeUpdate('
DELETE from Users
WHERE id IN (
SELECT id FROM (
SELECT templates.id
FROM Users users, Users templates
WHERE templates.model_of = users.id AND (users.deleted = 1 OR users.model_of IS NOT NULL)
) as temporaryTable
)
');
$em->getConnection()->executeUpdate('
DELETE from Users
WHERE id IN (
SELECT id FROM (
SELECT templates.id
FROM Users templates
WHERE templates.model_of NOT IN (SELECT id FROM Users)
) as temporaryTable
)
');
$em->getConnection()->executeUpdate(' DELETE from Users WHERE deleted = 1 AND model_of IS NOT NULL');
} | [
"private",
"function",
"updateTemplateOwner",
"(",
"EntityManager",
"$",
"em",
")",
"{",
"$",
"em",
"->",
"getConnection",
"(",
")",
"->",
"executeUpdate",
"(",
"'\n UPDATE Users\n INNER JOIN usr ON (\n usr.usr_id = Users.id\n ... | Sets model from usr table. | [
"Sets",
"model",
"from",
"usr",
"table",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/Upgrade39Users.php#L458-L494 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Prod/ExportController.php | ExportController.displayMultiExport | public function displayMultiExport(Request $request)
{
$download = new \set_export(
$this->app,
$request->request->get('lst', ''),
$request->request->get('ssel', ''),
$request->request->get('story')
);
return new Response($this->render('common/dialog_export.html.twig', [
'download' => $download,
'ssttid' => $request->request->get('ssel'),
'lst' => $download->serialize_list(),
'default_export_title' => $this->getConf()->get(['registry', 'actions', 'default-export-title']),
'choose_export_title' => $this->getConf()->get(['registry', 'actions', 'export-title-choice'])
]));
} | php | public function displayMultiExport(Request $request)
{
$download = new \set_export(
$this->app,
$request->request->get('lst', ''),
$request->request->get('ssel', ''),
$request->request->get('story')
);
return new Response($this->render('common/dialog_export.html.twig', [
'download' => $download,
'ssttid' => $request->request->get('ssel'),
'lst' => $download->serialize_list(),
'default_export_title' => $this->getConf()->get(['registry', 'actions', 'default-export-title']),
'choose_export_title' => $this->getConf()->get(['registry', 'actions', 'export-title-choice'])
]));
} | [
"public",
"function",
"displayMultiExport",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"download",
"=",
"new",
"\\",
"set_export",
"(",
"$",
"this",
"->",
"app",
",",
"$",
"request",
"->",
"request",
"->",
"get",
"(",
"'lst'",
",",
"''",
")",
",",
... | Display form to export documents
@param Request $request
@return Response | [
"Display",
"form",
"to",
"export",
"documents"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Prod/ExportController.php#L40-L56 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Prod/ExportController.php | ExportController.exportMail | public function exportMail(Request $request)
{
set_time_limit(0);
session_write_close();
ignore_user_abort(true);
$lst = $request->request->get('lst', '');
$ssttid = $request->request->get('ssttid', '');
//prepare export
$download = new \set_export($this->app, $lst, $ssttid);
$list = $download->prepare_export(
$this->getAuthenticatedUser(),
$this->getFilesystem(),
(array) $request->request->get('obj'),
$request->request->get("type") == "title" ? : false,
$request->request->get('businessfields')
);
$list['export_name'] = sprintf("%s.zip", $download->getExportName());
$separator = '/\ |\;|\,/';
// add PREG_SPLIT_NO_EMPTY to only return non-empty values
$list['email'] = implode(';', preg_split($separator, $request->request->get("destmail", ""), -1, PREG_SPLIT_NO_EMPTY));
$destMails = [];
//get destination mails
foreach (explode(";", $list['email']) as $mail) {
if (filter_var($mail, FILTER_VALIDATE_EMAIL)) {
$destMails[] = $mail;
} else {
$this->dispatch(PhraseaEvents::EXPORT_MAIL_FAILURE, new ExportFailureEvent(
$this->getAuthenticatedUser(),
$ssttid,
$lst,
\eventsmanager_notify_downloadmailfail::MAIL_NO_VALID,
$mail
));
}
}
$token = $this->getTokenManipulator()->createEmailExportToken(serialize($list));
if (count($destMails) > 0) {
//zip documents
\set_export::build_zip(
$this->app,
$token,
$list,
$this->app['tmp.download.path'].'/'. $token->getValue() . '.zip'
);
$remaingEmails = $destMails;
$url = $this->app->url('prepare_download', ['token' => $token->getValue(), 'anonymous' => false, 'type' => \Session_Logger::EVENT_EXPORTMAIL]);
$user = $this->getAuthenticatedUser();
$emitter = new Emitter($user->getDisplayName(), $user->getEmail());
foreach ($destMails as $key => $mail) {
try {
$receiver = new Receiver(null, trim($mail));
} catch (InvalidArgumentException $e) {
continue;
}
$mail = MailRecordsExport::create($this->app, $receiver, $emitter, $request->request->get('textmail'));
$mail->setButtonUrl($url);
$mail->setExpiration($token->getExpiration());
$this->deliver($mail, !!$request->request->get('reading_confirm', false));
unset($remaingEmails[$key]);
}
//some mails failed
if (count($remaingEmails) > 0) {
foreach ($remaingEmails as $mail) {
$this->dispatch(PhraseaEvents::EXPORT_MAIL_FAILURE, new ExportFailureEvent($this->getAuthenticatedUser(), $ssttid, $lst, \eventsmanager_notify_downloadmailfail::MAIL_FAIL, $mail));
}
}
}
return $this->app->json([
'success' => true,
'message' => ''
]);
} | php | public function exportMail(Request $request)
{
set_time_limit(0);
session_write_close();
ignore_user_abort(true);
$lst = $request->request->get('lst', '');
$ssttid = $request->request->get('ssttid', '');
//prepare export
$download = new \set_export($this->app, $lst, $ssttid);
$list = $download->prepare_export(
$this->getAuthenticatedUser(),
$this->getFilesystem(),
(array) $request->request->get('obj'),
$request->request->get("type") == "title" ? : false,
$request->request->get('businessfields')
);
$list['export_name'] = sprintf("%s.zip", $download->getExportName());
$separator = '/\ |\;|\,/';
// add PREG_SPLIT_NO_EMPTY to only return non-empty values
$list['email'] = implode(';', preg_split($separator, $request->request->get("destmail", ""), -1, PREG_SPLIT_NO_EMPTY));
$destMails = [];
//get destination mails
foreach (explode(";", $list['email']) as $mail) {
if (filter_var($mail, FILTER_VALIDATE_EMAIL)) {
$destMails[] = $mail;
} else {
$this->dispatch(PhraseaEvents::EXPORT_MAIL_FAILURE, new ExportFailureEvent(
$this->getAuthenticatedUser(),
$ssttid,
$lst,
\eventsmanager_notify_downloadmailfail::MAIL_NO_VALID,
$mail
));
}
}
$token = $this->getTokenManipulator()->createEmailExportToken(serialize($list));
if (count($destMails) > 0) {
//zip documents
\set_export::build_zip(
$this->app,
$token,
$list,
$this->app['tmp.download.path'].'/'. $token->getValue() . '.zip'
);
$remaingEmails = $destMails;
$url = $this->app->url('prepare_download', ['token' => $token->getValue(), 'anonymous' => false, 'type' => \Session_Logger::EVENT_EXPORTMAIL]);
$user = $this->getAuthenticatedUser();
$emitter = new Emitter($user->getDisplayName(), $user->getEmail());
foreach ($destMails as $key => $mail) {
try {
$receiver = new Receiver(null, trim($mail));
} catch (InvalidArgumentException $e) {
continue;
}
$mail = MailRecordsExport::create($this->app, $receiver, $emitter, $request->request->get('textmail'));
$mail->setButtonUrl($url);
$mail->setExpiration($token->getExpiration());
$this->deliver($mail, !!$request->request->get('reading_confirm', false));
unset($remaingEmails[$key]);
}
//some mails failed
if (count($remaingEmails) > 0) {
foreach ($remaingEmails as $mail) {
$this->dispatch(PhraseaEvents::EXPORT_MAIL_FAILURE, new ExportFailureEvent($this->getAuthenticatedUser(), $ssttid, $lst, \eventsmanager_notify_downloadmailfail::MAIL_FAIL, $mail));
}
}
}
return $this->app->json([
'success' => true,
'message' => ''
]);
} | [
"public",
"function",
"exportMail",
"(",
"Request",
"$",
"request",
")",
"{",
"set_time_limit",
"(",
"0",
")",
";",
"session_write_close",
"(",
")",
";",
"ignore_user_abort",
"(",
"true",
")",
";",
"$",
"lst",
"=",
"$",
"request",
"->",
"request",
"->",
... | Export document by mail
@param Request $request
@return JsonResponse | [
"Export",
"document",
"by",
"mail"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Prod/ExportController.php#L152-L238 |
alchemy-fr/Phraseanet | lib/classes/module/report/activity.php | module_report_activity.getAllQuestionByUser | public function getAllQuestionByUser($value, $what)
{
$result = [];
$sqlBuilder = new module_report_sql($this->app, $this);
$filter = $sqlBuilder->getFilters()->getReportFilter();
$params = array_merge([':main_value' => $value], $filter['params']);
$sql = "
SELECT DATE_FORMAT(log_search.date,'%Y-%m-%d %H:%i:%S') AS date ,
log_search.search ,log_search.results
FROM (log_search)
INNER JOIN log FORCE INDEX (date_site) ON (log.id = log_search.log_id)
INNER JOIN log_colls FORCE INDEX (couple) ON (log.id = log_colls.log_id)
WHERE (" . $filter['sql'] . ")
AND log.`" . $what . "` = :main_value
ORDER BY date ";
$stmt = $sqlBuilder->getConnBas()->prepare($sql);
$stmt->execute($params);
$sqlBuilder->setTotalrows($stmt->rowCount());
$stmt->closeCursor();
$sql .= $sqlBuilder->getFilters()->getLimitFilter();
$stmt = $sqlBuilder->getConnBas()->prepare($sql);
$stmt->execute($params);
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$this->setChamp($rs);
$this->initDefaultConfigColumn($this->champ);
$i = 0;
foreach ($rs as $row) {
foreach ($this->champ as $value) {
$result[$i][$value] = $row[$value];
}
$i++;
}
$this->title = $this->app->trans('report:: questions');
$this->setResult($result);
return $this->result;
} | php | public function getAllQuestionByUser($value, $what)
{
$result = [];
$sqlBuilder = new module_report_sql($this->app, $this);
$filter = $sqlBuilder->getFilters()->getReportFilter();
$params = array_merge([':main_value' => $value], $filter['params']);
$sql = "
SELECT DATE_FORMAT(log_search.date,'%Y-%m-%d %H:%i:%S') AS date ,
log_search.search ,log_search.results
FROM (log_search)
INNER JOIN log FORCE INDEX (date_site) ON (log.id = log_search.log_id)
INNER JOIN log_colls FORCE INDEX (couple) ON (log.id = log_colls.log_id)
WHERE (" . $filter['sql'] . ")
AND log.`" . $what . "` = :main_value
ORDER BY date ";
$stmt = $sqlBuilder->getConnBas()->prepare($sql);
$stmt->execute($params);
$sqlBuilder->setTotalrows($stmt->rowCount());
$stmt->closeCursor();
$sql .= $sqlBuilder->getFilters()->getLimitFilter();
$stmt = $sqlBuilder->getConnBas()->prepare($sql);
$stmt->execute($params);
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$this->setChamp($rs);
$this->initDefaultConfigColumn($this->champ);
$i = 0;
foreach ($rs as $row) {
foreach ($this->champ as $value) {
$result[$i][$value] = $row[$value];
}
$i++;
}
$this->title = $this->app->trans('report:: questions');
$this->setResult($result);
return $this->result;
} | [
"public",
"function",
"getAllQuestionByUser",
"(",
"$",
"value",
",",
"$",
"what",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"$",
"sqlBuilder",
"=",
"new",
"module_report_sql",
"(",
"$",
"this",
"->",
"app",
",",
"$",
"this",
")",
";",
"$",
"filte... | Get all questions by user
@param string $value
@param string $what | [
"Get",
"all",
"questions",
"by",
"user"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/module/report/activity.php#L148-L194 |
alchemy-fr/Phraseanet | lib/classes/module/report/activity.php | module_report_activity.getTopQuestion | public function getTopQuestion($tab = false, $no_answer = false)
{
$this->report['value'] = [];
$this->report['value2'] = [];
$this->setDateField('log_search.date');
$sqlBuilder = new module_report_sql($this->app, $this);
$filter = $sqlBuilder->getFilters()->getReportFilter();
$params = array_merge([], $filter['params']);
($no_answer) ? $this->title = $this->app->trans('report:: questions sans reponses') : $this->title = $this->app->trans('report:: questions les plus posees');
$sql = "
SELECT TRIM(log_search.search) AS search, COUNT(log_search.id) AS nb, ROUND(avg(results)) AS nb_rep
FROM (log_search)
INNER JOIN log FORCE INDEX (date_site) ON (log_search.log_id = log.id)
WHERE (" . $filter['sql'] . ") AND !ISNULL(usrid)
AND log_search.search != 'all' " .
($no_answer ? ' AND log_search.results = 0 ' : '') . "
GROUP BY search
ORDER BY nb DESC";
// no_file_put_contents("/tmp/report.txt", sprintf("%s (%s)\n%s\n\n", __FILE__, __LINE__, $sql), FILE_APPEND);
$sql .= !$no_answer ? ' LIMIT ' . $this->nb_top : '';
$stmt = $sqlBuilder->getConnBas()->prepare($sql);
$stmt->execute($params);
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$this->setChamp($rs);
$this->setDisplay($tab);
$i = 0;
foreach ($rs as $row) {
foreach ($this->champ as $value) {
$this->result[$i][$value] = $row[$value];
}
$i++;
$this->report['legend'][] = $row['search'];
$this->report['value'][] = $row['nb'];
$this->report['value2'][] = $row['nb_rep'];
}
$this->total = sizeof($this->result);
//calculate prev and next page
$this->calculatePages();
//do we display navigator ?
$this->setDisplayNav();
//set report
$this->setReport();
return $this->report;
} | php | public function getTopQuestion($tab = false, $no_answer = false)
{
$this->report['value'] = [];
$this->report['value2'] = [];
$this->setDateField('log_search.date');
$sqlBuilder = new module_report_sql($this->app, $this);
$filter = $sqlBuilder->getFilters()->getReportFilter();
$params = array_merge([], $filter['params']);
($no_answer) ? $this->title = $this->app->trans('report:: questions sans reponses') : $this->title = $this->app->trans('report:: questions les plus posees');
$sql = "
SELECT TRIM(log_search.search) AS search, COUNT(log_search.id) AS nb, ROUND(avg(results)) AS nb_rep
FROM (log_search)
INNER JOIN log FORCE INDEX (date_site) ON (log_search.log_id = log.id)
WHERE (" . $filter['sql'] . ") AND !ISNULL(usrid)
AND log_search.search != 'all' " .
($no_answer ? ' AND log_search.results = 0 ' : '') . "
GROUP BY search
ORDER BY nb DESC";
// no_file_put_contents("/tmp/report.txt", sprintf("%s (%s)\n%s\n\n", __FILE__, __LINE__, $sql), FILE_APPEND);
$sql .= !$no_answer ? ' LIMIT ' . $this->nb_top : '';
$stmt = $sqlBuilder->getConnBas()->prepare($sql);
$stmt->execute($params);
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$this->setChamp($rs);
$this->setDisplay($tab);
$i = 0;
foreach ($rs as $row) {
foreach ($this->champ as $value) {
$this->result[$i][$value] = $row[$value];
}
$i++;
$this->report['legend'][] = $row['search'];
$this->report['value'][] = $row['nb'];
$this->report['value2'][] = $row['nb_rep'];
}
$this->total = sizeof($this->result);
//calculate prev and next page
$this->calculatePages();
//do we display navigator ?
$this->setDisplayNav();
//set report
$this->setReport();
return $this->report;
} | [
"public",
"function",
"getTopQuestion",
"(",
"$",
"tab",
"=",
"false",
",",
"$",
"no_answer",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"report",
"[",
"'value'",
"]",
"=",
"[",
"]",
";",
"$",
"this",
"->",
"report",
"[",
"'value2'",
"]",
"=",
"[",... | get the most asked question
@param array $tab config for html table
@param bool $no_answer true for question with no answer | [
"get",
"the",
"most",
"asked",
"question"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/module/report/activity.php#L202-L259 |
alchemy-fr/Phraseanet | lib/classes/module/report/activity.php | module_report_activity.getDetailDownload | public function getDetailDownload($tab = false, $on = "")
{
empty($on) ? $on = "user" : ""; //by default always report on user
//set title
$this->title = $this->app->trans('report:: Detail des telechargements');
$this->setDateField('log_docs.date');
$sqlBuilder = new module_report_sql($this->app, $this);
$filter = $sqlBuilder->getFilters()->getReportFilter();
$params = array_merge([], $filter['params']);
$sql = "
SELECT TRIM(" . $on . ") AS " . $on . ", SUM(1) AS nb, log_docs.final, log.usrid
FROM log_docs
INNER JOIN log FORCE INDEX (date_site) ON (log.id = log_docs.log_id)
LEFT JOIN record ON (record.record_id = log_docs.record_id)
WHERE (" . $filter['sql'] . ") AND !ISNULL(usrid)
AND (log_docs.action = 'download' OR log_docs.action = 'mail')
AND (log_docs.final = 'preview' OR log_docs.final = 'document')
GROUP BY usrid";
// no_file_put_contents("/tmp/report.txt", sprintf("%s (%s)\n%s\n\n", __FILE__, __LINE__, $sql), FILE_APPEND);
$stmt = $sqlBuilder->getConnBas()->prepare($sql);
$stmt->execute($params);
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$save_user = "";
$i = -1;
$total = [
'nbdoc' => 0,
'nbprev' => 0,
];
$this->setChamp($rs);
$this->setDisplay($tab);
foreach ($rs as $row) {
$user = $row[$on];
if (($save_user != $user) && ! is_null($user) && ! empty($user)) {
if ($i >= 0) {
if (($this->result[$i]['nbprev'] + $this->result[$i]['nbdoc']) == 0) {
unset($this->result[$i]);
}
}
$i ++;
$this->result[$i]['nbprev'] = 0;
$this->result[$i]['nbdoc'] = 0;
}
//doc info
if ($row['final'] == 'document' &&
! is_null($user) && ! is_null($row['usrid'])) {
$this->result[$i]['nbdoc'] = ( ! is_null($row['nb']) ? $row['nb'] : 0);
$this->result[$i]['user'] = empty($row[$on]) ?
"<i>" . $this->app->trans('report:: non-renseigne') . "</i>" : $row[$on];
$total['nbdoc'] += $this->result[$i]['nbdoc'];
$this->result[$i]['usrid'] = $row['usrid'];
}
//preview info
if (($row['final'] == 'preview') &&
! is_null($user) &&
! is_null($row['usrid'])) {
$this->result[$i]['nbprev'] += ( ! is_null($row['nb']) ? $row['nb'] : 0);
$this->result[$i]['user'] = empty($row[$on]) ?
"<i>" . $this->app->trans('report:: non-renseigne') . "</i>" : $row[$on];
$total['nbprev'] += ( ! is_null($row['nb']) ? $row['nb'] : 0);
$this->result[$i]['usrid'] = $row['usrid'];
}
$save_user = $user;
}
unset($this->result[$i]);
$nb_row = $i + 1;
$this->total = $nb_row;
if ($this->total > 0) {
$this->result[$nb_row]['user'] = '<b>TOTAL</b>';
$this->result[$nb_row]['nbdoc'] = '<b>' . $total['nbdoc'] . '</b>';
$this->result[$nb_row]['nbprev'] = '<b>' . $total['nbprev'] . '</b>';
}
foreach($this->result as $k=>$row) {
$_row = array();
foreach((array) $tab as $k2=>$f) {
$_row[$k2] = array_key_exists($k2, $row) ? $row[$k2] : '';
}
$_row['usrid'] = array_key_exists('usrid', $row) ? $row['usrid'] : '';
$this->result[$k] = $_row;
}
// no_file_put_contents("/tmp/report.txt", sprintf("%s (%s) %s\n\n", __FILE__, __LINE__, var_export($this->result, true)), FILE_APPEND);
$this->total = sizeof($this->result);
$this->calculatePages();
$this->setDisplayNav();
$this->setReport();
return $this->report;
} | php | public function getDetailDownload($tab = false, $on = "")
{
empty($on) ? $on = "user" : ""; //by default always report on user
//set title
$this->title = $this->app->trans('report:: Detail des telechargements');
$this->setDateField('log_docs.date');
$sqlBuilder = new module_report_sql($this->app, $this);
$filter = $sqlBuilder->getFilters()->getReportFilter();
$params = array_merge([], $filter['params']);
$sql = "
SELECT TRIM(" . $on . ") AS " . $on . ", SUM(1) AS nb, log_docs.final, log.usrid
FROM log_docs
INNER JOIN log FORCE INDEX (date_site) ON (log.id = log_docs.log_id)
LEFT JOIN record ON (record.record_id = log_docs.record_id)
WHERE (" . $filter['sql'] . ") AND !ISNULL(usrid)
AND (log_docs.action = 'download' OR log_docs.action = 'mail')
AND (log_docs.final = 'preview' OR log_docs.final = 'document')
GROUP BY usrid";
// no_file_put_contents("/tmp/report.txt", sprintf("%s (%s)\n%s\n\n", __FILE__, __LINE__, $sql), FILE_APPEND);
$stmt = $sqlBuilder->getConnBas()->prepare($sql);
$stmt->execute($params);
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$save_user = "";
$i = -1;
$total = [
'nbdoc' => 0,
'nbprev' => 0,
];
$this->setChamp($rs);
$this->setDisplay($tab);
foreach ($rs as $row) {
$user = $row[$on];
if (($save_user != $user) && ! is_null($user) && ! empty($user)) {
if ($i >= 0) {
if (($this->result[$i]['nbprev'] + $this->result[$i]['nbdoc']) == 0) {
unset($this->result[$i]);
}
}
$i ++;
$this->result[$i]['nbprev'] = 0;
$this->result[$i]['nbdoc'] = 0;
}
//doc info
if ($row['final'] == 'document' &&
! is_null($user) && ! is_null($row['usrid'])) {
$this->result[$i]['nbdoc'] = ( ! is_null($row['nb']) ? $row['nb'] : 0);
$this->result[$i]['user'] = empty($row[$on]) ?
"<i>" . $this->app->trans('report:: non-renseigne') . "</i>" : $row[$on];
$total['nbdoc'] += $this->result[$i]['nbdoc'];
$this->result[$i]['usrid'] = $row['usrid'];
}
//preview info
if (($row['final'] == 'preview') &&
! is_null($user) &&
! is_null($row['usrid'])) {
$this->result[$i]['nbprev'] += ( ! is_null($row['nb']) ? $row['nb'] : 0);
$this->result[$i]['user'] = empty($row[$on]) ?
"<i>" . $this->app->trans('report:: non-renseigne') . "</i>" : $row[$on];
$total['nbprev'] += ( ! is_null($row['nb']) ? $row['nb'] : 0);
$this->result[$i]['usrid'] = $row['usrid'];
}
$save_user = $user;
}
unset($this->result[$i]);
$nb_row = $i + 1;
$this->total = $nb_row;
if ($this->total > 0) {
$this->result[$nb_row]['user'] = '<b>TOTAL</b>';
$this->result[$nb_row]['nbdoc'] = '<b>' . $total['nbdoc'] . '</b>';
$this->result[$nb_row]['nbprev'] = '<b>' . $total['nbprev'] . '</b>';
}
foreach($this->result as $k=>$row) {
$_row = array();
foreach((array) $tab as $k2=>$f) {
$_row[$k2] = array_key_exists($k2, $row) ? $row[$k2] : '';
}
$_row['usrid'] = array_key_exists('usrid', $row) ? $row['usrid'] : '';
$this->result[$k] = $_row;
}
// no_file_put_contents("/tmp/report.txt", sprintf("%s (%s) %s\n\n", __FILE__, __LINE__, var_export($this->result, true)), FILE_APPEND);
$this->total = sizeof($this->result);
$this->calculatePages();
$this->setDisplayNav();
$this->setReport();
return $this->report;
} | [
"public",
"function",
"getDetailDownload",
"(",
"$",
"tab",
"=",
"false",
",",
"$",
"on",
"=",
"\"\"",
")",
"{",
"empty",
"(",
"$",
"on",
")",
"?",
"$",
"on",
"=",
"\"user\"",
":",
"\"\"",
";",
"//by default always report on user",
"//set title",
"$",
"t... | Get the detail of download by users
@param array $tab config for the html table
@param String $on
@return array | [
"Get",
"the",
"detail",
"of",
"download",
"by",
"users"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/module/report/activity.php#L448-L555 |
alchemy-fr/Phraseanet | lib/classes/module/report/activity.php | module_report_activity.topTenUser | public static function topTenUser(Application $app, $dmin, $dmax, $sbas_id, $list_coll_id)
{
$databox = $app->findDataboxById($sbas_id);
$conn = $databox->get_connection();
$result = [];
$result['top_ten_doc'] = [];
$result['top_ten_prev'] = [];
$result['top_ten_poiddoc'] = [];
$result['top_ten_poidprev'] = [];
$params = [':site_id' => $app['conf']->get(['main', 'key'])];
$datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax, 'log_docs.date');
$params = array_merge($params, $datefilter['params']);
/*
$sql = "SELECT tt.usrid, tt.user, tt.final, tt.record_id, SUM(1) AS nb, SUM(size) AS poid
FROM (
SELECT DISTINCT(log.id), log.usrid, user, final, log_date.record_id
FROM (log_docs AS log_date)
INNER JOIN log FORCE INDEX (date_site) ON (log.id = log_date.log_id)
INNER JOIN log_colls FORCE INDEX (couple) ON (log.id = log_colls.log_id)
WHERE log.site = :site_id
AND log_date.action = 'download'
AND (" . $datefilter['sql'] . ")" .
(('' !== $collfilter['sql']) ? "AND (" . $collfilter['sql'] . ")" : '')
. "
) AS tt
LEFT JOIN subdef AS s ON (s.record_id = tt.record_id)
WHERE s.name = tt.final
GROUP BY tt.user, tt.final";
*/
$sql = "SELECT tt.usrid, tt.user, tt.final, tt.record_id, SUM(1) AS nb, SUM(size) AS poid\n"
. " FROM (\n"
. " SELECT DISTINCT(log.id), log.usrid, user, final, log_docs.record_id\n"
. " FROM (log_docs)\n"
. " INNER JOIN log FORCE INDEX (date_site) ON (log.id = log_docs.log_id)\n"
. " WHERE log.site = :site_id\n"
. " AND log_docs.action = 'download'\n"
. " AND (" . $datefilter['sql'] . ")\n"
. ") AS tt\n"
. "LEFT JOIN subdef AS s ON (s.record_id = tt.record_id)\n"
. "WHERE s.name = tt.final\n"
. "GROUP BY tt.user, tt.final";
// no_file_put_contents("/tmp/report.txt", sprintf("%s (%s)\n%s\n\n", __FILE__, __LINE__, $sql), FILE_APPEND);
$stmt = $conn->prepare($sql);
$stmt->execute($params);
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
foreach ($rs as $row) {
$kttd = 'top_ten_doc';
$kttp = 'top_ten_poiddoc';
$kttpr = 'top_ten_prev';
$kttpp = 'top_ten_poidprev';
$id = $row['usrid'];
if ( ! is_null($row['usrid'])
&& ! is_null($row['user'])
&& ! is_null($row['final']) && ! is_null($row['nb'])
&& ! is_null($row['poid'])) {
if ($row['final'] == 'document') {
$result[$kttd][$id]['lib'] = $row['user'];
$result[$kttd][$id]['id'] = $id;
$result[$kttd][$id]['nb'] = ! is_null($row['nb']) ?
(int) $row['nb'] : 0;
$result[$kttp][$id]['nb'] = ! is_null($row['poid']) ?
(int) $row['poid'] : 0;
$result[$kttp][$id]['lib'] = $row['user'];
$result[$kttp][$id]['id'] = $id;
if ( ! isset($result[$kttd][$id]['nb']))
$result[$kttd][$id]['nb'] = 0;
}
if ($row['final'] == 'preview') {
$result[$kttpr][$id]['lib'] = $row['user'];
$result[$kttpr][$id]['id'] = $id;
if ( ! isset($result[$kttpr][$id]['nb']))
$result[$kttpr][$id]['nb'] = 0;
$result[$kttpr][$id]['nb'] = ! is_null($row['nb']) ?
(int) $row['nb'] : 0;
$result[$kttpp][$id]['nb'] = ! is_null($row['poid']) ?
(int) $row['poid'] : 0;
$result[$kttpp][$id]['lib'] = $row['user'];
$result[$kttpp][$id]['id'] = $id;
}
}
}
return $result;
} | php | public static function topTenUser(Application $app, $dmin, $dmax, $sbas_id, $list_coll_id)
{
$databox = $app->findDataboxById($sbas_id);
$conn = $databox->get_connection();
$result = [];
$result['top_ten_doc'] = [];
$result['top_ten_prev'] = [];
$result['top_ten_poiddoc'] = [];
$result['top_ten_poidprev'] = [];
$params = [':site_id' => $app['conf']->get(['main', 'key'])];
$datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax, 'log_docs.date');
$params = array_merge($params, $datefilter['params']);
/*
$sql = "SELECT tt.usrid, tt.user, tt.final, tt.record_id, SUM(1) AS nb, SUM(size) AS poid
FROM (
SELECT DISTINCT(log.id), log.usrid, user, final, log_date.record_id
FROM (log_docs AS log_date)
INNER JOIN log FORCE INDEX (date_site) ON (log.id = log_date.log_id)
INNER JOIN log_colls FORCE INDEX (couple) ON (log.id = log_colls.log_id)
WHERE log.site = :site_id
AND log_date.action = 'download'
AND (" . $datefilter['sql'] . ")" .
(('' !== $collfilter['sql']) ? "AND (" . $collfilter['sql'] . ")" : '')
. "
) AS tt
LEFT JOIN subdef AS s ON (s.record_id = tt.record_id)
WHERE s.name = tt.final
GROUP BY tt.user, tt.final";
*/
$sql = "SELECT tt.usrid, tt.user, tt.final, tt.record_id, SUM(1) AS nb, SUM(size) AS poid\n"
. " FROM (\n"
. " SELECT DISTINCT(log.id), log.usrid, user, final, log_docs.record_id\n"
. " FROM (log_docs)\n"
. " INNER JOIN log FORCE INDEX (date_site) ON (log.id = log_docs.log_id)\n"
. " WHERE log.site = :site_id\n"
. " AND log_docs.action = 'download'\n"
. " AND (" . $datefilter['sql'] . ")\n"
. ") AS tt\n"
. "LEFT JOIN subdef AS s ON (s.record_id = tt.record_id)\n"
. "WHERE s.name = tt.final\n"
. "GROUP BY tt.user, tt.final";
// no_file_put_contents("/tmp/report.txt", sprintf("%s (%s)\n%s\n\n", __FILE__, __LINE__, $sql), FILE_APPEND);
$stmt = $conn->prepare($sql);
$stmt->execute($params);
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
foreach ($rs as $row) {
$kttd = 'top_ten_doc';
$kttp = 'top_ten_poiddoc';
$kttpr = 'top_ten_prev';
$kttpp = 'top_ten_poidprev';
$id = $row['usrid'];
if ( ! is_null($row['usrid'])
&& ! is_null($row['user'])
&& ! is_null($row['final']) && ! is_null($row['nb'])
&& ! is_null($row['poid'])) {
if ($row['final'] == 'document') {
$result[$kttd][$id]['lib'] = $row['user'];
$result[$kttd][$id]['id'] = $id;
$result[$kttd][$id]['nb'] = ! is_null($row['nb']) ?
(int) $row['nb'] : 0;
$result[$kttp][$id]['nb'] = ! is_null($row['poid']) ?
(int) $row['poid'] : 0;
$result[$kttp][$id]['lib'] = $row['user'];
$result[$kttp][$id]['id'] = $id;
if ( ! isset($result[$kttd][$id]['nb']))
$result[$kttd][$id]['nb'] = 0;
}
if ($row['final'] == 'preview') {
$result[$kttpr][$id]['lib'] = $row['user'];
$result[$kttpr][$id]['id'] = $id;
if ( ! isset($result[$kttpr][$id]['nb']))
$result[$kttpr][$id]['nb'] = 0;
$result[$kttpr][$id]['nb'] = ! is_null($row['nb']) ?
(int) $row['nb'] : 0;
$result[$kttpp][$id]['nb'] = ! is_null($row['poid']) ?
(int) $row['poid'] : 0;
$result[$kttpp][$id]['lib'] = $row['user'];
$result[$kttpp][$id]['id'] = $id;
}
}
}
return $result;
} | [
"public",
"static",
"function",
"topTenUser",
"(",
"Application",
"$",
"app",
",",
"$",
"dmin",
",",
"$",
"dmax",
",",
"$",
"sbas_id",
",",
"$",
"list_coll_id",
")",
"{",
"$",
"databox",
"=",
"$",
"app",
"->",
"findDataboxById",
"(",
"$",
"sbas_id",
")... | ========================== ???????????????? =========================== | [
"==========================",
"????????????????",
"==========================="
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/module/report/activity.php#L558-L650 |
alchemy-fr/Phraseanet | lib/classes/module/report/activity.php | module_report_activity.activity | public static function activity(Application $app, $dmin, $dmax, $sbas_id, $list_coll_id)
{
$databox = $app->findDataboxById($sbas_id);
$conn = $databox->get_connection();
$res = [];
$datefilter =
module_report_sqlfilter::constructDateFilter($dmin, $dmax);
$params = [':site_id' => $app['conf']->get(['main', 'key'])];
$params = array_merge($params, $datefilter['params']);
/*
$sql = "
SELECT tt.id, HOUR(tt.heures) AS heures
FROM (
SELECT DISTINCT(log_date.id), log_date.date AS heures
FROM log AS log_date FORCE INDEX (date_site)
INNER JOIN log_colls FORCE INDEX (couple) ON (log_date.id = log_colls.log_id)
WHERE " . $datefilter['sql'] . "" .
(('' !== $collfilter['sql']) ? "AND (" . $collfilter['sql'] . ")" : '')
. " AND log_date.site = :site_id
) AS tt";
*/
$sql = "SELECT tt.id, HOUR(tt.heures) AS heures\n"
. " FROM (\n"
. " SELECT DISTINCT(log_date.id), log_date.date AS heures\n"
. " FROM log AS log_date FORCE INDEX (date_site)\n"
. " WHERE " . $datefilter['sql'] . " AND !ISNULL(usrid)"
. " AND log_date.site = :site_id\n"
. " ) AS tt";
// no_file_put_contents("/tmp/report.txt", sprintf("%s (%s)\n%s\n\n", __FILE__, __LINE__, $sql), FILE_APPEND);
$stmt = $conn->prepare($sql);
$stmt->execute($params);
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$total = $stmt->rowCount();
$stmt->closeCursor();
for ($i = 0; $i < 24; $i ++) {
$res[$i] = 0;
}
foreach ($rs as $row) {
if ($total > 0) {
$res[$row["heures"]]++;
}
}
foreach ($res as $heure => $value) {
$res[$heure] = number_format(($value / 24), 2, '.', '');
}
return $res;
} | php | public static function activity(Application $app, $dmin, $dmax, $sbas_id, $list_coll_id)
{
$databox = $app->findDataboxById($sbas_id);
$conn = $databox->get_connection();
$res = [];
$datefilter =
module_report_sqlfilter::constructDateFilter($dmin, $dmax);
$params = [':site_id' => $app['conf']->get(['main', 'key'])];
$params = array_merge($params, $datefilter['params']);
/*
$sql = "
SELECT tt.id, HOUR(tt.heures) AS heures
FROM (
SELECT DISTINCT(log_date.id), log_date.date AS heures
FROM log AS log_date FORCE INDEX (date_site)
INNER JOIN log_colls FORCE INDEX (couple) ON (log_date.id = log_colls.log_id)
WHERE " . $datefilter['sql'] . "" .
(('' !== $collfilter['sql']) ? "AND (" . $collfilter['sql'] . ")" : '')
. " AND log_date.site = :site_id
) AS tt";
*/
$sql = "SELECT tt.id, HOUR(tt.heures) AS heures\n"
. " FROM (\n"
. " SELECT DISTINCT(log_date.id), log_date.date AS heures\n"
. " FROM log AS log_date FORCE INDEX (date_site)\n"
. " WHERE " . $datefilter['sql'] . " AND !ISNULL(usrid)"
. " AND log_date.site = :site_id\n"
. " ) AS tt";
// no_file_put_contents("/tmp/report.txt", sprintf("%s (%s)\n%s\n\n", __FILE__, __LINE__, $sql), FILE_APPEND);
$stmt = $conn->prepare($sql);
$stmt->execute($params);
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$total = $stmt->rowCount();
$stmt->closeCursor();
for ($i = 0; $i < 24; $i ++) {
$res[$i] = 0;
}
foreach ($rs as $row) {
if ($total > 0) {
$res[$row["heures"]]++;
}
}
foreach ($res as $heure => $value) {
$res[$heure] = number_format(($value / 24), 2, '.', '');
}
return $res;
} | [
"public",
"static",
"function",
"activity",
"(",
"Application",
"$",
"app",
",",
"$",
"dmin",
",",
"$",
"dmax",
",",
"$",
"sbas_id",
",",
"$",
"list_coll_id",
")",
"{",
"$",
"databox",
"=",
"$",
"app",
"->",
"findDataboxById",
"(",
"$",
"sbas_id",
")",... | ============================= Dashboard ========================= | [
"=============================",
"Dashboard",
"========================="
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/module/report/activity.php#L653-L706 |
alchemy-fr/Phraseanet | lib/classes/module/report/activity.php | module_report_activity.activityDay | public static function activityDay(Application $app, $dmin, $dmax, $sbas_id, $list_coll_id)
{
$databox = $app->findDataboxById($sbas_id);
$conn = $databox->get_connection();
$result = array();
$res = array();
$datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax);
$params = [':site_id' => $app['conf']->get(['main', 'key'])];
$params = array_merge($params, $datefilter['params']);
/*
$sql = "
SELECT tt.ddate, COUNT( DATE_FORMAT( tt.ddate, '%d' ) ) AS activity
FROM (
SELECT DISTINCT(log_date.id), DATE_FORMAT( log_date.date, '%Y-%m-%d' ) AS ddate
FROM log AS log_date FORCE INDEX (date_site) INNER JOIN log_colls FORCE INDEX (couple) ON (log_date.id = log_colls.log_id)
WHERE " . $datefilter['sql'] . "
AND log_date.site = :site_id" .
(('' !== $collfilter['sql']) ? (" AND (" . $collfilter['sql'] . ")") : '')
. ") AS tt
GROUP by tt.ddate
ORDER BY tt.ddate ASC";
*/
$sql = "SELECT tt.ddate, COUNT( DATE_FORMAT( tt.ddate, '%d' ) ) AS activity\n"
. " FROM (\n"
. " SELECT DISTINCT(log_date.id), DATE_FORMAT( log_date.date, '%Y-%m-%d' ) AS ddate\n"
. " FROM log AS log_date FORCE INDEX (date_site)\n"
. " WHERE " . $datefilter['sql'] . "\n"
. " AND log_date.site = :site_id AND !ISNULL(usrid)"
. ") AS tt\n"
. " GROUP by tt.ddate\n"
. " ORDER BY tt.ddate ASC";
// no_file_put_contents("/tmp/report.txt", sprintf("%s (%s)\n%s\n\n", __FILE__, __LINE__, $sql), FILE_APPEND);
$stmt = $conn->prepare($sql);
$stmt->execute($params);
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
foreach ($rs as $row) {
$date = new DateTime($row['ddate']);
$result[$date->format(DATE_ATOM)] = $row['activity'];
}
foreach ($result as $key => $act) {
$res[$key] = number_format($act, 2, '.', '');
}
return $res;
} | php | public static function activityDay(Application $app, $dmin, $dmax, $sbas_id, $list_coll_id)
{
$databox = $app->findDataboxById($sbas_id);
$conn = $databox->get_connection();
$result = array();
$res = array();
$datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax);
$params = [':site_id' => $app['conf']->get(['main', 'key'])];
$params = array_merge($params, $datefilter['params']);
/*
$sql = "
SELECT tt.ddate, COUNT( DATE_FORMAT( tt.ddate, '%d' ) ) AS activity
FROM (
SELECT DISTINCT(log_date.id), DATE_FORMAT( log_date.date, '%Y-%m-%d' ) AS ddate
FROM log AS log_date FORCE INDEX (date_site) INNER JOIN log_colls FORCE INDEX (couple) ON (log_date.id = log_colls.log_id)
WHERE " . $datefilter['sql'] . "
AND log_date.site = :site_id" .
(('' !== $collfilter['sql']) ? (" AND (" . $collfilter['sql'] . ")") : '')
. ") AS tt
GROUP by tt.ddate
ORDER BY tt.ddate ASC";
*/
$sql = "SELECT tt.ddate, COUNT( DATE_FORMAT( tt.ddate, '%d' ) ) AS activity\n"
. " FROM (\n"
. " SELECT DISTINCT(log_date.id), DATE_FORMAT( log_date.date, '%Y-%m-%d' ) AS ddate\n"
. " FROM log AS log_date FORCE INDEX (date_site)\n"
. " WHERE " . $datefilter['sql'] . "\n"
. " AND log_date.site = :site_id AND !ISNULL(usrid)"
. ") AS tt\n"
. " GROUP by tt.ddate\n"
. " ORDER BY tt.ddate ASC";
// no_file_put_contents("/tmp/report.txt", sprintf("%s (%s)\n%s\n\n", __FILE__, __LINE__, $sql), FILE_APPEND);
$stmt = $conn->prepare($sql);
$stmt->execute($params);
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
foreach ($rs as $row) {
$date = new DateTime($row['ddate']);
$result[$date->format(DATE_ATOM)] = $row['activity'];
}
foreach ($result as $key => $act) {
$res[$key] = number_format($act, 2, '.', '');
}
return $res;
} | [
"public",
"static",
"function",
"activityDay",
"(",
"Application",
"$",
"app",
",",
"$",
"dmin",
",",
"$",
"dmax",
",",
"$",
"sbas_id",
",",
"$",
"list_coll_id",
")",
"{",
"$",
"databox",
"=",
"$",
"app",
"->",
"findDataboxById",
"(",
"$",
"sbas_id",
"... | ============================= Dashboard ========================= | [
"=============================",
"Dashboard",
"========================="
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/module/report/activity.php#L709-L759 |
alchemy-fr/Phraseanet | lib/classes/module/report/activity.php | module_report_activity.activiteTopTenSiteView | public static function activiteTopTenSiteView(Application $app, $dmin, $dmax, $sbas_id, $list_coll_id)
{
$databox = $app->findDataboxById($sbas_id);
$conn = $databox->get_connection();
$result = [];
$datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax);
$params = [];
$params = array_merge($params, $datefilter['params']);
/*
$sql = "
SELECT tt.referrer, SUM(1) AS nb_view
FROM (
SELECT DISTINCT(log_date.id), referrer
FROM (log_view)
INNER JOIN log AS log_date FORCE INDEX (date_site) ON (log_view.log_id = log_date.id)
INNER JOIN log_colls FORCE INDEX (couple) ON (log_date.id = log_colls.log_id)
WHERE " . $datefilter['sql'] . "" .
(('' !== $collfilter['sql']) ? " AND (" . $collfilter['sql'] . ")" : '')
. ") AS tt
GROUP BY referrer
ORDER BY nb_view DESC ";
*/
$sql = "SELECT tt.referrer, SUM(1) AS nb_view\n"
. " FROM (\n"
. " SELECT DISTINCT(log_date.id), referrer\n"
. " FROM (log_view)\n"
. " INNER JOIN log AS log_date FORCE INDEX (date_site) ON (log_view.log_id = log_date.id)\n"
. " WHERE " . $datefilter['sql']
. ") AS tt\n"
. " GROUP BY referrer\n"
. " ORDER BY nb_view DESC ";
// no_file_put_contents("/tmp/report.txt", sprintf("%s (%s)\n%s\n\n", __FILE__, __LINE__, $sql), FILE_APPEND);
$stmt = $conn->prepare($sql);
$stmt->execute($params);
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
foreach ($rs as $row) {
($row['referrer'] != 'NO REFERRER') ?
$host = parent::getHost($row['referrer']) :
$host = 'NO REFERRER';
if ( ! isset($result[$host]['nb']))
$result[$host]['nb'] = 0;
if ( ! isset($result[$host]['lib']))
$result[$host]['lib'] = $host;
$result[$host]['nb']+= ( (int) $row['nb_view']);
$result[$host]['id'] = "false";
}
return $result;
} | php | public static function activiteTopTenSiteView(Application $app, $dmin, $dmax, $sbas_id, $list_coll_id)
{
$databox = $app->findDataboxById($sbas_id);
$conn = $databox->get_connection();
$result = [];
$datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax);
$params = [];
$params = array_merge($params, $datefilter['params']);
/*
$sql = "
SELECT tt.referrer, SUM(1) AS nb_view
FROM (
SELECT DISTINCT(log_date.id), referrer
FROM (log_view)
INNER JOIN log AS log_date FORCE INDEX (date_site) ON (log_view.log_id = log_date.id)
INNER JOIN log_colls FORCE INDEX (couple) ON (log_date.id = log_colls.log_id)
WHERE " . $datefilter['sql'] . "" .
(('' !== $collfilter['sql']) ? " AND (" . $collfilter['sql'] . ")" : '')
. ") AS tt
GROUP BY referrer
ORDER BY nb_view DESC ";
*/
$sql = "SELECT tt.referrer, SUM(1) AS nb_view\n"
. " FROM (\n"
. " SELECT DISTINCT(log_date.id), referrer\n"
. " FROM (log_view)\n"
. " INNER JOIN log AS log_date FORCE INDEX (date_site) ON (log_view.log_id = log_date.id)\n"
. " WHERE " . $datefilter['sql']
. ") AS tt\n"
. " GROUP BY referrer\n"
. " ORDER BY nb_view DESC ";
// no_file_put_contents("/tmp/report.txt", sprintf("%s (%s)\n%s\n\n", __FILE__, __LINE__, $sql), FILE_APPEND);
$stmt = $conn->prepare($sql);
$stmt->execute($params);
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
foreach ($rs as $row) {
($row['referrer'] != 'NO REFERRER') ?
$host = parent::getHost($row['referrer']) :
$host = 'NO REFERRER';
if ( ! isset($result[$host]['nb']))
$result[$host]['nb'] = 0;
if ( ! isset($result[$host]['lib']))
$result[$host]['lib'] = $host;
$result[$host]['nb']+= ( (int) $row['nb_view']);
$result[$host]['id'] = "false";
}
return $result;
} | [
"public",
"static",
"function",
"activiteTopTenSiteView",
"(",
"Application",
"$",
"app",
",",
"$",
"dmin",
",",
"$",
"dmax",
",",
"$",
"sbas_id",
",",
"$",
"list_coll_id",
")",
"{",
"$",
"databox",
"=",
"$",
"app",
"->",
"findDataboxById",
"(",
"$",
"sb... | ============================= Dashboard ========================= | [
"=============================",
"Dashboard",
"========================="
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/module/report/activity.php#L871-L926 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Feed/Aggregate.php | Aggregate.createFromUser | public static function createFromUser(Application $app, User $user, array $restrictions = [])
{
/** @var FeedRepository $feedRepository */
$feedRepository = $app['repo.feeds'];
$feeds = $feedRepository->filterUserAccessibleByIds($app->getAclForUser($user), $restrictions);
$token = $app['repo.aggregate-tokens']->findOneBy(['user' => $user]);
return new static($app['orm.em'], $feeds, $token);
} | php | public static function createFromUser(Application $app, User $user, array $restrictions = [])
{
/** @var FeedRepository $feedRepository */
$feedRepository = $app['repo.feeds'];
$feeds = $feedRepository->filterUserAccessibleByIds($app->getAclForUser($user), $restrictions);
$token = $app['repo.aggregate-tokens']->findOneBy(['user' => $user]);
return new static($app['orm.em'], $feeds, $token);
} | [
"public",
"static",
"function",
"createFromUser",
"(",
"Application",
"$",
"app",
",",
"User",
"$",
"user",
",",
"array",
"$",
"restrictions",
"=",
"[",
"]",
")",
"{",
"/** @var FeedRepository $feedRepository */",
"$",
"feedRepository",
"=",
"$",
"app",
"[",
"... | Creates an aggregate from all the feeds available to a given user.
@param Application $app
@param User $user
@param array $restrictions
@return Aggregate | [
"Creates",
"an",
"aggregate",
"from",
"all",
"the",
"feeds",
"available",
"to",
"a",
"given",
"user",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Feed/Aggregate.php#L80-L88 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Feed/Aggregate.php | Aggregate.create | public static function create(Application $app, array $feed_ids)
{
$feeds = $app['repo.feeds']->findByIds($feed_ids);
return new static($app, $feeds);
} | php | public static function create(Application $app, array $feed_ids)
{
$feeds = $app['repo.feeds']->findByIds($feed_ids);
return new static($app, $feeds);
} | [
"public",
"static",
"function",
"create",
"(",
"Application",
"$",
"app",
",",
"array",
"$",
"feed_ids",
")",
"{",
"$",
"feeds",
"=",
"$",
"app",
"[",
"'repo.feeds'",
"]",
"->",
"findByIds",
"(",
"$",
"feed_ids",
")",
";",
"return",
"new",
"static",
"(... | Creates an aggregate from given Feed id array.
@param Application $app
@param array $feed_ids
@return Aggregate | [
"Creates",
"an",
"aggregate",
"from",
"given",
"Feed",
"id",
"array",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Feed/Aggregate.php#L97-L102 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Feed/Aggregate.php | Aggregate.getCountTotalEntries | public function getCountTotalEntries()
{
if ($this->feeds->isEmpty()) {
return 0;
}
/** @var FeedEntryRepository $feedEntryRepository */
$feedEntryRepository = $this->em->getRepository('Phraseanet:FeedEntry');
return $feedEntryRepository->countByFeeds($this->feeds->getKeys());
} | php | public function getCountTotalEntries()
{
if ($this->feeds->isEmpty()) {
return 0;
}
/** @var FeedEntryRepository $feedEntryRepository */
$feedEntryRepository = $this->em->getRepository('Phraseanet:FeedEntry');
return $feedEntryRepository->countByFeeds($this->feeds->getKeys());
} | [
"public",
"function",
"getCountTotalEntries",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"feeds",
"->",
"isEmpty",
"(",
")",
")",
"{",
"return",
"0",
";",
"}",
"/** @var FeedEntryRepository $feedEntryRepository */",
"$",
"feedEntryRepository",
"=",
"$",
"this"... | Returns the total number of entries from all the feeds.
@return int | [
"Returns",
"the",
"total",
"number",
"of",
"entries",
"from",
"all",
"the",
"feeds",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Feed/Aggregate.php#L197-L207 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Feed/Aggregate.php | Aggregate.hasPage | public function hasPage($pageNumber, $nbEntriesByPage)
{
if (0 >= $nbEntriesByPage) {
throw new LogicException;
}
$count = $this->getCountTotalEntries();
if (0 > $pageNumber && $pageNumber <= $count / $nbEntriesByPage) {
return true;
}
return false;
} | php | public function hasPage($pageNumber, $nbEntriesByPage)
{
if (0 >= $nbEntriesByPage) {
throw new LogicException;
}
$count = $this->getCountTotalEntries();
if (0 > $pageNumber && $pageNumber <= $count / $nbEntriesByPage) {
return true;
}
return false;
} | [
"public",
"function",
"hasPage",
"(",
"$",
"pageNumber",
",",
"$",
"nbEntriesByPage",
")",
"{",
"if",
"(",
"0",
">=",
"$",
"nbEntriesByPage",
")",
"{",
"throw",
"new",
"LogicException",
";",
"}",
"$",
"count",
"=",
"$",
"this",
"->",
"getCountTotalEntries"... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Feed/Aggregate.php#L212-L224 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Prod/RecordController.php | RecordController.getRecord | public function getRecord(Request $request)
{
if (!$request->isXmlHttpRequest()) {
$this->app->abort(400);
}
$searchEngine = $options = null;
$train = '';
if ('' === $env = strtoupper($request->get('env', ''))) {
$this->app->abort(400, '`env` parameter is missing');
}
// Use $request->get as HTTP method can be POST or GET
if ('RESULT' == $env = strtoupper($request->get('env', ''))) {
try {
$options = SearchEngineOptions::hydrate($this->app, $request->get('options_serial'));
$searchEngine = $this->getSearchEngine();
} catch (\Exception $e) {
$this->app->abort(400, 'Search-engine options are not valid or missing');
}
}
$pos = (int) $request->get('pos', 0);
$query = $request->get('query', '');
$reloadTrain = !! $request->get('roll', false);
$record = new \record_preview(
$this->app,
$env,
$pos < 0 ? 0 : $pos,
$request->get('cont', ''),
$searchEngine,
$query,
$options
);
$currentRecord = $this->getContainerResult($record);
if ($record->is_from_reg()) {
$train = $this->render('prod/preview/reg_train.html.twig', ['record' => $record]);
} else if ($record->is_from_basket() && $reloadTrain) {
$train = $this->render('prod/preview/basket_train.html.twig', ['record' => $record]);
} else if ($record->is_from_feed()) {
$train = $this->render('prod/preview/feed_train.html.twig', ['record' => $record]);
}
$recordCaptions = [];
foreach ($record->get_caption()->get_fields(null, true) as $field) {
// get field's values
$recordCaptions[$field->get_name()] = $field->get_serialized_values();
}
$recordCaptions["technicalInfo"] = $record->getPositionFromTechnicalInfos();
// escape record title before rendering
$recordTitle = explode("</span>", $record->get_title());
if (count($recordTitle) >1) {
$recordTitle[1] = htmlspecialchars($recordTitle[1]);
$recordTitle = implode("</span>", $recordTitle);
} else {
$recordTitle = htmlspecialchars($record->get_title());
}
return $this->app->json([
"desc" => $this->render('prod/preview/caption.html.twig', [
'record' => $record,
'highlight' => $query,
'searchEngine' => $searchEngine,
'searchOptions' => $options,
]),
"recordCaptions" => $recordCaptions,
"html_preview" => $this->render('common/preview.html.twig', [
'record' => $record
]),
"others" => $this->render('prod/preview/appears_in.html.twig', [
'parents' => $record->get_grouping_parents(),
'baskets' => $record->get_container_baskets($this->getEntityManager(), $this->getAuthenticatedUser()),
]),
"current" => $train,
"record" => $currentRecord,
"history" => $this->render('prod/preview/short_history.html.twig', [
'record' => $record,
]),
"popularity" => $this->render('prod/preview/popularity.html.twig', [
'record' => $record,
]),
"tools" => $this->render('prod/preview/tools.html.twig', [
'record' => $record,
]),
"pos" => $record->getNumber(),
"title" => $recordTitle,
"databox_name" => $record->getDatabox()->get_dbname(),
"collection_name" => $record->getCollection()->get_name(),
"collection_logo" => $record->getCollection()->getLogo($record->getBaseId(), $this->app),
]);
} | php | public function getRecord(Request $request)
{
if (!$request->isXmlHttpRequest()) {
$this->app->abort(400);
}
$searchEngine = $options = null;
$train = '';
if ('' === $env = strtoupper($request->get('env', ''))) {
$this->app->abort(400, '`env` parameter is missing');
}
// Use $request->get as HTTP method can be POST or GET
if ('RESULT' == $env = strtoupper($request->get('env', ''))) {
try {
$options = SearchEngineOptions::hydrate($this->app, $request->get('options_serial'));
$searchEngine = $this->getSearchEngine();
} catch (\Exception $e) {
$this->app->abort(400, 'Search-engine options are not valid or missing');
}
}
$pos = (int) $request->get('pos', 0);
$query = $request->get('query', '');
$reloadTrain = !! $request->get('roll', false);
$record = new \record_preview(
$this->app,
$env,
$pos < 0 ? 0 : $pos,
$request->get('cont', ''),
$searchEngine,
$query,
$options
);
$currentRecord = $this->getContainerResult($record);
if ($record->is_from_reg()) {
$train = $this->render('prod/preview/reg_train.html.twig', ['record' => $record]);
} else if ($record->is_from_basket() && $reloadTrain) {
$train = $this->render('prod/preview/basket_train.html.twig', ['record' => $record]);
} else if ($record->is_from_feed()) {
$train = $this->render('prod/preview/feed_train.html.twig', ['record' => $record]);
}
$recordCaptions = [];
foreach ($record->get_caption()->get_fields(null, true) as $field) {
// get field's values
$recordCaptions[$field->get_name()] = $field->get_serialized_values();
}
$recordCaptions["technicalInfo"] = $record->getPositionFromTechnicalInfos();
// escape record title before rendering
$recordTitle = explode("</span>", $record->get_title());
if (count($recordTitle) >1) {
$recordTitle[1] = htmlspecialchars($recordTitle[1]);
$recordTitle = implode("</span>", $recordTitle);
} else {
$recordTitle = htmlspecialchars($record->get_title());
}
return $this->app->json([
"desc" => $this->render('prod/preview/caption.html.twig', [
'record' => $record,
'highlight' => $query,
'searchEngine' => $searchEngine,
'searchOptions' => $options,
]),
"recordCaptions" => $recordCaptions,
"html_preview" => $this->render('common/preview.html.twig', [
'record' => $record
]),
"others" => $this->render('prod/preview/appears_in.html.twig', [
'parents' => $record->get_grouping_parents(),
'baskets' => $record->get_container_baskets($this->getEntityManager(), $this->getAuthenticatedUser()),
]),
"current" => $train,
"record" => $currentRecord,
"history" => $this->render('prod/preview/short_history.html.twig', [
'record' => $record,
]),
"popularity" => $this->render('prod/preview/popularity.html.twig', [
'record' => $record,
]),
"tools" => $this->render('prod/preview/tools.html.twig', [
'record' => $record,
]),
"pos" => $record->getNumber(),
"title" => $recordTitle,
"databox_name" => $record->getDatabox()->get_dbname(),
"collection_name" => $record->getCollection()->get_name(),
"collection_logo" => $record->getCollection()->getLogo($record->getBaseId(), $this->app),
]);
} | [
"public",
"function",
"getRecord",
"(",
"Request",
"$",
"request",
")",
"{",
"if",
"(",
"!",
"$",
"request",
"->",
"isXmlHttpRequest",
"(",
")",
")",
"{",
"$",
"this",
"->",
"app",
"->",
"abort",
"(",
"400",
")",
";",
"}",
"$",
"searchEngine",
"=",
... | Get record detailed view
@param Request $request
@return Response | [
"Get",
"record",
"detailed",
"view"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Prod/RecordController.php#L39-L134 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Prod/RecordController.php | RecordController.doDeleteRecords | public function doDeleteRecords(Request $request)
{
$flatten = (bool)($request->request->get('del_children')) ? RecordsRequest::FLATTEN_YES_PRESERVE_STORIES : RecordsRequest::FLATTEN_NO;
$records = RecordsRequest::fromRequest(
$this->app,
$request,$flatten,
[\ACL::CANDELETERECORD]
);
$basketElementsRepository = $this->getBasketElementRepository();
$StoryWZRepository = $this->getStoryWorkZoneRepository();
$deleted = [];
/** @var \collection[] $trashCollectionsBySbasId */
$trashCollectionsBySbasId = [];
$manager = $this->getEntityManager();
/** @var \record_adapter $record */
foreach ($records as $record) {
try {
$basketElements = $basketElementsRepository->findElementsByRecord($record);
foreach ($basketElements as $element) {
$manager->remove($element);
$deleted[] = $element->getRecord($this->app)->getId();
}
$attachedStories = $StoryWZRepository->findByRecord($this->app, $record);
foreach ($attachedStories as $attachedStory) {
$manager->remove($attachedStory);
}
foreach($record->get_grouping_parents() as $story) {
$this->getEventDispatcher()->dispatch(PhraseaEvents::RECORD_EDIT, new RecordEdit($story));
}
$sbasId = $record->getDatabox()->get_sbas_id();
if(!array_key_exists($sbasId, $trashCollectionsBySbasId)) {
$trashCollectionsBySbasId[$sbasId] = $record->getDatabox()->getTrashCollection();
}
$deleted[] = $record->getId();
if($trashCollectionsBySbasId[$sbasId] !== null) {
if($record->getCollection()->get_coll_id() == $trashCollectionsBySbasId[$sbasId]->get_coll_id()) {
// record is already in trash so delete it
$record->delete();
} else {
// move to trash collection
$record->move_to_collection($trashCollectionsBySbasId[$sbasId], $this->getApplicationBox());
// disable permalinks
foreach($record->get_subdefs() as $subdef) {
if( ($pl = $subdef->get_permalink()) ) {
$pl->set_is_activated(false);
}
}
}
} else {
// no trash collection, delete
$record->delete();
}
} catch (\Exception $e) {
}
}
$manager->flush();
return $this->app->json($deleted);
} | php | public function doDeleteRecords(Request $request)
{
$flatten = (bool)($request->request->get('del_children')) ? RecordsRequest::FLATTEN_YES_PRESERVE_STORIES : RecordsRequest::FLATTEN_NO;
$records = RecordsRequest::fromRequest(
$this->app,
$request,$flatten,
[\ACL::CANDELETERECORD]
);
$basketElementsRepository = $this->getBasketElementRepository();
$StoryWZRepository = $this->getStoryWorkZoneRepository();
$deleted = [];
/** @var \collection[] $trashCollectionsBySbasId */
$trashCollectionsBySbasId = [];
$manager = $this->getEntityManager();
/** @var \record_adapter $record */
foreach ($records as $record) {
try {
$basketElements = $basketElementsRepository->findElementsByRecord($record);
foreach ($basketElements as $element) {
$manager->remove($element);
$deleted[] = $element->getRecord($this->app)->getId();
}
$attachedStories = $StoryWZRepository->findByRecord($this->app, $record);
foreach ($attachedStories as $attachedStory) {
$manager->remove($attachedStory);
}
foreach($record->get_grouping_parents() as $story) {
$this->getEventDispatcher()->dispatch(PhraseaEvents::RECORD_EDIT, new RecordEdit($story));
}
$sbasId = $record->getDatabox()->get_sbas_id();
if(!array_key_exists($sbasId, $trashCollectionsBySbasId)) {
$trashCollectionsBySbasId[$sbasId] = $record->getDatabox()->getTrashCollection();
}
$deleted[] = $record->getId();
if($trashCollectionsBySbasId[$sbasId] !== null) {
if($record->getCollection()->get_coll_id() == $trashCollectionsBySbasId[$sbasId]->get_coll_id()) {
// record is already in trash so delete it
$record->delete();
} else {
// move to trash collection
$record->move_to_collection($trashCollectionsBySbasId[$sbasId], $this->getApplicationBox());
// disable permalinks
foreach($record->get_subdefs() as $subdef) {
if( ($pl = $subdef->get_permalink()) ) {
$pl->set_is_activated(false);
}
}
}
} else {
// no trash collection, delete
$record->delete();
}
} catch (\Exception $e) {
}
}
$manager->flush();
return $this->app->json($deleted);
} | [
"public",
"function",
"doDeleteRecords",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"flatten",
"=",
"(",
"bool",
")",
"(",
"$",
"request",
"->",
"request",
"->",
"get",
"(",
"'del_children'",
")",
")",
"?",
"RecordsRequest",
"::",
"FLATTEN_YES_PRESERVE_S... | Delete a record or a list of records
@param Request $request
@return Response | [
"Delete",
"a",
"record",
"or",
"a",
"list",
"of",
"records"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Prod/RecordController.php#L190-L259 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Prod/RecordController.php | RecordController.whatCanIDelete | public function whatCanIDelete(Request $request)
{
$records = RecordsRequest::fromRequest(
$this->app,
$request,
!!$request->request->get('del_children'),
[\ACL::CANDELETERECORD]
);
$filteredRecord = $this->filterRecordToDelete($records);
return $this->app->json([
'renderView' => $this->render('prod/actions/delete_records_confirm.html.twig', [
'records' => $records,
'filteredRecord' => $filteredRecord
]),
'filteredRecord' => $filteredRecord
]);
} | php | public function whatCanIDelete(Request $request)
{
$records = RecordsRequest::fromRequest(
$this->app,
$request,
!!$request->request->get('del_children'),
[\ACL::CANDELETERECORD]
);
$filteredRecord = $this->filterRecordToDelete($records);
return $this->app->json([
'renderView' => $this->render('prod/actions/delete_records_confirm.html.twig', [
'records' => $records,
'filteredRecord' => $filteredRecord
]),
'filteredRecord' => $filteredRecord
]);
} | [
"public",
"function",
"whatCanIDelete",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"records",
"=",
"RecordsRequest",
"::",
"fromRequest",
"(",
"$",
"this",
"->",
"app",
",",
"$",
"request",
",",
"!",
"!",
"$",
"request",
"->",
"request",
"->",
"get",... | Delete a record or a list of records
@param Request $request
@return Response | [
"Delete",
"a",
"record",
"or",
"a",
"list",
"of",
"records"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Prod/RecordController.php#L283-L302 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Controller/Prod/RecordController.php | RecordController.renewUrl | public function renewUrl(Request $request)
{
$records = RecordsRequest::fromRequest($this->app, $request, !!$request->request->get('renew_children_url'));
$renewed = [];
foreach ($records as $record) {
$renewed[$record->getId()] = (string) $record->get_preview()->renew_url();
};
return $this->app->json($renewed);
} | php | public function renewUrl(Request $request)
{
$records = RecordsRequest::fromRequest($this->app, $request, !!$request->request->get('renew_children_url'));
$renewed = [];
foreach ($records as $record) {
$renewed[$record->getId()] = (string) $record->get_preview()->renew_url();
};
return $this->app->json($renewed);
} | [
"public",
"function",
"renewUrl",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"records",
"=",
"RecordsRequest",
"::",
"fromRequest",
"(",
"$",
"this",
"->",
"app",
",",
"$",
"request",
",",
"!",
"!",
"$",
"request",
"->",
"request",
"->",
"get",
"("... | Renew url list of records
@param Request $request
@return Response | [
"Renew",
"url",
"list",
"of",
"records"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Prod/RecordController.php#L341-L351 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Core/Configuration/PropertyAccess.php | PropertyAccess.get | public function get($props, $default = null)
{
return \igorw\get_in($this->conf->getConfig(), $this->arrayize($props), $default);
} | php | public function get($props, $default = null)
{
return \igorw\get_in($this->conf->getConfig(), $this->arrayize($props), $default);
} | [
"public",
"function",
"get",
"(",
"$",
"props",
",",
"$",
"default",
"=",
"null",
")",
"{",
"return",
"\\",
"igorw",
"\\",
"get_in",
"(",
"$",
"this",
"->",
"conf",
"->",
"getConfig",
"(",
")",
",",
"$",
"this",
"->",
"arrayize",
"(",
"$",
"props",... | Gets the value given one or more properties
@param array|string $props The property to get
@param mixed $default The default value to return in case the property is not accessible
@return mixed | [
"Gets",
"the",
"value",
"given",
"one",
"or",
"more",
"properties"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Core/Configuration/PropertyAccess.php#L39-L42 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Core/Configuration/PropertyAccess.php | PropertyAccess.has | public function has($props)
{
$current = $this->conf->getConfig();
$props = $this->arrayize($props);
foreach ($props as $prop) {
if (!isset($current[$prop])) {
return false;
}
$current = $current[$prop];
}
return true;
} | php | public function has($props)
{
$current = $this->conf->getConfig();
$props = $this->arrayize($props);
foreach ($props as $prop) {
if (!isset($current[$prop])) {
return false;
}
$current = $current[$prop];
}
return true;
} | [
"public",
"function",
"has",
"(",
"$",
"props",
")",
"{",
"$",
"current",
"=",
"$",
"this",
"->",
"conf",
"->",
"getConfig",
"(",
")",
";",
"$",
"props",
"=",
"$",
"this",
"->",
"arrayize",
"(",
"$",
"props",
")",
";",
"foreach",
"(",
"$",
"props... | Checks if a property exists.
@param array|string $props The property to check
@return Boolean | [
"Checks",
"if",
"a",
"property",
"exists",
"."
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Core/Configuration/PropertyAccess.php#L51-L65 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Core/Configuration/PropertyAccess.php | PropertyAccess.set | public function set($props, $value)
{
$this->conf->setConfig(\igorw\assoc_in($this->conf->getConfig(), $this->arrayize($props), $value));
return $value;
} | php | public function set($props, $value)
{
$this->conf->setConfig(\igorw\assoc_in($this->conf->getConfig(), $this->arrayize($props), $value));
return $value;
} | [
"public",
"function",
"set",
"(",
"$",
"props",
",",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"conf",
"->",
"setConfig",
"(",
"\\",
"igorw",
"\\",
"assoc_in",
"(",
"$",
"this",
"->",
"conf",
"->",
"getConfig",
"(",
")",
",",
"$",
"this",
"->",
... | Set a value to a property
@param array|string $props The property to set
@param mixed $value
@return mixed The set value | [
"Set",
"a",
"value",
"to",
"a",
"property"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Core/Configuration/PropertyAccess.php#L75-L80 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Core/Configuration/PropertyAccess.php | PropertyAccess.merge | public function merge($props, array $value)
{
$conf = $this->conf->getConfig();
$ret = $this->doMerge($conf, $this->arrayize($props), $value);
$this->conf->setConfig($conf);
return $ret;
} | php | public function merge($props, array $value)
{
$conf = $this->conf->getConfig();
$ret = $this->doMerge($conf, $this->arrayize($props), $value);
$this->conf->setConfig($conf);
return $ret;
} | [
"public",
"function",
"merge",
"(",
"$",
"props",
",",
"array",
"$",
"value",
")",
"{",
"$",
"conf",
"=",
"$",
"this",
"->",
"conf",
"->",
"getConfig",
"(",
")",
";",
"$",
"ret",
"=",
"$",
"this",
"->",
"doMerge",
"(",
"$",
"conf",
",",
"$",
"t... | Merges a value to the current property value
@param array|string $props The property to set
@param array $value
@throws InvalidArgumentException If the target property contains a scalar.
@return mixed The merged value | [
"Merges",
"a",
"value",
"to",
"the",
"current",
"property",
"value"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Core/Configuration/PropertyAccess.php#L92-L99 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Core/Configuration/PropertyAccess.php | PropertyAccess.remove | public function remove($props)
{
$conf = $this->conf->getConfig();
$value = $this->doRemove($conf, $this->arrayize($props));
$this->conf->setConfig($conf);
return $value;
} | php | public function remove($props)
{
$conf = $this->conf->getConfig();
$value = $this->doRemove($conf, $this->arrayize($props));
$this->conf->setConfig($conf);
return $value;
} | [
"public",
"function",
"remove",
"(",
"$",
"props",
")",
"{",
"$",
"conf",
"=",
"$",
"this",
"->",
"conf",
"->",
"getConfig",
"(",
")",
";",
"$",
"value",
"=",
"$",
"this",
"->",
"doRemove",
"(",
"$",
"conf",
",",
"$",
"this",
"->",
"arrayize",
"(... | Removes a property
@param array|string $props The property to remove
@return mixed The value of the removed property | [
"Removes",
"a",
"property"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Core/Configuration/PropertyAccess.php#L108-L115 |
alchemy-fr/Phraseanet | lib/classes/patch/390alpha17a.php | patch_390alpha17a.apply | public function apply(base $appbox, Application $app)
{
$this->fillApplicationTable($app['orm.em']);
$this->fillAccountTable($app['orm.em']);
$this->fillLogTable($app['orm.em']);
$this->fillCodeTable($app['orm.em']);
$this->fillRefreshTokenTable($app['orm.em']);
$this->fillOauthTokenTable($app['orm.em']);
$this->setOauthTokenExpiresToNull($app['orm.em']);
$this->updateLogsTable($app['orm.em']);
} | php | public function apply(base $appbox, Application $app)
{
$this->fillApplicationTable($app['orm.em']);
$this->fillAccountTable($app['orm.em']);
$this->fillLogTable($app['orm.em']);
$this->fillCodeTable($app['orm.em']);
$this->fillRefreshTokenTable($app['orm.em']);
$this->fillOauthTokenTable($app['orm.em']);
$this->setOauthTokenExpiresToNull($app['orm.em']);
$this->updateLogsTable($app['orm.em']);
} | [
"public",
"function",
"apply",
"(",
"base",
"$",
"appbox",
",",
"Application",
"$",
"app",
")",
"{",
"$",
"this",
"->",
"fillApplicationTable",
"(",
"$",
"app",
"[",
"'orm.em'",
"]",
")",
";",
"$",
"this",
"->",
"fillAccountTable",
"(",
"$",
"app",
"["... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/390alpha17a.php#L58-L68 |
alchemy-fr/Phraseanet | lib/Alchemy/Phrasea/Command/Setup/FixAutoincrements.php | FixAutoincrements.doExecute | protected function doExecute(InputInterface $input, OutputInterface $output)
{
$this->input = $input;
$this->output = $output;
$this->appBox = $this->getContainer()->getApplicationBox();
$this->databoxes = [];
foreach ($this->getContainer()->getDataboxes() as $databox) {
$this->databoxes[] = $databox;
}
$this
->ab_fix_bas()
->ab_fix_BasketElements()
->ab_fix_Baskets()
->ab_fix_Sessions()
->db_fix_coll()
->db_fix_record()
;
} | php | protected function doExecute(InputInterface $input, OutputInterface $output)
{
$this->input = $input;
$this->output = $output;
$this->appBox = $this->getContainer()->getApplicationBox();
$this->databoxes = [];
foreach ($this->getContainer()->getDataboxes() as $databox) {
$this->databoxes[] = $databox;
}
$this
->ab_fix_bas()
->ab_fix_BasketElements()
->ab_fix_Baskets()
->ab_fix_Sessions()
->db_fix_coll()
->db_fix_record()
;
} | [
"protected",
"function",
"doExecute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"this",
"->",
"input",
"=",
"$",
"input",
";",
"$",
"this",
"->",
"output",
"=",
"$",
"output",
";",
"$",
"this",
"->",
"ap... | {@inheritdoc} | [
"{"
] | train | https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/Setup/FixAutoincrements.php#L50-L68 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.