repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1
value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
cakephp/authentication | src/Identifier/Ldap/ExtensionAdapter.php | ExtensionAdapter.unbind | public function unbind()
{
$this->_setErrorHandler();
ldap_unbind($this->_connection);
$this->_unsetErrorHandler();
$this->_connection = null;
} | php | public function unbind()
{
$this->_setErrorHandler();
ldap_unbind($this->_connection);
$this->_unsetErrorHandler();
$this->_connection = null;
} | [
"public",
"function",
"unbind",
"(",
")",
"{",
"$",
"this",
"->",
"_setErrorHandler",
"(",
")",
";",
"ldap_unbind",
"(",
"$",
"this",
"->",
"_connection",
")",
";",
"$",
"this",
"->",
"_unsetErrorHandler",
"(",
")",
";",
"$",
"this",
"->",
"_connection",... | Unbind from LDAP directory
@return void | [
"Unbind",
"from",
"LDAP",
"directory"
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Identifier/Ldap/ExtensionAdapter.php#L151-L158 | train |
cakephp/authentication | src/View/Helper/IdentityHelper.php | IdentityHelper.get | public function get($key = null)
{
if (empty($this->_identity)) {
return null;
}
if ($key === null) {
return $this->_identity->getOriginalData();
}
return Hash::get($this->_identity, $key);
} | php | public function get($key = null)
{
if (empty($this->_identity)) {
return null;
}
if ($key === null) {
return $this->_identity->getOriginalData();
}
return Hash::get($this->_identity, $key);
} | [
"public",
"function",
"get",
"(",
"$",
"key",
"=",
"null",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"_identity",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"$",
"key",
"===",
"null",
")",
"{",
"return",
"$",
"this",
"->"... | Gets user data
@param string|null $key Key of something you want to get from the identity data
@return mixed | [
"Gets",
"user",
"data"
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/View/Helper/IdentityHelper.php#L107-L118 | train |
cakephp/authentication | src/Identity.php | Identity.get | protected function get($field)
{
$map = $this->_config['fieldMap'];
if (isset($map[$field])) {
$field = $map[$field];
}
if (isset($this->data[$field])) {
return $this->data[$field];
}
return null;
} | php | protected function get($field)
{
$map = $this->_config['fieldMap'];
if (isset($map[$field])) {
$field = $map[$field];
}
if (isset($this->data[$field])) {
return $this->data[$field];
}
return null;
} | [
"protected",
"function",
"get",
"(",
"$",
"field",
")",
"{",
"$",
"map",
"=",
"$",
"this",
"->",
"_config",
"[",
"'fieldMap'",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"map",
"[",
"$",
"field",
"]",
")",
")",
"{",
"$",
"field",
"=",
"$",
"map",
... | Get data from the identity
@param string $field Field in the user data.
@return mixed | [
"Get",
"data",
"from",
"the",
"identity"
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Identity.php#L104-L116 | train |
cakephp/authentication | src/Authenticator/AuthenticatorCollection.php | AuthenticatorCollection._create | protected function _create($className, $alias, $config)
{
$authenticator = new $className($this->_identifiers, $config);
if (!($authenticator instanceof AuthenticatorInterface)) {
throw new RuntimeException(sprintf(
'Authenticator class `%s` must implement \Auth\Authentication\AuthenticatorInterface',
$className
));
}
return $authenticator;
} | php | protected function _create($className, $alias, $config)
{
$authenticator = new $className($this->_identifiers, $config);
if (!($authenticator instanceof AuthenticatorInterface)) {
throw new RuntimeException(sprintf(
'Authenticator class `%s` must implement \Auth\Authentication\AuthenticatorInterface',
$className
));
}
return $authenticator;
} | [
"protected",
"function",
"_create",
"(",
"$",
"className",
",",
"$",
"alias",
",",
"$",
"config",
")",
"{",
"$",
"authenticator",
"=",
"new",
"$",
"className",
"(",
"$",
"this",
"->",
"_identifiers",
",",
"$",
"config",
")",
";",
"if",
"(",
"!",
"(",... | Creates authenticator instance.
@param string $className Authenticator class.
@param string $alias Authenticator alias.
@param array $config Config array.
@return \Authentication\Authenticator\AuthenticatorInterface
@throws \RuntimeException | [
"Creates",
"authenticator",
"instance",
"."
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Authenticator/AuthenticatorCollection.php#L53-L64 | train |
cakephp/authentication | src/PasswordHasher/PasswordHasherFactory.php | PasswordHasherFactory.build | public static function build($passwordHasher)
{
$config = [];
if (is_string($passwordHasher)) {
$class = $passwordHasher;
} else {
$class = $passwordHasher['className'];
$config = $passwordHasher;
unset($config['className']);
}
$className = App::className($class, 'PasswordHasher', 'PasswordHasher');
if ($className === false) {
throw new RuntimeException(sprintf('Password hasher class `%s` was not found.', $class));
}
$hasher = new $className($config);
if (!($hasher instanceof PasswordHasherInterface)) {
throw new RuntimeException('Password hasher must implement PasswordHasherInterface.');
}
return $hasher;
} | php | public static function build($passwordHasher)
{
$config = [];
if (is_string($passwordHasher)) {
$class = $passwordHasher;
} else {
$class = $passwordHasher['className'];
$config = $passwordHasher;
unset($config['className']);
}
$className = App::className($class, 'PasswordHasher', 'PasswordHasher');
if ($className === false) {
throw new RuntimeException(sprintf('Password hasher class `%s` was not found.', $class));
}
$hasher = new $className($config);
if (!($hasher instanceof PasswordHasherInterface)) {
throw new RuntimeException('Password hasher must implement PasswordHasherInterface.');
}
return $hasher;
} | [
"public",
"static",
"function",
"build",
"(",
"$",
"passwordHasher",
")",
"{",
"$",
"config",
"=",
"[",
"]",
";",
"if",
"(",
"is_string",
"(",
"$",
"passwordHasher",
")",
")",
"{",
"$",
"class",
"=",
"$",
"passwordHasher",
";",
"}",
"else",
"{",
"$",... | Returns password hasher object out of a hasher name or a configuration array
@param string|array $passwordHasher Name of the password hasher or an array with
at least the key `className` set to the name of the class to use
@return \Authentication\PasswordHasher\PasswordHasherInterface Password hasher instance
@throws \RuntimeException If password hasher class not found or it does
not implement \Authentication\PasswordHasher\PasswordHasherInterface | [
"Returns",
"password",
"hasher",
"object",
"out",
"of",
"a",
"hasher",
"name",
"or",
"a",
"configuration",
"array"
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/PasswordHasher/PasswordHasherFactory.php#L34-L56 | train |
cakephp/authentication | src/Identifier/PasswordIdentifier.php | PasswordIdentifier.getPasswordHasher | public function getPasswordHasher()
{
if ($this->_passwordHasher === null) {
$passwordHasher = $this->getConfig('passwordHasher');
if ($passwordHasher !== null) {
$passwordHasher = PasswordHasherFactory::build($passwordHasher);
} else {
$passwordHasher = $this->_getPasswordHasher();
}
$this->_passwordHasher = $passwordHasher;
}
return $this->_passwordHasher;
} | php | public function getPasswordHasher()
{
if ($this->_passwordHasher === null) {
$passwordHasher = $this->getConfig('passwordHasher');
if ($passwordHasher !== null) {
$passwordHasher = PasswordHasherFactory::build($passwordHasher);
} else {
$passwordHasher = $this->_getPasswordHasher();
}
$this->_passwordHasher = $passwordHasher;
}
return $this->_passwordHasher;
} | [
"public",
"function",
"getPasswordHasher",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_passwordHasher",
"===",
"null",
")",
"{",
"$",
"passwordHasher",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'passwordHasher'",
")",
";",
"if",
"(",
"$",
"passwordHash... | Return password hasher object.
@return \Authentication\PasswordHasher\PasswordHasherInterface Password hasher instance. | [
"Return",
"password",
"hasher",
"object",
"."
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Identifier/PasswordIdentifier.php#L73-L86 | train |
cakephp/authentication | src/Identifier/PasswordIdentifier.php | PasswordIdentifier._checkPassword | protected function _checkPassword($identity, $password)
{
$passwordField = $this->getConfig('fields.' . self::CREDENTIAL_PASSWORD);
if ($identity === null) {
$identity = [
$passwordField => ''
];
}
$hasher = $this->getPasswordHasher();
$hashedPassword = $identity[$passwordField];
if (!$hasher->check($password, $hashedPassword)) {
return false;
}
$this->_needsPasswordRehash = $hasher->needsRehash($hashedPassword);
return true;
} | php | protected function _checkPassword($identity, $password)
{
$passwordField = $this->getConfig('fields.' . self::CREDENTIAL_PASSWORD);
if ($identity === null) {
$identity = [
$passwordField => ''
];
}
$hasher = $this->getPasswordHasher();
$hashedPassword = $identity[$passwordField];
if (!$hasher->check($password, $hashedPassword)) {
return false;
}
$this->_needsPasswordRehash = $hasher->needsRehash($hashedPassword);
return true;
} | [
"protected",
"function",
"_checkPassword",
"(",
"$",
"identity",
",",
"$",
"password",
")",
"{",
"$",
"passwordField",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'fields.'",
".",
"self",
"::",
"CREDENTIAL_PASSWORD",
")",
";",
"if",
"(",
"$",
"identity",
"=... | Find a user record using the username and password provided.
Input passwords will be hashed even when a user doesn't exist. This
helps mitigate timing attacks that are attempting to find valid usernames.
@param array|\ArrayAccess|null $identity The identity or null.
@param string|null $password The password.
@return bool | [
"Find",
"a",
"user",
"record",
"using",
"the",
"username",
"and",
"password",
"provided",
".",
"Input",
"passwords",
"will",
"be",
"hashed",
"even",
"when",
"a",
"user",
"doesn",
"t",
"exist",
".",
"This",
"helps",
"mitigate",
"timing",
"attacks",
"that",
... | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Identifier/PasswordIdentifier.php#L117-L136 | train |
cakephp/authentication | src/Authenticator/FormAuthenticator.php | FormAuthenticator._buildLoginUrlErrorResult | protected function _buildLoginUrlErrorResult($request)
{
$errors = [
sprintf(
'Login URL `%s` did not match `%s`.',
(string)$request->getUri(),
implode('` or `', (array)$this->getConfig('loginUrl'))
)
];
return new Result(null, Result::FAILURE_OTHER, $errors);
} | php | protected function _buildLoginUrlErrorResult($request)
{
$errors = [
sprintf(
'Login URL `%s` did not match `%s`.',
(string)$request->getUri(),
implode('` or `', (array)$this->getConfig('loginUrl'))
)
];
return new Result(null, Result::FAILURE_OTHER, $errors);
} | [
"protected",
"function",
"_buildLoginUrlErrorResult",
"(",
"$",
"request",
")",
"{",
"$",
"errors",
"=",
"[",
"sprintf",
"(",
"'Login URL `%s` did not match `%s`.'",
",",
"(",
"string",
")",
"$",
"request",
"->",
"getUri",
"(",
")",
",",
"implode",
"(",
"'` or... | Prepares the error object for a login URL error
@param \Psr\Http\Message\ServerRequestInterface $request The request that contains login information.
@return \Authentication\Authenticator\ResultInterface | [
"Prepares",
"the",
"error",
"object",
"for",
"a",
"login",
"URL",
"error"
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Authenticator/FormAuthenticator.php#L83-L94 | train |
Interfacelab/ilab-media-tools | classes/Utilities/Prefixer.php | Prefixer.genUUID | private function genUUID() {
return sprintf('%04x%04x%04x%03x4%04x%04x%04x%04x',
mt_rand(0, 65535),
mt_rand(0, 65535),
mt_rand(0, 65535),
mt_rand(0, 4095),
bindec(substr_replace(sprintf('%016b', mt_rand(0, 65535)), '01', 6, 2)),
mt_rand(0, 65535),
mt_rand(0, 65535),
mt_rand(0, 65535)
);
} | php | private function genUUID() {
return sprintf('%04x%04x%04x%03x4%04x%04x%04x%04x',
mt_rand(0, 65535),
mt_rand(0, 65535),
mt_rand(0, 65535),
mt_rand(0, 4095),
bindec(substr_replace(sprintf('%016b', mt_rand(0, 65535)), '01', 6, 2)),
mt_rand(0, 65535),
mt_rand(0, 65535),
mt_rand(0, 65535)
);
} | [
"private",
"function",
"genUUID",
"(",
")",
"{",
"return",
"sprintf",
"(",
"'%04x%04x%04x%03x4%04x%04x%04x%04x'",
",",
"mt_rand",
"(",
"0",
",",
"65535",
")",
",",
"mt_rand",
"(",
"0",
",",
"65535",
")",
",",
"mt_rand",
"(",
"0",
",",
"65535",
")",
",",
... | Generates a UUID string.
@return string | [
"Generates",
"a",
"UUID",
"string",
"."
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Utilities/Prefixer.php#L54-L65 | train |
Interfacelab/ilab-media-tools | classes/Utilities/Prefixer.php | Prefixer.genUUIDPath | private function genUUIDPath() {
$uid = $this->genUUID();
$result = '/';
$segments = 8;
if($segments > strlen($uid) / 2) {
$segments = strlen($uid) / 2;
}
for($i = 0; $i < $segments; $i ++) {
$result .= substr($uid, $i * 2, 2).'/';
}
return $result;
} | php | private function genUUIDPath() {
$uid = $this->genUUID();
$result = '/';
$segments = 8;
if($segments > strlen($uid) / 2) {
$segments = strlen($uid) / 2;
}
for($i = 0; $i < $segments; $i ++) {
$result .= substr($uid, $i * 2, 2).'/';
}
return $result;
} | [
"private",
"function",
"genUUIDPath",
"(",
")",
"{",
"$",
"uid",
"=",
"$",
"this",
"->",
"genUUID",
"(",
")",
";",
"$",
"result",
"=",
"'/'",
";",
"$",
"segments",
"=",
"8",
";",
"if",
"(",
"$",
"segments",
">",
"strlen",
"(",
"$",
"uid",
")",
... | Generates a UUID path
@return string | [
"Generates",
"a",
"UUID",
"path"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Utilities/Prefixer.php#L71-L84 | train |
Interfacelab/ilab-media-tools | classes/Utilities/Prefixer.php | Prefixer.getObjectVersion | private function getObjectVersion($id = null) {
if(!empty($id) && !empty($this->versionedIds[$id])) {
return $this->versionedIds[$id];
}
$date_format = 'dHis';
// Use current time so that object version is unique
$time = current_time('timestamp');
$object_version = date($date_format, $time).'/';
$object_version = apply_filters('as3cf_get_object_version_string', $object_version);
if(!empty($id)) {
$this->versionedIds[$id] = $object_version;
}
return $object_version;
} | php | private function getObjectVersion($id = null) {
if(!empty($id) && !empty($this->versionedIds[$id])) {
return $this->versionedIds[$id];
}
$date_format = 'dHis';
// Use current time so that object version is unique
$time = current_time('timestamp');
$object_version = date($date_format, $time).'/';
$object_version = apply_filters('as3cf_get_object_version_string', $object_version);
if(!empty($id)) {
$this->versionedIds[$id] = $object_version;
}
return $object_version;
} | [
"private",
"function",
"getObjectVersion",
"(",
"$",
"id",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"id",
")",
"&&",
"!",
"empty",
"(",
"$",
"this",
"->",
"versionedIds",
"[",
"$",
"id",
"]",
")",
")",
"{",
"return",
"$",
"this",... | Gets an Offload S3 compatible object version string.
@param int $id
@return string|null | [
"Gets",
"an",
"Offload",
"S3",
"compatible",
"object",
"version",
"string",
"."
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Utilities/Prefixer.php#L93-L111 | train |
Interfacelab/ilab-media-tools | classes/Tasks/BatchManager.php | BatchManager.incrementTotalTime | public function incrementTotalTime($batch, $lastTime) {
update_option("ilab_media_tools_{$batch}_last_time", $lastTime);
update_option("ilab_media_tools_{$batch}_total_time", $this->totalTime($batch) + $lastTime);
} | php | public function incrementTotalTime($batch, $lastTime) {
update_option("ilab_media_tools_{$batch}_last_time", $lastTime);
update_option("ilab_media_tools_{$batch}_total_time", $this->totalTime($batch) + $lastTime);
} | [
"public",
"function",
"incrementTotalTime",
"(",
"$",
"batch",
",",
"$",
"lastTime",
")",
"{",
"update_option",
"(",
"\"ilab_media_tools_{$batch}_last_time\"",
",",
"$",
"lastTime",
")",
";",
"update_option",
"(",
"\"ilab_media_tools_{$batch}_total_time\"",
",",
"$",
... | Increments the total processing time for the batch
@param $batch
@param float $lastTime | [
"Increments",
"the",
"total",
"processing",
"time",
"for",
"the",
"batch"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tasks/BatchManager.php#L257-L260 | train |
Interfacelab/ilab-media-tools | classes/Tasks/BatchManager.php | BatchManager.setErrorMessage | public function setErrorMessage($batch, $error) {
update_option("ilab_media_tools_{$batch}_error_id", $batch.'-error-'.sanitize_title(microtime(true)).'-forever');
update_option("ilab_media_tools_{$batch}_error_message", $error);
} | php | public function setErrorMessage($batch, $error) {
update_option("ilab_media_tools_{$batch}_error_id", $batch.'-error-'.sanitize_title(microtime(true)).'-forever');
update_option("ilab_media_tools_{$batch}_error_message", $error);
} | [
"public",
"function",
"setErrorMessage",
"(",
"$",
"batch",
",",
"$",
"error",
")",
"{",
"update_option",
"(",
"\"ilab_media_tools_{$batch}_error_id\"",
",",
"$",
"batch",
".",
"'-error-'",
".",
"sanitize_title",
"(",
"microtime",
"(",
"true",
")",
")",
".",
"... | Sets the current error
@param $batch
@param $error | [
"Sets",
"the",
"current",
"error"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tasks/BatchManager.php#L267-L270 | train |
Interfacelab/ilab-media-tools | classes/Tasks/BatchManager.php | BatchManager.lastUpdate | public function lastUpdate($batch) {
$lu = get_option("ilab_media_tools_{$batch}_last_update", 0);
if ($lu > 0) {
$lu = microtime(true) - $lu;
}
return $lu;
} | php | public function lastUpdate($batch) {
$lu = get_option("ilab_media_tools_{$batch}_last_update", 0);
if ($lu > 0) {
$lu = microtime(true) - $lu;
}
return $lu;
} | [
"public",
"function",
"lastUpdate",
"(",
"$",
"batch",
")",
"{",
"$",
"lu",
"=",
"get_option",
"(",
"\"ilab_media_tools_{$batch}_last_update\"",
",",
"0",
")",
";",
"if",
"(",
"$",
"lu",
">",
"0",
")",
"{",
"$",
"lu",
"=",
"microtime",
"(",
"true",
")"... | Returns the amount of time that has elapsed since the last item was processed.
@param $batch
@return float | [
"Returns",
"the",
"amount",
"of",
"time",
"that",
"has",
"elapsed",
"since",
"the",
"last",
"item",
"was",
"processed",
"."
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tasks/BatchManager.php#L296-L303 | train |
Interfacelab/ilab-media-tools | classes/Tasks/BatchManager.php | BatchManager.stats | public function stats($batch) {
$total = $this->totalCount($batch);
$current = $this->current($batch);
$totalTime = $this->totalTime($batch);
$progress = 0;
if ($total > 0) {
$progress = ($current / $total) * 100;
}
$postsPerMinute = 0;
$eta = 0;
if (($totalTime > 0) && ($current > 1)) {
$postsPerSecond = ($totalTime / ($current - 1));
if ($postsPerSecond > 0) {
$postsPerMinute = 60 / $postsPerSecond;
$eta = ($total - $current) / $postsPerMinute;
}
}
$thumbUrl = null;
$icon = false;
if (!empty($this->currentID($batch))) {
$thumb = wp_get_attachment_image_src($this->currentID($batch), 'thumbnail', true);
if (!empty($thumb)) {
$thumbUrl = $thumb[0];
$icon = (($thumb[1] != 150) && ($thumb[2] != 150));
}
}
return [
'running' => $this->status($batch),
'current' => $current,
'currentID' => $this->currentID($batch),
'thumb' => $thumbUrl,
'icon' => $icon,
'currentFile' => $this->currentFile($batch),
'total' => $total,
'totalTime' => $totalTime,
'lastTime' => $this->lastTime($batch),
'lastRun' => $this->lastRun($batch),
'lastUpdate' => $this->lastUpdate($batch),
'eta' => $eta,
'progress' => $progress,
'postsPerMinute' => $postsPerMinute,
'shouldCancel' => $this->shouldCancel($batch)
];
} | php | public function stats($batch) {
$total = $this->totalCount($batch);
$current = $this->current($batch);
$totalTime = $this->totalTime($batch);
$progress = 0;
if ($total > 0) {
$progress = ($current / $total) * 100;
}
$postsPerMinute = 0;
$eta = 0;
if (($totalTime > 0) && ($current > 1)) {
$postsPerSecond = ($totalTime / ($current - 1));
if ($postsPerSecond > 0) {
$postsPerMinute = 60 / $postsPerSecond;
$eta = ($total - $current) / $postsPerMinute;
}
}
$thumbUrl = null;
$icon = false;
if (!empty($this->currentID($batch))) {
$thumb = wp_get_attachment_image_src($this->currentID($batch), 'thumbnail', true);
if (!empty($thumb)) {
$thumbUrl = $thumb[0];
$icon = (($thumb[1] != 150) && ($thumb[2] != 150));
}
}
return [
'running' => $this->status($batch),
'current' => $current,
'currentID' => $this->currentID($batch),
'thumb' => $thumbUrl,
'icon' => $icon,
'currentFile' => $this->currentFile($batch),
'total' => $total,
'totalTime' => $totalTime,
'lastTime' => $this->lastTime($batch),
'lastRun' => $this->lastRun($batch),
'lastUpdate' => $this->lastUpdate($batch),
'eta' => $eta,
'progress' => $progress,
'postsPerMinute' => $postsPerMinute,
'shouldCancel' => $this->shouldCancel($batch)
];
} | [
"public",
"function",
"stats",
"(",
"$",
"batch",
")",
"{",
"$",
"total",
"=",
"$",
"this",
"->",
"totalCount",
"(",
"$",
"batch",
")",
";",
"$",
"current",
"=",
"$",
"this",
"->",
"current",
"(",
"$",
"batch",
")",
";",
"$",
"totalTime",
"=",
"$... | Returns stats about this batch
@param $batch
@return array | [
"Returns",
"stats",
"about",
"this",
"batch"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tasks/BatchManager.php#L313-L363 | train |
Interfacelab/ilab-media-tools | classes/Tasks/BatchManager.php | BatchManager.displayAnyErrors | public function displayAnyErrors($batch) {
$error = $this->errorMessage($batch);
if (!empty($error)) {
NoticeManager::instance()->displayAdminNotice('error', $error, true, $this->errorMessageId($batch));
}
} | php | public function displayAnyErrors($batch) {
$error = $this->errorMessage($batch);
if (!empty($error)) {
NoticeManager::instance()->displayAdminNotice('error', $error, true, $this->errorMessageId($batch));
}
} | [
"public",
"function",
"displayAnyErrors",
"(",
"$",
"batch",
")",
"{",
"$",
"error",
"=",
"$",
"this",
"->",
"errorMessage",
"(",
"$",
"batch",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"error",
")",
")",
"{",
"NoticeManager",
"::",
"instance",
"(... | Display any error for a batch
@param $batch | [
"Display",
"any",
"error",
"for",
"a",
"batch"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tasks/BatchManager.php#L369-L375 | train |
Interfacelab/ilab-media-tools | classes/Tasks/BatchManager.php | BatchManager.reset | public function reset($batch) {
delete_option("ilab_media_tools_{$batch}_status");
delete_option("ilab_media_tools_{$batch}_current");
delete_option("ilab_media_tools_{$batch}_file");
delete_option("ilab_media_tools_{$batch}_total");
delete_option("ilab_media_tools_{$batch}_last_run");
delete_option("ilab_media_tools_{$batch}_total_time");
delete_option("ilab_media_tools_{$batch}_last_time");
delete_option("ilab_media_tools_{$batch}_last_update");
} | php | public function reset($batch) {
delete_option("ilab_media_tools_{$batch}_status");
delete_option("ilab_media_tools_{$batch}_current");
delete_option("ilab_media_tools_{$batch}_file");
delete_option("ilab_media_tools_{$batch}_total");
delete_option("ilab_media_tools_{$batch}_last_run");
delete_option("ilab_media_tools_{$batch}_total_time");
delete_option("ilab_media_tools_{$batch}_last_time");
delete_option("ilab_media_tools_{$batch}_last_update");
} | [
"public",
"function",
"reset",
"(",
"$",
"batch",
")",
"{",
"delete_option",
"(",
"\"ilab_media_tools_{$batch}_status\"",
")",
";",
"delete_option",
"(",
"\"ilab_media_tools_{$batch}_current\"",
")",
";",
"delete_option",
"(",
"\"ilab_media_tools_{$batch}_file\"",
")",
";... | Removes an stored information about the batch
@param $batch | [
"Removes",
"an",
"stored",
"information",
"about",
"the",
"batch"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tasks/BatchManager.php#L381-L390 | train |
Interfacelab/ilab-media-tools | classes/Tasks/BatchManager.php | BatchManager.addToBatchAndRun | public function addToBatchAndRun($batch, $postIDs) {
if (!isset(static::$batchClasses[$batch])) {
throw new \Exception("Batch '$batch' is not registered.");
}
$this->reset($batch);
if (count($postIDs) == 0) {
return;
}
$testResult = $this->testConnectivity();
if ($testResult !== true) {
$error = 'Unknown';
if (is_wp_error($testResult)) {
$error = $testResult->get_error_message();
} else if (is_array($testResult)) {
$error = 'HTTP response code was '.$testResult['response']['code'];
}
$storageSettingsURL = admin_url('admin.php?page=media-tools-s3#ilab-media-s3-batch-settings');
$message = "There was an error attempting to run your batch. Try changing the <strong>Connection Timeout</strong> in <a href='$storageSettingsURL'>Storage Settings</a> to a higher number like 0.1 or 1 to see if that helps. The actual error was: $error";
$this->setErrorMessage($batch, $message);
throw new \Exception($message);
}
$firstPostFile = get_attached_file($postIDs[0]);
$fileName = basename($firstPostFile);
$this->setCurrent($batch, 1);
$this->setTotalCount($batch, count($postIDs));
$this->setCurrentFile($batch, $fileName);
$this->setShouldCancel($batch, false);
$this->setStatus($batch, true);
/** @var BackgroundProcess $batchProcess */
$batchProcess = new static::$batchClasses[$batch]();
$index = 0;
foreach($postIDs as $postID) {
$batchProcess->push_to_queue(['index' => $index, 'post' => $postID]);
$index++;
}
$batchProcess->save();
$batchProcess->dispatch();
$this->setLastRun($batch, time());
} | php | public function addToBatchAndRun($batch, $postIDs) {
if (!isset(static::$batchClasses[$batch])) {
throw new \Exception("Batch '$batch' is not registered.");
}
$this->reset($batch);
if (count($postIDs) == 0) {
return;
}
$testResult = $this->testConnectivity();
if ($testResult !== true) {
$error = 'Unknown';
if (is_wp_error($testResult)) {
$error = $testResult->get_error_message();
} else if (is_array($testResult)) {
$error = 'HTTP response code was '.$testResult['response']['code'];
}
$storageSettingsURL = admin_url('admin.php?page=media-tools-s3#ilab-media-s3-batch-settings');
$message = "There was an error attempting to run your batch. Try changing the <strong>Connection Timeout</strong> in <a href='$storageSettingsURL'>Storage Settings</a> to a higher number like 0.1 or 1 to see if that helps. The actual error was: $error";
$this->setErrorMessage($batch, $message);
throw new \Exception($message);
}
$firstPostFile = get_attached_file($postIDs[0]);
$fileName = basename($firstPostFile);
$this->setCurrent($batch, 1);
$this->setTotalCount($batch, count($postIDs));
$this->setCurrentFile($batch, $fileName);
$this->setShouldCancel($batch, false);
$this->setStatus($batch, true);
/** @var BackgroundProcess $batchProcess */
$batchProcess = new static::$batchClasses[$batch]();
$index = 0;
foreach($postIDs as $postID) {
$batchProcess->push_to_queue(['index' => $index, 'post' => $postID]);
$index++;
}
$batchProcess->save();
$batchProcess->dispatch();
$this->setLastRun($batch, time());
} | [
"public",
"function",
"addToBatchAndRun",
"(",
"$",
"batch",
",",
"$",
"postIDs",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"static",
"::",
"$",
"batchClasses",
"[",
"$",
"batch",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"\"Batch '$bat... | Adds posts to a batch and runs it. If another one of this batch type is running, it will be cancelled.
@param $batch
@param $postIDs
@throws \Exception | [
"Adds",
"posts",
"to",
"a",
"batch",
"and",
"runs",
"it",
".",
"If",
"another",
"one",
"of",
"this",
"batch",
"type",
"is",
"running",
"it",
"will",
"be",
"cancelled",
"."
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tasks/BatchManager.php#L398-L448 | train |
Interfacelab/ilab-media-tools | classes/Tasks/BatchManager.php | BatchManager.dispatchBatchesIfNeeded | public function dispatchBatchesIfNeeded() {
foreach(static::$batchClasses as $batch => $batchClass) {
if ($this->status($batch)) {
$lastRun = $this->lastRun($batch);
if ((time() - $lastRun) > 60) {
$this->setLastRun($batch, time());
/** @var BackgroundProcess $process */
$process = new $batchClass();
$process->dispatch();
}
}
}
} | php | public function dispatchBatchesIfNeeded() {
foreach(static::$batchClasses as $batch => $batchClass) {
if ($this->status($batch)) {
$lastRun = $this->lastRun($batch);
if ((time() - $lastRun) > 60) {
$this->setLastRun($batch, time());
/** @var BackgroundProcess $process */
$process = new $batchClass();
$process->dispatch();
}
}
}
} | [
"public",
"function",
"dispatchBatchesIfNeeded",
"(",
")",
"{",
"foreach",
"(",
"static",
"::",
"$",
"batchClasses",
"as",
"$",
"batch",
"=>",
"$",
"batchClass",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"status",
"(",
"$",
"batch",
")",
")",
"{",
"$",
... | Determines if enough time has elapsed since the last time the batch was "forced" to run and then runs it if so | [
"Determines",
"if",
"enough",
"time",
"has",
"elapsed",
"since",
"the",
"last",
"time",
"the",
"batch",
"was",
"forced",
"to",
"run",
"and",
"then",
"runs",
"it",
"if",
"so"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tasks/BatchManager.php#L453-L467 | train |
Interfacelab/ilab-media-tools | classes/Utilities/Logging/DatabaseLogger.php | DatabaseLogger.log | public function log($channel, $level, $message, $context = '') {
if (!$this->enabled) {
return;
}
$message = ltrim($message);
global $wpdb;
$query = $wpdb->prepare("insert into {$this->table} (date, channel, level, message, context) values (%s, %s, %s, %s, %s)", current_time('mysql', true), $channel, $level, $message, $context);
$wpdb->query($query);
} | php | public function log($channel, $level, $message, $context = '') {
if (!$this->enabled) {
return;
}
$message = ltrim($message);
global $wpdb;
$query = $wpdb->prepare("insert into {$this->table} (date, channel, level, message, context) values (%s, %s, %s, %s, %s)", current_time('mysql', true), $channel, $level, $message, $context);
$wpdb->query($query);
} | [
"public",
"function",
"log",
"(",
"$",
"channel",
",",
"$",
"level",
",",
"$",
"message",
",",
"$",
"context",
"=",
"''",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"enabled",
")",
"{",
"return",
";",
"}",
"$",
"message",
"=",
"ltrim",
"(",
"... | Logs to the database
@param $channel
@param $level
@param $message
@param $context | [
"Logs",
"to",
"the",
"database"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Utilities/Logging/DatabaseLogger.php#L51-L62 | train |
Interfacelab/ilab-media-tools | classes/Utilities/Logging/DatabaseLogger.php | DatabaseLogger.insureTable | protected function insureTable() {
global $wpdb;
$this->table = $wpdb->prefix.'ilab_mc_logging';
$tableSchema = <<<SQL
create table {$this->table} (
id bigint not null auto_increment,
date datetime not null,
channel varchar(32) not null,
level varchar(16) not null,
message text,
context text,
primary key(id)
);
SQL;
global $wpdb;
$query = $wpdb->prepare("SHOW TABLES LIKE %s", $wpdb->esc_like($this->table));
$this->enabled = ($wpdb->get_var($query) == $this->table);
if (!$this->enabled) {
$wpdb->query($tableSchema);
$this->enabled = ($wpdb->get_var($query) == $this->table);
}
} | php | protected function insureTable() {
global $wpdb;
$this->table = $wpdb->prefix.'ilab_mc_logging';
$tableSchema = <<<SQL
create table {$this->table} (
id bigint not null auto_increment,
date datetime not null,
channel varchar(32) not null,
level varchar(16) not null,
message text,
context text,
primary key(id)
);
SQL;
global $wpdb;
$query = $wpdb->prepare("SHOW TABLES LIKE %s", $wpdb->esc_like($this->table));
$this->enabled = ($wpdb->get_var($query) == $this->table);
if (!$this->enabled) {
$wpdb->query($tableSchema);
$this->enabled = ($wpdb->get_var($query) == $this->table);
}
} | [
"protected",
"function",
"insureTable",
"(",
")",
"{",
"global",
"$",
"wpdb",
";",
"$",
"this",
"->",
"table",
"=",
"$",
"wpdb",
"->",
"prefix",
".",
"'ilab_mc_logging'",
";",
"$",
"tableSchema",
"=",
" <<<SQL\n create table {$this->table} (\n id big... | Insures the table exists | [
"Insures",
"the",
"table",
"exists"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Utilities/Logging/DatabaseLogger.php#L70-L98 | train |
Interfacelab/ilab-media-tools | classes/Utilities/Logging/DatabaseLogger.php | DatabaseLogger.csv | public function csv() {
global $wpdb;
$fd = fopen('php://temp/maxmemory:1048576', 'w');
fputcsv($fd, ["date", "channel", "level", "message", "context"]);
$rows = $wpdb->get_results("select date, channel, level, message, context from {$this->table} order by id asc", ARRAY_N);
if (is_array($rows) && count($rows) > 0) {
foreach($rows as $row) {
fputcsv($fd, $row);
}
}
rewind($fd);
$csv = stream_get_contents($fd);
fclose($fd);
return $csv;
} | php | public function csv() {
global $wpdb;
$fd = fopen('php://temp/maxmemory:1048576', 'w');
fputcsv($fd, ["date", "channel", "level", "message", "context"]);
$rows = $wpdb->get_results("select date, channel, level, message, context from {$this->table} order by id asc", ARRAY_N);
if (is_array($rows) && count($rows) > 0) {
foreach($rows as $row) {
fputcsv($fd, $row);
}
}
rewind($fd);
$csv = stream_get_contents($fd);
fclose($fd);
return $csv;
} | [
"public",
"function",
"csv",
"(",
")",
"{",
"global",
"$",
"wpdb",
";",
"$",
"fd",
"=",
"fopen",
"(",
"'php://temp/maxmemory:1048576'",
",",
"'w'",
")",
";",
"fputcsv",
"(",
"$",
"fd",
",",
"[",
"\"date\"",
",",
"\"channel\"",
",",
"\"level\"",
",",
"\... | Exports the log to CSV
@return bool|string | [
"Exports",
"the",
"log",
"to",
"CSV"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Utilities/Logging/DatabaseLogger.php#L136-L155 | train |
Interfacelab/ilab-media-tools | classes/Tasks/AsyncRequest.php | AsyncRequest.dispatch | public function dispatch() {
$url = add_query_arg( $this->get_query_args(), $this->get_query_url() );
$args = $this->get_post_args();
Logger::info( "Background dispatching $url", $args);
$rawUrl = esc_url_raw( $url );
Logger::info("Async call to $rawUrl", ['args' => $args]);
$result = wp_remote_post( $rawUrl, $args );
Logger::info("Async call complete.", ['url' => $rawUrl, 'result'=>$result]);
return $result;
} | php | public function dispatch() {
$url = add_query_arg( $this->get_query_args(), $this->get_query_url() );
$args = $this->get_post_args();
Logger::info( "Background dispatching $url", $args);
$rawUrl = esc_url_raw( $url );
Logger::info("Async call to $rawUrl", ['args' => $args]);
$result = wp_remote_post( $rawUrl, $args );
Logger::info("Async call complete.", ['url' => $rawUrl, 'result'=>$result]);
return $result;
} | [
"public",
"function",
"dispatch",
"(",
")",
"{",
"$",
"url",
"=",
"add_query_arg",
"(",
"$",
"this",
"->",
"get_query_args",
"(",
")",
",",
"$",
"this",
"->",
"get_query_url",
"(",
")",
")",
";",
"$",
"args",
"=",
"$",
"this",
"->",
"get_post_args",
... | Dispatch the async request
@return array|WP_Error | [
"Dispatch",
"the",
"async",
"request"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tasks/AsyncRequest.php#L83-L94 | train |
Interfacelab/ilab-media-tools | classes/Tasks/AsyncRequest.php | AsyncRequest.get_query_args | protected function get_query_args() {
if ( property_exists( $this, 'query_args' ) ) {
return $this->query_args;
}
return array(
'action' => $this->identifier,
'nonce' => wp_create_nonce( $this->identifier ),
);
} | php | protected function get_query_args() {
if ( property_exists( $this, 'query_args' ) ) {
return $this->query_args;
}
return array(
'action' => $this->identifier,
'nonce' => wp_create_nonce( $this->identifier ),
);
} | [
"protected",
"function",
"get_query_args",
"(",
")",
"{",
"if",
"(",
"property_exists",
"(",
"$",
"this",
",",
"'query_args'",
")",
")",
"{",
"return",
"$",
"this",
"->",
"query_args",
";",
"}",
"return",
"array",
"(",
"'action'",
"=>",
"$",
"this",
"->"... | Get query args
@return array | [
"Get",
"query",
"args"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tasks/AsyncRequest.php#L101-L110 | train |
Interfacelab/ilab-media-tools | classes/Tasks/AsyncRequest.php | AsyncRequest.get_post_args | protected function get_post_args() {
if ( property_exists( $this, 'post_args' ) ) {
return $this->post_args;
}
$timeout = EnvironmentOptions::Option('ilab-media-s3-batch-timeout', null, 0.1);
return array(
'timeout' => $timeout,
'blocking' => false,
'body' => $this->data,
'cookies' => $_COOKIE,
'sslverify' => apply_filters( 'https_local_ssl_verify', false ),
);
} | php | protected function get_post_args() {
if ( property_exists( $this, 'post_args' ) ) {
return $this->post_args;
}
$timeout = EnvironmentOptions::Option('ilab-media-s3-batch-timeout', null, 0.1);
return array(
'timeout' => $timeout,
'blocking' => false,
'body' => $this->data,
'cookies' => $_COOKIE,
'sslverify' => apply_filters( 'https_local_ssl_verify', false ),
);
} | [
"protected",
"function",
"get_post_args",
"(",
")",
"{",
"if",
"(",
"property_exists",
"(",
"$",
"this",
",",
"'post_args'",
")",
")",
"{",
"return",
"$",
"this",
"->",
"post_args",
";",
"}",
"$",
"timeout",
"=",
"EnvironmentOptions",
"::",
"Option",
"(",
... | Get post args
@return array | [
"Get",
"post",
"args"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tasks/AsyncRequest.php#L130-L143 | train |
Interfacelab/ilab-media-tools | classes/Tools/Imgix/ImgixTool.php | ImgixTool.buildSizedImgixImage | private function buildSizedImgixImage($id, $size) {
$meta = wp_get_attachment_metadata($id);
if(!$meta || empty($meta)) {
return false;
}
if(!isset($meta['s3'])) {
return [];
}
$imgix = new UrlBuilder($this->imgixDomains, $this->useHTTPS);
if($this->signingKey) {
$imgix->setSignKey($this->signingKey);
}
$is_crop = ((count($size) >= 3) && ($size[2] == 'crop'));
if (!$is_crop && $this->shouldCrop) {
$this->shouldCrop = false;
$is_crop = true;
}
if ($is_crop && (($size[0] === 0) || ($size[1] === 0))) {
if ($size[0] === 0) {
$size[0] = 10000;
} else {
$size[1] = 10000;
}
$is_crop = false;
}
if(isset($size['width'])) {
$size = [
$size['width'],
$size['height']
];
}
$params = [
'fit' => ($is_crop) ? 'crop' : 'fit',
'w' => $size[0],
'h' => $size[1],
'fm' => 'jpg'
];
$params = apply_filters('ilab-imgix-filter-parameters', $params, $size, $id, $meta);
$imageFile = (isset($meta['s3'])) ? $meta['s3']['key'] : $meta['file'];
$result = [
$imgix->createURL(str_replace('%2F', '/', urlencode($imageFile)), $params),
$size[0],
$size[1]
];
return $result;
} | php | private function buildSizedImgixImage($id, $size) {
$meta = wp_get_attachment_metadata($id);
if(!$meta || empty($meta)) {
return false;
}
if(!isset($meta['s3'])) {
return [];
}
$imgix = new UrlBuilder($this->imgixDomains, $this->useHTTPS);
if($this->signingKey) {
$imgix->setSignKey($this->signingKey);
}
$is_crop = ((count($size) >= 3) && ($size[2] == 'crop'));
if (!$is_crop && $this->shouldCrop) {
$this->shouldCrop = false;
$is_crop = true;
}
if ($is_crop && (($size[0] === 0) || ($size[1] === 0))) {
if ($size[0] === 0) {
$size[0] = 10000;
} else {
$size[1] = 10000;
}
$is_crop = false;
}
if(isset($size['width'])) {
$size = [
$size['width'],
$size['height']
];
}
$params = [
'fit' => ($is_crop) ? 'crop' : 'fit',
'w' => $size[0],
'h' => $size[1],
'fm' => 'jpg'
];
$params = apply_filters('ilab-imgix-filter-parameters', $params, $size, $id, $meta);
$imageFile = (isset($meta['s3'])) ? $meta['s3']['key'] : $meta['file'];
$result = [
$imgix->createURL(str_replace('%2F', '/', urlencode($imageFile)), $params),
$size[0],
$size[1]
];
return $result;
} | [
"private",
"function",
"buildSizedImgixImage",
"(",
"$",
"id",
",",
"$",
"size",
")",
"{",
"$",
"meta",
"=",
"wp_get_attachment_metadata",
"(",
"$",
"id",
")",
";",
"if",
"(",
"!",
"$",
"meta",
"||",
"empty",
"(",
"$",
"meta",
")",
")",
"{",
"return"... | Builds an Imgix URL for a dynamically sized image.
@param int $id
@param array $size
@return array|bool | [
"Builds",
"an",
"Imgix",
"URL",
"for",
"a",
"dynamically",
"sized",
"image",
"."
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Imgix/ImgixTool.php#L355-L412 | train |
Interfacelab/ilab-media-tools | classes/Tools/Imgix/ImgixTool.php | ImgixTool.buildSrcSetURL | public function buildSrcSetURL($post_id, $parentSize, $newSize) {
return $this->buildImgixImage($post_id, $parentSize, null, false, null, $newSize);
} | php | public function buildSrcSetURL($post_id, $parentSize, $newSize) {
return $this->buildImgixImage($post_id, $parentSize, null, false, null, $newSize);
} | [
"public",
"function",
"buildSrcSetURL",
"(",
"$",
"post_id",
",",
"$",
"parentSize",
",",
"$",
"newSize",
")",
"{",
"return",
"$",
"this",
"->",
"buildImgixImage",
"(",
"$",
"post_id",
",",
"$",
"parentSize",
",",
"null",
",",
"false",
",",
"null",
",",
... | Builds the URL for a srcSet Image
@param int $post_id
@param array $parentSize
@param array $newSize
@return array|bool | [
"Builds",
"the",
"URL",
"for",
"a",
"srcSet",
"Image"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Imgix/ImgixTool.php#L449-L451 | train |
Interfacelab/ilab-media-tools | classes/Tools/Imgix/ImgixTool.php | ImgixTool.imageGetIntermediateSize | public function imageGetIntermediateSize($data, $post_id, $size) {
$result = $this->buildImgixImage($post_id, $size);
if (is_array($result) && !empty($result)) {
$data['url'] = $result[0];
}
return $data;
} | php | public function imageGetIntermediateSize($data, $post_id, $size) {
$result = $this->buildImgixImage($post_id, $size);
if (is_array($result) && !empty($result)) {
$data['url'] = $result[0];
}
return $data;
} | [
"public",
"function",
"imageGetIntermediateSize",
"(",
"$",
"data",
",",
"$",
"post_id",
",",
"$",
"size",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"buildImgixImage",
"(",
"$",
"post_id",
",",
"$",
"size",
")",
";",
"if",
"(",
"is_array",
"(",
... | Filters the image data for intermediate sizes.
@param array $data
@param int $post_idid
@param array|string $size
@return array | [
"Filters",
"the",
"image",
"data",
"for",
"intermediate",
"sizes",
"."
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Imgix/ImgixTool.php#L919-L927 | train |
Interfacelab/ilab-media-tools | classes/Tools/Imgix/ImgixTool.php | ImgixTool.buildPresetsUI | private function buildPresetsUI($image_id, $size) {
$presets = get_option('ilab-imgix-presets');
if(!$presets) {
$presets = [];
}
$sizePresets = get_option('ilab-imgix-size-presets');
if(!$sizePresets) {
$sizePresets = [];
}
$presetsUI = [];
foreach($presets as $pkey => $pinfo) {
$default_for = '';
foreach($sizePresets as $psize => $psizePreset) {
if($psizePreset == $pkey) {
$default_for = $psize;
break;
}
}
$psettings = $pinfo['settings'];
foreach($this->paramPropsByType['media-chooser'] as $mkey => $minfo) {
if(isset($psettings[$mkey])) {
if(!empty($psettings[$mkey])) {
$psettings[$mkey.'_url'] = wp_get_attachment_url($psettings[$mkey]);
}
}
}
$presetsUI[$pkey] = [
'title' => $pinfo['title'],
'default_for' => $default_for,
'settings' => $psettings
];
}
return $presetsUI;
} | php | private function buildPresetsUI($image_id, $size) {
$presets = get_option('ilab-imgix-presets');
if(!$presets) {
$presets = [];
}
$sizePresets = get_option('ilab-imgix-size-presets');
if(!$sizePresets) {
$sizePresets = [];
}
$presetsUI = [];
foreach($presets as $pkey => $pinfo) {
$default_for = '';
foreach($sizePresets as $psize => $psizePreset) {
if($psizePreset == $pkey) {
$default_for = $psize;
break;
}
}
$psettings = $pinfo['settings'];
foreach($this->paramPropsByType['media-chooser'] as $mkey => $minfo) {
if(isset($psettings[$mkey])) {
if(!empty($psettings[$mkey])) {
$psettings[$mkey.'_url'] = wp_get_attachment_url($psettings[$mkey]);
}
}
}
$presetsUI[$pkey] = [
'title' => $pinfo['title'],
'default_for' => $default_for,
'settings' => $psettings
];
}
return $presetsUI;
} | [
"private",
"function",
"buildPresetsUI",
"(",
"$",
"image_id",
",",
"$",
"size",
")",
"{",
"$",
"presets",
"=",
"get_option",
"(",
"'ilab-imgix-presets'",
")",
";",
"if",
"(",
"!",
"$",
"presets",
")",
"{",
"$",
"presets",
"=",
"[",
"]",
";",
"}",
"$... | Builds the presets UI
@param int $image_id
@param string $size
@return array | [
"Builds",
"the",
"presets",
"UI"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Imgix/ImgixTool.php#L1316-L1354 | train |
Interfacelab/ilab-media-tools | classes/Tools/Imgix/ImgixTool.php | ImgixTool.saveAdjustments | public function saveAdjustments() {
$image_id = esc_html($_POST['image_id']);
$size = esc_html($_POST['size']);
$params = (isset($_POST['settings'])) ? $_POST['settings'] : [];
if(!current_user_can('edit_post', $image_id)) {
json_response([
'status' => 'error',
'message' => 'You are not strong enough, smart enough or fast enough.'
]);
}
$meta = wp_get_attachment_metadata($image_id);
if(!$meta) {
json_response([
'status' => 'error',
'message' => 'Invalid image id.'
]);
}
if($size == 'full') {
$meta['imgix-params'] = $params;
} else {
$meta['imgix-size-params'][$size] = $params;
}
wp_update_attachment_metadata($image_id, $meta);
json_response([
'status' => 'ok'
]);
} | php | public function saveAdjustments() {
$image_id = esc_html($_POST['image_id']);
$size = esc_html($_POST['size']);
$params = (isset($_POST['settings'])) ? $_POST['settings'] : [];
if(!current_user_can('edit_post', $image_id)) {
json_response([
'status' => 'error',
'message' => 'You are not strong enough, smart enough or fast enough.'
]);
}
$meta = wp_get_attachment_metadata($image_id);
if(!$meta) {
json_response([
'status' => 'error',
'message' => 'Invalid image id.'
]);
}
if($size == 'full') {
$meta['imgix-params'] = $params;
} else {
$meta['imgix-size-params'][$size] = $params;
}
wp_update_attachment_metadata($image_id, $meta);
json_response([
'status' => 'ok'
]);
} | [
"public",
"function",
"saveAdjustments",
"(",
")",
"{",
"$",
"image_id",
"=",
"esc_html",
"(",
"$",
"_POST",
"[",
"'image_id'",
"]",
")",
";",
"$",
"size",
"=",
"esc_html",
"(",
"$",
"_POST",
"[",
"'size'",
"]",
")",
";",
"$",
"params",
"=",
"(",
"... | Save The Parameters | [
"Save",
"The",
"Parameters"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Imgix/ImgixTool.php#L1361-L1393 | train |
Interfacelab/ilab-media-tools | classes/Tools/Imgix/ImgixTool.php | ImgixTool.previewAdjustments | public function previewAdjustments() {
$image_id = esc_html($_POST['image_id']);
$size = esc_html($_POST['size']);
if(!current_user_can('edit_post', $image_id)) {
json_response([
'status' => 'error',
'message' => 'You are not strong enough, smart enough or fast enough.'
]);
}
$params = (isset($_POST['settings'])) ? $_POST['settings'] : [];
$result = $this->buildImgixImage($image_id, $size, $params);
json_response(['status' => 'ok', 'src' => $result[0]]);
} | php | public function previewAdjustments() {
$image_id = esc_html($_POST['image_id']);
$size = esc_html($_POST['size']);
if(!current_user_can('edit_post', $image_id)) {
json_response([
'status' => 'error',
'message' => 'You are not strong enough, smart enough or fast enough.'
]);
}
$params = (isset($_POST['settings'])) ? $_POST['settings'] : [];
$result = $this->buildImgixImage($image_id, $size, $params);
json_response(['status' => 'ok', 'src' => $result[0]]);
} | [
"public",
"function",
"previewAdjustments",
"(",
")",
"{",
"$",
"image_id",
"=",
"esc_html",
"(",
"$",
"_POST",
"[",
"'image_id'",
"]",
")",
";",
"$",
"size",
"=",
"esc_html",
"(",
"$",
"_POST",
"[",
"'size'",
"]",
")",
";",
"if",
"(",
"!",
"current_... | Preview the adjustment | [
"Preview",
"the",
"adjustment"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Imgix/ImgixTool.php#L1398-L1414 | train |
Interfacelab/ilab-media-tools | classes/Tools/Imgix/ImgixTool.php | ImgixTool.doUpdatePresets | private function doUpdatePresets($key, $name, $settings, $size, $makeDefault) {
$image_id = esc_html($_POST['image_id']);
$presets = get_option('ilab-imgix-presets');
if(!$presets) {
$presets = [];
}
$presets[$key] = [
'title' => $name,
'settings' => $settings
];
update_option('ilab-imgix-presets', $presets);
$sizePresets = get_option('ilab-imgix-size-presets');
if(!$sizePresets) {
$sizePresets = [];
}
if($size && $makeDefault) {
$sizePresets[$size] = $key;
} else if($size && !$makeDefault) {
foreach($sizePresets as $s => $k) {
if($k == $key) {
unset($sizePresets[$s]);
}
}
}
update_option('ilab-imgix-size-presets', $sizePresets);
json_response([
'status' => 'ok',
'currentPreset' => $key,
'presets' => $this->buildPresetsUI($image_id, $size)
]);
} | php | private function doUpdatePresets($key, $name, $settings, $size, $makeDefault) {
$image_id = esc_html($_POST['image_id']);
$presets = get_option('ilab-imgix-presets');
if(!$presets) {
$presets = [];
}
$presets[$key] = [
'title' => $name,
'settings' => $settings
];
update_option('ilab-imgix-presets', $presets);
$sizePresets = get_option('ilab-imgix-size-presets');
if(!$sizePresets) {
$sizePresets = [];
}
if($size && $makeDefault) {
$sizePresets[$size] = $key;
} else if($size && !$makeDefault) {
foreach($sizePresets as $s => $k) {
if($k == $key) {
unset($sizePresets[$s]);
}
}
}
update_option('ilab-imgix-size-presets', $sizePresets);
json_response([
'status' => 'ok',
'currentPreset' => $key,
'presets' => $this->buildPresetsUI($image_id, $size)
]);
} | [
"private",
"function",
"doUpdatePresets",
"(",
"$",
"key",
",",
"$",
"name",
",",
"$",
"settings",
",",
"$",
"size",
",",
"$",
"makeDefault",
")",
"{",
"$",
"image_id",
"=",
"esc_html",
"(",
"$",
"_POST",
"[",
"'image_id'",
"]",
")",
";",
"$",
"prese... | Update the presets
@param string $key
@param string $name
@param array $settings
@param string $size
@param bool $makeDefault | [
"Update",
"the",
"presets"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Imgix/ImgixTool.php#L1425-L1461 | train |
Interfacelab/ilab-media-tools | classes/Tools/Imgix/ImgixTool.php | ImgixTool.newPreset | public function newPreset() {
$name = esc_html($_POST['name']);
if(empty($name)) {
json_response([
'status' => 'error',
'error' => 'Seems that you may have forgotten something.'
]);
}
$key = sanitize_title($name);
$newKey = $key;
$presets = get_option('ilab-imgix-presets');
if($presets) {
$keyIndex = 1;
while(isset($presets[$newKey])) {
$keyIndex ++;
$newKey = $key.$keyIndex;
}
}
$settings = $_POST['settings'];
$size = (isset($_POST['size'])) ? esc_html($_POST['size']) : null;
$makeDefault = (isset($_POST['make_default'])) ? ($_POST['make_default'] == 1) : false;
$this->doUpdatePresets($newKey, $name, $settings, $size, $makeDefault);
} | php | public function newPreset() {
$name = esc_html($_POST['name']);
if(empty($name)) {
json_response([
'status' => 'error',
'error' => 'Seems that you may have forgotten something.'
]);
}
$key = sanitize_title($name);
$newKey = $key;
$presets = get_option('ilab-imgix-presets');
if($presets) {
$keyIndex = 1;
while(isset($presets[$newKey])) {
$keyIndex ++;
$newKey = $key.$keyIndex;
}
}
$settings = $_POST['settings'];
$size = (isset($_POST['size'])) ? esc_html($_POST['size']) : null;
$makeDefault = (isset($_POST['make_default'])) ? ($_POST['make_default'] == 1) : false;
$this->doUpdatePresets($newKey, $name, $settings, $size, $makeDefault);
} | [
"public",
"function",
"newPreset",
"(",
")",
"{",
"$",
"name",
"=",
"esc_html",
"(",
"$",
"_POST",
"[",
"'name'",
"]",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"name",
")",
")",
"{",
"json_response",
"(",
"[",
"'status'",
"=>",
"'error'",
",",
"'err... | Create a new preset | [
"Create",
"a",
"new",
"preset"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Imgix/ImgixTool.php#L1466-L1493 | train |
Interfacelab/ilab-media-tools | classes/Tools/Imgix/ImgixTool.php | ImgixTool.savePreset | public function savePreset() {
$key = esc_html($_POST['key']);
if(empty($key)) {
json_response([
'status' => 'error',
'error' => 'Seems that you may have forgotten something.'
]);
}
$presets = get_option('ilab-imgix-presets');
if(!isset($presets[$key])) {
json_response([
'status' => 'error',
'error' => 'Seems that you may have forgotten something.'
]);
}
$name = $presets[$key]['title'];
$settings = $_POST['settings'];
$size = (isset($_POST['size'])) ? esc_html($_POST['size']) : null;
$makeDefault = (isset($_POST['make_default'])) ? ($_POST['make_default'] == 1) : false;
$this->doUpdatePresets($key, $name, $settings, $size, $makeDefault);
} | php | public function savePreset() {
$key = esc_html($_POST['key']);
if(empty($key)) {
json_response([
'status' => 'error',
'error' => 'Seems that you may have forgotten something.'
]);
}
$presets = get_option('ilab-imgix-presets');
if(!isset($presets[$key])) {
json_response([
'status' => 'error',
'error' => 'Seems that you may have forgotten something.'
]);
}
$name = $presets[$key]['title'];
$settings = $_POST['settings'];
$size = (isset($_POST['size'])) ? esc_html($_POST['size']) : null;
$makeDefault = (isset($_POST['make_default'])) ? ($_POST['make_default'] == 1) : false;
$this->doUpdatePresets($key, $name, $settings, $size, $makeDefault);
} | [
"public",
"function",
"savePreset",
"(",
")",
"{",
"$",
"key",
"=",
"esc_html",
"(",
"$",
"_POST",
"[",
"'key'",
"]",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"key",
")",
")",
"{",
"json_response",
"(",
"[",
"'status'",
"=>",
"'error'",
",",
"'error... | Save an existing preset | [
"Save",
"an",
"existing",
"preset"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Imgix/ImgixTool.php#L1498-L1521 | train |
Interfacelab/ilab-media-tools | classes/Tools/Imgix/ImgixTool.php | ImgixTool.deletePreset | public function deletePreset() {
$key = esc_html($_POST['key']);
if(empty($key)) {
json_response([
'status' => 'error',
'error' => 'Seems that you may have forgotten something.'
]);
}
$presets = get_option('ilab-imgix-presets');
if($presets) {
unset($presets[$key]);
update_option('ilab-imgix-presets', $presets);
}
$sizePresets = get_option('ilab-imgix-size-presets');
if(!$sizePresets) {
$sizePresets = [];
}
foreach($sizePresets as $size => $preset) {
if($preset == $key) {
unset($sizePresets[$size]);
break;
}
}
update_option('ilab-imgix-size-presets', $sizePresets);
return $this->displayEditUI(1);
} | php | public function deletePreset() {
$key = esc_html($_POST['key']);
if(empty($key)) {
json_response([
'status' => 'error',
'error' => 'Seems that you may have forgotten something.'
]);
}
$presets = get_option('ilab-imgix-presets');
if($presets) {
unset($presets[$key]);
update_option('ilab-imgix-presets', $presets);
}
$sizePresets = get_option('ilab-imgix-size-presets');
if(!$sizePresets) {
$sizePresets = [];
}
foreach($sizePresets as $size => $preset) {
if($preset == $key) {
unset($sizePresets[$size]);
break;
}
}
update_option('ilab-imgix-size-presets', $sizePresets);
return $this->displayEditUI(1);
} | [
"public",
"function",
"deletePreset",
"(",
")",
"{",
"$",
"key",
"=",
"esc_html",
"(",
"$",
"_POST",
"[",
"'key'",
"]",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"key",
")",
")",
"{",
"json_response",
"(",
"[",
"'status'",
"=>",
"'error'",
",",
"'err... | Delete an existing preset | [
"Delete",
"an",
"existing",
"preset"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Imgix/ImgixTool.php#L1526-L1557 | train |
Interfacelab/ilab-media-tools | classes/Cloud/Storage/Driver/S3/WasabiStorage.php | WasabiStorage.uploadUrl | public function uploadUrl($key, $acl, $mimeType = null, $cacheControl = null, $expires = null) {
try {
$optionsData = [
'ACL' => $acl,
'Bucket' => $this->bucket,
'ContentType' => $mimeType,
'Key' => $key
];
if(!empty($cacheControl)) {
$optionsData[] = ['CacheControl' => $cacheControl];
}
if(!empty($expires)) {
$optionsData[] = ['Expires' => $expires];
}
$putCommand = $this->client->getCommand('PutObject',$optionsData);
$request = $this->client->createPresignedRequest($putCommand, '+20 minutes');
$signedUrl = (string)$request->getUri();
return new OtherS3UploadInfo($key,$signedUrl,$acl);
}
catch(AwsException $ex) {
Logger::error('S3 Generate File Upload URL Error', ['exception' => $ex->getMessage()]);
throw new StorageException($ex->getMessage(), $ex->getCode(), $ex);
}
} | php | public function uploadUrl($key, $acl, $mimeType = null, $cacheControl = null, $expires = null) {
try {
$optionsData = [
'ACL' => $acl,
'Bucket' => $this->bucket,
'ContentType' => $mimeType,
'Key' => $key
];
if(!empty($cacheControl)) {
$optionsData[] = ['CacheControl' => $cacheControl];
}
if(!empty($expires)) {
$optionsData[] = ['Expires' => $expires];
}
$putCommand = $this->client->getCommand('PutObject',$optionsData);
$request = $this->client->createPresignedRequest($putCommand, '+20 minutes');
$signedUrl = (string)$request->getUri();
return new OtherS3UploadInfo($key,$signedUrl,$acl);
}
catch(AwsException $ex) {
Logger::error('S3 Generate File Upload URL Error', ['exception' => $ex->getMessage()]);
throw new StorageException($ex->getMessage(), $ex->getCode(), $ex);
}
} | [
"public",
"function",
"uploadUrl",
"(",
"$",
"key",
",",
"$",
"acl",
",",
"$",
"mimeType",
"=",
"null",
",",
"$",
"cacheControl",
"=",
"null",
",",
"$",
"expires",
"=",
"null",
")",
"{",
"try",
"{",
"$",
"optionsData",
"=",
"[",
"'ACL'",
"=>",
"$",... | region Direct Uploads | [
"region",
"Direct",
"Uploads"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Cloud/Storage/Driver/S3/WasabiStorage.php#L133-L160 | train |
Interfacelab/ilab-media-tools | classes/Utilities/Logging/Logger.php | Logger.logSystemError | protected function logSystemError($type, $message, $file, $line) {
switch($type) {
case E_ERROR:
case E_USER_ERROR:
case E_RECOVERABLE_ERROR:
case E_PARSE:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
$this->doLogError($message, ['file' => $file, 'line' => $line]);
break;
case E_WARNING:
case E_CORE_WARNING:
case E_COMPILE_WARNING:
case E_USER_WARNING:
$this->doLogWarning($message, ['file' => $file, 'line' => $line]);
break;
default:
$this->doLogInfo($message, ['file' => $file, 'line' => $line]);
break;
}
} | php | protected function logSystemError($type, $message, $file, $line) {
switch($type) {
case E_ERROR:
case E_USER_ERROR:
case E_RECOVERABLE_ERROR:
case E_PARSE:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
$this->doLogError($message, ['file' => $file, 'line' => $line]);
break;
case E_WARNING:
case E_CORE_WARNING:
case E_COMPILE_WARNING:
case E_USER_WARNING:
$this->doLogWarning($message, ['file' => $file, 'line' => $line]);
break;
default:
$this->doLogInfo($message, ['file' => $file, 'line' => $line]);
break;
}
} | [
"protected",
"function",
"logSystemError",
"(",
"$",
"type",
",",
"$",
"message",
",",
"$",
"file",
",",
"$",
"line",
")",
"{",
"switch",
"(",
"$",
"type",
")",
"{",
"case",
"E_ERROR",
":",
"case",
"E_USER_ERROR",
":",
"case",
"E_RECOVERABLE_ERROR",
":",... | region Protected Logging Methods | [
"region",
"Protected",
"Logging",
"Methods"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Utilities/Logging/Logger.php#L84-L104 | train |
Interfacelab/ilab-media-tools | classes/Tools/Crop/CropTool.php | CropTool.setup | public function setup()
{
if ($this->enabled())
{
$this->hookupUI();
add_action('admin_enqueue_scripts', [$this,'enqueueTheGoods']);
add_action('wp_ajax_ilab_crop_image_page',[$this,'displayCropUI']);
add_action('wp_ajax_ilab_perform_crop',[$this,'performCrop']);
add_filter('ilab_s3_process_crop', function($size, $path, $sizeMeta){
return $sizeMeta;
}, 3, 3);
add_filter('ilab_s3_process_file_name', function($filename) {
return $filename;
}, 3, 1);
}
} | php | public function setup()
{
if ($this->enabled())
{
$this->hookupUI();
add_action('admin_enqueue_scripts', [$this,'enqueueTheGoods']);
add_action('wp_ajax_ilab_crop_image_page',[$this,'displayCropUI']);
add_action('wp_ajax_ilab_perform_crop',[$this,'performCrop']);
add_filter('ilab_s3_process_crop', function($size, $path, $sizeMeta){
return $sizeMeta;
}, 3, 3);
add_filter('ilab_s3_process_file_name', function($filename) {
return $filename;
}, 3, 1);
}
} | [
"public",
"function",
"setup",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"enabled",
"(",
")",
")",
"{",
"$",
"this",
"->",
"hookupUI",
"(",
")",
";",
"add_action",
"(",
"'admin_enqueue_scripts'",
",",
"[",
"$",
"this",
",",
"'enqueueTheGoods'",
"]",... | Setup the plugin | [
"Setup",
"the",
"plugin"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Crop/CropTool.php#L45-L62 | train |
Interfacelab/ilab-media-tools | classes/Tools/Crop/CropTool.php | CropTool.enqueueTheGoods | public function enqueueTheGoods($hook)
{
add_thickbox();
if ($hook == 'post.php')
wp_enqueue_media ();
else if ($hook == 'upload.php')
{
$mode = get_user_option('media_library_mode', get_current_user_id()) ? get_user_option('media_library_mode', get_current_user_id()) : 'grid';
if (isset($_GET['mode']) && in_array($_GET ['mode'], ['grid','list']))
{
$mode = $_GET['mode'];
update_user_option(get_current_user_id(), 'media_library_mode', $mode);
}
if ($mode=='list')
{
$version = get_bloginfo('version');
if (version_compare($version, '4.2.2') < 0)
wp_dequeue_script ( 'media' );
wp_enqueue_media ();
}
}
else
wp_enqueue_style ( 'media-views' );
wp_enqueue_style( 'wp-pointer' );
wp_enqueue_style ( 'ilab-modal-css', ILAB_PUB_CSS_URL . '/ilab-modal.min.css' );
wp_enqueue_style ( 'ilab-media-tools-css', ILAB_PUB_CSS_URL . '/ilab-media-tools.min.css' );
wp_enqueue_script( 'wp-pointer' );
wp_enqueue_script ( 'ilab-modal-js', ILAB_PUB_JS_URL. '/ilab-modal.js', ['jquery'], false, true );
wp_enqueue_script ( 'ilab-media-tools-js', ILAB_PUB_JS_URL. '/ilab-media-tools.js', ['jquery'], false, true );
} | php | public function enqueueTheGoods($hook)
{
add_thickbox();
if ($hook == 'post.php')
wp_enqueue_media ();
else if ($hook == 'upload.php')
{
$mode = get_user_option('media_library_mode', get_current_user_id()) ? get_user_option('media_library_mode', get_current_user_id()) : 'grid';
if (isset($_GET['mode']) && in_array($_GET ['mode'], ['grid','list']))
{
$mode = $_GET['mode'];
update_user_option(get_current_user_id(), 'media_library_mode', $mode);
}
if ($mode=='list')
{
$version = get_bloginfo('version');
if (version_compare($version, '4.2.2') < 0)
wp_dequeue_script ( 'media' );
wp_enqueue_media ();
}
}
else
wp_enqueue_style ( 'media-views' );
wp_enqueue_style( 'wp-pointer' );
wp_enqueue_style ( 'ilab-modal-css', ILAB_PUB_CSS_URL . '/ilab-modal.min.css' );
wp_enqueue_style ( 'ilab-media-tools-css', ILAB_PUB_CSS_URL . '/ilab-media-tools.min.css' );
wp_enqueue_script( 'wp-pointer' );
wp_enqueue_script ( 'ilab-modal-js', ILAB_PUB_JS_URL. '/ilab-modal.js', ['jquery'], false, true );
wp_enqueue_script ( 'ilab-media-tools-js', ILAB_PUB_JS_URL. '/ilab-media-tools.js', ['jquery'], false, true );
} | [
"public",
"function",
"enqueueTheGoods",
"(",
"$",
"hook",
")",
"{",
"add_thickbox",
"(",
")",
";",
"if",
"(",
"$",
"hook",
"==",
"'post.php'",
")",
"wp_enqueue_media",
"(",
")",
";",
"else",
"if",
"(",
"$",
"hook",
"==",
"'upload.php'",
")",
"{",
"$",... | Enqueue the CSS and JS needed to make the magic happen
@param $hook | [
"Enqueue",
"the",
"CSS",
"and",
"JS",
"needed",
"to",
"make",
"the",
"magic",
"happen"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Crop/CropTool.php#L68-L101 | train |
Interfacelab/ilab-media-tools | classes/Cloud/Storage/StorageManager.php | StorageManager.storageInstance | public static function storageInstance() {
if (self::$instance) {
return self::$instance;
}
if (!isset(self::$registry[self::driver()])) {
throw new StorageException("Invalid driver '".self::driver()."'");
}
$class = self::$registry[self::driver()];
self::$instance = new $class();
return self::$instance;
} | php | public static function storageInstance() {
if (self::$instance) {
return self::$instance;
}
if (!isset(self::$registry[self::driver()])) {
throw new StorageException("Invalid driver '".self::driver()."'");
}
$class = self::$registry[self::driver()];
self::$instance = new $class();
return self::$instance;
} | [
"public",
"static",
"function",
"storageInstance",
"(",
")",
"{",
"if",
"(",
"self",
"::",
"$",
"instance",
")",
"{",
"return",
"self",
"::",
"$",
"instance",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"registry",
"[",
"self",
"::",
... | Gets the currently configured storage interface.
@throws StorageException
@return StorageInterface | [
"Gets",
"the",
"currently",
"configured",
"storage",
"interface",
"."
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Cloud/Storage/StorageManager.php#L34-L47 | train |
Interfacelab/ilab-media-tools | classes/Tools/MediaUpload/UploadTool.php | UploadTool.setupAdmin | public function setupAdmin() {
add_action('admin_enqueue_scripts', function() {
wp_enqueue_script('wp-util');
wp_enqueue_style('ilab-media-upload-css', ILAB_PUB_CSS_URL.'/ilab-media-upload.min.css');
wp_enqueue_script('ilab-media-upload-js', ILAB_PUB_JS_URL.'/ilab-media-upload.js', [
'jquery',
'wp-util'
], false, true);
});
$this->client->enqueueUploaderScripts();
add_action('admin_menu', function() {
if(current_user_can('upload_files')) {
if($this->enabled()) {
add_media_page('Cloud Upload', 'Cloud Upload', 'upload_files', 'media-cloud-upload', [
$this,
'renderSettings'
]);
}
}
});
add_filter('media_upload_tabs', function($tabs) {
if(current_user_can('upload_files')) {
$tabs = array_merge(['ilab_cloud_upload' => 'Cloud Upload'], $tabs);
}
return $tabs;
});
add_action('media_upload_ilab_cloud_upload', function() {
wp_iframe([$this, 'renderInsertSettings']);
});
} | php | public function setupAdmin() {
add_action('admin_enqueue_scripts', function() {
wp_enqueue_script('wp-util');
wp_enqueue_style('ilab-media-upload-css', ILAB_PUB_CSS_URL.'/ilab-media-upload.min.css');
wp_enqueue_script('ilab-media-upload-js', ILAB_PUB_JS_URL.'/ilab-media-upload.js', [
'jquery',
'wp-util'
], false, true);
});
$this->client->enqueueUploaderScripts();
add_action('admin_menu', function() {
if(current_user_can('upload_files')) {
if($this->enabled()) {
add_media_page('Cloud Upload', 'Cloud Upload', 'upload_files', 'media-cloud-upload', [
$this,
'renderSettings'
]);
}
}
});
add_filter('media_upload_tabs', function($tabs) {
if(current_user_can('upload_files')) {
$tabs = array_merge(['ilab_cloud_upload' => 'Cloud Upload'], $tabs);
}
return $tabs;
});
add_action('media_upload_ilab_cloud_upload', function() {
wp_iframe([$this, 'renderInsertSettings']);
});
} | [
"public",
"function",
"setupAdmin",
"(",
")",
"{",
"add_action",
"(",
"'admin_enqueue_scripts'",
",",
"function",
"(",
")",
"{",
"wp_enqueue_script",
"(",
"'wp-util'",
")",
";",
"wp_enqueue_style",
"(",
"'ilab-media-upload-css'",
",",
"ILAB_PUB_CSS_URL",
".",
"'/ila... | Setup upload UI | [
"Setup",
"upload",
"UI"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/MediaUpload/UploadTool.php#L80-L115 | train |
Interfacelab/ilab-media-tools | classes/Tools/MediaUpload/UploadTool.php | UploadTool.setupAdminAjax | public function setupAdminAjax() {
add_action('wp_ajax_ilab_upload_prepare', function() {
$this->prepareUpload();
});
add_action('wp_ajax_ilab_upload_import_cloud_file', function() {
$this->importUploadedFile();
});
add_action('wp_ajax_ilab_upload_attachment_info', function() {
$postId = $_POST['postId'];
json_response(wp_prepare_attachment_for_js($postId));
});
} | php | public function setupAdminAjax() {
add_action('wp_ajax_ilab_upload_prepare', function() {
$this->prepareUpload();
});
add_action('wp_ajax_ilab_upload_import_cloud_file', function() {
$this->importUploadedFile();
});
add_action('wp_ajax_ilab_upload_attachment_info', function() {
$postId = $_POST['postId'];
json_response(wp_prepare_attachment_for_js($postId));
});
} | [
"public",
"function",
"setupAdminAjax",
"(",
")",
"{",
"add_action",
"(",
"'wp_ajax_ilab_upload_prepare'",
",",
"function",
"(",
")",
"{",
"$",
"this",
"->",
"prepareUpload",
"(",
")",
";",
"}",
")",
";",
"add_action",
"(",
"'wp_ajax_ilab_upload_import_cloud_file'... | Install Ajax Endpoints | [
"Install",
"Ajax",
"Endpoints"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/MediaUpload/UploadTool.php#L120-L134 | train |
Interfacelab/ilab-media-tools | classes/Tools/MediaUpload/UploadTool.php | UploadTool.importUploadedFile | private function importUploadedFile() {
if(!current_user_can('upload_files')) {
json_response(["status" => "error", "message" => "Current user can't upload."]);
}
$key = $_POST['key'];
if(empty($key)) {
json_response(['status' => 'error', 'message' => 'Missing key.']);
}
$info = $this->client->info($key);
$unknownMimes = [
'application/octet-stream',
'application/binary',
'unknown/unknown'
];
if(!empty($info->mimeType()) && !in_array($info->mimeType(), $unknownMimes)) {
if(strpos($info->mimeType(), 'image/') === 0) {
$result = apply_filters('ilab_cloud_import_from_storage', $info);
if($result) {
json_response(['status' => 'success', 'data' => $result]);
} else {
json_response(['status' => 'error', 'message' => 'Error importing S3 file into WordPress.']);
}
} else {
json_response(['status' => 'error', 'message' => 'Unknown type.', 'type' => $info->mimeType()]);
}
} else {
json_response(['status' => 'error', 'message' => 'Unknown type.', 'type' => $info->mimeType()]);
}
} | php | private function importUploadedFile() {
if(!current_user_can('upload_files')) {
json_response(["status" => "error", "message" => "Current user can't upload."]);
}
$key = $_POST['key'];
if(empty($key)) {
json_response(['status' => 'error', 'message' => 'Missing key.']);
}
$info = $this->client->info($key);
$unknownMimes = [
'application/octet-stream',
'application/binary',
'unknown/unknown'
];
if(!empty($info->mimeType()) && !in_array($info->mimeType(), $unknownMimes)) {
if(strpos($info->mimeType(), 'image/') === 0) {
$result = apply_filters('ilab_cloud_import_from_storage', $info);
if($result) {
json_response(['status' => 'success', 'data' => $result]);
} else {
json_response(['status' => 'error', 'message' => 'Error importing S3 file into WordPress.']);
}
} else {
json_response(['status' => 'error', 'message' => 'Unknown type.', 'type' => $info->mimeType()]);
}
} else {
json_response(['status' => 'error', 'message' => 'Unknown type.', 'type' => $info->mimeType()]);
}
} | [
"private",
"function",
"importUploadedFile",
"(",
")",
"{",
"if",
"(",
"!",
"current_user_can",
"(",
"'upload_files'",
")",
")",
"{",
"json_response",
"(",
"[",
"\"status\"",
"=>",
"\"error\"",
",",
"\"message\"",
"=>",
"\"Current user can't upload.\"",
"]",
")",
... | Called after a file has been uploaded and needs to be imported into the system. | [
"Called",
"after",
"a",
"file",
"has",
"been",
"uploaded",
"and",
"needs",
"to",
"be",
"imported",
"into",
"the",
"system",
"."
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/MediaUpload/UploadTool.php#L141-L173 | train |
Interfacelab/ilab-media-tools | classes/Tools/MediaUpload/UploadTool.php | UploadTool.prepareUpload | private function prepareUpload() {
if(!current_user_can('upload_files')) {
json_response(["status" => "error", "message" => "Current user can't upload."]);
}
if (!$this->client || !$this->client->enabled()) {
json_response(["status" => "error", "message" => "Storage settings are invalid."]);
}
$filename = $_POST['filename'];
$type = $_POST['type'];
if (empty($filename) || empty($type)) {
json_response(["status" => "error", "message" => "Invalid file name or missing type."]);
}
$prefix = StorageSettings::prefix(null);
$parts = explode('/', $filename);
$bucketFilename = array_pop($parts);
$uploadInfo = $this->client->uploadUrl($prefix.$bucketFilename,StorageSettings::privacy(), $type,StorageSettings::cacheControl(), StorageSettings::expires());
$res = $uploadInfo->toArray();
$res['status'] = 'ready';
json_response($res);
} | php | private function prepareUpload() {
if(!current_user_can('upload_files')) {
json_response(["status" => "error", "message" => "Current user can't upload."]);
}
if (!$this->client || !$this->client->enabled()) {
json_response(["status" => "error", "message" => "Storage settings are invalid."]);
}
$filename = $_POST['filename'];
$type = $_POST['type'];
if (empty($filename) || empty($type)) {
json_response(["status" => "error", "message" => "Invalid file name or missing type."]);
}
$prefix = StorageSettings::prefix(null);
$parts = explode('/', $filename);
$bucketFilename = array_pop($parts);
$uploadInfo = $this->client->uploadUrl($prefix.$bucketFilename,StorageSettings::privacy(), $type,StorageSettings::cacheControl(), StorageSettings::expires());
$res = $uploadInfo->toArray();
$res['status'] = 'ready';
json_response($res);
} | [
"private",
"function",
"prepareUpload",
"(",
")",
"{",
"if",
"(",
"!",
"current_user_can",
"(",
"'upload_files'",
")",
")",
"{",
"json_response",
"(",
"[",
"\"status\"",
"=>",
"\"error\"",
",",
"\"message\"",
"=>",
"\"Current user can't upload.\"",
"]",
")",
";"... | Called when ready to upload to the storage service | [
"Called",
"when",
"ready",
"to",
"upload",
"to",
"the",
"storage",
"service"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/MediaUpload/UploadTool.php#L178-L202 | train |
Interfacelab/ilab-media-tools | classes/CLI/Rekognition/RekognitionCommands.php | RekognitionCommands.process | public function process($args, $assoc_args) {
/** @var RekognitionTool $tool */
$tool = ToolsManager::instance()->tools['rekognition'];
if (!$tool || !$tool->enabled()) {
Command::Error('Rekognition tool is not enabled in Media Cloud or the settings are incorrect.');
return;
}
global $wpdb;
$sql = <<<SQL
select
posts.ID
from
{$wpdb->posts} posts
where
posts.post_type = 'attachment'
and
posts.post_status = 'inherit'
and
posts.post_mime_type in ('image/jpeg', 'image/jpg', 'image/png')
and
posts.ID in (select post_id from wp_postmeta where meta_key = '_wp_attachment_metadata' and meta_value like '%s:2:"s3";a:%');
SQL;
$rows = $wpdb->get_results($sql);
$posts = [];
foreach($rows as $row) {
$posts[] = $row->ID;
}
$postCount = count($posts);
if($postCount > 0) {
BatchManager::instance()->reset('rekognizer');
BatchManager::instance()->setStatus('rekognizer', true);
BatchManager::instance()->setTotalCount('rekognizer', $postCount);
BatchManager::instance()->setCurrent('rekognizer', 1);
BatchManager::instance()->setShouldCancel('rekognizer', false);
Command::Info("Total posts found: %Y{$postCount}.", true);
for($i = 1; $i <= $postCount; $i++) {
$postId = $posts[$i - 1];
$upload_file = get_attached_file($postId);
$fileName = basename($upload_file);
BatchManager::instance()->setCurrentFile('rekognizer', $fileName);
BatchManager::instance()->setCurrent('rekognizer', $i);
Command::Info("%w[%C{$i}%w of %C{$postCount}%w] %NProcessing %Y$fileName%N %w(%N$postId%w)%N ... ");
$data = wp_get_attachment_metadata($postId);
if (empty($data)) {
Command::info( 'Missing metadata, skipping.', true);
continue;
}
if (!isset($data['s3'])) {
Command::info( 'Missing cloud storage metadata, skipping.', true);
continue;
}
$data = $tool->processImageMeta($data, $postId);
wp_update_attachment_metadata($postId, $data);
Command::Info("%YDone%N.", true);
}
BatchManager::instance()->reset('rekognizer');
}
} | php | public function process($args, $assoc_args) {
/** @var RekognitionTool $tool */
$tool = ToolsManager::instance()->tools['rekognition'];
if (!$tool || !$tool->enabled()) {
Command::Error('Rekognition tool is not enabled in Media Cloud or the settings are incorrect.');
return;
}
global $wpdb;
$sql = <<<SQL
select
posts.ID
from
{$wpdb->posts} posts
where
posts.post_type = 'attachment'
and
posts.post_status = 'inherit'
and
posts.post_mime_type in ('image/jpeg', 'image/jpg', 'image/png')
and
posts.ID in (select post_id from wp_postmeta where meta_key = '_wp_attachment_metadata' and meta_value like '%s:2:"s3";a:%');
SQL;
$rows = $wpdb->get_results($sql);
$posts = [];
foreach($rows as $row) {
$posts[] = $row->ID;
}
$postCount = count($posts);
if($postCount > 0) {
BatchManager::instance()->reset('rekognizer');
BatchManager::instance()->setStatus('rekognizer', true);
BatchManager::instance()->setTotalCount('rekognizer', $postCount);
BatchManager::instance()->setCurrent('rekognizer', 1);
BatchManager::instance()->setShouldCancel('rekognizer', false);
Command::Info("Total posts found: %Y{$postCount}.", true);
for($i = 1; $i <= $postCount; $i++) {
$postId = $posts[$i - 1];
$upload_file = get_attached_file($postId);
$fileName = basename($upload_file);
BatchManager::instance()->setCurrentFile('rekognizer', $fileName);
BatchManager::instance()->setCurrent('rekognizer', $i);
Command::Info("%w[%C{$i}%w of %C{$postCount}%w] %NProcessing %Y$fileName%N %w(%N$postId%w)%N ... ");
$data = wp_get_attachment_metadata($postId);
if (empty($data)) {
Command::info( 'Missing metadata, skipping.', true);
continue;
}
if (!isset($data['s3'])) {
Command::info( 'Missing cloud storage metadata, skipping.', true);
continue;
}
$data = $tool->processImageMeta($data, $postId);
wp_update_attachment_metadata($postId, $data);
Command::Info("%YDone%N.", true);
}
BatchManager::instance()->reset('rekognizer');
}
} | [
"public",
"function",
"process",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"/** @var RekognitionTool $tool */",
"$",
"tool",
"=",
"ToolsManager",
"::",
"instance",
"(",
")",
"->",
"tools",
"[",
"'rekognition'",
"]",
";",
"if",
"(",
"!",
"$",
"too... | Processes the media library with Rekognition
@when after_wp_load
@param $args
@param $assoc_args | [
"Processes",
"the",
"media",
"library",
"with",
"Rekognition"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/CLI/Rekognition/RekognitionCommands.php#L39-L113 | train |
Interfacelab/ilab-media-tools | classes/Tools/Storage/StorageTool.php | StorageTool.deleteAttachment | public function deleteAttachment($id) {
if(!StorageSettings::deleteFromStorage()) {
return $id;
}
$data = wp_get_attachment_metadata($id);
if(isset($data['file']) && !isset($data['s3'])) {
return $id;
}
if($this->client && $this->client->enabled()) {
if(!isset($data['file'])) {
$file = get_attached_file($id);
if($file) {
if(strpos($file, 'http') === 0) {
$pi = parse_url($file);
$file = trim($pi['path'], '/');
if(0 === strpos($file, $this->client->bucket())) {
$file = substr($file, strlen($this->client->bucket())).'';
$file = trim($file, '/');
}
} else {
$pi = pathinfo($file);
$upload_info = wp_upload_dir();
$upload_path = $upload_info['basedir'];
$file = trim(str_replace($upload_path, '', $pi['dirname']), '/').'/'.$pi['basename'];
}
$this->deleteFile($file);
}
} else {
$deletedFiles = [];
$deletedFiles[] = $data['s3']['key'];
$this->deleteFile($data['s3']['key']);
if(isset($data['sizes'])) {
$pathParts = explode('/', $data['s3']['key']);
array_pop($pathParts);
$path_base = implode('/', $pathParts);
foreach($data['sizes'] as $key => $size) {
$file = arrayPath($size,'s3/key', false);
if (!$file) {
$file = $path_base.'/'.$size['file'];
}
if (in_array($file, $deletedFiles)) {
Logger::info("File '$file' has already been deleted.");
continue;
}
$this->deleteFile($file);
$deletedFiles[] = $file;
}
}
}
}
return $id;
} | php | public function deleteAttachment($id) {
if(!StorageSettings::deleteFromStorage()) {
return $id;
}
$data = wp_get_attachment_metadata($id);
if(isset($data['file']) && !isset($data['s3'])) {
return $id;
}
if($this->client && $this->client->enabled()) {
if(!isset($data['file'])) {
$file = get_attached_file($id);
if($file) {
if(strpos($file, 'http') === 0) {
$pi = parse_url($file);
$file = trim($pi['path'], '/');
if(0 === strpos($file, $this->client->bucket())) {
$file = substr($file, strlen($this->client->bucket())).'';
$file = trim($file, '/');
}
} else {
$pi = pathinfo($file);
$upload_info = wp_upload_dir();
$upload_path = $upload_info['basedir'];
$file = trim(str_replace($upload_path, '', $pi['dirname']), '/').'/'.$pi['basename'];
}
$this->deleteFile($file);
}
} else {
$deletedFiles = [];
$deletedFiles[] = $data['s3']['key'];
$this->deleteFile($data['s3']['key']);
if(isset($data['sizes'])) {
$pathParts = explode('/', $data['s3']['key']);
array_pop($pathParts);
$path_base = implode('/', $pathParts);
foreach($data['sizes'] as $key => $size) {
$file = arrayPath($size,'s3/key', false);
if (!$file) {
$file = $path_base.'/'.$size['file'];
}
if (in_array($file, $deletedFiles)) {
Logger::info("File '$file' has already been deleted.");
continue;
}
$this->deleteFile($file);
$deletedFiles[] = $file;
}
}
}
}
return $id;
} | [
"public",
"function",
"deleteAttachment",
"(",
"$",
"id",
")",
"{",
"if",
"(",
"!",
"StorageSettings",
"::",
"deleteFromStorage",
"(",
")",
")",
"{",
"return",
"$",
"id",
";",
"}",
"$",
"data",
"=",
"wp_get_attachment_metadata",
"(",
"$",
"id",
")",
";",... | Filters for when attachments are deleted
@param $id
@return mixed | [
"Filters",
"for",
"when",
"attachments",
"are",
"deleted"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Storage/StorageTool.php#L427-L489 | train |
Interfacelab/ilab-media-tools | classes/Tools/Storage/StorageTool.php | StorageTool.forcedImageDownsize | public function forcedImageDownsize($fail, $id, $size) {
if(empty($size) || empty($id) || is_array($size)) {
return $fail;
}
$meta = wp_get_attachment_metadata($id);
if(empty($meta)) {
return $fail;
}
if(!isset($meta['sizes'])) {
return $fail;
}
if(!isset($meta['sizes'][$size])) {
return $fail;
}
$isOffloadS3 = (arrayPath($meta, 's3/provider', null) == 'aws');
$sizeMeta = $meta['sizes'][$size];
if(!isset($sizeMeta['s3'])) {
if ($isOffloadS3) {
if ($this->fixOffloadS3Meta($id, $meta)) {
return $this->forcedImageDownsize($fail, $id, $size);
} else {
return $fail;
}
} else {
return $fail;
}
}
$url = $this->getAttachmentURLFromMeta($sizeMeta);// $sizeMeta['s3']['url'];
$result = [
$url,
$sizeMeta['width'],
$sizeMeta['height'],
true
];
return $result;
} | php | public function forcedImageDownsize($fail, $id, $size) {
if(empty($size) || empty($id) || is_array($size)) {
return $fail;
}
$meta = wp_get_attachment_metadata($id);
if(empty($meta)) {
return $fail;
}
if(!isset($meta['sizes'])) {
return $fail;
}
if(!isset($meta['sizes'][$size])) {
return $fail;
}
$isOffloadS3 = (arrayPath($meta, 's3/provider', null) == 'aws');
$sizeMeta = $meta['sizes'][$size];
if(!isset($sizeMeta['s3'])) {
if ($isOffloadS3) {
if ($this->fixOffloadS3Meta($id, $meta)) {
return $this->forcedImageDownsize($fail, $id, $size);
} else {
return $fail;
}
} else {
return $fail;
}
}
$url = $this->getAttachmentURLFromMeta($sizeMeta);// $sizeMeta['s3']['url'];
$result = [
$url,
$sizeMeta['width'],
$sizeMeta['height'],
true
];
return $result;
} | [
"public",
"function",
"forcedImageDownsize",
"(",
"$",
"fail",
",",
"$",
"id",
",",
"$",
"size",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"size",
")",
"||",
"empty",
"(",
"$",
"id",
")",
"||",
"is_array",
"(",
"$",
"size",
")",
")",
"{",
"return",... | Performs the image downsize regardless if Imgix is enabled or not.
@param $fail
@param $id
@param $size
@return array
@throws StorageException | [
"Performs",
"the",
"image",
"downsize",
"regardless",
"if",
"Imgix",
"is",
"enabled",
"or",
"not",
"."
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Storage/StorageTool.php#L670-L714 | train |
Interfacelab/ilab-media-tools | classes/Tools/Storage/StorageTool.php | StorageTool.getOffloadS3URL | private function getOffloadS3URL($post_id, $info) {
if(!is_array($info) && (count($info) < 1)) {
return null;
}
$region = $info[0]['region'];
$bucket = $info[0]['bucket'];
$file = $info[0]['key'];
return "https://s3-$region.amazonaws.com/$bucket/$file";
} | php | private function getOffloadS3URL($post_id, $info) {
if(!is_array($info) && (count($info) < 1)) {
return null;
}
$region = $info[0]['region'];
$bucket = $info[0]['bucket'];
$file = $info[0]['key'];
return "https://s3-$region.amazonaws.com/$bucket/$file";
} | [
"private",
"function",
"getOffloadS3URL",
"(",
"$",
"post_id",
",",
"$",
"info",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"info",
")",
"&&",
"(",
"count",
"(",
"$",
"info",
")",
"<",
"1",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"... | For compatibility with Offload S3.
@param int $post_id
@param array $info
@return null|string | [
"For",
"compatibility",
"with",
"Offload",
"S3",
"."
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Storage/StorageTool.php#L1054-L1064 | train |
Interfacelab/ilab-media-tools | classes/Tools/Storage/StorageTool.php | StorageTool.processCrop | public function processCrop($size, $upload_path, $file, $sizeMeta) {
$upload_info = wp_upload_dir();
$subdir = trim(str_replace($upload_info['basedir'], '', $upload_path), '/');
$upload_path = rtrim(str_replace($subdir, '', $upload_path), '/');
if($this->client && $this->client->enabled()) {
$sizeMeta = $this->processFile($upload_path, $subdir.'/'.$file, $sizeMeta);
}
return $sizeMeta;
} | php | public function processCrop($size, $upload_path, $file, $sizeMeta) {
$upload_info = wp_upload_dir();
$subdir = trim(str_replace($upload_info['basedir'], '', $upload_path), '/');
$upload_path = rtrim(str_replace($subdir, '', $upload_path), '/');
if($this->client && $this->client->enabled()) {
$sizeMeta = $this->processFile($upload_path, $subdir.'/'.$file, $sizeMeta);
}
return $sizeMeta;
} | [
"public",
"function",
"processCrop",
"(",
"$",
"size",
",",
"$",
"upload_path",
",",
"$",
"file",
",",
"$",
"sizeMeta",
")",
"{",
"$",
"upload_info",
"=",
"wp_upload_dir",
"(",
")",
";",
"$",
"subdir",
"=",
"trim",
"(",
"str_replace",
"(",
"$",
"upload... | Processes a file after a crop has been performed, uploading it to storage if it exists
@param string $size
@param string $upload_path
@param string $file
@param array $sizeMeta
@return array | [
"Processes",
"a",
"file",
"after",
"a",
"crop",
"has",
"been",
"performed",
"uploading",
"it",
"to",
"storage",
"if",
"it",
"exists"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Storage/StorageTool.php#L1079-L1089 | train |
Interfacelab/ilab-media-tools | classes/Tools/Storage/StorageTool.php | StorageTool.deleteFile | private function deleteFile($file) {
try {
if($this->client && $this->client->enabled()) {
$this->client->delete($file);
}
}
catch(StorageException $ex) {
Logger::error("Error deleting file '$file'.", ['exception' => $ex->getMessage(), 'Key' => $file]);
}
} | php | private function deleteFile($file) {
try {
if($this->client && $this->client->enabled()) {
$this->client->delete($file);
}
}
catch(StorageException $ex) {
Logger::error("Error deleting file '$file'.", ['exception' => $ex->getMessage(), 'Key' => $file]);
}
} | [
"private",
"function",
"deleteFile",
"(",
"$",
"file",
")",
"{",
"try",
"{",
"if",
"(",
"$",
"this",
"->",
"client",
"&&",
"$",
"this",
"->",
"client",
"->",
"enabled",
"(",
")",
")",
"{",
"$",
"this",
"->",
"client",
"->",
"delete",
"(",
"$",
"f... | Deletes a file from storage
@param $file | [
"Deletes",
"a",
"file",
"from",
"storage"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Storage/StorageTool.php#L1196-L1205 | train |
Interfacelab/ilab-media-tools | classes/Tools/Storage/StorageTool.php | StorageTool.hookMediaList | private function hookMediaList() {
if(!$this->mediaListIntegration) {
return;
}
add_action('admin_init', function() {
add_filter('manage_media_columns', function($cols) {
$cols["cloud"] = 'Cloud';
return $cols;
});
add_action('manage_media_custom_column', function($column_name, $id) {
if($column_name == "cloud") {
$meta = wp_get_attachment_metadata($id);
if(!empty($meta) && isset($meta['s3'])) {
echo "<a href='".$meta['s3']['url']."' target=_blank>View</a>";
}
}
}, 10, 2);
});
add_action('wp_enqueue_media', function() {
add_action('admin_head', function() {
if(get_current_screen()->base == 'upload') {
?>
<style>
th.column-s3, td.column-s3 {
width: 60px !important;
max-width: 60px !important;
}
</style>
<?php
}
});
});
} | php | private function hookMediaList() {
if(!$this->mediaListIntegration) {
return;
}
add_action('admin_init', function() {
add_filter('manage_media_columns', function($cols) {
$cols["cloud"] = 'Cloud';
return $cols;
});
add_action('manage_media_custom_column', function($column_name, $id) {
if($column_name == "cloud") {
$meta = wp_get_attachment_metadata($id);
if(!empty($meta) && isset($meta['s3'])) {
echo "<a href='".$meta['s3']['url']."' target=_blank>View</a>";
}
}
}, 10, 2);
});
add_action('wp_enqueue_media', function() {
add_action('admin_head', function() {
if(get_current_screen()->base == 'upload') {
?>
<style>
th.column-s3, td.column-s3 {
width: 60px !important;
max-width: 60px !important;
}
</style>
<?php
}
});
});
} | [
"private",
"function",
"hookMediaList",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"mediaListIntegration",
")",
"{",
"return",
";",
"}",
"add_action",
"(",
"'admin_init'",
",",
"function",
"(",
")",
"{",
"add_filter",
"(",
"'manage_media_columns'",
",... | Adds a custom column to the media list. | [
"Adds",
"a",
"custom",
"column",
"to",
"the",
"media",
"list",
"."
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Storage/StorageTool.php#L1248-L1284 | train |
Interfacelab/ilab-media-tools | classes/Tools/Storage/StorageTool.php | StorageTool.doRenderStorageInfoMeta | private function doRenderStorageInfoMeta($postId = null, $readOnly = false) {
global $post;
if(empty($postId)) {
$postId = $post->ID;
}
$meta = wp_get_attachment_metadata($postId);
if(empty($meta)) {
return;
}
if(!isset($meta['s3'])) {
$meta = get_post_meta($postId, 'ilab_s3_info', true);
}
if(empty($meta) || !isset($meta['s3'])) {
?>
Not uploaded.
<?php
die;
}
$type = arrayPath($meta, 'type', false);
if (empty($type)) {
$type = get_post_mime_type($postId);
}
if(strpos($type, 'image') === 0) {
$this->doRenderStoreageInfoMetaImage($postId, $meta, $readOnly);
} else {
$this->doRenderStorageinfoMetaDocument($postId, $meta, $readOnly);
}
} | php | private function doRenderStorageInfoMeta($postId = null, $readOnly = false) {
global $post;
if(empty($postId)) {
$postId = $post->ID;
}
$meta = wp_get_attachment_metadata($postId);
if(empty($meta)) {
return;
}
if(!isset($meta['s3'])) {
$meta = get_post_meta($postId, 'ilab_s3_info', true);
}
if(empty($meta) || !isset($meta['s3'])) {
?>
Not uploaded.
<?php
die;
}
$type = arrayPath($meta, 'type', false);
if (empty($type)) {
$type = get_post_mime_type($postId);
}
if(strpos($type, 'image') === 0) {
$this->doRenderStoreageInfoMetaImage($postId, $meta, $readOnly);
} else {
$this->doRenderStorageinfoMetaDocument($postId, $meta, $readOnly);
}
} | [
"private",
"function",
"doRenderStorageInfoMeta",
"(",
"$",
"postId",
"=",
"null",
",",
"$",
"readOnly",
"=",
"false",
")",
"{",
"global",
"$",
"post",
";",
"if",
"(",
"empty",
"(",
"$",
"postId",
")",
")",
"{",
"$",
"postId",
"=",
"$",
"post",
"->",... | Renders the Cloud Storage metabox
@param $postId
@param $readOnly | [
"Renders",
"the",
"Cloud",
"Storage",
"metabox"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Storage/StorageTool.php#L1455-L1488 | train |
Interfacelab/ilab-media-tools | classes/Tools/Storage/StorageTool.php | StorageTool.regenerateFile | public function regenerateFile($postId) {
@set_time_limit(120);
$fullsizepath = get_attached_file( $postId );
if (!file_exists($fullsizepath)) {
if (function_exists('_load_image_to_edit_path')) {
$fullsizepath = _load_image_to_edit_path($postId);
} else {
Logger::warning("The function '_load_image_to_edit_path' does not exist, using internal implementation.");
$fullsizepath = $this->loadImageToEditPath($postId);
Logger::warning("$postId => $fullsizepath");
}
}
if (!file_exists($fullsizepath)) {
if (strpos($fullsizepath, 'http') === 0) {
$path = parse_url($fullsizepath, PHP_URL_PATH);
$pathParts = explode('/', $path);
$file = array_pop($pathParts);
$uploadDirInfo = wp_upload_dir();
$filepath = $uploadDirInfo['path'].'/'.$file;
Logger::startTiming("Downloading fullsize '$fullsizepath' to '$filepath'");
file_put_contents($filepath, file_get_contents($fullsizepath));
Logger::endTiming("Finished downloading fullsize '$fullsizepath' to '$filepath'");
if (!file_exists($filepath)) {
return "File '$fullsizepath' could not be downloaded.";
}
$fullsizepath = $filepath;
} else {
return "Local file '$fullsizepath' does not exist and is not a URL.";
}
}
Logger::startTiming('Regenerating metadata ...', ['id' => $postId]);
$metadata = wp_generate_attachment_metadata( $postId, $fullsizepath );
Logger::endTiming('Regenerating metadata ...', ['id' => $postId]);
wp_update_attachment_metadata($postId, $metadata);
return true;
} | php | public function regenerateFile($postId) {
@set_time_limit(120);
$fullsizepath = get_attached_file( $postId );
if (!file_exists($fullsizepath)) {
if (function_exists('_load_image_to_edit_path')) {
$fullsizepath = _load_image_to_edit_path($postId);
} else {
Logger::warning("The function '_load_image_to_edit_path' does not exist, using internal implementation.");
$fullsizepath = $this->loadImageToEditPath($postId);
Logger::warning("$postId => $fullsizepath");
}
}
if (!file_exists($fullsizepath)) {
if (strpos($fullsizepath, 'http') === 0) {
$path = parse_url($fullsizepath, PHP_URL_PATH);
$pathParts = explode('/', $path);
$file = array_pop($pathParts);
$uploadDirInfo = wp_upload_dir();
$filepath = $uploadDirInfo['path'].'/'.$file;
Logger::startTiming("Downloading fullsize '$fullsizepath' to '$filepath'");
file_put_contents($filepath, file_get_contents($fullsizepath));
Logger::endTiming("Finished downloading fullsize '$fullsizepath' to '$filepath'");
if (!file_exists($filepath)) {
return "File '$fullsizepath' could not be downloaded.";
}
$fullsizepath = $filepath;
} else {
return "Local file '$fullsizepath' does not exist and is not a URL.";
}
}
Logger::startTiming('Regenerating metadata ...', ['id' => $postId]);
$metadata = wp_generate_attachment_metadata( $postId, $fullsizepath );
Logger::endTiming('Regenerating metadata ...', ['id' => $postId]);
wp_update_attachment_metadata($postId, $metadata);
return true;
} | [
"public",
"function",
"regenerateFile",
"(",
"$",
"postId",
")",
"{",
"@",
"set_time_limit",
"(",
"120",
")",
";",
"$",
"fullsizepath",
"=",
"get_attached_file",
"(",
"$",
"postId",
")",
";",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"fullsizepath",
")",
... | Regenerates an image's thumbnails and re-uploads them to the storage service.
@param $postId
@return bool|string | [
"Regenerates",
"an",
"image",
"s",
"thumbnails",
"and",
"re",
"-",
"uploads",
"them",
"to",
"the",
"storage",
"service",
"."
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Storage/StorageTool.php#L1644-L1688 | train |
Interfacelab/ilab-media-tools | classes/Tools/Storage/StorageTool.php | StorageTool.uploadUrlForFile | public function uploadUrlForFile($filename) {
$prefix = StorageSettings::prefix(null);
$parts = explode('/', $filename);
$bucketFilename = array_pop($parts);
if($this->client && $this->client->enabled()) {
try {
return $this->client->uploadUrl($prefix.$bucketFilename, StorageSettings::privacy(), StorageSettings::cacheControl(), StorageSettings::expires());
}
catch(StorageException $ex) {
Logger::error('Generate File Upload URL Error', ['exception' => $ex->getMessage()]);
}
}
return null;
} | php | public function uploadUrlForFile($filename) {
$prefix = StorageSettings::prefix(null);
$parts = explode('/', $filename);
$bucketFilename = array_pop($parts);
if($this->client && $this->client->enabled()) {
try {
return $this->client->uploadUrl($prefix.$bucketFilename, StorageSettings::privacy(), StorageSettings::cacheControl(), StorageSettings::expires());
}
catch(StorageException $ex) {
Logger::error('Generate File Upload URL Error', ['exception' => $ex->getMessage()]);
}
}
return null;
} | [
"public",
"function",
"uploadUrlForFile",
"(",
"$",
"filename",
")",
"{",
"$",
"prefix",
"=",
"StorageSettings",
"::",
"prefix",
"(",
"null",
")",
";",
"$",
"parts",
"=",
"explode",
"(",
"'/'",
",",
"$",
"filename",
")",
";",
"$",
"bucketFilename",
"=",
... | Gets a pre-signed URL for uploading directly to the storage backend
@param string $filename
@return array|null | [
"Gets",
"a",
"pre",
"-",
"signed",
"URL",
"for",
"uploading",
"directly",
"to",
"the",
"storage",
"backend"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Storage/StorageTool.php#L1823-L1838 | train |
Interfacelab/ilab-media-tools | classes/Tools/Storage/StorageTool.php | StorageTool.handleImageOptimizer | public function handleImageOptimizer($postId) {
$this->processingOptimized = true;
Logger::info('Handle Image Optimizer: '.$postId);
add_filter('ilab_ignore_existing_s3_data', function($shouldIgnore, $attachmentId) use ($postId) {
if ($postId == $attachmentId) {
return true;
}
return $shouldIgnore;
}, 10000, 2);
$this->processImport(1, $postId, null);
} | php | public function handleImageOptimizer($postId) {
$this->processingOptimized = true;
Logger::info('Handle Image Optimizer: '.$postId);
add_filter('ilab_ignore_existing_s3_data', function($shouldIgnore, $attachmentId) use ($postId) {
if ($postId == $attachmentId) {
return true;
}
return $shouldIgnore;
}, 10000, 2);
$this->processImport(1, $postId, null);
} | [
"public",
"function",
"handleImageOptimizer",
"(",
"$",
"postId",
")",
"{",
"$",
"this",
"->",
"processingOptimized",
"=",
"true",
";",
"Logger",
"::",
"info",
"(",
"'Handle Image Optimizer: '",
".",
"$",
"postId",
")",
";",
"add_filter",
"(",
"'ilab_ignore_exis... | region Image Optimizer | [
"region",
"Image",
"Optimizer"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Storage/StorageTool.php#L1953-L1968 | train |
Interfacelab/ilab-media-tools | classes/Cloud/Storage/Driver/S3/S3Storage.php | S3Storage.getBucketRegion | protected function getBucketRegion() {
if(!$this->enabled()) {
return false;
}
$config = [
'version' => 'latest',
'credentials' => [
'key' => $this->key,
'secret' => $this->secret
]
];
if(!empty($this->endpoint)) {
$config['endpoint'] = $this->endpoint;
if($this->endPointPathStyle) {
$config['use_path_style_endpoint'] = true;
}
}
$s3 = new S3MultiRegionClient($config);
$region = false;
try {
$region = $s3->determineBucketRegion($this->bucket);
}
catch(AwsException $ex) {
Logger::error("AWS Error fetching region", ['exception' => $ex->getMessage()]);
}
return $region;
} | php | protected function getBucketRegion() {
if(!$this->enabled()) {
return false;
}
$config = [
'version' => 'latest',
'credentials' => [
'key' => $this->key,
'secret' => $this->secret
]
];
if(!empty($this->endpoint)) {
$config['endpoint'] = $this->endpoint;
if($this->endPointPathStyle) {
$config['use_path_style_endpoint'] = true;
}
}
$s3 = new S3MultiRegionClient($config);
$region = false;
try {
$region = $s3->determineBucketRegion($this->bucket);
}
catch(AwsException $ex) {
Logger::error("AWS Error fetching region", ['exception' => $ex->getMessage()]);
}
return $region;
} | [
"protected",
"function",
"getBucketRegion",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"enabled",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"config",
"=",
"[",
"'version'",
"=>",
"'latest'",
",",
"'credentials'",
"=>",
"[",
"'key'",
... | Attempts to determine the region for the bucket
@return bool|string | [
"Attempts",
"to",
"determine",
"the",
"region",
"for",
"the",
"bucket"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Cloud/Storage/Driver/S3/S3Storage.php#L275-L305 | train |
Interfacelab/ilab-media-tools | classes/Cloud/Storage/Driver/S3/S3Storage.php | S3Storage.getS3MultiRegionClient | protected function getS3MultiRegionClient() {
if(!$this->enabled()) {
return null;
}
$config = [
'version' => 'latest',
'credentials' => [
'key' => $this->key,
'secret' => $this->secret
]
];
if(!empty($this->endpoint)) {
$config['endpoint'] = $this->endpoint;
if($this->endPointPathStyle) {
$config['use_path_style_endpoint'] = true;
}
}
if($this->useTransferAcceleration) {
$config['use_accelerate_endpoint'] = true;
}
$s3 = new S3MultiRegionClient($config);
return $s3;
} | php | protected function getS3MultiRegionClient() {
if(!$this->enabled()) {
return null;
}
$config = [
'version' => 'latest',
'credentials' => [
'key' => $this->key,
'secret' => $this->secret
]
];
if(!empty($this->endpoint)) {
$config['endpoint'] = $this->endpoint;
if($this->endPointPathStyle) {
$config['use_path_style_endpoint'] = true;
}
}
if($this->useTransferAcceleration) {
$config['use_accelerate_endpoint'] = true;
}
$s3 = new S3MultiRegionClient($config);
return $s3;
} | [
"protected",
"function",
"getS3MultiRegionClient",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"enabled",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"config",
"=",
"[",
"'version'",
"=>",
"'latest'",
",",
"'credentials'",
"=>",
"[",
"'k... | Builds and returns an S3MultiRegionClient
@return S3MultiRegionClient|null | [
"Builds",
"and",
"returns",
"an",
"S3MultiRegionClient"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Cloud/Storage/Driver/S3/S3Storage.php#L311-L339 | train |
Interfacelab/ilab-media-tools | classes/Cloud/Storage/Driver/S3/S3Storage.php | S3Storage.getS3Client | protected function getS3Client($region = false, $errorCollector = null) {
if(!$this->enabled()) {
return null;
}
if(empty($region)) {
if(empty($this->region)) {
$this->region = $this->getBucketRegion();
if(empty($this->region)) {
if ($errorCollector) {
$errorCollector->addError('Could not determine region.');
}
Logger::info("Could not get region from server.");
return null;
}
update_option('ilab-media-s3-region', $this->region);
}
$region = $this->region;
}
if(empty($region)) {
if ($errorCollector) {
$errorCollector->addError("Could not determine region or the region was not specified.");
}
return null;
}
$config = [
'version' => 'latest',
'credentials' => [
'key' => $this->key,
'secret' => $this->secret
],
'region' => $region
];
if(!empty($this->endpoint)) {
$config['endpoint'] = $this->endpoint;
if($this->endPointPathStyle) {
$config['use_path_style_endpoint'] = true;
}
}
if($this->useTransferAcceleration) {
$config['use_accelerate_endpoint'] = true;
}
$s3 = new S3Client($config);
return $s3;
} | php | protected function getS3Client($region = false, $errorCollector = null) {
if(!$this->enabled()) {
return null;
}
if(empty($region)) {
if(empty($this->region)) {
$this->region = $this->getBucketRegion();
if(empty($this->region)) {
if ($errorCollector) {
$errorCollector->addError('Could not determine region.');
}
Logger::info("Could not get region from server.");
return null;
}
update_option('ilab-media-s3-region', $this->region);
}
$region = $this->region;
}
if(empty($region)) {
if ($errorCollector) {
$errorCollector->addError("Could not determine region or the region was not specified.");
}
return null;
}
$config = [
'version' => 'latest',
'credentials' => [
'key' => $this->key,
'secret' => $this->secret
],
'region' => $region
];
if(!empty($this->endpoint)) {
$config['endpoint'] = $this->endpoint;
if($this->endPointPathStyle) {
$config['use_path_style_endpoint'] = true;
}
}
if($this->useTransferAcceleration) {
$config['use_accelerate_endpoint'] = true;
}
$s3 = new S3Client($config);
return $s3;
} | [
"protected",
"function",
"getS3Client",
"(",
"$",
"region",
"=",
"false",
",",
"$",
"errorCollector",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"enabled",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"empty",
"(",
"$",... | Attempts to build the S3Client. This requires a region be defined or determinable.
@param bool $region
@param ErrorCollector|null $errorCollector
@return S3Client|null | [
"Attempts",
"to",
"build",
"the",
"S3Client",
".",
"This",
"requires",
"a",
"region",
"be",
"defined",
"or",
"determinable",
"."
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Cloud/Storage/Driver/S3/S3Storage.php#L349-L404 | train |
Interfacelab/ilab-media-tools | classes/Cloud/Storage/Driver/S3/S3Storage.php | S3Storage.getClient | protected function getClient($errorCollector = null) {
if(!$this->enabled()) {
if ($errorCollector) {
$errorCollector->addError("Account ID, account secret and/or the bucket are incorrect or missing.");
}
return null;
}
$s3 = $this->getS3Client(false, $errorCollector);
if(!$s3) {
Logger::info('Could not create regular client, creating multi-region client instead.');
if ($errorCollector) {
$errorCollector->addError("Could not create regular client, creating multi-region client instead.");
}
$s3 = $this->getS3MultiRegionClient();
if (!$s3 && $errorCollector) {
$errorCollector->addError("Could not create regular client, creating multi-region client instead.");
}
}
return $s3;
} | php | protected function getClient($errorCollector = null) {
if(!$this->enabled()) {
if ($errorCollector) {
$errorCollector->addError("Account ID, account secret and/or the bucket are incorrect or missing.");
}
return null;
}
$s3 = $this->getS3Client(false, $errorCollector);
if(!$s3) {
Logger::info('Could not create regular client, creating multi-region client instead.');
if ($errorCollector) {
$errorCollector->addError("Could not create regular client, creating multi-region client instead.");
}
$s3 = $this->getS3MultiRegionClient();
if (!$s3 && $errorCollector) {
$errorCollector->addError("Could not create regular client, creating multi-region client instead.");
}
}
return $s3;
} | [
"protected",
"function",
"getClient",
"(",
"$",
"errorCollector",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"enabled",
"(",
")",
")",
"{",
"if",
"(",
"$",
"errorCollector",
")",
"{",
"$",
"errorCollector",
"->",
"addError",
"(",
"\"Acco... | Gets the S3Client
@param ErrorCollector|null $errorCollector
@return S3Client|S3MultiRegionClient|null | [
"Gets",
"the",
"S3Client"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Cloud/Storage/Driver/S3/S3Storage.php#L412-L437 | train |
Interfacelab/ilab-media-tools | classes/Tools/ToolBase.php | ToolBase.enabled | public function enabled()
{
if ($this->badPluginsInstalled) {
return false;
}
$env = ($this->env_variable) ? getenv($this->env_variable) : false;
$enabled=get_option("ilab-media-tool-enabled-$this->toolName", $env);
if ($enabled && isset($this->toolInfo['dependencies']))
{
foreach($this->toolInfo['dependencies'] as $dep)
{
if (is_array($dep)) {
$enabledCount = 0;
foreach($dep as $toolDep) {
if ($this->toolManager->toolEnabled($toolDep)) {
$enabledCount++;
break;
}
}
if ($enabledCount == 0) {
return false;
}
} else {
if (!$this->toolManager->toolEnabled($dep))
return false;
}
}
}
return $enabled;
} | php | public function enabled()
{
if ($this->badPluginsInstalled) {
return false;
}
$env = ($this->env_variable) ? getenv($this->env_variable) : false;
$enabled=get_option("ilab-media-tool-enabled-$this->toolName", $env);
if ($enabled && isset($this->toolInfo['dependencies']))
{
foreach($this->toolInfo['dependencies'] as $dep)
{
if (is_array($dep)) {
$enabledCount = 0;
foreach($dep as $toolDep) {
if ($this->toolManager->toolEnabled($toolDep)) {
$enabledCount++;
break;
}
}
if ($enabledCount == 0) {
return false;
}
} else {
if (!$this->toolManager->toolEnabled($dep))
return false;
}
}
}
return $enabled;
} | [
"public",
"function",
"enabled",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"badPluginsInstalled",
")",
"{",
"return",
"false",
";",
"}",
"$",
"env",
"=",
"(",
"$",
"this",
"->",
"env_variable",
")",
"?",
"getenv",
"(",
"$",
"this",
"->",
"env_vari... | Determines if this tool is enabled or not | [
"Determines",
"if",
"this",
"tool",
"is",
"enabled",
"or",
"not"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/ToolBase.php#L252-L285 | train |
Interfacelab/ilab-media-tools | classes/Tools/ToolBase.php | ToolBase.registerMenu | public function registerMenu($top_menu_slug)
{
if (!isset($this->toolInfo['settings']))
return;
if ($this->only_when_enabled && (!$this->enabled())) {
return;
}
$settings=$this->toolInfo['settings'];
add_submenu_page( $top_menu_slug, $settings['title'], $settings['menu'], 'manage_options', $this->options_page, [$this,'renderSettings']);
foreach($this->batchTools as $batchTool) {
if ($batchTool->enabled()) {
add_submenu_page($top_menu_slug, $batchTool->pageTitle(), $batchTool->menuTitle(), $batchTool->capabilityRequirement(), $batchTool->menuSlug(), [
$batchTool,
'renderBatchTool'
]);
}
}
} | php | public function registerMenu($top_menu_slug)
{
if (!isset($this->toolInfo['settings']))
return;
if ($this->only_when_enabled && (!$this->enabled())) {
return;
}
$settings=$this->toolInfo['settings'];
add_submenu_page( $top_menu_slug, $settings['title'], $settings['menu'], 'manage_options', $this->options_page, [$this,'renderSettings']);
foreach($this->batchTools as $batchTool) {
if ($batchTool->enabled()) {
add_submenu_page($top_menu_slug, $batchTool->pageTitle(), $batchTool->menuTitle(), $batchTool->capabilityRequirement(), $batchTool->menuSlug(), [
$batchTool,
'renderBatchTool'
]);
}
}
} | [
"public",
"function",
"registerMenu",
"(",
"$",
"top_menu_slug",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"toolInfo",
"[",
"'settings'",
"]",
")",
")",
"return",
";",
"if",
"(",
"$",
"this",
"->",
"only_when_enabled",
"&&",
"(",
"!",
... | Register menu pages
@param $top_menu_slug | [
"Register",
"menu",
"pages"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/ToolBase.php#L373-L393 | train |
Interfacelab/ilab-media-tools | classes/Tools/ToolBase.php | ToolBase.registerSettingsSection | protected function registerSettingsSection($slug,$title,$description)
{
$this->settingSections[$slug]=[
'title'=>$title,
'description'=>$description,
'fields'=>[]
];
add_settings_section($slug,$title,[$this,'renderSettingsSection'],$this->options_page);
} | php | protected function registerSettingsSection($slug,$title,$description)
{
$this->settingSections[$slug]=[
'title'=>$title,
'description'=>$description,
'fields'=>[]
];
add_settings_section($slug,$title,[$this,'renderSettingsSection'],$this->options_page);
} | [
"protected",
"function",
"registerSettingsSection",
"(",
"$",
"slug",
",",
"$",
"title",
",",
"$",
"description",
")",
"{",
"$",
"this",
"->",
"settingSections",
"[",
"$",
"slug",
"]",
"=",
"[",
"'title'",
"=>",
"$",
"title",
",",
"'description'",
"=>",
... | Registers a settings section
@param $slug
@param $title
@param $description | [
"Registers",
"a",
"settings",
"section"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/ToolBase.php#L419-L428 | train |
Interfacelab/ilab-media-tools | classes/Tools/ToolBase.php | ToolBase.renderSettingsSection | public function renderSettingsSection($section)
{
if (!isset($this->settingSections[$section['id']]))
return;
$settingSection=$this->settingSections[$section['id']];
echo "<a name='{$section['id']}'></a>";
if (is_array($settingSection['description'])) {
foreach($settingSection['description'] as $description) {
echo "<p>$description</p>";
}
} else {
echo "<p>{$settingSection['description']}</p>";
}
} | php | public function renderSettingsSection($section)
{
if (!isset($this->settingSections[$section['id']]))
return;
$settingSection=$this->settingSections[$section['id']];
echo "<a name='{$section['id']}'></a>";
if (is_array($settingSection['description'])) {
foreach($settingSection['description'] as $description) {
echo "<p>$description</p>";
}
} else {
echo "<p>{$settingSection['description']}</p>";
}
} | [
"public",
"function",
"renderSettingsSection",
"(",
"$",
"section",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"settingSections",
"[",
"$",
"section",
"[",
"'id'",
"]",
"]",
")",
")",
"return",
";",
"$",
"settingSection",
"=",
"$",
"thi... | Renders a settings section description
@param $section | [
"Renders",
"a",
"settings",
"section",
"description"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/ToolBase.php#L434-L450 | train |
Interfacelab/ilab-media-tools | classes/Tasks/BackgroundProcess.php | BackgroundProcess.maybe_handle | public function maybe_handle() {
if ( $this->is_process_running() ) {
// Background process already running.
wp_die();
}
if ( $this->is_queue_empty() ) {
// No data to process.
wp_die();
}
check_ajax_referer( $this->identifier, 'nonce' );
$this->handle();
wp_die();
} | php | public function maybe_handle() {
if ( $this->is_process_running() ) {
// Background process already running.
wp_die();
}
if ( $this->is_queue_empty() ) {
// No data to process.
wp_die();
}
check_ajax_referer( $this->identifier, 'nonce' );
$this->handle();
wp_die();
} | [
"public",
"function",
"maybe_handle",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"is_process_running",
"(",
")",
")",
"{",
"// Background process already running.",
"wp_die",
"(",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"is_queue_empty",
"(",
")",
"... | Maybe process queue
Checks whether data exists within the queue and that
the process is not already running. | [
"Maybe",
"process",
"queue"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tasks/BackgroundProcess.php#L162-L178 | train |
Interfacelab/ilab-media-tools | classes/Tasks/BackgroundProcess.php | BackgroundProcess.is_queue_empty | protected function is_queue_empty() {
global $wpdb;
$table = $wpdb->options;
$column = 'option_name';
if ( is_multisite() ) {
$table = $wpdb->sitemeta;
$column = 'meta_key';
}
$key = $this->identifier . '_batch_%';
$count = $wpdb->get_var( $wpdb->prepare( "
SELECT COUNT(*)
FROM {$table}
WHERE {$column} LIKE %s
", $key ) );
return ( $count > 0 ) ? false : true;
} | php | protected function is_queue_empty() {
global $wpdb;
$table = $wpdb->options;
$column = 'option_name';
if ( is_multisite() ) {
$table = $wpdb->sitemeta;
$column = 'meta_key';
}
$key = $this->identifier . '_batch_%';
$count = $wpdb->get_var( $wpdb->prepare( "
SELECT COUNT(*)
FROM {$table}
WHERE {$column} LIKE %s
", $key ) );
return ( $count > 0 ) ? false : true;
} | [
"protected",
"function",
"is_queue_empty",
"(",
")",
"{",
"global",
"$",
"wpdb",
";",
"$",
"table",
"=",
"$",
"wpdb",
"->",
"options",
";",
"$",
"column",
"=",
"'option_name'",
";",
"if",
"(",
"is_multisite",
"(",
")",
")",
"{",
"$",
"table",
"=",
"$... | Is queue empty
@return bool | [
"Is",
"queue",
"empty"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tasks/BackgroundProcess.php#L185-L205 | train |
Interfacelab/ilab-media-tools | classes/Tasks/BackgroundProcess.php | BackgroundProcess.is_process_running | protected function is_process_running() {
$lockData = get_option($this->identifier . '_process_lock', null);
if (!empty($lockData) || isset($lockData['expires'])) {
if (time() <= $lockData['expires']) {
Logger::info('Lock still active. Expires in: '.($lockData['expires'] - time()));
return true;
} else {
Logger::info("Lock expired");
}
}
if (!empty($lockData)) {
delete_option($this->identifier . '_process_lock');
} else {
Logger::info('No lock data.');
}
return false;
} | php | protected function is_process_running() {
$lockData = get_option($this->identifier . '_process_lock', null);
if (!empty($lockData) || isset($lockData['expires'])) {
if (time() <= $lockData['expires']) {
Logger::info('Lock still active. Expires in: '.($lockData['expires'] - time()));
return true;
} else {
Logger::info("Lock expired");
}
}
if (!empty($lockData)) {
delete_option($this->identifier . '_process_lock');
} else {
Logger::info('No lock data.');
}
return false;
} | [
"protected",
"function",
"is_process_running",
"(",
")",
"{",
"$",
"lockData",
"=",
"get_option",
"(",
"$",
"this",
"->",
"identifier",
".",
"'_process_lock'",
",",
"null",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"lockData",
")",
"||",
"isset",
"(",... | Is process running
Check whether the current process is already running
in a background process. | [
"Is",
"process",
"running"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tasks/BackgroundProcess.php#L213-L233 | train |
Interfacelab/ilab-media-tools | classes/Tasks/BackgroundProcess.php | BackgroundProcess.schedule_cron_healthcheck | public function schedule_cron_healthcheck( $schedules ) {
$interval = apply_filters( $this->identifier . '_cron_interval', 5 );
if ( property_exists( $this, 'cron_interval' ) ) {
$interval = apply_filters( $this->identifier . '_cron_interval', $this->cron_interval_identifier );
}
// Adds every 5 minutes to the existing schedules.
$schedules[ $this->identifier . '_cron_interval' ] = array(
'interval' => MINUTE_IN_SECONDS * $interval,
'display' => sprintf( __( 'Every %d Minutes' ), $interval ),
);
return $schedules;
} | php | public function schedule_cron_healthcheck( $schedules ) {
$interval = apply_filters( $this->identifier . '_cron_interval', 5 );
if ( property_exists( $this, 'cron_interval' ) ) {
$interval = apply_filters( $this->identifier . '_cron_interval', $this->cron_interval_identifier );
}
// Adds every 5 minutes to the existing schedules.
$schedules[ $this->identifier . '_cron_interval' ] = array(
'interval' => MINUTE_IN_SECONDS * $interval,
'display' => sprintf( __( 'Every %d Minutes' ), $interval ),
);
return $schedules;
} | [
"public",
"function",
"schedule_cron_healthcheck",
"(",
"$",
"schedules",
")",
"{",
"$",
"interval",
"=",
"apply_filters",
"(",
"$",
"this",
"->",
"identifier",
".",
"'_cron_interval'",
",",
"5",
")",
";",
"if",
"(",
"property_exists",
"(",
"$",
"this",
",",... | Schedule cron healthcheck
@access public
@param mixed $schedules Schedules.
@return mixed | [
"Schedule",
"cron",
"healthcheck"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tasks/BackgroundProcess.php#L450-L464 | train |
Interfacelab/ilab-media-tools | classes/Tasks/BackgroundProcess.php | BackgroundProcess.handle_cron_healthcheck | public function handle_cron_healthcheck() {
if ( $this->is_process_running() ) {
// Background process already running.
exit;
}
if ( $this->is_queue_empty() ) {
// No data to process.
$this->clear_scheduled_event();
exit;
}
$this->handle();
exit;
} | php | public function handle_cron_healthcheck() {
if ( $this->is_process_running() ) {
// Background process already running.
exit;
}
if ( $this->is_queue_empty() ) {
// No data to process.
$this->clear_scheduled_event();
exit;
}
$this->handle();
exit;
} | [
"public",
"function",
"handle_cron_healthcheck",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"is_process_running",
"(",
")",
")",
"{",
"// Background process already running.",
"exit",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"is_queue_empty",
"(",
")",
")",
... | Handle cron healthcheck
Restart the background process if not already running
and data exists in the queue. | [
"Handle",
"cron",
"healthcheck"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tasks/BackgroundProcess.php#L472-L487 | train |
Interfacelab/ilab-media-tools | classes/Tasks/BackgroundProcess.php | BackgroundProcess.clear_scheduled_event | protected function clear_scheduled_event() {
$timestamp = wp_next_scheduled( $this->cron_hook_identifier );
if ( $timestamp ) {
wp_unschedule_event( $timestamp, $this->cron_hook_identifier );
}
} | php | protected function clear_scheduled_event() {
$timestamp = wp_next_scheduled( $this->cron_hook_identifier );
if ( $timestamp ) {
wp_unschedule_event( $timestamp, $this->cron_hook_identifier );
}
} | [
"protected",
"function",
"clear_scheduled_event",
"(",
")",
"{",
"$",
"timestamp",
"=",
"wp_next_scheduled",
"(",
"$",
"this",
"->",
"cron_hook_identifier",
")",
";",
"if",
"(",
"$",
"timestamp",
")",
"{",
"wp_unschedule_event",
"(",
"$",
"timestamp",
",",
"$"... | Clear scheduled event | [
"Clear",
"scheduled",
"event"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tasks/BackgroundProcess.php#L501-L507 | train |
Interfacelab/ilab-media-tools | classes/Cloud/Storage/UploadInfo.php | UploadInfo.toArray | public function toArray() {
return [
'key' => $this->key(),
'url' => $this->url(),
'formData' => $this->formData(),
'cacheControl' => $this->cacheControl(),
'expires' => $this->expires(),
'acl' => $this->acl()
];
} | php | public function toArray() {
return [
'key' => $this->key(),
'url' => $this->url(),
'formData' => $this->formData(),
'cacheControl' => $this->cacheControl(),
'expires' => $this->expires(),
'acl' => $this->acl()
];
} | [
"public",
"function",
"toArray",
"(",
")",
"{",
"return",
"[",
"'key'",
"=>",
"$",
"this",
"->",
"key",
"(",
")",
",",
"'url'",
"=>",
"$",
"this",
"->",
"url",
"(",
")",
",",
"'formData'",
"=>",
"$",
"this",
"->",
"formData",
"(",
")",
",",
"'cac... | Returns the upload info as an array
@return array | [
"Returns",
"the",
"upload",
"info",
"as",
"an",
"array"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Cloud/Storage/UploadInfo.php#L67-L76 | train |
Interfacelab/ilab-media-tools | classes/Utilities/EnvironmentOptions.php | EnvironmentOptions.Option | public static function Option($optionName = null, $envVariableName = null, $default = false) {
if (empty($optionName) && empty($envVariableName)) {
return $default;
}
if ($envVariableName == null) {
$envVariableName = str_replace('-','_', strtoupper($optionName));
}
if (is_array($envVariableName)) {
foreach($envVariableName as $envVariable) {
$envval = getenv($envVariable);
if ($envval) {
return $envval;
}
}
} else {
$envval = getenv($envVariableName);
if ($envval) {
return $envval;
}
}
if (empty($optionName)) {
return $default;
}
return get_option($optionName, $default);
} | php | public static function Option($optionName = null, $envVariableName = null, $default = false) {
if (empty($optionName) && empty($envVariableName)) {
return $default;
}
if ($envVariableName == null) {
$envVariableName = str_replace('-','_', strtoupper($optionName));
}
if (is_array($envVariableName)) {
foreach($envVariableName as $envVariable) {
$envval = getenv($envVariable);
if ($envval) {
return $envval;
}
}
} else {
$envval = getenv($envVariableName);
if ($envval) {
return $envval;
}
}
if (empty($optionName)) {
return $default;
}
return get_option($optionName, $default);
} | [
"public",
"static",
"function",
"Option",
"(",
"$",
"optionName",
"=",
"null",
",",
"$",
"envVariableName",
"=",
"null",
",",
"$",
"default",
"=",
"false",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"optionName",
")",
"&&",
"empty",
"(",
"$",
"envVariable... | Fetches an option from WordPress or the environment.
@param string|null $optionName
@param string|array|null $envVariableName
@param bool $default
@return array|false|mixed|string|null | [
"Fetches",
"an",
"option",
"from",
"WordPress",
"or",
"the",
"environment",
"."
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Utilities/EnvironmentOptions.php#L32-L60 | train |
Interfacelab/ilab-media-tools | classes/CLI/Storage/StorageCommands.php | StorageCommands.import | public function import($args, $assoc_args) {
$this->debugMode = (\WP_CLI::get_config('debug') == 'mediacloud');
// Force the logger to initialize
Logger::instance();
/** @var StorageTool $storageTool */
$storageTool = ToolsManager::instance()->tools['storage'];
if (!$storageTool || !$storageTool->enabled()) {
Command::Error('Storage tool is not enabled in Media Cloud or the settings are incorrect.');
return;
}
$postArgs = [
'post_type' => 'attachment',
'post_status' => 'inherit',
'nopaging' => true,
'fields' => 'ids',
];
if(!StorageSettings::uploadDocuments()) {
$args['post_mime_type'] = 'image';
}
$query = new \WP_Query($postArgs);
if($query->post_count > 0) {
BatchManager::instance()->reset('storage');
BatchManager::instance()->setStatus('storage', true);
BatchManager::instance()->setTotalCount('storage', $query->post_count);
BatchManager::instance()->setCurrent('storage', 1);
BatchManager::instance()->setShouldCancel('storage', false);
Command::Info("Total posts found: %Y{$query->post_count}.", true);
$pd = new DefaultProgressDelegate();
for($i = 1; $i <= $query->post_count; $i++) {
$postId = $query->posts[$i - 1];
$upload_file = get_attached_file($postId);
$fileName = basename($upload_file);
BatchManager::instance()->setCurrentFile('storage', $fileName);
BatchManager::instance()->setCurrent('storage', $i);
Command::Info("%w[%C{$i}%w of %C{$query->post_count}%w] %NImporting %Y$fileName%N %w(Post ID %N$postId%w)%N ... ", $this->debugMode);
$storageTool->processImport($i - 1, $postId, $pd);
if (!$this->debugMode) {
Command::Info("%YDone%N.", true);
}
}
BatchManager::instance()->reset('storage');
}
} | php | public function import($args, $assoc_args) {
$this->debugMode = (\WP_CLI::get_config('debug') == 'mediacloud');
// Force the logger to initialize
Logger::instance();
/** @var StorageTool $storageTool */
$storageTool = ToolsManager::instance()->tools['storage'];
if (!$storageTool || !$storageTool->enabled()) {
Command::Error('Storage tool is not enabled in Media Cloud or the settings are incorrect.');
return;
}
$postArgs = [
'post_type' => 'attachment',
'post_status' => 'inherit',
'nopaging' => true,
'fields' => 'ids',
];
if(!StorageSettings::uploadDocuments()) {
$args['post_mime_type'] = 'image';
}
$query = new \WP_Query($postArgs);
if($query->post_count > 0) {
BatchManager::instance()->reset('storage');
BatchManager::instance()->setStatus('storage', true);
BatchManager::instance()->setTotalCount('storage', $query->post_count);
BatchManager::instance()->setCurrent('storage', 1);
BatchManager::instance()->setShouldCancel('storage', false);
Command::Info("Total posts found: %Y{$query->post_count}.", true);
$pd = new DefaultProgressDelegate();
for($i = 1; $i <= $query->post_count; $i++) {
$postId = $query->posts[$i - 1];
$upload_file = get_attached_file($postId);
$fileName = basename($upload_file);
BatchManager::instance()->setCurrentFile('storage', $fileName);
BatchManager::instance()->setCurrent('storage', $i);
Command::Info("%w[%C{$i}%w of %C{$query->post_count}%w] %NImporting %Y$fileName%N %w(Post ID %N$postId%w)%N ... ", $this->debugMode);
$storageTool->processImport($i - 1, $postId, $pd);
if (!$this->debugMode) {
Command::Info("%YDone%N.", true);
}
}
BatchManager::instance()->reset('storage');
}
} | [
"public",
"function",
"import",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"$",
"this",
"->",
"debugMode",
"=",
"(",
"\\",
"WP_CLI",
"::",
"get_config",
"(",
"'debug'",
")",
"==",
"'mediacloud'",
")",
";",
"// Force the logger to initialize",
"Logge... | Imports the media library to the cloud.
@when after_wp_load
@param $args
@param $assoc_args | [
"Imports",
"the",
"media",
"library",
"to",
"the",
"cloud",
"."
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/CLI/Storage/StorageCommands.php#L45-L101 | train |
Interfacelab/ilab-media-tools | classes/Tools/Rekognition/RekognitionTool.php | RekognitionTool.attachmentTaxonomies | public function attachmentTaxonomies() {
$taxonomies = [
'category' => 'Category',
'post_tag' => 'Tag'
];
$attachTaxes = get_object_taxonomies('attachment');
if (!empty($attachTaxes)) {
foreach($attachTaxes as $attachTax) {
if (!in_array($attachTax, ['post_tag', 'category'])) {
$taxonomies[$attachTax] = ucwords(str_replace('_', ' ', $attachTax));
}
}
}
return $taxonomies;
} | php | public function attachmentTaxonomies() {
$taxonomies = [
'category' => 'Category',
'post_tag' => 'Tag'
];
$attachTaxes = get_object_taxonomies('attachment');
if (!empty($attachTaxes)) {
foreach($attachTaxes as $attachTax) {
if (!in_array($attachTax, ['post_tag', 'category'])) {
$taxonomies[$attachTax] = ucwords(str_replace('_', ' ', $attachTax));
}
}
}
return $taxonomies;
} | [
"public",
"function",
"attachmentTaxonomies",
"(",
")",
"{",
"$",
"taxonomies",
"=",
"[",
"'category'",
"=>",
"'Category'",
",",
"'post_tag'",
"=>",
"'Tag'",
"]",
";",
"$",
"attachTaxes",
"=",
"get_object_taxonomies",
"(",
"'attachment'",
")",
";",
"if",
"(",
... | Returns a list of taxonomies for Attachments, used in the Rekognition settings page.
@return array | [
"Returns",
"a",
"list",
"of",
"taxonomies",
"for",
"Attachments",
"used",
"in",
"the",
"Rekognition",
"settings",
"page",
"."
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Rekognition/RekognitionTool.php#L178-L195 | train |
Interfacelab/ilab-media-tools | classes/Tools/Rekognition/RekognitionTool.php | RekognitionTool.processTags | private function processTags($tags, $tax, $postID) {
if (empty($tags)) {
return;
}
$tagsToAdd = [];
foreach($tags as $tag) {
$term = false;
if (term_exists($tag['tag'], $tax)) {
$term = get_term_by('name', $tag['tag'], $tax);
} else {
$parent = false;
if (isset($tag['parent'])) {
if (!term_exists($tag['parent'])) {
$parentTermInfo = wp_insert_term($tag['parent'], $tax);
$parent = get_term_by('id', $parentTermInfo['term_id'], $tax);
} else {
$parent = get_term_by('name', $tag['parent'], $tax);
}
}
$tagInfo = [];
if ($parent) {
$tagInfo['parent'] = $parent->term_id;
}
$tagInfo = wp_insert_term($tag['tag'], $tax, $tagInfo);
$term = get_term_by('id', $tagInfo['term_id'], $tax);
}
if ($term) {
$tagsToAdd[] = $term->term_id;
}
}
if (!empty($tagsToAdd)) {
wp_set_object_terms($postID, $tagsToAdd, $tax, true);
}
} | php | private function processTags($tags, $tax, $postID) {
if (empty($tags)) {
return;
}
$tagsToAdd = [];
foreach($tags as $tag) {
$term = false;
if (term_exists($tag['tag'], $tax)) {
$term = get_term_by('name', $tag['tag'], $tax);
} else {
$parent = false;
if (isset($tag['parent'])) {
if (!term_exists($tag['parent'])) {
$parentTermInfo = wp_insert_term($tag['parent'], $tax);
$parent = get_term_by('id', $parentTermInfo['term_id'], $tax);
} else {
$parent = get_term_by('name', $tag['parent'], $tax);
}
}
$tagInfo = [];
if ($parent) {
$tagInfo['parent'] = $parent->term_id;
}
$tagInfo = wp_insert_term($tag['tag'], $tax, $tagInfo);
$term = get_term_by('id', $tagInfo['term_id'], $tax);
}
if ($term) {
$tagsToAdd[] = $term->term_id;
}
}
if (!empty($tagsToAdd)) {
wp_set_object_terms($postID, $tagsToAdd, $tax, true);
}
} | [
"private",
"function",
"processTags",
"(",
"$",
"tags",
",",
"$",
"tax",
",",
"$",
"postID",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"tags",
")",
")",
"{",
"return",
";",
"}",
"$",
"tagsToAdd",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"tags",
"... | Process the tags found with Rekognition
@param array $tags
@param string $tax
@param int $postID | [
"Process",
"the",
"tags",
"found",
"with",
"Rekognition"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Rekognition/RekognitionTool.php#L404-L443 | train |
Interfacelab/ilab-media-tools | classes/Tools/Storage/StorageImageEditor.php | StorageImageEditor.resize | public function resize($max_w, $max_h, $crop = false) {
return $this->imageEditor->resize($max_w, $max_h, $crop);
} | php | public function resize($max_w, $max_h, $crop = false) {
return $this->imageEditor->resize($max_w, $max_h, $crop);
} | [
"public",
"function",
"resize",
"(",
"$",
"max_w",
",",
"$",
"max_h",
",",
"$",
"crop",
"=",
"false",
")",
"{",
"return",
"$",
"this",
"->",
"imageEditor",
"->",
"resize",
"(",
"$",
"max_w",
",",
"$",
"max_h",
",",
"$",
"crop",
")",
";",
"}"
] | Resizes current image.
At minimum, either a height or width must be provided.
If one of the two is set to null, the resize will
maintain aspect ratio according to the provided dimension.
@since 3.5.0
@param int|null $max_w Image width.
@param int|null $max_h Image height.
@param bool $crop
@return bool|WP_Error | [
"Resizes",
"current",
"image",
"."
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Storage/StorageImageEditor.php#L120-L122 | train |
Interfacelab/ilab-media-tools | classes/Tools/Storage/StorageImageEditor.php | StorageImageEditor.crop | public function crop($src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false) {
return $this->imageEditor->crop($src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs);
} | php | public function crop($src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false) {
return $this->imageEditor->crop($src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs);
} | [
"public",
"function",
"crop",
"(",
"$",
"src_x",
",",
"$",
"src_y",
",",
"$",
"src_w",
",",
"$",
"src_h",
",",
"$",
"dst_w",
"=",
"null",
",",
"$",
"dst_h",
"=",
"null",
",",
"$",
"src_abs",
"=",
"false",
")",
"{",
"return",
"$",
"this",
"->",
... | Crops Image.
@since 3.5.0
@param int $src_x The start x position to crop from.
@param int $src_y The start y position to crop from.
@param int $src_w The width to crop.
@param int $src_h The height to crop.
@param int $dst_w Optional. The destination width.
@param int $dst_h Optional. The destination height.
@param bool $src_abs Optional. If the source crop points are absolute.
@return bool|WP_Error | [
"Crops",
"Image",
"."
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/Storage/StorageImageEditor.php#L158-L160 | train |
Interfacelab/ilab-media-tools | classes/Tools/BatchTool.php | BatchTool.setup | public function setup () {
if ($this->enabled()) {
BatchManager::instance()->displayAnyErrors($this->batchIdentifier());
if ($this->mediaListIntegration) {
add_action('admin_init', function() {
add_filter('bulk_actions-upload', function($actions) {
return $this->registerBulkActions($actions);
});
add_filter('handle_bulk_actions-upload', function($redirect_to, $action_name, $post_ids) {
return $this->handleBulkActions($redirect_to, $action_name, $post_ids);
}, 1000, 3);
});
}
}
} | php | public function setup () {
if ($this->enabled()) {
BatchManager::instance()->displayAnyErrors($this->batchIdentifier());
if ($this->mediaListIntegration) {
add_action('admin_init', function() {
add_filter('bulk_actions-upload', function($actions) {
return $this->registerBulkActions($actions);
});
add_filter('handle_bulk_actions-upload', function($redirect_to, $action_name, $post_ids) {
return $this->handleBulkActions($redirect_to, $action_name, $post_ids);
}, 1000, 3);
});
}
}
} | [
"public",
"function",
"setup",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"enabled",
"(",
")",
")",
"{",
"BatchManager",
"::",
"instance",
"(",
")",
"->",
"displayAnyErrors",
"(",
"$",
"this",
"->",
"batchIdentifier",
"(",
")",
")",
";",
"if",
"(",... | Performs any additional setup | [
"Performs",
"any",
"additional",
"setup"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/BatchTool.php#L61-L77 | train |
Interfacelab/ilab-media-tools | classes/Tools/BatchTool.php | BatchTool.getImportBatch | protected function getImportBatch($page, $forceImages = false) {
$total = 0;
$pages = 1;
$shouldRun = false;
$fromSelection = false;
if (isset($_POST['selection'])) {
$postIds = $_POST['selection'];
$total = count($postIds);
$shouldRun = true;
} else {
$postIds = get_site_transient($this->batchPrefix().'_post_selection');
if (!empty($postIds)) {
delete_site_transient($this->batchPrefix().'_post_selection');
$total = count($postIds);
$shouldRun = true;
$fromSelection = true;
} else {
$args = [
'post_type' => 'attachment',
'post_status' => 'inherit',
'posts_per_page' => 100,
'fields' => 'ids',
'paged' => $page
];
if ($page == -1) {
unset($args['posts_per_page']);
unset($args['paged']);
$args['nopaging'] = true;
}
$args = $this->filterPostArgs($args);
if($forceImages || !StorageSettings::uploadDocuments()) {
$args['post_mime_type'] = 'image';
}
$query = new \WP_Query($args);
$postIds = $query->posts;
$total = (int)$query->found_posts;
$pages = $query->max_num_pages;
}
}
$posts = [];
foreach($postIds as $post) {
$thumb = wp_get_attachment_image_src($post, 'thumbnail', true);
$thumbUrl = null;
$icon = false;
if (!empty($thumb)) {
$thumbUrl = $thumb[0];
$icon = (($thumb[1] != 150) && ($thumb[2] != 150));
}
$posts[] = [
'id' => $post,
'title' => pathinfo(get_attached_file($post), PATHINFO_BASENAME),
'thumb' => $thumbUrl,
'icon' => $icon
];
}
return [
'posts' =>$posts,
'total' => $total,
'pages' => $pages,
'shouldRun' => $shouldRun,
'fromSelection' => $fromSelection
];
} | php | protected function getImportBatch($page, $forceImages = false) {
$total = 0;
$pages = 1;
$shouldRun = false;
$fromSelection = false;
if (isset($_POST['selection'])) {
$postIds = $_POST['selection'];
$total = count($postIds);
$shouldRun = true;
} else {
$postIds = get_site_transient($this->batchPrefix().'_post_selection');
if (!empty($postIds)) {
delete_site_transient($this->batchPrefix().'_post_selection');
$total = count($postIds);
$shouldRun = true;
$fromSelection = true;
} else {
$args = [
'post_type' => 'attachment',
'post_status' => 'inherit',
'posts_per_page' => 100,
'fields' => 'ids',
'paged' => $page
];
if ($page == -1) {
unset($args['posts_per_page']);
unset($args['paged']);
$args['nopaging'] = true;
}
$args = $this->filterPostArgs($args);
if($forceImages || !StorageSettings::uploadDocuments()) {
$args['post_mime_type'] = 'image';
}
$query = new \WP_Query($args);
$postIds = $query->posts;
$total = (int)$query->found_posts;
$pages = $query->max_num_pages;
}
}
$posts = [];
foreach($postIds as $post) {
$thumb = wp_get_attachment_image_src($post, 'thumbnail', true);
$thumbUrl = null;
$icon = false;
if (!empty($thumb)) {
$thumbUrl = $thumb[0];
$icon = (($thumb[1] != 150) && ($thumb[2] != 150));
}
$posts[] = [
'id' => $post,
'title' => pathinfo(get_attached_file($post), PATHINFO_BASENAME),
'thumb' => $thumbUrl,
'icon' => $icon
];
}
return [
'posts' =>$posts,
'total' => $total,
'pages' => $pages,
'shouldRun' => $shouldRun,
'fromSelection' => $fromSelection
];
} | [
"protected",
"function",
"getImportBatch",
"(",
"$",
"page",
",",
"$",
"forceImages",
"=",
"false",
")",
"{",
"$",
"total",
"=",
"0",
";",
"$",
"pages",
"=",
"1",
";",
"$",
"shouldRun",
"=",
"false",
";",
"$",
"fromSelection",
"=",
"false",
";",
"if"... | Gets the post data to process for this batch. Data is paged to minimize memory usage.
@param $page
@param bool $forceImages
@return array | [
"Gets",
"the",
"post",
"data",
"to",
"process",
"for",
"this",
"batch",
".",
"Data",
"is",
"paged",
"to",
"minimize",
"memory",
"usage",
"."
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/BatchTool.php#L223-L297 | train |
Interfacelab/ilab-media-tools | classes/Tools/BatchTool.php | BatchTool.renderBatchTool | public function renderBatchTool() {
wp_enqueue_style('ilab-media-importer-css', ILAB_PUB_CSS_URL.'/ilab-media-importer.min.css');
$data = BatchManager::instance()->stats($this->batchIdentifier());
$postData = $this->getImportBatch(1);
$data['posts'] = $postData['posts'];
$data['pages'] = $postData['pages'];
$background = EnvironmentOptions::Option('ilab-media-s3-batch-background-processing', null, true);
if (!$background) {
$data['total'] = $postData['total'];
} else {
if($data['total'] == 0) {
$data['total'] = $postData['total'];
}
}
if ($postData['shouldRun']) {
$data['status'] = 'running';
} else {
$data['status'] = ($data['running']) ? 'running' : 'idle';
}
$data['shouldRun'] = $postData['shouldRun'];
$data['enabled'] = $this->enabled();
$data['title'] = $this->title();
$data['instructions'] = View::render_view($this->instructionView(), ['background' => $background]);
$data['fromSelection'] = $postData['fromSelection'];
$data['disabledText'] = 'enable Storage';
$data['commandLine'] = null;
$data['commandTitle'] = 'Run Tool';
$data['cancelCommandTitle'] = 'Cancel Tool';
$data['cancelAction'] = $this->cancelActionName();
$data['startAction'] = $this->startActionName();
$data['manualAction'] = $this->manualActionName();
$data['progressAction'] = $this->progressActionName();
$data['nextBatchAction'] = $this->nextBatchActionName();
$data['background'] = $background;
$data = $this->filterRenderData($data);
echo View::render_view('importer/importer.php', $data);
} | php | public function renderBatchTool() {
wp_enqueue_style('ilab-media-importer-css', ILAB_PUB_CSS_URL.'/ilab-media-importer.min.css');
$data = BatchManager::instance()->stats($this->batchIdentifier());
$postData = $this->getImportBatch(1);
$data['posts'] = $postData['posts'];
$data['pages'] = $postData['pages'];
$background = EnvironmentOptions::Option('ilab-media-s3-batch-background-processing', null, true);
if (!$background) {
$data['total'] = $postData['total'];
} else {
if($data['total'] == 0) {
$data['total'] = $postData['total'];
}
}
if ($postData['shouldRun']) {
$data['status'] = 'running';
} else {
$data['status'] = ($data['running']) ? 'running' : 'idle';
}
$data['shouldRun'] = $postData['shouldRun'];
$data['enabled'] = $this->enabled();
$data['title'] = $this->title();
$data['instructions'] = View::render_view($this->instructionView(), ['background' => $background]);
$data['fromSelection'] = $postData['fromSelection'];
$data['disabledText'] = 'enable Storage';
$data['commandLine'] = null;
$data['commandTitle'] = 'Run Tool';
$data['cancelCommandTitle'] = 'Cancel Tool';
$data['cancelAction'] = $this->cancelActionName();
$data['startAction'] = $this->startActionName();
$data['manualAction'] = $this->manualActionName();
$data['progressAction'] = $this->progressActionName();
$data['nextBatchAction'] = $this->nextBatchActionName();
$data['background'] = $background;
$data = $this->filterRenderData($data);
echo View::render_view('importer/importer.php', $data);
} | [
"public",
"function",
"renderBatchTool",
"(",
")",
"{",
"wp_enqueue_style",
"(",
"'ilab-media-importer-css'",
",",
"ILAB_PUB_CSS_URL",
".",
"'/ilab-media-importer.min.css'",
")",
";",
"$",
"data",
"=",
"BatchManager",
"::",
"instance",
"(",
")",
"->",
"stats",
"(",
... | Renders the batch tool | [
"Renders",
"the",
"batch",
"tool"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/BatchTool.php#L311-L354 | train |
Interfacelab/ilab-media-tools | classes/Tools/BatchTool.php | BatchTool.startAction | public function startAction() {
$posts = $this->getImportBatch(-1);
if($posts['total'] > 0) {
try {
$postIDs = [];
foreach($posts['posts'] as $post) {
$postIDs[] = $post['id'];
}
BatchManager::instance()->addToBatchAndRun($this->batchIdentifier(), $postIDs);
} catch (\Exception $ex) {
json_response(["status"=>"error", "error" => $ex->getMessage()]);
}
} else {
BatchManager::instance()->reset($this->batchIdentifier());
json_response(['status' => 'finished']);
}
$data = [
'status' => 'running',
'total' => $posts['total'],
'first' => $posts['posts'][0]
];
json_response($data);
} | php | public function startAction() {
$posts = $this->getImportBatch(-1);
if($posts['total'] > 0) {
try {
$postIDs = [];
foreach($posts['posts'] as $post) {
$postIDs[] = $post['id'];
}
BatchManager::instance()->addToBatchAndRun($this->batchIdentifier(), $postIDs);
} catch (\Exception $ex) {
json_response(["status"=>"error", "error" => $ex->getMessage()]);
}
} else {
BatchManager::instance()->reset($this->batchIdentifier());
json_response(['status' => 'finished']);
}
$data = [
'status' => 'running',
'total' => $posts['total'],
'first' => $posts['posts'][0]
];
json_response($data);
} | [
"public",
"function",
"startAction",
"(",
")",
"{",
"$",
"posts",
"=",
"$",
"this",
"->",
"getImportBatch",
"(",
"-",
"1",
")",
";",
"if",
"(",
"$",
"posts",
"[",
"'total'",
"]",
">",
"0",
")",
"{",
"try",
"{",
"$",
"postIDs",
"=",
"[",
"]",
";... | The action that starts a batch in motion | [
"The",
"action",
"that",
"starts",
"a",
"batch",
"in",
"motion"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/BatchTool.php#L368-L394 | train |
Interfacelab/ilab-media-tools | classes/Tools/BatchTool.php | BatchTool.progressAction | public function progressAction() {
$data = BatchManager::instance()->stats($this->batchIdentifier());
$data['status'] = ($data['running']) ? 'running' : 'idle';
$data['enabled'] = $this->enabled();
json_response($data);
} | php | public function progressAction() {
$data = BatchManager::instance()->stats($this->batchIdentifier());
$data['status'] = ($data['running']) ? 'running' : 'idle';
$data['enabled'] = $this->enabled();
json_response($data);
} | [
"public",
"function",
"progressAction",
"(",
")",
"{",
"$",
"data",
"=",
"BatchManager",
"::",
"instance",
"(",
")",
"->",
"stats",
"(",
"$",
"this",
"->",
"batchIdentifier",
"(",
")",
")",
";",
"$",
"data",
"[",
"'status'",
"]",
"=",
"(",
"$",
"data... | Reports progress on a batch | [
"Reports",
"progress",
"on",
"a",
"batch"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/BatchTool.php#L399-L406 | train |
Interfacelab/ilab-media-tools | classes/Tools/BatchTool.php | BatchTool.nextBatchAction | public function nextBatchAction() {
$page = isset($_POST['page']) ? (int)$_POST['page'] : 1;
$postData = $this->getImportBatch($page);
json_response($postData);
} | php | public function nextBatchAction() {
$page = isset($_POST['page']) ? (int)$_POST['page'] : 1;
$postData = $this->getImportBatch($page);
json_response($postData);
} | [
"public",
"function",
"nextBatchAction",
"(",
")",
"{",
"$",
"page",
"=",
"isset",
"(",
"$",
"_POST",
"[",
"'page'",
"]",
")",
"?",
"(",
"int",
")",
"$",
"_POST",
"[",
"'page'",
"]",
":",
"1",
";",
"$",
"postData",
"=",
"$",
"this",
"->",
"getImp... | Fetches the next group of posts to process | [
"Fetches",
"the",
"next",
"group",
"of",
"posts",
"to",
"process"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/BatchTool.php#L411-L417 | train |
Interfacelab/ilab-media-tools | classes/Tools/BatchTool.php | BatchTool.cancelAction | public function cancelAction() {
BatchManager::instance()->setShouldCancel($this->batchIdentifier(), true);
call_user_func([$this->batchProcessClassName(), 'cancelAll']);
json_response(['status' => 'ok']);
} | php | public function cancelAction() {
BatchManager::instance()->setShouldCancel($this->batchIdentifier(), true);
call_user_func([$this->batchProcessClassName(), 'cancelAll']);
json_response(['status' => 'ok']);
} | [
"public",
"function",
"cancelAction",
"(",
")",
"{",
"BatchManager",
"::",
"instance",
"(",
")",
"->",
"setShouldCancel",
"(",
"$",
"this",
"->",
"batchIdentifier",
"(",
")",
",",
"true",
")",
";",
"call_user_func",
"(",
"[",
"$",
"this",
"->",
"batchProce... | Cancels the batch | [
"Cancels",
"the",
"batch"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/BatchTool.php#L427-L433 | train |
Interfacelab/ilab-media-tools | classes/Tools/ToolsManager.php | ToolsManager.toolEnabled | public function toolEnabled($toolName) {
if (isset($this->tools[$toolName]))
return $this->tools[$toolName]->enabled();
return false;
} | php | public function toolEnabled($toolName) {
if (isset($this->tools[$toolName]))
return $this->tools[$toolName]->enabled();
return false;
} | [
"public",
"function",
"toolEnabled",
"(",
"$",
"toolName",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"tools",
"[",
"$",
"toolName",
"]",
")",
")",
"return",
"$",
"this",
"->",
"tools",
"[",
"$",
"toolName",
"]",
"->",
"enabled",
"(",
")... | Determines if a tool is enabled or not
@param $toolName
@return bool | [
"Determines",
"if",
"a",
"tool",
"is",
"enabled",
"or",
"not"
] | eb3ad995724d5c6355a9016870257eb80c20d91f | https://github.com/Interfacelab/ilab-media-tools/blob/eb3ad995724d5c6355a9016870257eb80c20d91f/classes/Tools/ToolsManager.php#L136-L141 | train |
johnbillion/user-switching | user-switching.php | user_switching.init_hooks | public function init_hooks() {
// Required functionality:
add_filter( 'user_has_cap', array( $this, 'filter_user_has_cap' ), 10, 4 );
add_filter( 'map_meta_cap', array( $this, 'filter_map_meta_cap' ), 10, 4 );
add_filter( 'user_row_actions', array( $this, 'filter_user_row_actions' ), 10, 2 );
add_action( 'plugins_loaded', array( $this, 'action_plugins_loaded' ) );
add_action( 'init', array( $this, 'action_init' ) );
add_action( 'all_admin_notices', array( $this, 'action_admin_notices' ), 1 );
add_action( 'wp_logout', 'user_switching_clear_olduser_cookie' );
add_action( 'wp_login', 'user_switching_clear_olduser_cookie' );
// Nice-to-haves:
add_filter( 'ms_user_row_actions', array( $this, 'filter_user_row_actions' ), 10, 2 );
add_filter( 'login_message', array( $this, 'filter_login_message' ), 1 );
add_filter( 'removable_query_args', array( $this, 'filter_removable_query_args' ) );
add_action( 'wp_meta', array( $this, 'action_wp_meta' ) );
add_action( 'wp_footer', array( $this, 'action_wp_footer' ) );
add_action( 'personal_options', array( $this, 'action_personal_options' ) );
add_action( 'admin_bar_menu', array( $this, 'action_admin_bar_menu' ), 11 );
add_action( 'bp_member_header_actions', array( $this, 'action_bp_button' ), 11 );
add_action( 'bp_directory_members_actions', array( $this, 'action_bp_button' ), 11 );
add_action( 'bbp_template_after_user_details', array( $this, 'action_bbpress_button' ) );
} | php | public function init_hooks() {
// Required functionality:
add_filter( 'user_has_cap', array( $this, 'filter_user_has_cap' ), 10, 4 );
add_filter( 'map_meta_cap', array( $this, 'filter_map_meta_cap' ), 10, 4 );
add_filter( 'user_row_actions', array( $this, 'filter_user_row_actions' ), 10, 2 );
add_action( 'plugins_loaded', array( $this, 'action_plugins_loaded' ) );
add_action( 'init', array( $this, 'action_init' ) );
add_action( 'all_admin_notices', array( $this, 'action_admin_notices' ), 1 );
add_action( 'wp_logout', 'user_switching_clear_olduser_cookie' );
add_action( 'wp_login', 'user_switching_clear_olduser_cookie' );
// Nice-to-haves:
add_filter( 'ms_user_row_actions', array( $this, 'filter_user_row_actions' ), 10, 2 );
add_filter( 'login_message', array( $this, 'filter_login_message' ), 1 );
add_filter( 'removable_query_args', array( $this, 'filter_removable_query_args' ) );
add_action( 'wp_meta', array( $this, 'action_wp_meta' ) );
add_action( 'wp_footer', array( $this, 'action_wp_footer' ) );
add_action( 'personal_options', array( $this, 'action_personal_options' ) );
add_action( 'admin_bar_menu', array( $this, 'action_admin_bar_menu' ), 11 );
add_action( 'bp_member_header_actions', array( $this, 'action_bp_button' ), 11 );
add_action( 'bp_directory_members_actions', array( $this, 'action_bp_button' ), 11 );
add_action( 'bbp_template_after_user_details', array( $this, 'action_bbpress_button' ) );
} | [
"public",
"function",
"init_hooks",
"(",
")",
"{",
"// Required functionality:",
"add_filter",
"(",
"'user_has_cap'",
",",
"array",
"(",
"$",
"this",
",",
"'filter_user_has_cap'",
")",
",",
"10",
",",
"4",
")",
";",
"add_filter",
"(",
"'map_meta_cap'",
",",
"a... | Sets up all the filters and actions. | [
"Sets",
"up",
"all",
"the",
"filters",
"and",
"actions",
"."
] | 259d29a7c52f203deede574cceed6b34162de34a | https://github.com/johnbillion/user-switching/blob/259d29a7c52f203deede574cceed6b34162de34a/user-switching.php#L48-L70 | train |
johnbillion/user-switching | user-switching.php | user_switching.action_plugins_loaded | public function action_plugins_loaded() {
// User Switching's auth_cookie
if ( ! defined( 'USER_SWITCHING_COOKIE' ) ) {
define( 'USER_SWITCHING_COOKIE', 'wordpress_user_sw_' . COOKIEHASH );
}
// User Switching's secure_auth_cookie
if ( ! defined( 'USER_SWITCHING_SECURE_COOKIE' ) ) {
define( 'USER_SWITCHING_SECURE_COOKIE', 'wordpress_user_sw_secure_' . COOKIEHASH );
}
// User Switching's logged_in_cookie
if ( ! defined( 'USER_SWITCHING_OLDUSER_COOKIE' ) ) {
define( 'USER_SWITCHING_OLDUSER_COOKIE', 'wordpress_user_sw_olduser_' . COOKIEHASH );
}
} | php | public function action_plugins_loaded() {
// User Switching's auth_cookie
if ( ! defined( 'USER_SWITCHING_COOKIE' ) ) {
define( 'USER_SWITCHING_COOKIE', 'wordpress_user_sw_' . COOKIEHASH );
}
// User Switching's secure_auth_cookie
if ( ! defined( 'USER_SWITCHING_SECURE_COOKIE' ) ) {
define( 'USER_SWITCHING_SECURE_COOKIE', 'wordpress_user_sw_secure_' . COOKIEHASH );
}
// User Switching's logged_in_cookie
if ( ! defined( 'USER_SWITCHING_OLDUSER_COOKIE' ) ) {
define( 'USER_SWITCHING_OLDUSER_COOKIE', 'wordpress_user_sw_olduser_' . COOKIEHASH );
}
} | [
"public",
"function",
"action_plugins_loaded",
"(",
")",
"{",
"// User Switching's auth_cookie",
"if",
"(",
"!",
"defined",
"(",
"'USER_SWITCHING_COOKIE'",
")",
")",
"{",
"define",
"(",
"'USER_SWITCHING_COOKIE'",
",",
"'wordpress_user_sw_'",
".",
"COOKIEHASH",
")",
";... | Defines the names of the cookies used by User Switching. | [
"Defines",
"the",
"names",
"of",
"the",
"cookies",
"used",
"by",
"User",
"Switching",
"."
] | 259d29a7c52f203deede574cceed6b34162de34a | https://github.com/johnbillion/user-switching/blob/259d29a7c52f203deede574cceed6b34162de34a/user-switching.php#L75-L90 | train |
johnbillion/user-switching | user-switching.php | user_switching.action_personal_options | public function action_personal_options( WP_User $user ) {
$link = self::maybe_switch_url( $user );
if ( ! $link ) {
return;
}
?>
<tr>
<th scope="row"><?php echo esc_html_x( 'User Switching', 'User Switching title on user profile screen', 'user-switching' ); ?></th>
<td><a href="<?php echo esc_url( $link ); ?>"><?php esc_html_e( 'Switch To', 'user-switching' ); ?></a></td>
</tr>
<?php
} | php | public function action_personal_options( WP_User $user ) {
$link = self::maybe_switch_url( $user );
if ( ! $link ) {
return;
}
?>
<tr>
<th scope="row"><?php echo esc_html_x( 'User Switching', 'User Switching title on user profile screen', 'user-switching' ); ?></th>
<td><a href="<?php echo esc_url( $link ); ?>"><?php esc_html_e( 'Switch To', 'user-switching' ); ?></a></td>
</tr>
<?php
} | [
"public",
"function",
"action_personal_options",
"(",
"WP_User",
"$",
"user",
")",
"{",
"$",
"link",
"=",
"self",
"::",
"maybe_switch_url",
"(",
"$",
"user",
")",
";",
"if",
"(",
"!",
"$",
"link",
")",
"{",
"return",
";",
"}",
"?>\n\t\t<tr>\n\t\t\t<th scop... | Outputs the 'Switch To' link on the user editing screen if the current user has permission to switch to them.
@param WP_User $user User object for this screen. | [
"Outputs",
"the",
"Switch",
"To",
"link",
"on",
"the",
"user",
"editing",
"screen",
"if",
"the",
"current",
"user",
"has",
"permission",
"to",
"switch",
"to",
"them",
"."
] | 259d29a7c52f203deede574cceed6b34162de34a | https://github.com/johnbillion/user-switching/blob/259d29a7c52f203deede574cceed6b34162de34a/user-switching.php#L97-L110 | train |
johnbillion/user-switching | user-switching.php | user_switching.get_old_user | public static function get_old_user() {
$cookie = user_switching_get_olduser_cookie();
if ( ! empty( $cookie ) ) {
$old_user_id = wp_validate_auth_cookie( $cookie, 'logged_in' );
if ( $old_user_id ) {
return get_userdata( $old_user_id );
}
}
return false;
} | php | public static function get_old_user() {
$cookie = user_switching_get_olduser_cookie();
if ( ! empty( $cookie ) ) {
$old_user_id = wp_validate_auth_cookie( $cookie, 'logged_in' );
if ( $old_user_id ) {
return get_userdata( $old_user_id );
}
}
return false;
} | [
"public",
"static",
"function",
"get_old_user",
"(",
")",
"{",
"$",
"cookie",
"=",
"user_switching_get_olduser_cookie",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"cookie",
")",
")",
"{",
"$",
"old_user_id",
"=",
"wp_validate_auth_cookie",
"(",
"$",
... | Validates the old user cookie and returns its user data.
@return false|WP_User False if there's no old user cookie or it's invalid, WP_User object if it's present and valid. | [
"Validates",
"the",
"old",
"user",
"cookie",
"and",
"returns",
"its",
"user",
"data",
"."
] | 259d29a7c52f203deede574cceed6b34162de34a | https://github.com/johnbillion/user-switching/blob/259d29a7c52f203deede574cceed6b34162de34a/user-switching.php#L371-L381 | train |
johnbillion/user-switching | user-switching.php | user_switching.authenticate_old_user | public static function authenticate_old_user( WP_User $user ) {
$cookie = user_switching_get_auth_cookie();
if ( ! empty( $cookie ) ) {
if ( self::secure_auth_cookie() ) {
$scheme = 'secure_auth';
} else {
$scheme = 'auth';
}
$old_user_id = wp_validate_auth_cookie( end( $cookie ), $scheme );
if ( $old_user_id ) {
return ( $user->ID === $old_user_id );
}
}
return false;
} | php | public static function authenticate_old_user( WP_User $user ) {
$cookie = user_switching_get_auth_cookie();
if ( ! empty( $cookie ) ) {
if ( self::secure_auth_cookie() ) {
$scheme = 'secure_auth';
} else {
$scheme = 'auth';
}
$old_user_id = wp_validate_auth_cookie( end( $cookie ), $scheme );
if ( $old_user_id ) {
return ( $user->ID === $old_user_id );
}
}
return false;
} | [
"public",
"static",
"function",
"authenticate_old_user",
"(",
"WP_User",
"$",
"user",
")",
"{",
"$",
"cookie",
"=",
"user_switching_get_auth_cookie",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"cookie",
")",
")",
"{",
"if",
"(",
"self",
"::",
"sec... | Authenticates an old user by verifying the latest entry in the auth cookie.
@param WP_User $user A WP_User object (usually from the logged_in cookie).
@return bool Whether verification with the auth cookie passed. | [
"Authenticates",
"an",
"old",
"user",
"by",
"verifying",
"the",
"latest",
"entry",
"in",
"the",
"auth",
"cookie",
"."
] | 259d29a7c52f203deede574cceed6b34162de34a | https://github.com/johnbillion/user-switching/blob/259d29a7c52f203deede574cceed6b34162de34a/user-switching.php#L389-L405 | train |
johnbillion/user-switching | user-switching.php | user_switching.filter_user_row_actions | public function filter_user_row_actions( array $actions, WP_User $user ) {
$link = self::maybe_switch_url( $user );
if ( ! $link ) {
return $actions;
}
$actions['switch_to_user'] = '<a href="' . esc_url( $link ) . '">' . esc_html__( 'Switch To', 'user-switching' ) . '</a>';
return $actions;
} | php | public function filter_user_row_actions( array $actions, WP_User $user ) {
$link = self::maybe_switch_url( $user );
if ( ! $link ) {
return $actions;
}
$actions['switch_to_user'] = '<a href="' . esc_url( $link ) . '">' . esc_html__( 'Switch To', 'user-switching' ) . '</a>';
return $actions;
} | [
"public",
"function",
"filter_user_row_actions",
"(",
"array",
"$",
"actions",
",",
"WP_User",
"$",
"user",
")",
"{",
"$",
"link",
"=",
"self",
"::",
"maybe_switch_url",
"(",
"$",
"user",
")",
";",
"if",
"(",
"!",
"$",
"link",
")",
"{",
"return",
"$",
... | Adds a 'Switch To' link to each list of user actions on the Users screen.
@param string[] $actions The actions to display for this user row.
@param WP_User $user The user object displayed in this row.
@return string[] The actions to display for this user row. | [
"Adds",
"a",
"Switch",
"To",
"link",
"to",
"each",
"list",
"of",
"user",
"actions",
"on",
"the",
"Users",
"screen",
"."
] | 259d29a7c52f203deede574cceed6b34162de34a | https://github.com/johnbillion/user-switching/blob/259d29a7c52f203deede574cceed6b34162de34a/user-switching.php#L580-L590 | train |
johnbillion/user-switching | user-switching.php | user_switching.action_bp_button | public function action_bp_button() {
$user = null;
if ( bp_is_user() ) {
$user = get_userdata( bp_displayed_user_id() );
} elseif ( bp_is_members_directory() ) {
$user = get_userdata( bp_get_member_user_id() );
}
if ( ! $user ) {
return;
}
$link = self::maybe_switch_url( $user );
if ( ! $link ) {
return;
}
$link = add_query_arg( array(
'redirect_to' => urlencode( bp_core_get_user_domain( $user->ID ) ),
), $link );
$components = array_keys( buddypress()->active_components );
echo bp_get_button( array(
'id' => 'user_switching',
'component' => reset( $components ),
'link_href' => esc_url( $link ),
'link_text' => esc_html__( 'Switch To', 'user-switching' ),
'wrapper_id' => 'user_switching_switch_to',
) );
} | php | public function action_bp_button() {
$user = null;
if ( bp_is_user() ) {
$user = get_userdata( bp_displayed_user_id() );
} elseif ( bp_is_members_directory() ) {
$user = get_userdata( bp_get_member_user_id() );
}
if ( ! $user ) {
return;
}
$link = self::maybe_switch_url( $user );
if ( ! $link ) {
return;
}
$link = add_query_arg( array(
'redirect_to' => urlencode( bp_core_get_user_domain( $user->ID ) ),
), $link );
$components = array_keys( buddypress()->active_components );
echo bp_get_button( array(
'id' => 'user_switching',
'component' => reset( $components ),
'link_href' => esc_url( $link ),
'link_text' => esc_html__( 'Switch To', 'user-switching' ),
'wrapper_id' => 'user_switching_switch_to',
) );
} | [
"public",
"function",
"action_bp_button",
"(",
")",
"{",
"$",
"user",
"=",
"null",
";",
"if",
"(",
"bp_is_user",
"(",
")",
")",
"{",
"$",
"user",
"=",
"get_userdata",
"(",
"bp_displayed_user_id",
"(",
")",
")",
";",
"}",
"elseif",
"(",
"bp_is_members_dir... | Adds a 'Switch To' link to each member's profile page and profile listings in BuddyPress. | [
"Adds",
"a",
"Switch",
"To",
"link",
"to",
"each",
"member",
"s",
"profile",
"page",
"and",
"profile",
"listings",
"in",
"BuddyPress",
"."
] | 259d29a7c52f203deede574cceed6b34162de34a | https://github.com/johnbillion/user-switching/blob/259d29a7c52f203deede574cceed6b34162de34a/user-switching.php#L595-L627 | train |
johnbillion/user-switching | user-switching.php | user_switching.action_bbpress_button | public function action_bbpress_button() {
$user = get_userdata( bbp_get_user_id() );
if ( ! $user ) {
return;
}
$link = self::maybe_switch_url( $user );
if ( ! $link ) {
return;
}
$link = add_query_arg( array(
'redirect_to' => urlencode( bbp_get_user_profile_url( $user->ID ) ),
), $link );
?>
<ul id="user_switching_switch_to">
<li><a href="<?php echo esc_url( $link ); ?>"><?php esc_html_e( 'Switch To', 'user-switching' ); ?></a></li>
</ul>
<?php
} | php | public function action_bbpress_button() {
$user = get_userdata( bbp_get_user_id() );
if ( ! $user ) {
return;
}
$link = self::maybe_switch_url( $user );
if ( ! $link ) {
return;
}
$link = add_query_arg( array(
'redirect_to' => urlencode( bbp_get_user_profile_url( $user->ID ) ),
), $link );
?>
<ul id="user_switching_switch_to">
<li><a href="<?php echo esc_url( $link ); ?>"><?php esc_html_e( 'Switch To', 'user-switching' ); ?></a></li>
</ul>
<?php
} | [
"public",
"function",
"action_bbpress_button",
"(",
")",
"{",
"$",
"user",
"=",
"get_userdata",
"(",
"bbp_get_user_id",
"(",
")",
")",
";",
"if",
"(",
"!",
"$",
"user",
")",
"{",
"return",
";",
"}",
"$",
"link",
"=",
"self",
"::",
"maybe_switch_url",
"... | Adds a 'Switch To' link to each member's profile page in bbPress. | [
"Adds",
"a",
"Switch",
"To",
"link",
"to",
"each",
"member",
"s",
"profile",
"page",
"in",
"bbPress",
"."
] | 259d29a7c52f203deede574cceed6b34162de34a | https://github.com/johnbillion/user-switching/blob/259d29a7c52f203deede574cceed6b34162de34a/user-switching.php#L632-L654 | train |
johnbillion/user-switching | user-switching.php | user_switching.maybe_switch_url | public static function maybe_switch_url( WP_User $user ) {
$old_user = self::get_old_user();
if ( $old_user && ( $old_user->ID === $user->ID ) ) {
return self::switch_back_url( $old_user );
} elseif ( current_user_can( 'switch_to_user', $user->ID ) ) {
return self::switch_to_url( $user );
} else {
return false;
}
} | php | public static function maybe_switch_url( WP_User $user ) {
$old_user = self::get_old_user();
if ( $old_user && ( $old_user->ID === $user->ID ) ) {
return self::switch_back_url( $old_user );
} elseif ( current_user_can( 'switch_to_user', $user->ID ) ) {
return self::switch_to_url( $user );
} else {
return false;
}
} | [
"public",
"static",
"function",
"maybe_switch_url",
"(",
"WP_User",
"$",
"user",
")",
"{",
"$",
"old_user",
"=",
"self",
"::",
"get_old_user",
"(",
")",
";",
"if",
"(",
"$",
"old_user",
"&&",
"(",
"$",
"old_user",
"->",
"ID",
"===",
"$",
"user",
"->",
... | Returns the switch to or switch back URL for a given user.
@param WP_User $user The user to be switched to.
@return string|false The required URL, or false if there's no old user or the user doesn't have the required capability. | [
"Returns",
"the",
"switch",
"to",
"or",
"switch",
"back",
"URL",
"for",
"a",
"given",
"user",
"."
] | 259d29a7c52f203deede574cceed6b34162de34a | https://github.com/johnbillion/user-switching/blob/259d29a7c52f203deede574cceed6b34162de34a/user-switching.php#L678-L688 | train |
johnbillion/user-switching | user-switching.php | user_switching.forget_woocommerce_session | public static function forget_woocommerce_session( WooCommerce $wc ) {
if ( ! property_exists( $wc, 'session' ) ) {
return false;
}
if ( ! method_exists( $wc->session, 'forget_session' ) ) {
return false;
}
$wc->session->forget_session();
} | php | public static function forget_woocommerce_session( WooCommerce $wc ) {
if ( ! property_exists( $wc, 'session' ) ) {
return false;
}
if ( ! method_exists( $wc->session, 'forget_session' ) ) {
return false;
}
$wc->session->forget_session();
} | [
"public",
"static",
"function",
"forget_woocommerce_session",
"(",
"WooCommerce",
"$",
"wc",
")",
"{",
"if",
"(",
"!",
"property_exists",
"(",
"$",
"wc",
",",
"'session'",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"method_exists",
"(",
... | Instructs WooCommerce to forget the session for the current user, without deleting it.
@param WooCommerce $wc The WooCommerce instance. | [
"Instructs",
"WooCommerce",
"to",
"forget",
"the",
"session",
"for",
"the",
"current",
"user",
"without",
"deleting",
"it",
"."
] | 259d29a7c52f203deede574cceed6b34162de34a | https://github.com/johnbillion/user-switching/blob/259d29a7c52f203deede574cceed6b34162de34a/user-switching.php#L782-L792 | train |
johnbillion/user-switching | user-switching.php | user_switching.filter_user_has_cap | public function filter_user_has_cap( array $user_caps, array $required_caps, array $args, WP_User $user ) {
if ( 'switch_to_user' === $args[0] ) {
if ( array_key_exists( 'switch_users', $user_caps ) ) {
$user_caps['switch_to_user'] = $user_caps['switch_users'];
return $user_caps;
}
$user_caps['switch_to_user'] = ( user_can( $user->ID, 'edit_user', $args[2] ) && ( $args[2] !== $user->ID ) );
} elseif ( 'switch_off' === $args[0] ) {
if ( array_key_exists( 'switch_users', $user_caps ) ) {
$user_caps['switch_off'] = $user_caps['switch_users'];
return $user_caps;
}
$user_caps['switch_off'] = user_can( $user->ID, 'edit_users' );
}
return $user_caps;
} | php | public function filter_user_has_cap( array $user_caps, array $required_caps, array $args, WP_User $user ) {
if ( 'switch_to_user' === $args[0] ) {
if ( array_key_exists( 'switch_users', $user_caps ) ) {
$user_caps['switch_to_user'] = $user_caps['switch_users'];
return $user_caps;
}
$user_caps['switch_to_user'] = ( user_can( $user->ID, 'edit_user', $args[2] ) && ( $args[2] !== $user->ID ) );
} elseif ( 'switch_off' === $args[0] ) {
if ( array_key_exists( 'switch_users', $user_caps ) ) {
$user_caps['switch_off'] = $user_caps['switch_users'];
return $user_caps;
}
$user_caps['switch_off'] = user_can( $user->ID, 'edit_users' );
}
return $user_caps;
} | [
"public",
"function",
"filter_user_has_cap",
"(",
"array",
"$",
"user_caps",
",",
"array",
"$",
"required_caps",
",",
"array",
"$",
"args",
",",
"WP_User",
"$",
"user",
")",
"{",
"if",
"(",
"'switch_to_user'",
"===",
"$",
"args",
"[",
"0",
"]",
")",
"{",... | Filters a user's capabilities so they can be altered at runtime.
This is used to:
- Grant the 'switch_to_user' capability to the user if they have the ability to edit the user they're trying to
switch to (and that user is not themselves).
- Grant the 'switch_off' capability to the user if they can edit other users.
Important: This does not get called for Super Admins. See filter_map_meta_cap() below.
@param bool[] $user_caps Array of key/value pairs where keys represent a capability name and boolean values
represent whether the user has that capability.
@param string[] $required_caps Required primitive capabilities for the requested capability.
@param array $args {
Arguments that accompany the requested capability check.
@type string $0 Requested capability.
@type int $1 Concerned user ID.
@type mixed ...$2 Optional second and further parameters.
}
@param WP_User $user Concerned user object.
@return bool[] Concerned user's capabilities. | [
"Filters",
"a",
"user",
"s",
"capabilities",
"so",
"they",
"can",
"be",
"altered",
"at",
"runtime",
"."
] | 259d29a7c52f203deede574cceed6b34162de34a | https://github.com/johnbillion/user-switching/blob/259d29a7c52f203deede574cceed6b34162de34a/user-switching.php#L817-L835 | train |
johnbillion/user-switching | user-switching.php | user_switching.filter_map_meta_cap | public function filter_map_meta_cap( array $required_caps, $cap, $user_id, array $args ) {
if ( ( 'switch_to_user' === $cap ) && ( $args[0] === $user_id ) ) {
$required_caps[] = 'do_not_allow';
}
return $required_caps;
} | php | public function filter_map_meta_cap( array $required_caps, $cap, $user_id, array $args ) {
if ( ( 'switch_to_user' === $cap ) && ( $args[0] === $user_id ) ) {
$required_caps[] = 'do_not_allow';
}
return $required_caps;
} | [
"public",
"function",
"filter_map_meta_cap",
"(",
"array",
"$",
"required_caps",
",",
"$",
"cap",
",",
"$",
"user_id",
",",
"array",
"$",
"args",
")",
"{",
"if",
"(",
"(",
"'switch_to_user'",
"===",
"$",
"cap",
")",
"&&",
"(",
"$",
"args",
"[",
"0",
... | Filters the required primitive capabilities for the given primitive or meta capability.
This is used to:
- Add the 'do_not_allow' capability to the list of required capabilities when a Super Admin is trying to switch
to themselves.
It affects nothing else as Super Admins can do everything by default.
@param string[] $required_caps Required primitive capabilities for the requested capability.
@param string $cap Capability or meta capability being checked.
@param int $user_id Concerned user ID.
@param array $args {
Arguments that accompany the requested capability check.
@type mixed ...$0 Optional second and further parameters.
}
@return string[] Required capabilities for the requested action. | [
"Filters",
"the",
"required",
"primitive",
"capabilities",
"for",
"the",
"given",
"primitive",
"or",
"meta",
"capability",
"."
] | 259d29a7c52f203deede574cceed6b34162de34a | https://github.com/johnbillion/user-switching/blob/259d29a7c52f203deede574cceed6b34162de34a/user-switching.php#L856-L861 | train |
johnbillion/user-switching | features/bootstrap/UserSwitchingContext.php | UserSwitchingContext.switch_to_user | public function switch_to_user( $user_id ) {
$user_id = $this->getUserIdFromLogin( $user_id );
PHPUnit_Framework_Assert::assertNotEmpty( $user_id );
$this->visitPath( sprintf( 'wp-admin/user-edit.php?user_id=%d', $user_id ) );
$this->getSession()->getPage()->clickLink( "Switch\xc2\xa0To" );
} | php | public function switch_to_user( $user_id ) {
$user_id = $this->getUserIdFromLogin( $user_id );
PHPUnit_Framework_Assert::assertNotEmpty( $user_id );
$this->visitPath( sprintf( 'wp-admin/user-edit.php?user_id=%d', $user_id ) );
$this->getSession()->getPage()->clickLink( "Switch\xc2\xa0To" );
} | [
"public",
"function",
"switch_to_user",
"(",
"$",
"user_id",
")",
"{",
"$",
"user_id",
"=",
"$",
"this",
"->",
"getUserIdFromLogin",
"(",
"$",
"user_id",
")",
";",
"PHPUnit_Framework_Assert",
"::",
"assertNotEmpty",
"(",
"$",
"user_id",
")",
";",
"$",
"this"... | Switch to the specified user
@param string $user_id
@When /^(?:|I )switch to user "(?P<user_id>[^"]+)"$/ | [
"Switch",
"to",
"the",
"specified",
"user"
] | 259d29a7c52f203deede574cceed6b34162de34a | https://github.com/johnbillion/user-switching/blob/259d29a7c52f203deede574cceed6b34162de34a/features/bootstrap/UserSwitchingContext.php#L19-L26 | train |
johnbillion/user-switching | features/bootstrap/UserSwitchingContext.php | UserSwitchingContext.logged_in_as | public function logged_in_as( $user_id ) {
$display_name = $this->getUserDataFromUsername( 'display_name', $user_id );
PHPUnit_Framework_Assert::assertNotEmpty( $display_name );
$this->visitPath( '/' );
PHPUnit_Framework_Assert::assertTrue( $this->getSession()->getPage()->hasContent( sprintf( 'Howdy, %s', $display_name ) ) );
} | php | public function logged_in_as( $user_id ) {
$display_name = $this->getUserDataFromUsername( 'display_name', $user_id );
PHPUnit_Framework_Assert::assertNotEmpty( $display_name );
$this->visitPath( '/' );
PHPUnit_Framework_Assert::assertTrue( $this->getSession()->getPage()->hasContent( sprintf( 'Howdy, %s', $display_name ) ) );
} | [
"public",
"function",
"logged_in_as",
"(",
"$",
"user_id",
")",
"{",
"$",
"display_name",
"=",
"$",
"this",
"->",
"getUserDataFromUsername",
"(",
"'display_name'",
",",
"$",
"user_id",
")",
";",
"PHPUnit_Framework_Assert",
"::",
"assertNotEmpty",
"(",
"$",
"disp... | Verify that the user is logged in as the specified user
@param string $user_id
@Then /^(?:|I )should be logged in as [user ]?"(?P<user_id>[^"]+)"$/ | [
"Verify",
"that",
"the",
"user",
"is",
"logged",
"in",
"as",
"the",
"specified",
"user"
] | 259d29a7c52f203deede574cceed6b34162de34a | https://github.com/johnbillion/user-switching/blob/259d29a7c52f203deede574cceed6b34162de34a/features/bootstrap/UserSwitchingContext.php#L35-L43 | train |
modxcms/xpdo | src/xPDO/Om/xPDOGenerator.php | xPDOGenerator.getTableName | public function getTableName($string, $prefix= '', $prefixRequired= false) {
if (!empty($prefix) && strpos($string, $prefix) === 0) {
$string= substr($string, strlen($prefix));
}
elseif ($prefixRequired) {
$string= '';
}
return $string;
} | php | public function getTableName($string, $prefix= '', $prefixRequired= false) {
if (!empty($prefix) && strpos($string, $prefix) === 0) {
$string= substr($string, strlen($prefix));
}
elseif ($prefixRequired) {
$string= '';
}
return $string;
} | [
"public",
"function",
"getTableName",
"(",
"$",
"string",
",",
"$",
"prefix",
"=",
"''",
",",
"$",
"prefixRequired",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"prefix",
")",
"&&",
"strpos",
"(",
"$",
"string",
",",
"$",
"prefix",
"... | Formats a class name to a specific value, stripping the prefix if
specified.
@access public
@param string $string The name to format.
@param string $prefix If specified, will strip the prefix out of the
first argument.
@param boolean $prefixRequired If true, will return a blank string if the
prefix specified is not found.
@return string The formatting string. | [
"Formats",
"a",
"class",
"name",
"to",
"a",
"specific",
"value",
"stripping",
"the",
"prefix",
"if",
"specified",
"."
] | 45e481377e80a3fd1a7362c1d285cddacda70048 | https://github.com/modxcms/xpdo/blob/45e481377e80a3fd1a7362c1d285cddacda70048/src/xPDO/Om/xPDOGenerator.php#L146-L154 | train |
modxcms/xpdo | src/xPDO/Om/xPDOGenerator.php | xPDOGenerator.getClassName | public function getClassName($string) {
if (is_string($string) && $strArray= explode('_', $string)) {
$return= '';
foreach ($strArray as $k => $v) {
$return.= strtoupper(substr($v, 0, 1)) . substr($v, 1) . '';
}
$string= $return;
}
return trim($string);
} | php | public function getClassName($string) {
if (is_string($string) && $strArray= explode('_', $string)) {
$return= '';
foreach ($strArray as $k => $v) {
$return.= strtoupper(substr($v, 0, 1)) . substr($v, 1) . '';
}
$string= $return;
}
return trim($string);
} | [
"public",
"function",
"getClassName",
"(",
"$",
"string",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"string",
")",
"&&",
"$",
"strArray",
"=",
"explode",
"(",
"'_'",
",",
"$",
"string",
")",
")",
"{",
"$",
"return",
"=",
"''",
";",
"foreach",
"("... | Gets a class name from a table name by splitting the string by _ and
capitalizing each token.
@access public
@param string $string The table name to format.
@return string The formatted string. | [
"Gets",
"a",
"class",
"name",
"from",
"a",
"table",
"name",
"by",
"splitting",
"the",
"string",
"by",
"_",
"and",
"capitalizing",
"each",
"token",
"."
] | 45e481377e80a3fd1a7362c1d285cddacda70048 | https://github.com/modxcms/xpdo/blob/45e481377e80a3fd1a7362c1d285cddacda70048/src/xPDO/Om/xPDOGenerator.php#L164-L173 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.