repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
pear/Mail | Mail/mail.php | Mail_mail.send | public function send($recipients, $headers, $body)
{
if (!is_array($headers)) {
return PEAR::raiseError('$headers must be an array');
}
$result = $this->_sanitizeHeaders($headers);
if (is_a($result, 'PEAR_Error')) {
return $result;
}
// If we're passed an array of recipients, implode it.
if (is_array($recipients)) {
$recipients = implode(', ', $recipients);
}
// Get the Subject out of the headers array so that we can
// pass it as a seperate argument to mail().
$subject = '';
if (isset($headers['Subject'])) {
$subject = $headers['Subject'];
unset($headers['Subject']);
}
// Also remove the To: header. The mail() function will add its own
// To: header based on the contents of $recipients.
unset($headers['To']);
// Flatten the headers out.
$headerElements = $this->prepareHeaders($headers);
if (is_a($headerElements, 'PEAR_Error')) {
return $headerElements;
}
list(, $text_headers) = $headerElements;
// We only use mail()'s optional fifth parameter if the additional
// parameters have been provided and we're not running in safe mode.
if (empty($this->_params) || ini_get('safe_mode')) {
$result = mail($recipients, $subject, $body, $text_headers);
} else {
$result = mail($recipients, $subject, $body, $text_headers,
$this->_params);
}
// If the mail() function returned failure, we need to create a
// PEAR_Error object and return it instead of the boolean result.
if ($result === false) {
$result = PEAR::raiseError('mail() returned failure');
}
return $result;
} | php | public function send($recipients, $headers, $body)
{
if (!is_array($headers)) {
return PEAR::raiseError('$headers must be an array');
}
$result = $this->_sanitizeHeaders($headers);
if (is_a($result, 'PEAR_Error')) {
return $result;
}
// If we're passed an array of recipients, implode it.
if (is_array($recipients)) {
$recipients = implode(', ', $recipients);
}
// Get the Subject out of the headers array so that we can
// pass it as a seperate argument to mail().
$subject = '';
if (isset($headers['Subject'])) {
$subject = $headers['Subject'];
unset($headers['Subject']);
}
// Also remove the To: header. The mail() function will add its own
// To: header based on the contents of $recipients.
unset($headers['To']);
// Flatten the headers out.
$headerElements = $this->prepareHeaders($headers);
if (is_a($headerElements, 'PEAR_Error')) {
return $headerElements;
}
list(, $text_headers) = $headerElements;
// We only use mail()'s optional fifth parameter if the additional
// parameters have been provided and we're not running in safe mode.
if (empty($this->_params) || ini_get('safe_mode')) {
$result = mail($recipients, $subject, $body, $text_headers);
} else {
$result = mail($recipients, $subject, $body, $text_headers,
$this->_params);
}
// If the mail() function returned failure, we need to create a
// PEAR_Error object and return it instead of the boolean result.
if ($result === false) {
$result = PEAR::raiseError('mail() returned failure');
}
return $result;
} | [
"public",
"function",
"send",
"(",
"$",
"recipients",
",",
"$",
"headers",
",",
"$",
"body",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"headers",
")",
")",
"{",
"return",
"PEAR",
"::",
"raiseError",
"(",
"'$headers must be an array'",
")",
";",
"... | Implements Mail_mail::send() function using php's built-in mail()
command.
@param mixed $recipients Either a comma-seperated list of recipients
(RFC822 compliant), or an array of recipients,
each RFC822 valid. This may contain recipients not
specified in the headers, for Bcc:, resending
messages, etc.
@param array $headers The array of headers to send with the mail, in an
associative array, where the array key is the
header name (ie, 'Subject'), and the array value
is the header value (ie, 'test'). The header
produced from those values would be 'Subject:
test'.
@param string $body The full text of the message body, including any
Mime parts, etc.
@return mixed Returns true on success, or a PEAR_Error
containing a descriptive error message on
failure. | [
"Implements",
"Mail_mail",
"::",
"send",
"()",
"function",
"using",
"php",
"s",
"built",
"-",
"in",
"mail",
"()",
"command",
"."
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/mail.php#L115-L166 |
pear/Mail | Mail/mock.php | Mail_mock.send | public function send($recipients, $headers, $body)
{
if ($this->_preSendCallback) {
call_user_func_array($this->_preSendCallback,
array(&$this, $recipients, $headers, $body));
}
$entry = array('recipients' => $recipients, 'headers' => $headers, 'body' => $body);
$this->sentMessages[] = $entry;
if ($this->_postSendCallback) {
call_user_func_array($this->_postSendCallback,
array(&$this, $recipients, $headers, $body));
}
return true;
} | php | public function send($recipients, $headers, $body)
{
if ($this->_preSendCallback) {
call_user_func_array($this->_preSendCallback,
array(&$this, $recipients, $headers, $body));
}
$entry = array('recipients' => $recipients, 'headers' => $headers, 'body' => $body);
$this->sentMessages[] = $entry;
if ($this->_postSendCallback) {
call_user_func_array($this->_postSendCallback,
array(&$this, $recipients, $headers, $body));
}
return true;
} | [
"public",
"function",
"send",
"(",
"$",
"recipients",
",",
"$",
"headers",
",",
"$",
"body",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_preSendCallback",
")",
"{",
"call_user_func_array",
"(",
"$",
"this",
"->",
"_preSendCallback",
",",
"array",
"(",
"&",... | Implements Mail_mock::send() function. Silently discards all
mail.
@param mixed $recipients Either a comma-seperated list of recipients
(RFC822 compliant), or an array of recipients,
each RFC822 valid. This may contain recipients not
specified in the headers, for Bcc:, resending
messages, etc.
@param array $headers The array of headers to send with the mail, in an
associative array, where the array key is the
header name (ie, 'Subject'), and the array value
is the header value (ie, 'test'). The header
produced from those values would be 'Subject:
test'.
@param string $body The full text of the message body, including any
Mime parts, etc.
@return mixed Returns true on success, or a PEAR_Error
containing a descriptive error message on
failure. | [
"Implements",
"Mail_mock",
"::",
"send",
"()",
"function",
".",
"Silently",
"discards",
"all",
"mail",
"."
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/mock.php#L124-L140 |
pear/Mail | Mail/RFC822.php | Mail_RFC822.parseAddressList | public function parseAddressList($address = null, $default_domain = null, $nest_groups = null, $validate = null, $limit = null)
{
if (!isset($this) || !isset($this->mailRFC822)) {
$obj = new Mail_RFC822($address, $default_domain, $nest_groups, $validate, $limit);
return $obj->parseAddressList();
}
if (isset($address)) $this->address = $address;
if (isset($default_domain)) $this->default_domain = $default_domain;
if (isset($nest_groups)) $this->nestGroups = $nest_groups;
if (isset($validate)) $this->validate = $validate;
if (isset($limit)) $this->limit = $limit;
$this->structure = array();
$this->addresses = array();
$this->error = null;
$this->index = null;
// Unfold any long lines in $this->address.
$this->address = preg_replace('/\r?\n/', "\r\n", $this->address);
$this->address = preg_replace('/\r\n(\t| )+/', ' ', $this->address);
while ($this->address = $this->_splitAddresses($this->address));
if ($this->address === false || isset($this->error)) {
require_once 'PEAR.php';
return PEAR::raiseError($this->error);
}
// Validate each address individually. If we encounter an invalid
// address, stop iterating and return an error immediately.
foreach ($this->addresses as $address) {
$valid = $this->_validateAddress($address);
if ($valid === false || isset($this->error)) {
require_once 'PEAR.php';
return PEAR::raiseError($this->error);
}
if (!$this->nestGroups) {
$this->structure = array_merge($this->structure, $valid);
} else {
$this->structure[] = $valid;
}
}
return $this->structure;
} | php | public function parseAddressList($address = null, $default_domain = null, $nest_groups = null, $validate = null, $limit = null)
{
if (!isset($this) || !isset($this->mailRFC822)) {
$obj = new Mail_RFC822($address, $default_domain, $nest_groups, $validate, $limit);
return $obj->parseAddressList();
}
if (isset($address)) $this->address = $address;
if (isset($default_domain)) $this->default_domain = $default_domain;
if (isset($nest_groups)) $this->nestGroups = $nest_groups;
if (isset($validate)) $this->validate = $validate;
if (isset($limit)) $this->limit = $limit;
$this->structure = array();
$this->addresses = array();
$this->error = null;
$this->index = null;
// Unfold any long lines in $this->address.
$this->address = preg_replace('/\r?\n/', "\r\n", $this->address);
$this->address = preg_replace('/\r\n(\t| )+/', ' ', $this->address);
while ($this->address = $this->_splitAddresses($this->address));
if ($this->address === false || isset($this->error)) {
require_once 'PEAR.php';
return PEAR::raiseError($this->error);
}
// Validate each address individually. If we encounter an invalid
// address, stop iterating and return an error immediately.
foreach ($this->addresses as $address) {
$valid = $this->_validateAddress($address);
if ($valid === false || isset($this->error)) {
require_once 'PEAR.php';
return PEAR::raiseError($this->error);
}
if (!$this->nestGroups) {
$this->structure = array_merge($this->structure, $valid);
} else {
$this->structure[] = $valid;
}
}
return $this->structure;
} | [
"public",
"function",
"parseAddressList",
"(",
"$",
"address",
"=",
"null",
",",
"$",
"default_domain",
"=",
"null",
",",
"$",
"nest_groups",
"=",
"null",
",",
"$",
"validate",
"=",
"null",
",",
"$",
"limit",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"i... | Starts the whole process. The address must either be set here
or when creating the object. One or the other.
@param string $address The address(es) to validate.
@param string $default_domain Default domain/host etc.
@param boolean $nest_groups Whether to return the structure with groups nested for easier viewing.
@param boolean $validate Whether to validate atoms. Turn this off if you need to run addresses through before encoding the personal names, for instance.
@return array A structured array of addresses. | [
"Starts",
"the",
"whole",
"process",
".",
"The",
"address",
"must",
"either",
"be",
"set",
"here",
"or",
"when",
"creating",
"the",
"object",
".",
"One",
"or",
"the",
"other",
"."
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/RFC822.php#L173-L220 |
pear/Mail | Mail/RFC822.php | Mail_RFC822._splitAddresses | protected function _splitAddresses($address)
{
if (!empty($this->limit) && count($this->addresses) == $this->limit) {
return '';
}
if ($this->_isGroup($address) && !isset($this->error)) {
$split_char = ';';
$is_group = true;
} elseif (!isset($this->error)) {
$split_char = ',';
$is_group = false;
} elseif (isset($this->error)) {
return false;
}
// Split the string based on the above ten or so lines.
$parts = explode($split_char, $address);
$string = $this->_splitCheck($parts, $split_char);
// If a group...
if ($is_group) {
// If $string does not contain a colon outside of
// brackets/quotes etc then something's fubar.
// First check there's a colon at all:
if (strpos($string, ':') === false) {
$this->error = 'Invalid address: ' . $string;
return false;
}
// Now check it's outside of brackets/quotes:
if (!$this->_splitCheck(explode(':', $string), ':')) {
return false;
}
// We must have a group at this point, so increase the counter:
$this->num_groups++;
}
// $string now contains the first full address/group.
// Add to the addresses array.
$this->addresses[] = array(
'address' => trim($string),
'group' => $is_group
);
// Remove the now stored address from the initial line, the +1
// is to account for the explode character.
$address = trim(substr($address, strlen($string) + 1));
// If the next char is a comma and this was a group, then
// there are more addresses, otherwise, if there are any more
// chars, then there is another address.
if ($is_group && substr($address, 0, 1) == ','){
$address = trim(substr($address, 1));
return $address;
} elseif (strlen($address) > 0) {
return $address;
} else {
return '';
}
// If you got here then something's off
return false;
} | php | protected function _splitAddresses($address)
{
if (!empty($this->limit) && count($this->addresses) == $this->limit) {
return '';
}
if ($this->_isGroup($address) && !isset($this->error)) {
$split_char = ';';
$is_group = true;
} elseif (!isset($this->error)) {
$split_char = ',';
$is_group = false;
} elseif (isset($this->error)) {
return false;
}
// Split the string based on the above ten or so lines.
$parts = explode($split_char, $address);
$string = $this->_splitCheck($parts, $split_char);
// If a group...
if ($is_group) {
// If $string does not contain a colon outside of
// brackets/quotes etc then something's fubar.
// First check there's a colon at all:
if (strpos($string, ':') === false) {
$this->error = 'Invalid address: ' . $string;
return false;
}
// Now check it's outside of brackets/quotes:
if (!$this->_splitCheck(explode(':', $string), ':')) {
return false;
}
// We must have a group at this point, so increase the counter:
$this->num_groups++;
}
// $string now contains the first full address/group.
// Add to the addresses array.
$this->addresses[] = array(
'address' => trim($string),
'group' => $is_group
);
// Remove the now stored address from the initial line, the +1
// is to account for the explode character.
$address = trim(substr($address, strlen($string) + 1));
// If the next char is a comma and this was a group, then
// there are more addresses, otherwise, if there are any more
// chars, then there is another address.
if ($is_group && substr($address, 0, 1) == ','){
$address = trim(substr($address, 1));
return $address;
} elseif (strlen($address) > 0) {
return $address;
} else {
return '';
}
// If you got here then something's off
return false;
} | [
"protected",
"function",
"_splitAddresses",
"(",
"$",
"address",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"limit",
")",
"&&",
"count",
"(",
"$",
"this",
"->",
"addresses",
")",
"==",
"$",
"this",
"->",
"limit",
")",
"{",
"return",
... | Splits an address into separate addresses.
@param string $address The addresses to split.
@return boolean Success or failure. | [
"Splits",
"an",
"address",
"into",
"separate",
"addresses",
"."
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/RFC822.php#L228-L295 |
pear/Mail | Mail/RFC822.php | Mail_RFC822._isGroup | protected function _isGroup($address)
{
// First comma not in quotes, angles or escaped:
$parts = explode(',', $address);
$string = $this->_splitCheck($parts, ',');
// Now we have the first address, we can reliably check for a
// group by searching for a colon that's not escaped or in
// quotes or angle brackets.
if (count($parts = explode(':', $string)) > 1) {
$string2 = $this->_splitCheck($parts, ':');
return ($string2 !== $string);
} else {
return false;
}
} | php | protected function _isGroup($address)
{
// First comma not in quotes, angles or escaped:
$parts = explode(',', $address);
$string = $this->_splitCheck($parts, ',');
// Now we have the first address, we can reliably check for a
// group by searching for a colon that's not escaped or in
// quotes or angle brackets.
if (count($parts = explode(':', $string)) > 1) {
$string2 = $this->_splitCheck($parts, ':');
return ($string2 !== $string);
} else {
return false;
}
} | [
"protected",
"function",
"_isGroup",
"(",
"$",
"address",
")",
"{",
"// First comma not in quotes, angles or escaped:",
"$",
"parts",
"=",
"explode",
"(",
"','",
",",
"$",
"address",
")",
";",
"$",
"string",
"=",
"$",
"this",
"->",
"_splitCheck",
"(",
"$",
"... | Checks for a group at the start of the string.
@param string $address The address to check.
@return boolean Whether or not there is a group at the start of the string. | [
"Checks",
"for",
"a",
"group",
"at",
"the",
"start",
"of",
"the",
"string",
"."
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/RFC822.php#L303-L318 |
pear/Mail | Mail/RFC822.php | Mail_RFC822._splitCheck | protected function _splitCheck($parts, $char)
{
$string = $parts[0];
for ($i = 0; $i < count($parts); $i++) {
if ($this->_hasUnclosedQuotes($string)
|| $this->_hasUnclosedBrackets($string, '<>')
|| $this->_hasUnclosedBrackets($string, '[]')
|| $this->_hasUnclosedBrackets($string, '()')
|| substr($string, -1) == '\\') {
if (isset($parts[$i + 1])) {
$string = $string . $char . $parts[$i + 1];
} else {
$this->error = 'Invalid address spec. Unclosed bracket or quotes';
return false;
}
} else {
$this->index = $i;
break;
}
}
return $string;
} | php | protected function _splitCheck($parts, $char)
{
$string = $parts[0];
for ($i = 0; $i < count($parts); $i++) {
if ($this->_hasUnclosedQuotes($string)
|| $this->_hasUnclosedBrackets($string, '<>')
|| $this->_hasUnclosedBrackets($string, '[]')
|| $this->_hasUnclosedBrackets($string, '()')
|| substr($string, -1) == '\\') {
if (isset($parts[$i + 1])) {
$string = $string . $char . $parts[$i + 1];
} else {
$this->error = 'Invalid address spec. Unclosed bracket or quotes';
return false;
}
} else {
$this->index = $i;
break;
}
}
return $string;
} | [
"protected",
"function",
"_splitCheck",
"(",
"$",
"parts",
",",
"$",
"char",
")",
"{",
"$",
"string",
"=",
"$",
"parts",
"[",
"0",
"]",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"count",
"(",
"$",
"parts",
")",
";",
"$",
"i",
... | A common function that will check an exploded string.
@param array $parts The exloded string.
@param string $char The char that was exploded on.
@return mixed False if the string contains unclosed quotes/brackets, or the string on success. | [
"A",
"common",
"function",
"that",
"will",
"check",
"an",
"exploded",
"string",
"."
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/RFC822.php#L327-L350 |
pear/Mail | Mail/RFC822.php | Mail_RFC822._hasUnclosedQuotes | protected function _hasUnclosedQuotes($string)
{
$string = trim($string);
$iMax = strlen($string);
$in_quote = false;
$i = $slashes = 0;
for (; $i < $iMax; ++$i) {
switch ($string[$i]) {
case '\\':
++$slashes;
break;
case '"':
if ($slashes % 2 == 0) {
$in_quote = !$in_quote;
}
// Fall through to default action below.
default:
$slashes = 0;
break;
}
}
return $in_quote;
} | php | protected function _hasUnclosedQuotes($string)
{
$string = trim($string);
$iMax = strlen($string);
$in_quote = false;
$i = $slashes = 0;
for (; $i < $iMax; ++$i) {
switch ($string[$i]) {
case '\\':
++$slashes;
break;
case '"':
if ($slashes % 2 == 0) {
$in_quote = !$in_quote;
}
// Fall through to default action below.
default:
$slashes = 0;
break;
}
}
return $in_quote;
} | [
"protected",
"function",
"_hasUnclosedQuotes",
"(",
"$",
"string",
")",
"{",
"$",
"string",
"=",
"trim",
"(",
"$",
"string",
")",
";",
"$",
"iMax",
"=",
"strlen",
"(",
"$",
"string",
")",
";",
"$",
"in_quote",
"=",
"false",
";",
"$",
"i",
"=",
"$",... | Checks if a string has unclosed quotes or not.
@param string $string The string to check.
@return boolean True if there are unclosed quotes inside the string,
false otherwise. | [
"Checks",
"if",
"a",
"string",
"has",
"unclosed",
"quotes",
"or",
"not",
"."
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/RFC822.php#L359-L385 |
pear/Mail | Mail/RFC822.php | Mail_RFC822._hasUnclosedBrackets | protected function _hasUnclosedBrackets($string, $chars)
{
$num_angle_start = substr_count($string, $chars[0]);
$num_angle_end = substr_count($string, $chars[1]);
$this->_hasUnclosedBracketsSub($string, $num_angle_start, $chars[0]);
$this->_hasUnclosedBracketsSub($string, $num_angle_end, $chars[1]);
if ($num_angle_start < $num_angle_end) {
$this->error = 'Invalid address spec. Unmatched quote or bracket (' . $chars . ')';
return false;
} else {
return ($num_angle_start > $num_angle_end);
}
} | php | protected function _hasUnclosedBrackets($string, $chars)
{
$num_angle_start = substr_count($string, $chars[0]);
$num_angle_end = substr_count($string, $chars[1]);
$this->_hasUnclosedBracketsSub($string, $num_angle_start, $chars[0]);
$this->_hasUnclosedBracketsSub($string, $num_angle_end, $chars[1]);
if ($num_angle_start < $num_angle_end) {
$this->error = 'Invalid address spec. Unmatched quote or bracket (' . $chars . ')';
return false;
} else {
return ($num_angle_start > $num_angle_end);
}
} | [
"protected",
"function",
"_hasUnclosedBrackets",
"(",
"$",
"string",
",",
"$",
"chars",
")",
"{",
"$",
"num_angle_start",
"=",
"substr_count",
"(",
"$",
"string",
",",
"$",
"chars",
"[",
"0",
"]",
")",
";",
"$",
"num_angle_end",
"=",
"substr_count",
"(",
... | Checks if a string has an unclosed brackets or not. IMPORTANT:
This function handles both angle brackets and square brackets;
@param string $string The string to check.
@param string $chars The characters to check for.
@return boolean True if there are unclosed brackets inside the string, false otherwise. | [
"Checks",
"if",
"a",
"string",
"has",
"an",
"unclosed",
"brackets",
"or",
"not",
".",
"IMPORTANT",
":",
"This",
"function",
"handles",
"both",
"angle",
"brackets",
"and",
"square",
"brackets",
";"
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/RFC822.php#L395-L409 |
pear/Mail | Mail/RFC822.php | Mail_RFC822._hasUnclosedBracketsSub | protected function _hasUnclosedBracketsSub($string, &$num, $char)
{
$parts = explode($char, $string);
for ($i = 0; $i < count($parts); $i++){
if (substr($parts[$i], -1) == '\\' || $this->_hasUnclosedQuotes($parts[$i]))
$num--;
if (isset($parts[$i + 1]))
$parts[$i + 1] = $parts[$i] . $char . $parts[$i + 1];
}
return $num;
} | php | protected function _hasUnclosedBracketsSub($string, &$num, $char)
{
$parts = explode($char, $string);
for ($i = 0; $i < count($parts); $i++){
if (substr($parts[$i], -1) == '\\' || $this->_hasUnclosedQuotes($parts[$i]))
$num--;
if (isset($parts[$i + 1]))
$parts[$i + 1] = $parts[$i] . $char . $parts[$i + 1];
}
return $num;
} | [
"protected",
"function",
"_hasUnclosedBracketsSub",
"(",
"$",
"string",
",",
"&",
"$",
"num",
",",
"$",
"char",
")",
"{",
"$",
"parts",
"=",
"explode",
"(",
"$",
"char",
",",
"$",
"string",
")",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",... | Sub function that is used only by hasUnclosedBrackets().
@param string $string The string to check.
@param integer &$num The number of occurences.
@param string $char The character to count.
@return integer The number of occurences of $char in $string, adjusted for backslashes. | [
"Sub",
"function",
"that",
"is",
"used",
"only",
"by",
"hasUnclosedBrackets",
"()",
"."
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/RFC822.php#L419-L430 |
pear/Mail | Mail/RFC822.php | Mail_RFC822._validateAddress | protected function _validateAddress($address)
{
$is_group = false;
$addresses = array();
if ($address['group']) {
$is_group = true;
// Get the group part of the name
$parts = explode(':', $address['address']);
$groupname = $this->_splitCheck($parts, ':');
$structure = array();
// And validate the group part of the name.
if (!$this->_validatePhrase($groupname)){
$this->error = 'Group name did not validate.';
return false;
} else {
// Don't include groups if we are not nesting
// them. This avoids returning invalid addresses.
if ($this->nestGroups) {
$structure = new stdClass;
$structure->groupname = $groupname;
}
}
$address['address'] = ltrim(substr($address['address'], strlen($groupname . ':')));
}
// If a group then split on comma and put into an array.
// Otherwise, Just put the whole address in an array.
if ($is_group) {
while (strlen($address['address']) > 0) {
$parts = explode(',', $address['address']);
$addresses[] = $this->_splitCheck($parts, ',');
$address['address'] = trim(substr($address['address'], strlen(end($addresses) . ',')));
}
} else {
$addresses[] = $address['address'];
}
// Trim the whitespace from all of the address strings.
array_map('trim', $addresses);
// Validate each mailbox.
// Format could be one of: name <geezer@domain.com>
// geezer@domain.com
// geezer
// ... or any other format valid by RFC 822.
for ($i = 0; $i < count($addresses); $i++) {
if (!$this->validateMailbox($addresses[$i])) {
if (empty($this->error)) {
$this->error = 'Validation failed for: ' . $addresses[$i];
}
return false;
}
}
// Nested format
if ($this->nestGroups) {
if ($is_group) {
$structure->addresses = $addresses;
} else {
$structure = $addresses[0];
}
// Flat format
} else {
if ($is_group) {
$structure = array_merge($structure, $addresses);
} else {
$structure = $addresses;
}
}
return $structure;
} | php | protected function _validateAddress($address)
{
$is_group = false;
$addresses = array();
if ($address['group']) {
$is_group = true;
// Get the group part of the name
$parts = explode(':', $address['address']);
$groupname = $this->_splitCheck($parts, ':');
$structure = array();
// And validate the group part of the name.
if (!$this->_validatePhrase($groupname)){
$this->error = 'Group name did not validate.';
return false;
} else {
// Don't include groups if we are not nesting
// them. This avoids returning invalid addresses.
if ($this->nestGroups) {
$structure = new stdClass;
$structure->groupname = $groupname;
}
}
$address['address'] = ltrim(substr($address['address'], strlen($groupname . ':')));
}
// If a group then split on comma and put into an array.
// Otherwise, Just put the whole address in an array.
if ($is_group) {
while (strlen($address['address']) > 0) {
$parts = explode(',', $address['address']);
$addresses[] = $this->_splitCheck($parts, ',');
$address['address'] = trim(substr($address['address'], strlen(end($addresses) . ',')));
}
} else {
$addresses[] = $address['address'];
}
// Trim the whitespace from all of the address strings.
array_map('trim', $addresses);
// Validate each mailbox.
// Format could be one of: name <geezer@domain.com>
// geezer@domain.com
// geezer
// ... or any other format valid by RFC 822.
for ($i = 0; $i < count($addresses); $i++) {
if (!$this->validateMailbox($addresses[$i])) {
if (empty($this->error)) {
$this->error = 'Validation failed for: ' . $addresses[$i];
}
return false;
}
}
// Nested format
if ($this->nestGroups) {
if ($is_group) {
$structure->addresses = $addresses;
} else {
$structure = $addresses[0];
}
// Flat format
} else {
if ($is_group) {
$structure = array_merge($structure, $addresses);
} else {
$structure = $addresses;
}
}
return $structure;
} | [
"protected",
"function",
"_validateAddress",
"(",
"$",
"address",
")",
"{",
"$",
"is_group",
"=",
"false",
";",
"$",
"addresses",
"=",
"array",
"(",
")",
";",
"if",
"(",
"$",
"address",
"[",
"'group'",
"]",
")",
"{",
"$",
"is_group",
"=",
"true",
";"... | Function to begin checking the address.
@param string $address The address to validate.
@return mixed False on failure, or a structured array of address information on success. | [
"Function",
"to",
"begin",
"checking",
"the",
"address",
"."
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/RFC822.php#L438-L514 |
pear/Mail | Mail/RFC822.php | Mail_RFC822._validatePhrase | protected function _validatePhrase($phrase)
{
// Splits on one or more Tab or space.
$parts = preg_split('/[ \\x09]+/', $phrase, -1, PREG_SPLIT_NO_EMPTY);
$phrase_parts = array();
while (count($parts) > 0){
$phrase_parts[] = $this->_splitCheck($parts, ' ');
for ($i = 0; $i < $this->index + 1; $i++)
array_shift($parts);
}
foreach ($phrase_parts as $part) {
// If quoted string:
if (substr($part, 0, 1) == '"') {
if (!$this->_validateQuotedString($part)) {
return false;
}
continue;
}
// Otherwise it's an atom:
if (!$this->_validateAtom($part)) return false;
}
return true;
} | php | protected function _validatePhrase($phrase)
{
// Splits on one or more Tab or space.
$parts = preg_split('/[ \\x09]+/', $phrase, -1, PREG_SPLIT_NO_EMPTY);
$phrase_parts = array();
while (count($parts) > 0){
$phrase_parts[] = $this->_splitCheck($parts, ' ');
for ($i = 0; $i < $this->index + 1; $i++)
array_shift($parts);
}
foreach ($phrase_parts as $part) {
// If quoted string:
if (substr($part, 0, 1) == '"') {
if (!$this->_validateQuotedString($part)) {
return false;
}
continue;
}
// Otherwise it's an atom:
if (!$this->_validateAtom($part)) return false;
}
return true;
} | [
"protected",
"function",
"_validatePhrase",
"(",
"$",
"phrase",
")",
"{",
"// Splits on one or more Tab or space.",
"$",
"parts",
"=",
"preg_split",
"(",
"'/[ \\\\x09]+/'",
",",
"$",
"phrase",
",",
"-",
"1",
",",
"PREG_SPLIT_NO_EMPTY",
")",
";",
"$",
"phrase_parts... | Function to validate a phrase.
@param string $phrase The phrase to check.
@return boolean Success or failure. | [
"Function",
"to",
"validate",
"a",
"phrase",
"."
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/RFC822.php#L522-L548 |
pear/Mail | Mail/RFC822.php | Mail_RFC822._validateAtom | protected function _validateAtom($atom)
{
if (!$this->validate) {
// Validation has been turned off; assume the atom is okay.
return true;
}
// Check for any char from ASCII 0 - ASCII 127
if (!preg_match('/^[\\x00-\\x7E]+$/i', $atom, $matches)) {
return false;
}
// Check for specials:
if (preg_match('/[][()<>@,;\\:". ]/', $atom)) {
return false;
}
// Check for control characters (ASCII 0-31):
if (preg_match('/[\\x00-\\x1F]+/', $atom)) {
return false;
}
return true;
} | php | protected function _validateAtom($atom)
{
if (!$this->validate) {
// Validation has been turned off; assume the atom is okay.
return true;
}
// Check for any char from ASCII 0 - ASCII 127
if (!preg_match('/^[\\x00-\\x7E]+$/i', $atom, $matches)) {
return false;
}
// Check for specials:
if (preg_match('/[][()<>@,;\\:". ]/', $atom)) {
return false;
}
// Check for control characters (ASCII 0-31):
if (preg_match('/[\\x00-\\x1F]+/', $atom)) {
return false;
}
return true;
} | [
"protected",
"function",
"_validateAtom",
"(",
"$",
"atom",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"validate",
")",
"{",
"// Validation has been turned off; assume the atom is okay.",
"return",
"true",
";",
"}",
"// Check for any char from ASCII 0 - ASCII 127",
"i... | Function to validate an atom which from rfc822 is:
atom = 1*<any CHAR except specials, SPACE and CTLs>
If validation ($this->validate) has been turned off, then
validateAtom() doesn't actually check anything. This is so that you
can split a list of addresses up before encoding personal names
(umlauts, etc.), for example.
@param string $atom The string to check.
@return boolean Success or failure. | [
"Function",
"to",
"validate",
"an",
"atom",
"which",
"from",
"rfc822",
"is",
":",
"atom",
"=",
"1",
"*",
"<any",
"CHAR",
"except",
"specials",
"SPACE",
"and",
"CTLs",
">"
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/RFC822.php#L562-L585 |
pear/Mail | Mail/RFC822.php | Mail_RFC822.validateMailbox | public function validateMailbox(&$mailbox)
{
// A couple of defaults.
$phrase = '';
$comment = '';
$comments = array();
// Catch any RFC822 comments and store them separately.
$_mailbox = $mailbox;
while (strlen(trim($_mailbox)) > 0) {
$parts = explode('(', $_mailbox);
$before_comment = $this->_splitCheck($parts, '(');
if ($before_comment != $_mailbox) {
// First char should be a (.
$comment = substr(str_replace($before_comment, '', $_mailbox), 1);
$parts = explode(')', $comment);
$comment = $this->_splitCheck($parts, ')');
$comments[] = $comment;
// +2 is for the brackets
$_mailbox = substr($_mailbox, strpos($_mailbox, '('.$comment)+strlen($comment)+2);
} else {
break;
}
}
foreach ($comments as $comment) {
$mailbox = str_replace("($comment)", '', $mailbox);
}
$mailbox = trim($mailbox);
// Check for name + route-addr
if (substr($mailbox, -1) == '>' && substr($mailbox, 0, 1) != '<') {
$parts = explode('<', $mailbox);
$name = $this->_splitCheck($parts, '<');
$phrase = trim($name);
$route_addr = trim(substr($mailbox, strlen($name.'<'), -1));
if ($this->_validatePhrase($phrase) === false || ($route_addr = $this->_validateRouteAddr($route_addr)) === false) {
return false;
}
// Only got addr-spec
} else {
// First snip angle brackets if present.
if (substr($mailbox, 0, 1) == '<' && substr($mailbox, -1) == '>') {
$addr_spec = substr($mailbox, 1, -1);
} else {
$addr_spec = $mailbox;
}
if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
return false;
}
}
// Construct the object that will be returned.
$mbox = new stdClass();
// Add the phrase (even if empty) and comments
$mbox->personal = $phrase;
$mbox->comment = isset($comments) ? $comments : array();
if (isset($route_addr)) {
$mbox->mailbox = $route_addr['local_part'];
$mbox->host = $route_addr['domain'];
$route_addr['adl'] !== '' ? $mbox->adl = $route_addr['adl'] : '';
} else {
$mbox->mailbox = $addr_spec['local_part'];
$mbox->host = $addr_spec['domain'];
}
$mailbox = $mbox;
return true;
} | php | public function validateMailbox(&$mailbox)
{
// A couple of defaults.
$phrase = '';
$comment = '';
$comments = array();
// Catch any RFC822 comments and store them separately.
$_mailbox = $mailbox;
while (strlen(trim($_mailbox)) > 0) {
$parts = explode('(', $_mailbox);
$before_comment = $this->_splitCheck($parts, '(');
if ($before_comment != $_mailbox) {
// First char should be a (.
$comment = substr(str_replace($before_comment, '', $_mailbox), 1);
$parts = explode(')', $comment);
$comment = $this->_splitCheck($parts, ')');
$comments[] = $comment;
// +2 is for the brackets
$_mailbox = substr($_mailbox, strpos($_mailbox, '('.$comment)+strlen($comment)+2);
} else {
break;
}
}
foreach ($comments as $comment) {
$mailbox = str_replace("($comment)", '', $mailbox);
}
$mailbox = trim($mailbox);
// Check for name + route-addr
if (substr($mailbox, -1) == '>' && substr($mailbox, 0, 1) != '<') {
$parts = explode('<', $mailbox);
$name = $this->_splitCheck($parts, '<');
$phrase = trim($name);
$route_addr = trim(substr($mailbox, strlen($name.'<'), -1));
if ($this->_validatePhrase($phrase) === false || ($route_addr = $this->_validateRouteAddr($route_addr)) === false) {
return false;
}
// Only got addr-spec
} else {
// First snip angle brackets if present.
if (substr($mailbox, 0, 1) == '<' && substr($mailbox, -1) == '>') {
$addr_spec = substr($mailbox, 1, -1);
} else {
$addr_spec = $mailbox;
}
if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
return false;
}
}
// Construct the object that will be returned.
$mbox = new stdClass();
// Add the phrase (even if empty) and comments
$mbox->personal = $phrase;
$mbox->comment = isset($comments) ? $comments : array();
if (isset($route_addr)) {
$mbox->mailbox = $route_addr['local_part'];
$mbox->host = $route_addr['domain'];
$route_addr['adl'] !== '' ? $mbox->adl = $route_addr['adl'] : '';
} else {
$mbox->mailbox = $addr_spec['local_part'];
$mbox->host = $addr_spec['domain'];
}
$mailbox = $mbox;
return true;
} | [
"public",
"function",
"validateMailbox",
"(",
"&",
"$",
"mailbox",
")",
"{",
"// A couple of defaults.",
"$",
"phrase",
"=",
"''",
";",
"$",
"comment",
"=",
"''",
";",
"$",
"comments",
"=",
"array",
"(",
")",
";",
"// Catch any RFC822 comments and store them sep... | Function to validate a mailbox, which is:
mailbox = addr-spec ; simple address
/ phrase route-addr ; name and route-addr
@param string &$mailbox The string to check.
@return boolean Success or failure. | [
"Function",
"to",
"validate",
"a",
"mailbox",
"which",
"is",
":",
"mailbox",
"=",
"addr",
"-",
"spec",
";",
"simple",
"address",
"/",
"phrase",
"route",
"-",
"addr",
";",
"name",
"and",
"route",
"-",
"addr"
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/RFC822.php#L611-L687 |
pear/Mail | Mail/RFC822.php | Mail_RFC822._validateRouteAddr | protected function _validateRouteAddr($route_addr)
{
// Check for colon.
if (strpos($route_addr, ':') !== false) {
$parts = explode(':', $route_addr);
$route = $this->_splitCheck($parts, ':');
} else {
$route = $route_addr;
}
// If $route is same as $route_addr then the colon was in
// quotes or brackets or, of course, non existent.
if ($route === $route_addr){
unset($route);
$addr_spec = $route_addr;
if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
return false;
}
} else {
// Validate route part.
if (($route = $this->_validateRoute($route)) === false) {
return false;
}
$addr_spec = substr($route_addr, strlen($route . ':'));
// Validate addr-spec part.
if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
return false;
}
}
if (isset($route)) {
$return['adl'] = $route;
} else {
$return['adl'] = '';
}
$return = array_merge($return, $addr_spec);
return $return;
} | php | protected function _validateRouteAddr($route_addr)
{
// Check for colon.
if (strpos($route_addr, ':') !== false) {
$parts = explode(':', $route_addr);
$route = $this->_splitCheck($parts, ':');
} else {
$route = $route_addr;
}
// If $route is same as $route_addr then the colon was in
// quotes or brackets or, of course, non existent.
if ($route === $route_addr){
unset($route);
$addr_spec = $route_addr;
if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
return false;
}
} else {
// Validate route part.
if (($route = $this->_validateRoute($route)) === false) {
return false;
}
$addr_spec = substr($route_addr, strlen($route . ':'));
// Validate addr-spec part.
if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
return false;
}
}
if (isset($route)) {
$return['adl'] = $route;
} else {
$return['adl'] = '';
}
$return = array_merge($return, $addr_spec);
return $return;
} | [
"protected",
"function",
"_validateRouteAddr",
"(",
"$",
"route_addr",
")",
"{",
"// Check for colon.",
"if",
"(",
"strpos",
"(",
"$",
"route_addr",
",",
"':'",
")",
"!==",
"false",
")",
"{",
"$",
"parts",
"=",
"explode",
"(",
"':'",
",",
"$",
"route_addr"... | This function validates a route-addr which is:
route-addr = "<" [route] addr-spec ">"
Angle brackets have already been removed at the point of
getting to this function.
@param string $route_addr The string to check.
@return mixed False on failure, or an array containing validated address/route information on success. | [
"This",
"function",
"validates",
"a",
"route",
"-",
"addr",
"which",
"is",
":",
"route",
"-",
"addr",
"=",
"<",
"[",
"route",
"]",
"addr",
"-",
"spec",
">"
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/RFC822.php#L699-L739 |
pear/Mail | Mail/RFC822.php | Mail_RFC822._validateRoute | protected function _validateRoute($route)
{
// Split on comma.
$domains = explode(',', trim($route));
foreach ($domains as $domain) {
$domain = str_replace('@', '', trim($domain));
if (!$this->_validateDomain($domain)) return false;
}
return $route;
} | php | protected function _validateRoute($route)
{
// Split on comma.
$domains = explode(',', trim($route));
foreach ($domains as $domain) {
$domain = str_replace('@', '', trim($domain));
if (!$this->_validateDomain($domain)) return false;
}
return $route;
} | [
"protected",
"function",
"_validateRoute",
"(",
"$",
"route",
")",
"{",
"// Split on comma.",
"$",
"domains",
"=",
"explode",
"(",
"','",
",",
"trim",
"(",
"$",
"route",
")",
")",
";",
"foreach",
"(",
"$",
"domains",
"as",
"$",
"domain",
")",
"{",
"$",... | Function to validate a route, which is:
route = 1#("@" domain) ":"
@param string $route The string to check.
@return mixed False on failure, or the validated $route on success. | [
"Function",
"to",
"validate",
"a",
"route",
"which",
"is",
":",
"route",
"=",
"1#",
"(",
"@",
"domain",
")",
":"
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/RFC822.php#L748-L759 |
pear/Mail | Mail/RFC822.php | Mail_RFC822._validateDomain | protected function _validateDomain($domain)
{
// Note the different use of $subdomains and $sub_domains
$subdomains = explode('.', $domain);
while (count($subdomains) > 0) {
$sub_domains[] = $this->_splitCheck($subdomains, '.');
for ($i = 0; $i < $this->index + 1; $i++)
array_shift($subdomains);
}
foreach ($sub_domains as $sub_domain) {
if (!$this->_validateSubdomain(trim($sub_domain)))
return false;
}
// Managed to get here, so return input.
return $domain;
} | php | protected function _validateDomain($domain)
{
// Note the different use of $subdomains and $sub_domains
$subdomains = explode('.', $domain);
while (count($subdomains) > 0) {
$sub_domains[] = $this->_splitCheck($subdomains, '.');
for ($i = 0; $i < $this->index + 1; $i++)
array_shift($subdomains);
}
foreach ($sub_domains as $sub_domain) {
if (!$this->_validateSubdomain(trim($sub_domain)))
return false;
}
// Managed to get here, so return input.
return $domain;
} | [
"protected",
"function",
"_validateDomain",
"(",
"$",
"domain",
")",
"{",
"// Note the different use of $subdomains and $sub_domains",
"$",
"subdomains",
"=",
"explode",
"(",
"'.'",
",",
"$",
"domain",
")",
";",
"while",
"(",
"count",
"(",
"$",
"subdomains",
")",
... | Function to validate a domain, though this is not quite what
you expect of a strict internet domain.
domain = sub-domain *("." sub-domain)
@param string $domain The string to check.
@return mixed False on failure, or the validated domain on success. | [
"Function",
"to",
"validate",
"a",
"domain",
"though",
"this",
"is",
"not",
"quite",
"what",
"you",
"expect",
"of",
"a",
"strict",
"internet",
"domain",
"."
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/RFC822.php#L770-L788 |
pear/Mail | Mail/RFC822.php | Mail_RFC822._validateSubdomain | protected function _validateSubdomain($subdomain)
{
if (preg_match('|^\[(.*)]$|', $subdomain, $arr)){
if (!$this->_validateDliteral($arr[1])) return false;
} else {
if (!$this->_validateAtom($subdomain)) return false;
}
// Got here, so return successful.
return true;
} | php | protected function _validateSubdomain($subdomain)
{
if (preg_match('|^\[(.*)]$|', $subdomain, $arr)){
if (!$this->_validateDliteral($arr[1])) return false;
} else {
if (!$this->_validateAtom($subdomain)) return false;
}
// Got here, so return successful.
return true;
} | [
"protected",
"function",
"_validateSubdomain",
"(",
"$",
"subdomain",
")",
"{",
"if",
"(",
"preg_match",
"(",
"'|^\\[(.*)]$|'",
",",
"$",
"subdomain",
",",
"$",
"arr",
")",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"_validateDliteral",
"(",
"$",
"arr"... | Function to validate a subdomain:
subdomain = domain-ref / domain-literal
@param string $subdomain The string to check.
@return boolean Success or failure. | [
"Function",
"to",
"validate",
"a",
"subdomain",
":",
"subdomain",
"=",
"domain",
"-",
"ref",
"/",
"domain",
"-",
"literal"
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/RFC822.php#L797-L807 |
pear/Mail | Mail/RFC822.php | Mail_RFC822._validateAddrSpec | protected function _validateAddrSpec($addr_spec)
{
$addr_spec = trim($addr_spec);
// Split on @ sign if there is one.
if (strpos($addr_spec, '@') !== false) {
$parts = explode('@', $addr_spec);
$local_part = $this->_splitCheck($parts, '@');
$domain = substr($addr_spec, strlen($local_part . '@'));
// No @ sign so assume the default domain.
} else {
$local_part = $addr_spec;
$domain = $this->default_domain;
}
if (($local_part = $this->_validateLocalPart($local_part)) === false) return false;
if (($domain = $this->_validateDomain($domain)) === false) return false;
// Got here so return successful.
return array('local_part' => $local_part, 'domain' => $domain);
} | php | protected function _validateAddrSpec($addr_spec)
{
$addr_spec = trim($addr_spec);
// Split on @ sign if there is one.
if (strpos($addr_spec, '@') !== false) {
$parts = explode('@', $addr_spec);
$local_part = $this->_splitCheck($parts, '@');
$domain = substr($addr_spec, strlen($local_part . '@'));
// No @ sign so assume the default domain.
} else {
$local_part = $addr_spec;
$domain = $this->default_domain;
}
if (($local_part = $this->_validateLocalPart($local_part)) === false) return false;
if (($domain = $this->_validateDomain($domain)) === false) return false;
// Got here so return successful.
return array('local_part' => $local_part, 'domain' => $domain);
} | [
"protected",
"function",
"_validateAddrSpec",
"(",
"$",
"addr_spec",
")",
"{",
"$",
"addr_spec",
"=",
"trim",
"(",
"$",
"addr_spec",
")",
";",
"// Split on @ sign if there is one.",
"if",
"(",
"strpos",
"(",
"$",
"addr_spec",
",",
"'@'",
")",
"!==",
"false",
... | Function to validate an addr-spec.
addr-spec = local-part "@" domain
@param string $addr_spec The string to check.
@return mixed False on failure, or the validated addr-spec on success. | [
"Function",
"to",
"validate",
"an",
"addr",
"-",
"spec",
"."
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/RFC822.php#L829-L850 |
pear/Mail | Mail/RFC822.php | Mail_RFC822._validateLocalPart | protected function _validateLocalPart($local_part)
{
$parts = explode('.', $local_part);
$words = array();
// Split the local_part into words.
while (count($parts) > 0) {
$words[] = $this->_splitCheck($parts, '.');
for ($i = 0; $i < $this->index + 1; $i++) {
array_shift($parts);
}
}
// Validate each word.
foreach ($words as $word) {
// word cannot be empty (#17317)
if ($word === '') {
return false;
}
// If this word contains an unquoted space, it is invalid. (6.2.4)
if (strpos($word, ' ') && $word[0] !== '"')
{
return false;
}
if ($this->_validatePhrase(trim($word)) === false) return false;
}
// Managed to get here, so return the input.
return $local_part;
} | php | protected function _validateLocalPart($local_part)
{
$parts = explode('.', $local_part);
$words = array();
// Split the local_part into words.
while (count($parts) > 0) {
$words[] = $this->_splitCheck($parts, '.');
for ($i = 0; $i < $this->index + 1; $i++) {
array_shift($parts);
}
}
// Validate each word.
foreach ($words as $word) {
// word cannot be empty (#17317)
if ($word === '') {
return false;
}
// If this word contains an unquoted space, it is invalid. (6.2.4)
if (strpos($word, ' ') && $word[0] !== '"')
{
return false;
}
if ($this->_validatePhrase(trim($word)) === false) return false;
}
// Managed to get here, so return the input.
return $local_part;
} | [
"protected",
"function",
"_validateLocalPart",
"(",
"$",
"local_part",
")",
"{",
"$",
"parts",
"=",
"explode",
"(",
"'.'",
",",
"$",
"local_part",
")",
";",
"$",
"words",
"=",
"array",
"(",
")",
";",
"// Split the local_part into words.",
"while",
"(",
"coun... | Function to validate the local part of an address:
local-part = word *("." word)
@param string $local_part
@return mixed False on failure, or the validated local part on success. | [
"Function",
"to",
"validate",
"the",
"local",
"part",
"of",
"an",
"address",
":",
"local",
"-",
"part",
"=",
"word",
"*",
"(",
".",
"word",
")"
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/RFC822.php#L859-L889 |
pear/Mail | Mail/RFC822.php | Mail_RFC822.isValidInetAddress | public function isValidInetAddress($data, $strict = false)
{
$regex = $strict ? '/^([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})$/i' : '/^([*+!.&#$|\'\\%\/0-9a-z^_`{}=?~:-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})$/i';
if (preg_match($regex, trim($data), $matches)) {
return array($matches[1], $matches[2]);
} else {
return false;
}
} | php | public function isValidInetAddress($data, $strict = false)
{
$regex = $strict ? '/^([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})$/i' : '/^([*+!.&#$|\'\\%\/0-9a-z^_`{}=?~:-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})$/i';
if (preg_match($regex, trim($data), $matches)) {
return array($matches[1], $matches[2]);
} else {
return false;
}
} | [
"public",
"function",
"isValidInetAddress",
"(",
"$",
"data",
",",
"$",
"strict",
"=",
"false",
")",
"{",
"$",
"regex",
"=",
"$",
"strict",
"?",
"'/^([.0-9a-z_+-]+)@(([0-9a-z-]+\\.)+[0-9a-z]{2,})$/i'",
":",
"'/^([*+!.&#$|\\'\\\\%\\/0-9a-z^_`{}=?~:-]+)@(([0-9a-z-]+\\.)+[0-9a... | This is a email validating function separate to the rest of the
class. It simply validates whether an email is of the common
internet form: <user>@<domain>. This can be sufficient for most
people. Optional stricter mode can be utilised which restricts
mailbox characters allowed to alphanumeric, full stop, hyphen
and underscore.
@param string $data Address to check
@param boolean $strict Optional stricter mode
@return mixed False if it fails, an indexed array
username/domain if it matches | [
"This",
"is",
"a",
"email",
"validating",
"function",
"separate",
"to",
"the",
"rest",
"of",
"the",
"class",
".",
"It",
"simply",
"validates",
"whether",
"an",
"email",
"is",
"of",
"the",
"common",
"internet",
"form",
":",
"<user",
">",
"@<domain",
">",
... | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/RFC822.php#L919-L927 |
pear/Mail | Mail/smtp.php | Mail_smtp.send | public function send($recipients, $headers, $body)
{
$result = $this->send_or_fail($recipients, $headers, $body);
/* If persistent connections are disabled, destroy our SMTP object. */
if ($this->persist === false) {
$this->disconnect();
}
return $result;
} | php | public function send($recipients, $headers, $body)
{
$result = $this->send_or_fail($recipients, $headers, $body);
/* If persistent connections are disabled, destroy our SMTP object. */
if ($this->persist === false) {
$this->disconnect();
}
return $result;
} | [
"public",
"function",
"send",
"(",
"$",
"recipients",
",",
"$",
"headers",
",",
"$",
"body",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"send_or_fail",
"(",
"$",
"recipients",
",",
"$",
"headers",
",",
"$",
"body",
")",
";",
"/* If persistent con... | Implements Mail::send() function using SMTP.
@param mixed $recipients Either a comma-seperated list of recipients
(RFC822 compliant), or an array of recipients,
each RFC822 valid. This may contain recipients not
specified in the headers, for Bcc:, resending
messages, etc.
@param array $headers The array of headers to send with the mail, in an
associative array, where the array key is the
header name (e.g., 'Subject'), and the array value
is the header value (e.g., 'test'). The header
produced from those values would be 'Subject:
test'.
@param string $body The full text of the message body, including any
MIME parts, etc.
@return mixed Returns true on success, or a PEAR_Error
containing a descriptive error message on
failure. | [
"Implements",
"Mail",
"::",
"send",
"()",
"function",
"using",
"SMTP",
"."
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/smtp.php#L256-L266 |
pear/Mail | Mail/smtp.php | Mail_smtp.getSMTPObject | public function getSMTPObject()
{
if (is_object($this->_smtp) !== false) {
return $this->_smtp;
}
include_once 'Net/SMTP.php';
$this->_smtp = new Net_SMTP($this->host,
$this->port,
$this->localhost,
$this->pipelining,
0,
$this->socket_options);
/* If we still don't have an SMTP object at this point, fail. */
if (is_object($this->_smtp) === false) {
return PEAR::raiseError('Failed to create a Net_SMTP object',
PEAR_MAIL_SMTP_ERROR_CREATE);
}
/* Configure the SMTP connection. */
if ($this->debug) {
$this->_smtp->setDebug(true);
}
/* Attempt to connect to the configured SMTP server. */
if (PEAR::isError($res = $this->_smtp->connect($this->timeout))) {
$error = $this->_error('Failed to connect to ' .
$this->host . ':' . $this->port,
$res);
return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_CONNECT);
}
/* Attempt to authenticate if authentication has been enabled. */
if ($this->auth) {
$method = is_string($this->auth) ? $this->auth : '';
if (PEAR::isError($res = $this->_smtp->auth($this->username,
$this->password,
$method))) {
$error = $this->_error("$method authentication failure",
$res);
$this->_smtp->rset();
return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_AUTH);
}
}
return $this->_smtp;
} | php | public function getSMTPObject()
{
if (is_object($this->_smtp) !== false) {
return $this->_smtp;
}
include_once 'Net/SMTP.php';
$this->_smtp = new Net_SMTP($this->host,
$this->port,
$this->localhost,
$this->pipelining,
0,
$this->socket_options);
/* If we still don't have an SMTP object at this point, fail. */
if (is_object($this->_smtp) === false) {
return PEAR::raiseError('Failed to create a Net_SMTP object',
PEAR_MAIL_SMTP_ERROR_CREATE);
}
/* Configure the SMTP connection. */
if ($this->debug) {
$this->_smtp->setDebug(true);
}
/* Attempt to connect to the configured SMTP server. */
if (PEAR::isError($res = $this->_smtp->connect($this->timeout))) {
$error = $this->_error('Failed to connect to ' .
$this->host . ':' . $this->port,
$res);
return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_CONNECT);
}
/* Attempt to authenticate if authentication has been enabled. */
if ($this->auth) {
$method = is_string($this->auth) ? $this->auth : '';
if (PEAR::isError($res = $this->_smtp->auth($this->username,
$this->password,
$method))) {
$error = $this->_error("$method authentication failure",
$res);
$this->_smtp->rset();
return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_AUTH);
}
}
return $this->_smtp;
} | [
"public",
"function",
"getSMTPObject",
"(",
")",
"{",
"if",
"(",
"is_object",
"(",
"$",
"this",
"->",
"_smtp",
")",
"!==",
"false",
")",
"{",
"return",
"$",
"this",
"->",
"_smtp",
";",
"}",
"include_once",
"'Net/SMTP.php'",
";",
"$",
"this",
"->",
"_sm... | Connect to the SMTP server by instantiating a Net_SMTP object.
@return mixed Returns a reference to the Net_SMTP object on success, or
a PEAR_Error containing a descriptive error message on
failure.
@since 1.2.0 | [
"Connect",
"to",
"the",
"SMTP",
"server",
"by",
"instantiating",
"a",
"Net_SMTP",
"object",
"."
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/smtp.php#L359-L407 |
pear/Mail | Mail/smtp.php | Mail_smtp._error | protected function _error($text, $error)
{
/* Split the SMTP response into a code and a response string. */
list($code, $response) = $this->_smtp->getResponse();
/* Build our standardized error string. */
return $text
. ' [SMTP: ' . $error->getMessage()
. " (code: $code, response: $response)]";
} | php | protected function _error($text, $error)
{
/* Split the SMTP response into a code and a response string. */
list($code, $response) = $this->_smtp->getResponse();
/* Build our standardized error string. */
return $text
. ' [SMTP: ' . $error->getMessage()
. " (code: $code, response: $response)]";
} | [
"protected",
"function",
"_error",
"(",
"$",
"text",
",",
"$",
"error",
")",
"{",
"/* Split the SMTP response into a code and a response string. */",
"list",
"(",
"$",
"code",
",",
"$",
"response",
")",
"=",
"$",
"this",
"->",
"_smtp",
"->",
"getResponse",
"(",
... | Build a standardized string describing the current SMTP error.
@param string $text Custom string describing the error context.
@param object $error Reference to the current PEAR_Error object.
@return string A string describing the current SMTP error.
@since 1.1.7 | [
"Build",
"a",
"standardized",
"string",
"describing",
"the",
"current",
"SMTP",
"error",
"."
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/smtp.php#L450-L459 |
pear/Mail | Mail/smtpmx.php | Mail_smtpmx.send | function send($recipients, $headers, $body)
{
if (!is_array($headers)) {
return PEAR::raiseError('$headers must be an array');
}
$result = $this->_sanitizeHeaders($headers);
if (is_a($result, 'PEAR_Error')) {
return $result;
}
// Prepare headers
$headerElements = $this->prepareHeaders($headers);
if (is_a($headerElements, 'PEAR_Error')) {
return $headerElements;
}
list($from, $textHeaders) = $headerElements;
// use 'Return-Path' if possible
if (!empty($headers['Return-Path'])) {
$from = $headers['Return-Path'];
}
if (!isset($from)) {
return $this->_raiseError('no_from');
}
// Prepare recipients
$recipients = $this->parseRecipients($recipients);
if (is_a($recipients, 'PEAR_Error')) {
return $recipients;
}
foreach ($recipients as $rcpt) {
list($user, $host) = explode('@', $rcpt);
$mx = $this->_getMx($host);
if (is_a($mx, 'PEAR_Error')) {
return $mx;
}
if (empty($mx)) {
$info = array('rcpt' => $rcpt);
return $this->_raiseError('no_mx', $info);
}
$connected = false;
foreach ($mx as $mserver => $mpriority) {
$this->_smtp = new Net_SMTP($mserver, $this->port, $this->mailname);
// configure the SMTP connection.
if ($this->debug) {
$this->_smtp->setDebug(true);
}
// attempt to connect to the configured SMTP server.
$res = $this->_smtp->connect($this->timeout);
if (is_a($res, 'PEAR_Error')) {
$this->_smtp = null;
continue;
}
// connection established
if ($res) {
$connected = true;
break;
}
}
if (!$connected) {
$info = array(
'host' => implode(', ', array_keys($mx)),
'port' => $this->port,
'rcpt' => $rcpt,
);
return $this->_raiseError('not_connected', $info);
}
// Verify recipient
if ($this->vrfy) {
$res = $this->_smtp->vrfy($rcpt);
if (is_a($res, 'PEAR_Error')) {
$info = array('rcpt' => $rcpt);
return $this->_raiseError('failed_vrfy_rcpt', $info);
}
}
// mail from:
$args['verp'] = $this->verp;
$res = $this->_smtp->mailFrom($from, $args);
if (is_a($res, 'PEAR_Error')) {
$info = array('from' => $from);
return $this->_raiseError('failed_set_from', $info);
}
// rcpt to:
$res = $this->_smtp->rcptTo($rcpt);
if (is_a($res, 'PEAR_Error')) {
$info = array('rcpt' => $rcpt);
return $this->_raiseError('failed_set_rcpt', $info);
}
// Don't send anything in test mode
if ($this->test) {
$result = $this->_smtp->rset();
$res = $this->_smtp->rset();
if (is_a($res, 'PEAR_Error')) {
return $this->_raiseError('failed_rset');
}
$this->_smtp->disconnect();
$this->_smtp = null;
return true;
}
// Send data
$res = $this->_smtp->data($body, $textHeaders);
if (is_a($res, 'PEAR_Error')) {
$info = array('rcpt' => $rcpt);
return $this->_raiseError('failed_send_data', $info);
}
$this->_smtp->disconnect();
$this->_smtp = null;
}
return true;
} | php | function send($recipients, $headers, $body)
{
if (!is_array($headers)) {
return PEAR::raiseError('$headers must be an array');
}
$result = $this->_sanitizeHeaders($headers);
if (is_a($result, 'PEAR_Error')) {
return $result;
}
// Prepare headers
$headerElements = $this->prepareHeaders($headers);
if (is_a($headerElements, 'PEAR_Error')) {
return $headerElements;
}
list($from, $textHeaders) = $headerElements;
// use 'Return-Path' if possible
if (!empty($headers['Return-Path'])) {
$from = $headers['Return-Path'];
}
if (!isset($from)) {
return $this->_raiseError('no_from');
}
// Prepare recipients
$recipients = $this->parseRecipients($recipients);
if (is_a($recipients, 'PEAR_Error')) {
return $recipients;
}
foreach ($recipients as $rcpt) {
list($user, $host) = explode('@', $rcpt);
$mx = $this->_getMx($host);
if (is_a($mx, 'PEAR_Error')) {
return $mx;
}
if (empty($mx)) {
$info = array('rcpt' => $rcpt);
return $this->_raiseError('no_mx', $info);
}
$connected = false;
foreach ($mx as $mserver => $mpriority) {
$this->_smtp = new Net_SMTP($mserver, $this->port, $this->mailname);
// configure the SMTP connection.
if ($this->debug) {
$this->_smtp->setDebug(true);
}
// attempt to connect to the configured SMTP server.
$res = $this->_smtp->connect($this->timeout);
if (is_a($res, 'PEAR_Error')) {
$this->_smtp = null;
continue;
}
// connection established
if ($res) {
$connected = true;
break;
}
}
if (!$connected) {
$info = array(
'host' => implode(', ', array_keys($mx)),
'port' => $this->port,
'rcpt' => $rcpt,
);
return $this->_raiseError('not_connected', $info);
}
// Verify recipient
if ($this->vrfy) {
$res = $this->_smtp->vrfy($rcpt);
if (is_a($res, 'PEAR_Error')) {
$info = array('rcpt' => $rcpt);
return $this->_raiseError('failed_vrfy_rcpt', $info);
}
}
// mail from:
$args['verp'] = $this->verp;
$res = $this->_smtp->mailFrom($from, $args);
if (is_a($res, 'PEAR_Error')) {
$info = array('from' => $from);
return $this->_raiseError('failed_set_from', $info);
}
// rcpt to:
$res = $this->_smtp->rcptTo($rcpt);
if (is_a($res, 'PEAR_Error')) {
$info = array('rcpt' => $rcpt);
return $this->_raiseError('failed_set_rcpt', $info);
}
// Don't send anything in test mode
if ($this->test) {
$result = $this->_smtp->rset();
$res = $this->_smtp->rset();
if (is_a($res, 'PEAR_Error')) {
return $this->_raiseError('failed_rset');
}
$this->_smtp->disconnect();
$this->_smtp = null;
return true;
}
// Send data
$res = $this->_smtp->data($body, $textHeaders);
if (is_a($res, 'PEAR_Error')) {
$info = array('rcpt' => $rcpt);
return $this->_raiseError('failed_send_data', $info);
}
$this->_smtp->disconnect();
$this->_smtp = null;
}
return true;
} | [
"function",
"send",
"(",
"$",
"recipients",
",",
"$",
"headers",
",",
"$",
"body",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"headers",
")",
")",
"{",
"return",
"PEAR",
"::",
"raiseError",
"(",
"'$headers must be an array'",
")",
";",
"}",
"$",
... | Implements Mail::send() function using SMTP direct delivery
@access public
@param mixed $recipients in RFC822 style or array
@param array $headers The array of headers to send with the mail.
@param string $body The full text of the message body,
@return mixed Returns true on success, or a PEAR_Error | [
"Implements",
"Mail",
"::",
"send",
"()",
"function",
"using",
"SMTP",
"direct",
"delivery"
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/smtpmx.php#L276-L402 |
pear/Mail | Mail/smtpmx.php | Mail_smtpmx._getMx | function _getMx($host)
{
$mx = array();
if ($this->withNetDns) {
$res = $this->_loadNetDns();
if (is_a($res, 'PEAR_Error')) {
return $res;
}
$response = $this->resolver->query($host, 'MX');
if (!$response) {
return false;
}
foreach ($response->answer as $rr) {
if ($rr->type == 'MX') {
$mx[$rr->exchange] = $rr->preference;
}
}
} else {
$mxHost = array();
$mxWeight = array();
if (!getmxrr($host, $mxHost, $mxWeight)) {
return false;
}
for ($i = 0; $i < count($mxHost); ++$i) {
$mx[$mxHost[$i]] = $mxWeight[$i];
}
}
asort($mx);
return $mx;
} | php | function _getMx($host)
{
$mx = array();
if ($this->withNetDns) {
$res = $this->_loadNetDns();
if (is_a($res, 'PEAR_Error')) {
return $res;
}
$response = $this->resolver->query($host, 'MX');
if (!$response) {
return false;
}
foreach ($response->answer as $rr) {
if ($rr->type == 'MX') {
$mx[$rr->exchange] = $rr->preference;
}
}
} else {
$mxHost = array();
$mxWeight = array();
if (!getmxrr($host, $mxHost, $mxWeight)) {
return false;
}
for ($i = 0; $i < count($mxHost); ++$i) {
$mx[$mxHost[$i]] = $mxWeight[$i];
}
}
asort($mx);
return $mx;
} | [
"function",
"_getMx",
"(",
"$",
"host",
")",
"{",
"$",
"mx",
"=",
"array",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"withNetDns",
")",
"{",
"$",
"res",
"=",
"$",
"this",
"->",
"_loadNetDns",
"(",
")",
";",
"if",
"(",
"is_a",
"(",
"$",
"re... | Recieve mx rexords for a spciefied host
The MX records
@access private
@param string $host mail host
@return mixed sorted | [
"Recieve",
"mx",
"rexords",
"for",
"a",
"spciefied",
"host"
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/smtpmx.php#L413-L447 |
pear/Mail | Mail/smtpmx.php | Mail_smtpmx._loadNetDns | function _loadNetDns()
{
if (is_object($this->resolver)) {
return true;
}
if (!include_once 'Net/DNS.php') {
return $this->_raiseError('no_resolver');
}
$this->resolver = new Net_DNS_Resolver();
if ($this->debug) {
$this->resolver->test = 1;
}
return true;
} | php | function _loadNetDns()
{
if (is_object($this->resolver)) {
return true;
}
if (!include_once 'Net/DNS.php') {
return $this->_raiseError('no_resolver');
}
$this->resolver = new Net_DNS_Resolver();
if ($this->debug) {
$this->resolver->test = 1;
}
return true;
} | [
"function",
"_loadNetDns",
"(",
")",
"{",
"if",
"(",
"is_object",
"(",
"$",
"this",
"->",
"resolver",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"!",
"include_once",
"'Net/DNS.php'",
")",
"{",
"return",
"$",
"this",
"->",
"_raiseError",
"(",... | initialize PEAR:Net_DNS_Resolver
@access private
@return boolean true on success | [
"initialize",
"PEAR",
":",
"Net_DNS_Resolver"
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/smtpmx.php#L455-L471 |
pear/Mail | Mail/smtpmx.php | Mail_smtpmx._raiseError | function _raiseError($id, $info = array())
{
$code = $this->errorCode[$id]['code'];
$msg = $this->errorCode[$id]['msg'];
// include info to messages
if (!empty($info)) {
$search = array();
$replace = array();
foreach ($info as $key => $value) {
array_push($search, '{' . strtoupper($key) . '}');
array_push($replace, $value);
}
$msg = str_replace($search, $replace, $msg);
}
return PEAR::raiseError($msg, $code);
} | php | function _raiseError($id, $info = array())
{
$code = $this->errorCode[$id]['code'];
$msg = $this->errorCode[$id]['msg'];
// include info to messages
if (!empty($info)) {
$search = array();
$replace = array();
foreach ($info as $key => $value) {
array_push($search, '{' . strtoupper($key) . '}');
array_push($replace, $value);
}
$msg = str_replace($search, $replace, $msg);
}
return PEAR::raiseError($msg, $code);
} | [
"function",
"_raiseError",
"(",
"$",
"id",
",",
"$",
"info",
"=",
"array",
"(",
")",
")",
"{",
"$",
"code",
"=",
"$",
"this",
"->",
"errorCode",
"[",
"$",
"id",
"]",
"[",
"'code'",
"]",
";",
"$",
"msg",
"=",
"$",
"this",
"->",
"errorCode",
"[",... | raise standardized error
include additional information in error message
@access private
@param string $id maps error ids to codes and message
@param array $info optional information in associative array
@see _errorCode | [
"raise",
"standardized",
"error"
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/smtpmx.php#L483-L502 |
pear/Mail | Mail/sendmail.php | Mail_sendmail.send | public function send($recipients, $headers, $body)
{
if (!is_array($headers)) {
return PEAR::raiseError('$headers must be an array');
}
$result = $this->_sanitizeHeaders($headers);
if (is_a($result, 'PEAR_Error')) {
return $result;
}
$recipients = $this->parseRecipients($recipients);
if (is_a($recipients, 'PEAR_Error')) {
return $recipients;
}
$recipients = implode(' ', array_map('escapeshellarg', $recipients));
$headerElements = $this->prepareHeaders($headers);
if (is_a($headerElements, 'PEAR_Error')) {
return $headerElements;
}
list($from, $text_headers) = $headerElements;
/* Since few MTAs are going to allow this header to be forged
* unless it's in the MAIL FROM: exchange, we'll use
* Return-Path instead of From: if it's set. */
if (!empty($headers['Return-Path'])) {
$from = $headers['Return-Path'];
}
if (!isset($from)) {
return PEAR::raiseError('No from address given.');
} elseif (strpos($from, ' ') !== false ||
strpos($from, ';') !== false ||
strpos($from, '&') !== false ||
strpos($from, '`') !== false) {
return PEAR::raiseError('From address specified with dangerous characters.');
}
$from = escapeshellarg($from); // Security bug #16200
$mail = @popen($this->sendmail_path . (!empty($this->sendmail_args) ? ' ' . $this->sendmail_args : '') . " -f$from -- $recipients", 'w');
if (!$mail) {
return PEAR::raiseError('Failed to open sendmail [' . $this->sendmail_path . '] for execution.');
}
// Write the headers following by two newlines: one to end the headers
// section and a second to separate the headers block from the body.
fputs($mail, $text_headers . $this->sep . $this->sep);
fputs($mail, $body);
$result = pclose($mail);
if (version_compare(phpversion(), '4.2.3') == -1) {
// With older php versions, we need to shift the pclose
// result to get the exit code.
$result = $result >> 8 & 0xFF;
}
if ($result != 0) {
return PEAR::raiseError('sendmail returned error code ' . $result,
$result);
}
return true;
} | php | public function send($recipients, $headers, $body)
{
if (!is_array($headers)) {
return PEAR::raiseError('$headers must be an array');
}
$result = $this->_sanitizeHeaders($headers);
if (is_a($result, 'PEAR_Error')) {
return $result;
}
$recipients = $this->parseRecipients($recipients);
if (is_a($recipients, 'PEAR_Error')) {
return $recipients;
}
$recipients = implode(' ', array_map('escapeshellarg', $recipients));
$headerElements = $this->prepareHeaders($headers);
if (is_a($headerElements, 'PEAR_Error')) {
return $headerElements;
}
list($from, $text_headers) = $headerElements;
/* Since few MTAs are going to allow this header to be forged
* unless it's in the MAIL FROM: exchange, we'll use
* Return-Path instead of From: if it's set. */
if (!empty($headers['Return-Path'])) {
$from = $headers['Return-Path'];
}
if (!isset($from)) {
return PEAR::raiseError('No from address given.');
} elseif (strpos($from, ' ') !== false ||
strpos($from, ';') !== false ||
strpos($from, '&') !== false ||
strpos($from, '`') !== false) {
return PEAR::raiseError('From address specified with dangerous characters.');
}
$from = escapeshellarg($from); // Security bug #16200
$mail = @popen($this->sendmail_path . (!empty($this->sendmail_args) ? ' ' . $this->sendmail_args : '') . " -f$from -- $recipients", 'w');
if (!$mail) {
return PEAR::raiseError('Failed to open sendmail [' . $this->sendmail_path . '] for execution.');
}
// Write the headers following by two newlines: one to end the headers
// section and a second to separate the headers block from the body.
fputs($mail, $text_headers . $this->sep . $this->sep);
fputs($mail, $body);
$result = pclose($mail);
if (version_compare(phpversion(), '4.2.3') == -1) {
// With older php versions, we need to shift the pclose
// result to get the exit code.
$result = $result >> 8 & 0xFF;
}
if ($result != 0) {
return PEAR::raiseError('sendmail returned error code ' . $result,
$result);
}
return true;
} | [
"public",
"function",
"send",
"(",
"$",
"recipients",
",",
"$",
"headers",
",",
"$",
"body",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"headers",
")",
")",
"{",
"return",
"PEAR",
"::",
"raiseError",
"(",
"'$headers must be an array'",
")",
";",
"... | Implements Mail::send() function using the sendmail
command-line binary.
@param mixed $recipients Either a comma-seperated list of recipients
(RFC822 compliant), or an array of recipients,
each RFC822 valid. This may contain recipients not
specified in the headers, for Bcc:, resending
messages, etc.
@param array $headers The array of headers to send with the mail, in an
associative array, where the array key is the
header name (ie, 'Subject'), and the array value
is the header value (ie, 'test'). The header
produced from those values would be 'Subject:
test'.
@param string $body The full text of the message body, including any
Mime parts, etc.
@return mixed Returns true on success, or a PEAR_Error
containing a descriptive error message on
failure. | [
"Implements",
"Mail",
"::",
"send",
"()",
"function",
"using",
"the",
"sendmail",
"command",
"-",
"line",
"binary",
"."
] | train | https://github.com/pear/Mail/blob/c79a855bf8720d4643ef61500b766381c27cc741/Mail/sendmail.php#L133-L197 |
akaunting/money | src/Provider.php | Provider.boot | public function boot()
{
$this->publishes([
__DIR__ . '/Config/money.php' => config_path('money.php'),
], 'money');
Money::setLocale($this->app->make('translator')->getLocale());
Currency::setCurrencies($this->app->make('config')->get('money'));
// Register blade directives
$this->app->afterResolving('blade.compiler', function (BladeCompiler $bladeCompiler) {
$bladeCompiler->directive('money', function ($expression) {
return "<?php echo money($expression); ?>";
});
});
$this->app->afterResolving('blade.compiler', function (BladeCompiler $bladeCompiler) {
$bladeCompiler->directive('currency', function ($expression) {
return "<?php echo currency($expression); ?>";
});
});
} | php | public function boot()
{
$this->publishes([
__DIR__ . '/Config/money.php' => config_path('money.php'),
], 'money');
Money::setLocale($this->app->make('translator')->getLocale());
Currency::setCurrencies($this->app->make('config')->get('money'));
// Register blade directives
$this->app->afterResolving('blade.compiler', function (BladeCompiler $bladeCompiler) {
$bladeCompiler->directive('money', function ($expression) {
return "<?php echo money($expression); ?>";
});
});
$this->app->afterResolving('blade.compiler', function (BladeCompiler $bladeCompiler) {
$bladeCompiler->directive('currency', function ($expression) {
return "<?php echo currency($expression); ?>";
});
});
} | [
"public",
"function",
"boot",
"(",
")",
"{",
"$",
"this",
"->",
"publishes",
"(",
"[",
"__DIR__",
".",
"'/Config/money.php'",
"=>",
"config_path",
"(",
"'money.php'",
")",
",",
"]",
",",
"'money'",
")",
";",
"Money",
"::",
"setLocale",
"(",
"$",
"this",
... | Bootstrap the application services.
@return void | [
"Bootstrap",
"the",
"application",
"services",
"."
] | train | https://github.com/akaunting/money/blob/52d5f3a8d30354dbc07b558263df0560dfa85bf1/src/Provider.php#L15-L36 |
akaunting/money | src/Money.php | Money.parseAmount | protected function parseAmount($amount, $convert = false)
{
$amount = $this->parseAmountFromString($this->parseAmountFromCallable($amount));
if (is_int($amount)) {
return (int) $this->convertAmount($amount, $convert);
}
if (is_float($amount)) {
return (float) round($this->convertAmount($amount, $convert), $this->currency->getPrecision());
}
throw new UnexpectedValueException('Invalid amount "' . $amount . '"');
} | php | protected function parseAmount($amount, $convert = false)
{
$amount = $this->parseAmountFromString($this->parseAmountFromCallable($amount));
if (is_int($amount)) {
return (int) $this->convertAmount($amount, $convert);
}
if (is_float($amount)) {
return (float) round($this->convertAmount($amount, $convert), $this->currency->getPrecision());
}
throw new UnexpectedValueException('Invalid amount "' . $amount . '"');
} | [
"protected",
"function",
"parseAmount",
"(",
"$",
"amount",
",",
"$",
"convert",
"=",
"false",
")",
"{",
"$",
"amount",
"=",
"$",
"this",
"->",
"parseAmountFromString",
"(",
"$",
"this",
"->",
"parseAmountFromCallable",
"(",
"$",
"amount",
")",
")",
";",
... | parseAmount.
@param mixed $amount
@param bool $convert
@throws \UnexpectedValueException
@return int|float | [
"parseAmount",
"."
] | train | https://github.com/akaunting/money/blob/52d5f3a8d30354dbc07b558263df0560dfa85bf1/src/Money.php#L230-L243 |
akaunting/money | src/Money.php | Money.parseAmountFromString | protected function parseAmountFromString($amount)
{
if (!is_string($amount)) {
return $amount;
}
$thousandsSeparator = $this->currency->getThousandsSeparator();
$decimalMark = $this->currency->getDecimalMark();
$amount = str_replace($this->currency->getSymbol(), '', $amount);
$amount = preg_replace('/[^0-9\\' . $thousandsSeparator . '\\' . $decimalMark . '\-\+]/', '', $amount);
$amount = str_replace($this->currency->getThousandsSeparator(), '', $amount);
$amount = str_replace($this->currency->getDecimalMark(), '.', $amount);
if (preg_match('/^([\-\+])?\d+$/', $amount)) {
$amount = (int) $amount;
} elseif (preg_match('/^([\-\+])?\d+\.\d+$/', $amount)) {
$amount = (float) $amount;
}
return $amount;
} | php | protected function parseAmountFromString($amount)
{
if (!is_string($amount)) {
return $amount;
}
$thousandsSeparator = $this->currency->getThousandsSeparator();
$decimalMark = $this->currency->getDecimalMark();
$amount = str_replace($this->currency->getSymbol(), '', $amount);
$amount = preg_replace('/[^0-9\\' . $thousandsSeparator . '\\' . $decimalMark . '\-\+]/', '', $amount);
$amount = str_replace($this->currency->getThousandsSeparator(), '', $amount);
$amount = str_replace($this->currency->getDecimalMark(), '.', $amount);
if (preg_match('/^([\-\+])?\d+$/', $amount)) {
$amount = (int) $amount;
} elseif (preg_match('/^([\-\+])?\d+\.\d+$/', $amount)) {
$amount = (float) $amount;
}
return $amount;
} | [
"protected",
"function",
"parseAmountFromString",
"(",
"$",
"amount",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"amount",
")",
")",
"{",
"return",
"$",
"amount",
";",
"}",
"$",
"thousandsSeparator",
"=",
"$",
"this",
"->",
"currency",
"->",
"getTh... | parseAmountFromString.
@param mixed $amount
@return int|float|mixed | [
"parseAmountFromString",
"."
] | train | https://github.com/akaunting/money/blob/52d5f3a8d30354dbc07b558263df0560dfa85bf1/src/Money.php#L268-L289 |
akaunting/money | src/Money.php | Money.convertAmount | protected function convertAmount($amount, $convert = false)
{
if (!$convert) {
return $amount;
}
return $amount * $this->currency->getSubunit();
} | php | protected function convertAmount($amount, $convert = false)
{
if (!$convert) {
return $amount;
}
return $amount * $this->currency->getSubunit();
} | [
"protected",
"function",
"convertAmount",
"(",
"$",
"amount",
",",
"$",
"convert",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"$",
"convert",
")",
"{",
"return",
"$",
"amount",
";",
"}",
"return",
"$",
"amount",
"*",
"$",
"this",
"->",
"currency",
"->",... | convertAmount.
@param int|float $amount
@param bool $convert
@return int|float | [
"convertAmount",
"."
] | train | https://github.com/akaunting/money/blob/52d5f3a8d30354dbc07b558263df0560dfa85bf1/src/Money.php#L299-L306 |
akaunting/money | src/Money.php | Money.assertSameCurrency | protected function assertSameCurrency(self $other)
{
if (!$this->isSameCurrency($other)) {
throw new InvalidArgumentException('Different currencies "' . $this->currency . '" and "' . $other->currency . '"');
}
} | php | protected function assertSameCurrency(self $other)
{
if (!$this->isSameCurrency($other)) {
throw new InvalidArgumentException('Different currencies "' . $this->currency . '" and "' . $other->currency . '"');
}
} | [
"protected",
"function",
"assertSameCurrency",
"(",
"self",
"$",
"other",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isSameCurrency",
"(",
"$",
"other",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Different currencies \"'",
".",
"$",
... | assertSameCurrency.
@param \Akaunting\Money\Money $other
@throws \InvalidArgumentException | [
"assertSameCurrency",
"."
] | train | https://github.com/akaunting/money/blob/52d5f3a8d30354dbc07b558263df0560dfa85bf1/src/Money.php#L356-L361 |
akaunting/money | src/Money.php | Money.assertRoundingMode | protected function assertRoundingMode($roundingMode)
{
$roundingModes = [self::ROUND_HALF_DOWN, self::ROUND_HALF_EVEN, self::ROUND_HALF_ODD, self::ROUND_HALF_UP];
if (!in_array($roundingMode, $roundingModes)) {
throw new OutOfBoundsException('Rounding mode should be ' . implode(' | ', $roundingModes));
}
} | php | protected function assertRoundingMode($roundingMode)
{
$roundingModes = [self::ROUND_HALF_DOWN, self::ROUND_HALF_EVEN, self::ROUND_HALF_ODD, self::ROUND_HALF_UP];
if (!in_array($roundingMode, $roundingModes)) {
throw new OutOfBoundsException('Rounding mode should be ' . implode(' | ', $roundingModes));
}
} | [
"protected",
"function",
"assertRoundingMode",
"(",
"$",
"roundingMode",
")",
"{",
"$",
"roundingModes",
"=",
"[",
"self",
"::",
"ROUND_HALF_DOWN",
",",
"self",
"::",
"ROUND_HALF_EVEN",
",",
"self",
"::",
"ROUND_HALF_ODD",
",",
"self",
"::",
"ROUND_HALF_UP",
"]"... | assertRoundingMode.
@param int $roundingMode
@throws \OutOfBoundsException | [
"assertRoundingMode",
"."
] | train | https://github.com/akaunting/money/blob/52d5f3a8d30354dbc07b558263df0560dfa85bf1/src/Money.php#L384-L391 |
akaunting/money | src/Money.php | Money.getValue | public function getValue()
{
return round($this->amount / $this->currency->getSubunit(), $this->currency->getPrecision());
} | php | public function getValue()
{
return round($this->amount / $this->currency->getSubunit(), $this->currency->getPrecision());
} | [
"public",
"function",
"getValue",
"(",
")",
"{",
"return",
"round",
"(",
"$",
"this",
"->",
"amount",
"/",
"$",
"this",
"->",
"currency",
"->",
"getSubunit",
"(",
")",
",",
"$",
"this",
"->",
"currency",
"->",
"getPrecision",
"(",
")",
")",
";",
"}"
... | getValue.
@return float | [
"getValue",
"."
] | train | https://github.com/akaunting/money/blob/52d5f3a8d30354dbc07b558263df0560dfa85bf1/src/Money.php#L408-L411 |
akaunting/money | src/Money.php | Money.compare | public function compare(self $other)
{
$this->assertSameCurrency($other);
if ($this->amount < $other->amount) {
return -1;
}
if ($this->amount > $other->amount) {
return 1;
}
return 0;
} | php | public function compare(self $other)
{
$this->assertSameCurrency($other);
if ($this->amount < $other->amount) {
return -1;
}
if ($this->amount > $other->amount) {
return 1;
}
return 0;
} | [
"public",
"function",
"compare",
"(",
"self",
"$",
"other",
")",
"{",
"$",
"this",
"->",
"assertSameCurrency",
"(",
"$",
"other",
")",
";",
"if",
"(",
"$",
"this",
"->",
"amount",
"<",
"$",
"other",
"->",
"amount",
")",
"{",
"return",
"-",
"1",
";"... | compare.
@param \Akaunting\Money\Money $other
@throws \InvalidArgumentException
@return int | [
"compare",
"."
] | train | https://github.com/akaunting/money/blob/52d5f3a8d30354dbc07b558263df0560dfa85bf1/src/Money.php#L444-L457 |
akaunting/money | src/Money.php | Money.convert | public function convert(Currency $currency, $ratio, $roundingMode = self::ROUND_HALF_UP)
{
$this->currency = $currency;
$this->assertOperand($ratio);
$this->assertRoundingMode($roundingMode);
if ($ratio < 1) {
return $this->divide($ratio, $roundingMode);
}
return $this->multiply($ratio, $roundingMode);
} | php | public function convert(Currency $currency, $ratio, $roundingMode = self::ROUND_HALF_UP)
{
$this->currency = $currency;
$this->assertOperand($ratio);
$this->assertRoundingMode($roundingMode);
if ($ratio < 1) {
return $this->divide($ratio, $roundingMode);
}
return $this->multiply($ratio, $roundingMode);
} | [
"public",
"function",
"convert",
"(",
"Currency",
"$",
"currency",
",",
"$",
"ratio",
",",
"$",
"roundingMode",
"=",
"self",
"::",
"ROUND_HALF_UP",
")",
"{",
"$",
"this",
"->",
"currency",
"=",
"$",
"currency",
";",
"$",
"this",
"->",
"assertOperand",
"(... | convert.
@param \Akaunting\Money\Currency $currency
@param int|float $ratio
@param int $roundingMode
@throws \InvalidArgumentException
@throws \OutOfBoundsException
@return \Akaunting\Money\Money | [
"convert",
"."
] | train | https://github.com/akaunting/money/blob/52d5f3a8d30354dbc07b558263df0560dfa85bf1/src/Money.php#L531-L543 |
akaunting/money | src/Money.php | Money.add | public function add(self $addend)
{
$this->assertSameCurrency($addend);
return new self($this->amount + $addend->amount, $this->currency);
} | php | public function add(self $addend)
{
$this->assertSameCurrency($addend);
return new self($this->amount + $addend->amount, $this->currency);
} | [
"public",
"function",
"add",
"(",
"self",
"$",
"addend",
")",
"{",
"$",
"this",
"->",
"assertSameCurrency",
"(",
"$",
"addend",
")",
";",
"return",
"new",
"self",
"(",
"$",
"this",
"->",
"amount",
"+",
"$",
"addend",
"->",
"amount",
",",
"$",
"this",... | add.
@param \Akaunting\Money\Money $addend
@throws \InvalidArgumentException
@return \Akaunting\Money\Money | [
"add",
"."
] | train | https://github.com/akaunting/money/blob/52d5f3a8d30354dbc07b558263df0560dfa85bf1/src/Money.php#L554-L559 |
akaunting/money | src/Money.php | Money.subtract | public function subtract(self $subtrahend)
{
$this->assertSameCurrency($subtrahend);
return new self($this->amount - $subtrahend->amount, $this->currency);
} | php | public function subtract(self $subtrahend)
{
$this->assertSameCurrency($subtrahend);
return new self($this->amount - $subtrahend->amount, $this->currency);
} | [
"public",
"function",
"subtract",
"(",
"self",
"$",
"subtrahend",
")",
"{",
"$",
"this",
"->",
"assertSameCurrency",
"(",
"$",
"subtrahend",
")",
";",
"return",
"new",
"self",
"(",
"$",
"this",
"->",
"amount",
"-",
"$",
"subtrahend",
"->",
"amount",
",",... | subtract.
@param \Akaunting\Money\Money $subtrahend
@throws \InvalidArgumentException
@return \Akaunting\Money\Money | [
"subtract",
"."
] | train | https://github.com/akaunting/money/blob/52d5f3a8d30354dbc07b558263df0560dfa85bf1/src/Money.php#L570-L575 |
akaunting/money | src/Money.php | Money.multiply | public function multiply($multiplier, $roundingMode = self::ROUND_HALF_UP)
{
return new self(round($this->amount * $multiplier, $this->currency->getPrecision(), $roundingMode), $this->currency);
} | php | public function multiply($multiplier, $roundingMode = self::ROUND_HALF_UP)
{
return new self(round($this->amount * $multiplier, $this->currency->getPrecision(), $roundingMode), $this->currency);
} | [
"public",
"function",
"multiply",
"(",
"$",
"multiplier",
",",
"$",
"roundingMode",
"=",
"self",
"::",
"ROUND_HALF_UP",
")",
"{",
"return",
"new",
"self",
"(",
"round",
"(",
"$",
"this",
"->",
"amount",
"*",
"$",
"multiplier",
",",
"$",
"this",
"->",
"... | multiply.
@param int|float $multiplier
@param int $roundingMode
@throws \InvalidArgumentException
@throws \OutOfBoundsException
@return \Akaunting\Money\Money | [
"multiply",
"."
] | train | https://github.com/akaunting/money/blob/52d5f3a8d30354dbc07b558263df0560dfa85bf1/src/Money.php#L588-L591 |
akaunting/money | src/Money.php | Money.divide | public function divide($divisor, $roundingMode = self::ROUND_HALF_UP)
{
$this->assertOperand($divisor);
$this->assertRoundingMode($roundingMode);
if ($divisor == 0) {
throw new InvalidArgumentException('Division by zero');
}
return new self(round($this->amount / $divisor, $this->currency->getPrecision(), $roundingMode), $this->currency);
} | php | public function divide($divisor, $roundingMode = self::ROUND_HALF_UP)
{
$this->assertOperand($divisor);
$this->assertRoundingMode($roundingMode);
if ($divisor == 0) {
throw new InvalidArgumentException('Division by zero');
}
return new self(round($this->amount / $divisor, $this->currency->getPrecision(), $roundingMode), $this->currency);
} | [
"public",
"function",
"divide",
"(",
"$",
"divisor",
",",
"$",
"roundingMode",
"=",
"self",
"::",
"ROUND_HALF_UP",
")",
"{",
"$",
"this",
"->",
"assertOperand",
"(",
"$",
"divisor",
")",
";",
"$",
"this",
"->",
"assertRoundingMode",
"(",
"$",
"roundingMode... | divide.
@param int|float $divisor
@param int $roundingMode
@throws \InvalidArgumentException
@throws \OutOfBoundsException
@return \Akaunting\Money\Money | [
"divide",
"."
] | train | https://github.com/akaunting/money/blob/52d5f3a8d30354dbc07b558263df0560dfa85bf1/src/Money.php#L604-L614 |
akaunting/money | src/Money.php | Money.allocate | public function allocate(array $ratios)
{
$remainder = $this->amount;
$results = [];
$total = array_sum($ratios);
foreach ($ratios as $ratio) {
$share = floor($this->amount * $ratio / $total);
$results[] = new self($share, $this->currency);
$remainder -= $share;
}
for ($i = 0; $remainder > 0; $i++) {
$results[$i]->amount++;
$remainder--;
}
return $results;
} | php | public function allocate(array $ratios)
{
$remainder = $this->amount;
$results = [];
$total = array_sum($ratios);
foreach ($ratios as $ratio) {
$share = floor($this->amount * $ratio / $total);
$results[] = new self($share, $this->currency);
$remainder -= $share;
}
for ($i = 0; $remainder > 0; $i++) {
$results[$i]->amount++;
$remainder--;
}
return $results;
} | [
"public",
"function",
"allocate",
"(",
"array",
"$",
"ratios",
")",
"{",
"$",
"remainder",
"=",
"$",
"this",
"->",
"amount",
";",
"$",
"results",
"=",
"[",
"]",
";",
"$",
"total",
"=",
"array_sum",
"(",
"$",
"ratios",
")",
";",
"foreach",
"(",
"$",... | allocate.
@param array $ratios
@return array | [
"allocate",
"."
] | train | https://github.com/akaunting/money/blob/52d5f3a8d30354dbc07b558263df0560dfa85bf1/src/Money.php#L623-L641 |
akaunting/money | src/Money.php | Money.formatLocale | public function formatLocale($locale = null, Closure $callback = null)
{
if (!class_exists('\NumberFormatter')) {
throw new BadFunctionCallException('Class NumberFormatter not exists. Require ext-intl extension.');
}
$formatter = new \NumberFormatter($locale ?: static::getLocale(), \NumberFormatter::CURRENCY);
if (is_callable($callback)) {
$callback($formatter);
}
return $formatter->formatCurrency($this->getValue(), $this->currency->getCurrency());
} | php | public function formatLocale($locale = null, Closure $callback = null)
{
if (!class_exists('\NumberFormatter')) {
throw new BadFunctionCallException('Class NumberFormatter not exists. Require ext-intl extension.');
}
$formatter = new \NumberFormatter($locale ?: static::getLocale(), \NumberFormatter::CURRENCY);
if (is_callable($callback)) {
$callback($formatter);
}
return $formatter->formatCurrency($this->getValue(), $this->currency->getCurrency());
} | [
"public",
"function",
"formatLocale",
"(",
"$",
"locale",
"=",
"null",
",",
"Closure",
"$",
"callback",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"class_exists",
"(",
"'\\NumberFormatter'",
")",
")",
"{",
"throw",
"new",
"BadFunctionCallException",
"(",
"'Class... | formatLocale.
@param string $locale
@param Closure $callback
@throws \BadFunctionCallException
@return string | [
"formatLocale",
"."
] | train | https://github.com/akaunting/money/blob/52d5f3a8d30354dbc07b558263df0560dfa85bf1/src/Money.php#L683-L696 |
akaunting/money | src/Money.php | Money.formatSimple | public function formatSimple()
{
return number_format(
$this->getValue(),
$this->currency->getPrecision(),
$this->currency->getDecimalMark(),
$this->currency->getThousandsSeparator()
);
} | php | public function formatSimple()
{
return number_format(
$this->getValue(),
$this->currency->getPrecision(),
$this->currency->getDecimalMark(),
$this->currency->getThousandsSeparator()
);
} | [
"public",
"function",
"formatSimple",
"(",
")",
"{",
"return",
"number_format",
"(",
"$",
"this",
"->",
"getValue",
"(",
")",
",",
"$",
"this",
"->",
"currency",
"->",
"getPrecision",
"(",
")",
",",
"$",
"this",
"->",
"currency",
"->",
"getDecimalMark",
... | formatSimple.
@return string | [
"formatSimple",
"."
] | train | https://github.com/akaunting/money/blob/52d5f3a8d30354dbc07b558263df0560dfa85bf1/src/Money.php#L703-L711 |
akaunting/money | src/Money.php | Money.format | public function format()
{
$negative = $this->isNegative();
$value = $this->getValue();
$amount = $negative ? -$value : $value;
$thousands = $this->currency->getThousandsSeparator();
$decimals = $this->currency->getDecimalMark();
$prefix = $this->currency->getPrefix();
$suffix = $this->currency->getSuffix();
$value = number_format($amount, $this->currency->getPrecision(), $decimals, $thousands);
return ($negative ? '-' : '') . $prefix . $value . $suffix;
} | php | public function format()
{
$negative = $this->isNegative();
$value = $this->getValue();
$amount = $negative ? -$value : $value;
$thousands = $this->currency->getThousandsSeparator();
$decimals = $this->currency->getDecimalMark();
$prefix = $this->currency->getPrefix();
$suffix = $this->currency->getSuffix();
$value = number_format($amount, $this->currency->getPrecision(), $decimals, $thousands);
return ($negative ? '-' : '') . $prefix . $value . $suffix;
} | [
"public",
"function",
"format",
"(",
")",
"{",
"$",
"negative",
"=",
"$",
"this",
"->",
"isNegative",
"(",
")",
";",
"$",
"value",
"=",
"$",
"this",
"->",
"getValue",
"(",
")",
";",
"$",
"amount",
"=",
"$",
"negative",
"?",
"-",
"$",
"value",
":"... | format.
@return string | [
"format",
"."
] | train | https://github.com/akaunting/money/blob/52d5f3a8d30354dbc07b558263df0560dfa85bf1/src/Money.php#L718-L730 |
akaunting/money | src/Currency.php | Currency.toArray | public function toArray()
{
return [$this->currency => [
'name' => $this->name,
'code' => $this->code,
'precision' => $this->precision,
'subunit' => $this->subunit,
'symbol' => $this->symbol,
'symbol_first' => $this->symbolFirst,
'decimal_mark' => $this->decimalMark,
'thousands_separator' => $this->thousandsSeparator,
'prefix' => $this->getPrefix(),
'suffix' => $this->getSuffix(),
]];
} | php | public function toArray()
{
return [$this->currency => [
'name' => $this->name,
'code' => $this->code,
'precision' => $this->precision,
'subunit' => $this->subunit,
'symbol' => $this->symbol,
'symbol_first' => $this->symbolFirst,
'decimal_mark' => $this->decimalMark,
'thousands_separator' => $this->thousandsSeparator,
'prefix' => $this->getPrefix(),
'suffix' => $this->getSuffix(),
]];
} | [
"public",
"function",
"toArray",
"(",
")",
"{",
"return",
"[",
"$",
"this",
"->",
"currency",
"=>",
"[",
"'name'",
"=>",
"$",
"this",
"->",
"name",
",",
"'code'",
"=>",
"$",
"this",
"->",
"code",
",",
"'precision'",
"=>",
"$",
"this",
"->",
"precisio... | Get the instance as an array.
@return array | [
"Get",
"the",
"instance",
"as",
"an",
"array",
"."
] | train | https://github.com/akaunting/money/blob/52d5f3a8d30354dbc07b558263df0560dfa85bf1/src/Currency.php#L433-L447 |
Philipp15b/php-i18n | i18n.class.php | i18n.getUserLangs | public function getUserLangs() {
$userLangs = array();
// Highest priority: forced language
if ($this->forcedLang != NULL) {
$userLangs[] = $this->forcedLang;
}
// 2nd highest priority: GET parameter 'lang'
if (isset($_GET['lang']) && is_string($_GET['lang'])) {
$userLangs[] = $_GET['lang'];
}
// 3rd highest priority: SESSION parameter 'lang'
if (isset($_SESSION['lang']) && is_string($_SESSION['lang'])) {
$userLangs[] = $_SESSION['lang'];
}
// 4th highest priority: HTTP_ACCEPT_LANGUAGE
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $part) {
$userLangs[] = strtolower(substr($part, 0, 2));
}
}
// Lowest priority: fallback
$userLangs[] = $this->fallbackLang;
// remove duplicate elements
$userLangs = array_unique($userLangs);
// remove illegal userLangs
$userLangs2 = array();
foreach ($userLangs as $key => $value) {
// only allow a-z, A-Z and 0-9 and _ and -
if (preg_match('/^[a-zA-Z0-9_-]*$/', $value) === 1)
$userLangs2[$key] = $value;
}
return $userLangs2;
} | php | public function getUserLangs() {
$userLangs = array();
// Highest priority: forced language
if ($this->forcedLang != NULL) {
$userLangs[] = $this->forcedLang;
}
// 2nd highest priority: GET parameter 'lang'
if (isset($_GET['lang']) && is_string($_GET['lang'])) {
$userLangs[] = $_GET['lang'];
}
// 3rd highest priority: SESSION parameter 'lang'
if (isset($_SESSION['lang']) && is_string($_SESSION['lang'])) {
$userLangs[] = $_SESSION['lang'];
}
// 4th highest priority: HTTP_ACCEPT_LANGUAGE
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $part) {
$userLangs[] = strtolower(substr($part, 0, 2));
}
}
// Lowest priority: fallback
$userLangs[] = $this->fallbackLang;
// remove duplicate elements
$userLangs = array_unique($userLangs);
// remove illegal userLangs
$userLangs2 = array();
foreach ($userLangs as $key => $value) {
// only allow a-z, A-Z and 0-9 and _ and -
if (preg_match('/^[a-zA-Z0-9_-]*$/', $value) === 1)
$userLangs2[$key] = $value;
}
return $userLangs2;
} | [
"public",
"function",
"getUserLangs",
"(",
")",
"{",
"$",
"userLangs",
"=",
"array",
"(",
")",
";",
"// Highest priority: forced language",
"if",
"(",
"$",
"this",
"->",
"forcedLang",
"!=",
"NULL",
")",
"{",
"$",
"userLangs",
"[",
"]",
"=",
"$",
"this",
... | getUserLangs()
Returns the user languages
Normally it returns an array like this:
1. Forced language
2. Language in $_GET['lang']
3. Language in $_SESSION['lang']
4. HTTP_ACCEPT_LANGUAGE
5. Fallback language
Note: duplicate values are deleted.
@return array with the user languages sorted by priority. | [
"getUserLangs",
"()",
"Returns",
"the",
"user",
"languages",
"Normally",
"it",
"returns",
"an",
"array",
"like",
"this",
":",
"1",
".",
"Forced",
"language",
"2",
".",
"Language",
"in",
"$_GET",
"[",
"lang",
"]",
"3",
".",
"Language",
"in",
"$_SESSION",
... | train | https://github.com/Philipp15b/php-i18n/blob/1f3e7bc4a060a135d1a1e8fe0e7fc5a3ec435e03/i18n.class.php#L249-L289 |
Philipp15b/php-i18n | i18n.class.php | i18n.compile | protected function compile($config, $prefix = '') {
$code = '';
foreach ($config as $key => $value) {
if (is_array($value)) {
$code .= $this->compile($value, $prefix . $key . $this->sectionSeparator);
} else {
$fullName = $prefix . $key;
if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $fullName)) {
throw new InvalidArgumentException(__CLASS__ . ": Cannot compile translation key " . $fullName . " because it is not a valid PHP identifier.");
}
$code .= 'const ' . $fullName . ' = \'' . str_replace('\'', '\\\'', $value) . "';\n";
}
}
return $code;
} | php | protected function compile($config, $prefix = '') {
$code = '';
foreach ($config as $key => $value) {
if (is_array($value)) {
$code .= $this->compile($value, $prefix . $key . $this->sectionSeparator);
} else {
$fullName = $prefix . $key;
if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $fullName)) {
throw new InvalidArgumentException(__CLASS__ . ": Cannot compile translation key " . $fullName . " because it is not a valid PHP identifier.");
}
$code .= 'const ' . $fullName . ' = \'' . str_replace('\'', '\\\'', $value) . "';\n";
}
}
return $code;
} | [
"protected",
"function",
"compile",
"(",
"$",
"config",
",",
"$",
"prefix",
"=",
"''",
")",
"{",
"$",
"code",
"=",
"''",
";",
"foreach",
"(",
"$",
"config",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"value",... | Recursively compile an associative array to PHP code. | [
"Recursively",
"compile",
"an",
"associative",
"array",
"to",
"PHP",
"code",
"."
] | train | https://github.com/Philipp15b/php-i18n/blob/1f3e7bc4a060a135d1a1e8fe0e7fc5a3ec435e03/i18n.class.php#L318-L332 |
wp-cli/cache-command | src/Transient_Command.php | Transient_Command.get | public function get( $args, $assoc_args ) {
list( $key ) = $args;
$func = Utils\get_flag_value( $assoc_args, 'network' ) ? 'get_site_transient' : 'get_transient';
$value = $func( $key );
if ( false === $value ) {
WP_CLI::warning( 'Transient with key "' . $key . '" is not set.' );
exit;
}
WP_CLI::print_value( $value, $assoc_args );
} | php | public function get( $args, $assoc_args ) {
list( $key ) = $args;
$func = Utils\get_flag_value( $assoc_args, 'network' ) ? 'get_site_transient' : 'get_transient';
$value = $func( $key );
if ( false === $value ) {
WP_CLI::warning( 'Transient with key "' . $key . '" is not set.' );
exit;
}
WP_CLI::print_value( $value, $assoc_args );
} | [
"public",
"function",
"get",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"list",
"(",
"$",
"key",
")",
"=",
"$",
"args",
";",
"$",
"func",
"=",
"Utils",
"\\",
"get_flag_value",
"(",
"$",
"assoc_args",
",",
"'network'",
")",
"?",
"'get_site_tr... | Gets a transient value.
For a more complete explanation of the transient cache, including the
network|site cache, please see docs for `wp transient`.
## OPTIONS
<key>
: Key for the transient.
[--format=<format>]
: Render output in a particular format.
---
default: table
options:
- table
- csv
- json
- yaml
---
[--network]
: Get the value of a network|site transient. On single site, this is
is a specially-named cache key. On multisite, this is a global cache
(instead of local to the site).
## EXAMPLES
$ wp transient get sample_key
test data
$ wp transient get random_key
Warning: Transient with key "random_key" is not set. | [
"Gets",
"a",
"transient",
"value",
"."
] | train | https://github.com/wp-cli/cache-command/blob/56e2a8186c28bc1edbb8bc1c0f3d3b30fa116ea8/src/Transient_Command.php#L76-L88 |
wp-cli/cache-command | src/Transient_Command.php | Transient_Command.set | public function set( $args, $assoc_args ) {
list( $key, $value ) = $args;
$expiration = Utils\get_flag_value( $args, 2, 0 );
$func = Utils\get_flag_value( $assoc_args, 'network' ) ? 'set_site_transient' : 'set_transient';
if ( $func( $key, $value, $expiration ) ) {
WP_CLI::success( 'Transient added.' );
} else {
WP_CLI::error( 'Transient could not be set.' );
}
} | php | public function set( $args, $assoc_args ) {
list( $key, $value ) = $args;
$expiration = Utils\get_flag_value( $args, 2, 0 );
$func = Utils\get_flag_value( $assoc_args, 'network' ) ? 'set_site_transient' : 'set_transient';
if ( $func( $key, $value, $expiration ) ) {
WP_CLI::success( 'Transient added.' );
} else {
WP_CLI::error( 'Transient could not be set.' );
}
} | [
"public",
"function",
"set",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"list",
"(",
"$",
"key",
",",
"$",
"value",
")",
"=",
"$",
"args",
";",
"$",
"expiration",
"=",
"Utils",
"\\",
"get_flag_value",
"(",
"$",
"args",
",",
"2",
",",
"0"... | Sets a transient value.
`<expiration>` is the time until expiration, in seconds.
For a more complete explanation of the transient cache, including the
network|site cache, please see docs for `wp transient`.
## OPTIONS
<key>
: Key for the transient.
<value>
: Value to be set for the transient.
[<expiration>]
: Time until expiration, in seconds.
[--network]
: Set the value of a network|site transient. On single site, this is
is a specially-named cache key. On multisite, this is a global cache
(instead of local to the site).
## EXAMPLES
$ wp transient set sample_key "test data" 3600
Success: Transient added. | [
"Sets",
"a",
"transient",
"value",
"."
] | train | https://github.com/wp-cli/cache-command/blob/56e2a8186c28bc1edbb8bc1c0f3d3b30fa116ea8/src/Transient_Command.php#L119-L130 |
wp-cli/cache-command | src/Transient_Command.php | Transient_Command.delete | public function delete( $args, $assoc_args ) {
$key = ( ! empty( $args ) ) ? $args[0] : null;
$all = Utils\get_flag_value( $assoc_args, 'all' );
$expired = Utils\get_flag_value( $assoc_args, 'expired' );
$network = Utils\get_flag_value( $assoc_args, 'network' );
if ( true === $all ) {
$this->delete_all( $network );
return;
} elseif ( true === $expired ) {
$this->delete_expired( $network );
return;
}
if ( ! $key ) {
WP_CLI::error( 'Please specify transient key, or use --all or --expired.' );
}
$func = $network ? 'delete_site_transient' : 'delete_transient';
if ( $func( $key ) ) {
WP_CLI::success( 'Transient deleted.' );
} else {
$func = Utils\get_flag_value( $assoc_args, 'network' ) ? 'get_site_transient' : 'get_transient';
if ( $func( $key ) ) {
WP_CLI::error( 'Transient was not deleted even though the transient appears to exist.' );
} else {
WP_CLI::warning( 'Transient was not deleted; however, the transient does not appear to exist.' );
}
}
} | php | public function delete( $args, $assoc_args ) {
$key = ( ! empty( $args ) ) ? $args[0] : null;
$all = Utils\get_flag_value( $assoc_args, 'all' );
$expired = Utils\get_flag_value( $assoc_args, 'expired' );
$network = Utils\get_flag_value( $assoc_args, 'network' );
if ( true === $all ) {
$this->delete_all( $network );
return;
} elseif ( true === $expired ) {
$this->delete_expired( $network );
return;
}
if ( ! $key ) {
WP_CLI::error( 'Please specify transient key, or use --all or --expired.' );
}
$func = $network ? 'delete_site_transient' : 'delete_transient';
if ( $func( $key ) ) {
WP_CLI::success( 'Transient deleted.' );
} else {
$func = Utils\get_flag_value( $assoc_args, 'network' ) ? 'get_site_transient' : 'get_transient';
if ( $func( $key ) ) {
WP_CLI::error( 'Transient was not deleted even though the transient appears to exist.' );
} else {
WP_CLI::warning( 'Transient was not deleted; however, the transient does not appear to exist.' );
}
}
} | [
"public",
"function",
"delete",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"$",
"key",
"=",
"(",
"!",
"empty",
"(",
"$",
"args",
")",
")",
"?",
"$",
"args",
"[",
"0",
"]",
":",
"null",
";",
"$",
"all",
"=",
"Utils",
"\\",
"get_flag_val... | Deletes a transient value.
For a more complete explanation of the transient cache, including the
network|site cache, please see docs for `wp transient`.
## OPTIONS
[<key>]
: Key for the transient.
[--network]
: Delete the value of a network|site transient. On single site, this is
is a specially-named cache key. On multisite, this is a global cache
(instead of local to the site).
[--all]
: Delete all transients.
[--expired]
: Delete all expired transients.
## EXAMPLES
# Delete transient.
$ wp transient delete sample_key
Success: Transient deleted.
# Delete expired transients.
$ wp transient delete --expired
Success: 12 expired transients deleted from the database.
# Delete expired site transients.
$ wp transient delete --expired --network
Success: 1 expired transient deleted from the database.
# Delete all transients.
$ wp transient delete --all
Success: 14 transients deleted from the database.
# Delete all site transients.
$ wp transient delete --all --network
Success: 2 transients deleted from the database.
# Delete all transients in a multsite.
$ wp transient delete --all --network && wp site list --field=url | xargs -n1 -I % wp --url=% transient delete --all | [
"Deletes",
"a",
"transient",
"value",
"."
] | train | https://github.com/wp-cli/cache-command/blob/56e2a8186c28bc1edbb8bc1c0f3d3b30fa116ea8/src/Transient_Command.php#L179-L210 |
wp-cli/cache-command | src/Transient_Command.php | Transient_Command.list_ | public function list_( $args, $assoc_args ) {
global $wpdb;
$network = Utils\get_flag_value( $assoc_args, 'network', false );
$unserialize = Utils\get_flag_value( $assoc_args, 'unserialize', false );
$human_readable = Utils\get_flag_value( $assoc_args, 'human-readable', false );
$fields = array( 'name', 'value', 'expiration' );
if ( isset( $assoc_args['fields'] ) ) {
$fields = explode( ',', $assoc_args['fields'] );
}
$pattern = '%';
$exclude = '';
if ( isset( $assoc_args['search'] ) ) {
$pattern = Utils\esc_like( $assoc_args['search'] );
// Substitute wildcards.
$pattern = str_replace(
array( '*', '?' ),
array( '%', '_' ),
$pattern
);
}
if ( isset( $assoc_args['exclude'] ) ) {
$exclude = Utils\esc_like( $assoc_args['exclude'] );
// Substitute wildcards.
$exclude = str_replace(
array( '*', '?' ),
array( '%', '_' ),
$exclude
);
}
if ( $network ) {
if ( is_multisite() ) {
$where = $wpdb->prepare(
'WHERE `meta_key` LIKE %s',
Utils\esc_like( '_site_transient_' ) . $pattern
);
$where .= $wpdb->prepare(
' AND meta_key NOT LIKE %s',
Utils\esc_like( '_site_transient_timeout_' ) . '%'
);
if ( $exclude ) {
$where .= $wpdb->prepare(
' AND meta_key NOT LIKE %s',
Utils\esc_like( '_site_transient_' ) . $exclude
);
}
$query = "SELECT `meta_key` as `name`, `meta_value` as `value` FROM {$wpdb->sitemeta} {$where}";
} else {
$where = $wpdb->prepare(
'WHERE `option_name` LIKE %s',
Utils\esc_like( '_site_transient_' ) . $pattern
);
$where .= $wpdb->prepare(
' AND option_name NOT LIKE %s',
Utils\esc_like( '_site_transient_timeout_' ) . '%'
);
if ( $exclude ) {
$where .= $wpdb->prepare(
' AND option_name NOT LIKE %s',
Utils\esc_like( '_site_transient_' ) . $exclude
);
}
$query = "SELECT `option_name` as `name`, `option_value` as `value` FROM {$wpdb->options} {$where}";
}
} else {
$where = $wpdb->prepare(
'WHERE `option_name` LIKE %s',
Utils\esc_like( '_transient_' ) . $pattern
);
$where .= $wpdb->prepare(
' AND option_name NOT LIKE %s',
Utils\esc_like( '_transient_timeout_' ) . '%'
);
if ( $exclude ) {
$where .= $wpdb->prepare(
' AND option_name NOT LIKE %s',
Utils\esc_like( '_transient_' ) . $exclude
);
}
$query = "SELECT `option_name` as `name`, `option_value` as `value` FROM {$wpdb->options} {$where}";
}
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Prepared properly above.
$results = $wpdb->get_results( $query );
foreach ( $results as $result ) {
$result->name = str_replace( array( '_site_transient_', '_transient_' ), '', $result->name );
$result->expiration = $this->get_transient_expiration( $result->name, $network, $human_readable );
if ( $unserialize ) {
$result->value = maybe_unserialize( $result->value );
}
}
$formatter = new \WP_CLI\Formatter(
$assoc_args,
$fields
);
$formatter->display_items( $results );
} | php | public function list_( $args, $assoc_args ) {
global $wpdb;
$network = Utils\get_flag_value( $assoc_args, 'network', false );
$unserialize = Utils\get_flag_value( $assoc_args, 'unserialize', false );
$human_readable = Utils\get_flag_value( $assoc_args, 'human-readable', false );
$fields = array( 'name', 'value', 'expiration' );
if ( isset( $assoc_args['fields'] ) ) {
$fields = explode( ',', $assoc_args['fields'] );
}
$pattern = '%';
$exclude = '';
if ( isset( $assoc_args['search'] ) ) {
$pattern = Utils\esc_like( $assoc_args['search'] );
// Substitute wildcards.
$pattern = str_replace(
array( '*', '?' ),
array( '%', '_' ),
$pattern
);
}
if ( isset( $assoc_args['exclude'] ) ) {
$exclude = Utils\esc_like( $assoc_args['exclude'] );
// Substitute wildcards.
$exclude = str_replace(
array( '*', '?' ),
array( '%', '_' ),
$exclude
);
}
if ( $network ) {
if ( is_multisite() ) {
$where = $wpdb->prepare(
'WHERE `meta_key` LIKE %s',
Utils\esc_like( '_site_transient_' ) . $pattern
);
$where .= $wpdb->prepare(
' AND meta_key NOT LIKE %s',
Utils\esc_like( '_site_transient_timeout_' ) . '%'
);
if ( $exclude ) {
$where .= $wpdb->prepare(
' AND meta_key NOT LIKE %s',
Utils\esc_like( '_site_transient_' ) . $exclude
);
}
$query = "SELECT `meta_key` as `name`, `meta_value` as `value` FROM {$wpdb->sitemeta} {$where}";
} else {
$where = $wpdb->prepare(
'WHERE `option_name` LIKE %s',
Utils\esc_like( '_site_transient_' ) . $pattern
);
$where .= $wpdb->prepare(
' AND option_name NOT LIKE %s',
Utils\esc_like( '_site_transient_timeout_' ) . '%'
);
if ( $exclude ) {
$where .= $wpdb->prepare(
' AND option_name NOT LIKE %s',
Utils\esc_like( '_site_transient_' ) . $exclude
);
}
$query = "SELECT `option_name` as `name`, `option_value` as `value` FROM {$wpdb->options} {$where}";
}
} else {
$where = $wpdb->prepare(
'WHERE `option_name` LIKE %s',
Utils\esc_like( '_transient_' ) . $pattern
);
$where .= $wpdb->prepare(
' AND option_name NOT LIKE %s',
Utils\esc_like( '_transient_timeout_' ) . '%'
);
if ( $exclude ) {
$where .= $wpdb->prepare(
' AND option_name NOT LIKE %s',
Utils\esc_like( '_transient_' ) . $exclude
);
}
$query = "SELECT `option_name` as `name`, `option_value` as `value` FROM {$wpdb->options} {$where}";
}
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Prepared properly above.
$results = $wpdb->get_results( $query );
foreach ( $results as $result ) {
$result->name = str_replace( array( '_site_transient_', '_transient_' ), '', $result->name );
$result->expiration = $this->get_transient_expiration( $result->name, $network, $human_readable );
if ( $unserialize ) {
$result->value = maybe_unserialize( $result->value );
}
}
$formatter = new \WP_CLI\Formatter(
$assoc_args,
$fields
);
$formatter->display_items( $results );
} | [
"public",
"function",
"list_",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"global",
"$",
"wpdb",
";",
"$",
"network",
"=",
"Utils",
"\\",
"get_flag_value",
"(",
"$",
"assoc_args",
",",
"'network'",
",",
"false",
")",
";",
"$",
"unserialize",
"... | Lists transients and their values.
## OPTIONS
[--search=<pattern>]
: Use wildcards ( * and ? ) to match transient name.
[--exclude=<pattern>]
: Pattern to exclude. Use wildcards ( * and ? ) to match transient name.
[--network]
: Get the values of network|site transients. On single site, this is
a specially-named cache key. On multisite, this is a global cache
(instead of local to the site).
[--unserialize]
: Unserialize transient values in output.
[--human-readable]
: Human-readable output for expirations.
[--fields=<fields>]
: Limit the output to specific object fields.
[--format=<format>]
: The serialization format for the value.
---
default: table
options:
- table
- json
- csv
- count
- yaml
---
## AVAILABLE FIELDS
This field will be displayed by default for each matching option:
* name
* value
* expiration
## EXAMPLES
# List all transients
$ wp transient list
+------+-------+---------------+
| name | value | expiration |
+------+-------+---------------+
| foo | bar | 39 mins |
| foo2 | bar2 | no expiration |
| foo3 | bar2 | expired |
| foo4 | bar4 | 4 hours |
+------+-------+---------------+
@subcommand list | [
"Lists",
"transients",
"and",
"their",
"values",
"."
] | train | https://github.com/wp-cli/cache-command/blob/56e2a8186c28bc1edbb8bc1c0f3d3b30fa116ea8/src/Transient_Command.php#L296-L401 |
wp-cli/cache-command | src/Transient_Command.php | Transient_Command.get_transient_expiration | private function get_transient_expiration( $name, $is_site_transient = false, $human_readable = false ) {
if ( $is_site_transient ) {
if ( is_multisite() ) {
$expiration = (int) get_site_option( '_site_transient_timeout_' . $name );
} else {
$expiration = (int) get_option( '_site_transient_timeout_' . $name );
}
} else {
$expiration = (int) get_option( '_transient_timeout_' . $name );
}
if ( 0 === $expiration ) {
return $human_readable ? 'never expires' : 'false';
}
if ( ! $human_readable ) {
return $expiration;
}
$now = time();
if ( $now > $expiration ) {
return 'expired';
}
return human_time_diff( $now, $expiration );
} | php | private function get_transient_expiration( $name, $is_site_transient = false, $human_readable = false ) {
if ( $is_site_transient ) {
if ( is_multisite() ) {
$expiration = (int) get_site_option( '_site_transient_timeout_' . $name );
} else {
$expiration = (int) get_option( '_site_transient_timeout_' . $name );
}
} else {
$expiration = (int) get_option( '_transient_timeout_' . $name );
}
if ( 0 === $expiration ) {
return $human_readable ? 'never expires' : 'false';
}
if ( ! $human_readable ) {
return $expiration;
}
$now = time();
if ( $now > $expiration ) {
return 'expired';
}
return human_time_diff( $now, $expiration );
} | [
"private",
"function",
"get_transient_expiration",
"(",
"$",
"name",
",",
"$",
"is_site_transient",
"=",
"false",
",",
"$",
"human_readable",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"is_site_transient",
")",
"{",
"if",
"(",
"is_multisite",
"(",
")",
")",
"... | Retrieves the expiration time.
@param string $name Transient name.
@param bool $is_site_transient Optional. Whether this is a site transient. Default false.
@param bool $human_readable Optional. Whether to return the difference between now and the
expiration time in a human-readable format. Default false.
@return string Expiration time string. | [
"Retrieves",
"the",
"expiration",
"time",
"."
] | train | https://github.com/wp-cli/cache-command/blob/56e2a8186c28bc1edbb8bc1c0f3d3b30fa116ea8/src/Transient_Command.php#L412-L438 |
wp-cli/cache-command | src/Transient_Command.php | Transient_Command.delete_expired | private function delete_expired( $network ) {
global $wpdb;
$count = 0;
if ( ! $network ) {
$count += $wpdb->query(
$wpdb->prepare(
"DELETE a, b FROM {$wpdb->options} a, {$wpdb->options} b
WHERE a.option_name LIKE %s
AND a.option_name NOT LIKE %s
AND b.option_name = CONCAT( '_transient_timeout_', SUBSTRING( a.option_name, 12 ) )
AND b.option_value < %d",
Utils\esc_like( '_transient_' ) . '%',
Utils\esc_like( '_transient_timeout_' ) . '%',
time()
)
);
} else {
if ( ! is_multisite() ) {
// Non-Multisite stores site transients in the options table.
$count += $wpdb->query(
$wpdb->prepare(
"DELETE a, b FROM {$wpdb->options} a, {$wpdb->options} b
WHERE a.option_name LIKE %s
AND a.option_name NOT LIKE %s
AND b.option_name = CONCAT( '_site_transient_timeout_', SUBSTRING( a.option_name, 17 ) )
AND b.option_value < %d",
Utils\esc_like( '_site_transient_' ) . '%',
Utils\esc_like( '_site_transient_timeout_' ) . '%',
time()
)
);
} else {
// Multisite stores site transients in the sitemeta table.
$count += $wpdb->query(
$wpdb->prepare(
"DELETE a, b FROM {$wpdb->sitemeta} a, {$wpdb->sitemeta} b
WHERE a.meta_key LIKE %s
AND a.meta_key NOT LIKE %s
AND b.meta_key = CONCAT( '_site_transient_timeout_', SUBSTRING( a.meta_key, 17 ) )
AND b.meta_value < %d",
Utils\esc_like( '_site_transient_' ) . '%',
Utils\esc_like( '_site_transient_timeout_' ) . '%',
time()
)
);
}
}
// The above queries delete the transient and the transient timeout
// thus each transient is counted twice.
$count = $count / 2;
if ( $count > 0 ) {
WP_CLI::success(
sprintf(
'%d expired %s deleted from the database.',
$count,
Utils\pluralize( 'transient', $count )
)
);
} else {
WP_CLI::success( 'No expired transients found.' );
}
if ( wp_using_ext_object_cache() ) {
WP_CLI::warning( 'Transients are stored in an external object cache, and this command only deletes those stored in the database. You must flush the cache to delete all transients.' );
}
} | php | private function delete_expired( $network ) {
global $wpdb;
$count = 0;
if ( ! $network ) {
$count += $wpdb->query(
$wpdb->prepare(
"DELETE a, b FROM {$wpdb->options} a, {$wpdb->options} b
WHERE a.option_name LIKE %s
AND a.option_name NOT LIKE %s
AND b.option_name = CONCAT( '_transient_timeout_', SUBSTRING( a.option_name, 12 ) )
AND b.option_value < %d",
Utils\esc_like( '_transient_' ) . '%',
Utils\esc_like( '_transient_timeout_' ) . '%',
time()
)
);
} else {
if ( ! is_multisite() ) {
// Non-Multisite stores site transients in the options table.
$count += $wpdb->query(
$wpdb->prepare(
"DELETE a, b FROM {$wpdb->options} a, {$wpdb->options} b
WHERE a.option_name LIKE %s
AND a.option_name NOT LIKE %s
AND b.option_name = CONCAT( '_site_transient_timeout_', SUBSTRING( a.option_name, 17 ) )
AND b.option_value < %d",
Utils\esc_like( '_site_transient_' ) . '%',
Utils\esc_like( '_site_transient_timeout_' ) . '%',
time()
)
);
} else {
// Multisite stores site transients in the sitemeta table.
$count += $wpdb->query(
$wpdb->prepare(
"DELETE a, b FROM {$wpdb->sitemeta} a, {$wpdb->sitemeta} b
WHERE a.meta_key LIKE %s
AND a.meta_key NOT LIKE %s
AND b.meta_key = CONCAT( '_site_transient_timeout_', SUBSTRING( a.meta_key, 17 ) )
AND b.meta_value < %d",
Utils\esc_like( '_site_transient_' ) . '%',
Utils\esc_like( '_site_transient_timeout_' ) . '%',
time()
)
);
}
}
// The above queries delete the transient and the transient timeout
// thus each transient is counted twice.
$count = $count / 2;
if ( $count > 0 ) {
WP_CLI::success(
sprintf(
'%d expired %s deleted from the database.',
$count,
Utils\pluralize( 'transient', $count )
)
);
} else {
WP_CLI::success( 'No expired transients found.' );
}
if ( wp_using_ext_object_cache() ) {
WP_CLI::warning( 'Transients are stored in an external object cache, and this command only deletes those stored in the database. You must flush the cache to delete all transients.' );
}
} | [
"private",
"function",
"delete_expired",
"(",
"$",
"network",
")",
"{",
"global",
"$",
"wpdb",
";",
"$",
"count",
"=",
"0",
";",
"if",
"(",
"!",
"$",
"network",
")",
"{",
"$",
"count",
"+=",
"$",
"wpdb",
"->",
"query",
"(",
"$",
"wpdb",
"->",
"pr... | Deletes all expired transients.
Only deletes the expired transients from the database.
@param bool $network Whether to delete transients or network|site transients. | [
"Deletes",
"all",
"expired",
"transients",
"."
] | train | https://github.com/wp-cli/cache-command/blob/56e2a8186c28bc1edbb8bc1c0f3d3b30fa116ea8/src/Transient_Command.php#L447-L516 |
wp-cli/cache-command | src/Transient_Command.php | Transient_Command.delete_all | private function delete_all( $network ) {
global $wpdb;
// To ensure proper count values we first delete all transients with a timeout
// and then the remaining transients without a timeout.
$count = 0;
if ( ! $network ) {
$deleted = $wpdb->query(
$wpdb->prepare(
"DELETE a, b FROM {$wpdb->options} a, {$wpdb->options} b
WHERE a.option_name LIKE %s
AND a.option_name NOT LIKE %s
AND b.option_name = CONCAT( '_transient_timeout_', SUBSTRING( a.option_name, 12 ) )",
Utils\esc_like( '_transient_' ) . '%',
Utils\esc_like( '_transient_timeout_' ) . '%'
)
);
$count += $deleted / 2; // Ignore affected rows for timeouts.
$count += $wpdb->query(
$wpdb->prepare(
"DELETE FROM $wpdb->options WHERE option_name LIKE %s",
Utils\esc_like( '_transient_' ) . '%'
)
);
} else {
if ( ! is_multisite() ) {
// Non-Multisite stores site transients in the options table.
$deleted = $wpdb->query(
$wpdb->prepare(
"DELETE a, b FROM {$wpdb->options} a, {$wpdb->options} b
WHERE a.option_name LIKE %s
AND a.option_name NOT LIKE %s
AND b.option_name = CONCAT( '_site_transient_timeout_', SUBSTRING( a.option_name, 17 ) )",
Utils\esc_like( '_site_transient_' ) . '%',
Utils\esc_like( '_site_transient_timeout_' ) . '%'
)
);
$count += $deleted / 2; // Ignore affected rows for timeouts.
$count += $wpdb->query(
$wpdb->prepare(
"DELETE FROM $wpdb->options WHERE option_name LIKE %s",
Utils\esc_like( '_site_transient_' ) . '%'
)
);
} else {
// Multisite stores site transients in the sitemeta table.
$deleted = $wpdb->query(
$wpdb->prepare(
"DELETE a, b FROM {$wpdb->sitemeta} a, {$wpdb->sitemeta} b
WHERE a.meta_key LIKE %s
AND a.meta_key NOT LIKE %s
AND b.meta_key = CONCAT( '_site_transient_timeout_', SUBSTRING( a.meta_key, 17 ) )",
Utils\esc_like( '_site_transient_' ) . '%',
Utils\esc_like( '_site_transient_timeout_' ) . '%'
)
);
$count += $deleted / 2; // Ignore affected rows for timeouts.
$count += $wpdb->query(
$wpdb->prepare(
"DELETE FROM $wpdb->sitemeta WHERE meta_key LIKE %s",
Utils\esc_like( '_site_transient_' ) . '%'
)
);
}
}
if ( $count > 0 ) {
WP_CLI::success(
sprintf(
'%d %s deleted from the database.',
$count,
Utils\pluralize( 'transient', $count )
)
);
} else {
WP_CLI::success( 'No transients found.' );
}
if ( wp_using_ext_object_cache() ) {
WP_CLI::warning( 'Transients are stored in an external object cache, and this command only deletes those stored in the database. You must flush the cache to delete all transients.' );
}
} | php | private function delete_all( $network ) {
global $wpdb;
// To ensure proper count values we first delete all transients with a timeout
// and then the remaining transients without a timeout.
$count = 0;
if ( ! $network ) {
$deleted = $wpdb->query(
$wpdb->prepare(
"DELETE a, b FROM {$wpdb->options} a, {$wpdb->options} b
WHERE a.option_name LIKE %s
AND a.option_name NOT LIKE %s
AND b.option_name = CONCAT( '_transient_timeout_', SUBSTRING( a.option_name, 12 ) )",
Utils\esc_like( '_transient_' ) . '%',
Utils\esc_like( '_transient_timeout_' ) . '%'
)
);
$count += $deleted / 2; // Ignore affected rows for timeouts.
$count += $wpdb->query(
$wpdb->prepare(
"DELETE FROM $wpdb->options WHERE option_name LIKE %s",
Utils\esc_like( '_transient_' ) . '%'
)
);
} else {
if ( ! is_multisite() ) {
// Non-Multisite stores site transients in the options table.
$deleted = $wpdb->query(
$wpdb->prepare(
"DELETE a, b FROM {$wpdb->options} a, {$wpdb->options} b
WHERE a.option_name LIKE %s
AND a.option_name NOT LIKE %s
AND b.option_name = CONCAT( '_site_transient_timeout_', SUBSTRING( a.option_name, 17 ) )",
Utils\esc_like( '_site_transient_' ) . '%',
Utils\esc_like( '_site_transient_timeout_' ) . '%'
)
);
$count += $deleted / 2; // Ignore affected rows for timeouts.
$count += $wpdb->query(
$wpdb->prepare(
"DELETE FROM $wpdb->options WHERE option_name LIKE %s",
Utils\esc_like( '_site_transient_' ) . '%'
)
);
} else {
// Multisite stores site transients in the sitemeta table.
$deleted = $wpdb->query(
$wpdb->prepare(
"DELETE a, b FROM {$wpdb->sitemeta} a, {$wpdb->sitemeta} b
WHERE a.meta_key LIKE %s
AND a.meta_key NOT LIKE %s
AND b.meta_key = CONCAT( '_site_transient_timeout_', SUBSTRING( a.meta_key, 17 ) )",
Utils\esc_like( '_site_transient_' ) . '%',
Utils\esc_like( '_site_transient_timeout_' ) . '%'
)
);
$count += $deleted / 2; // Ignore affected rows for timeouts.
$count += $wpdb->query(
$wpdb->prepare(
"DELETE FROM $wpdb->sitemeta WHERE meta_key LIKE %s",
Utils\esc_like( '_site_transient_' ) . '%'
)
);
}
}
if ( $count > 0 ) {
WP_CLI::success(
sprintf(
'%d %s deleted from the database.',
$count,
Utils\pluralize( 'transient', $count )
)
);
} else {
WP_CLI::success( 'No transients found.' );
}
if ( wp_using_ext_object_cache() ) {
WP_CLI::warning( 'Transients are stored in an external object cache, and this command only deletes those stored in the database. You must flush the cache to delete all transients.' );
}
} | [
"private",
"function",
"delete_all",
"(",
"$",
"network",
")",
"{",
"global",
"$",
"wpdb",
";",
"// To ensure proper count values we first delete all transients with a timeout",
"// and then the remaining transients without a timeout.",
"$",
"count",
"=",
"0",
";",
"if",
"(",... | Deletes all transients.
Only deletes the transients from the database.
@param bool $network Whether to delete transients or network|site transients. | [
"Deletes",
"all",
"transients",
"."
] | train | https://github.com/wp-cli/cache-command/blob/56e2a8186c28bc1edbb8bc1c0f3d3b30fa116ea8/src/Transient_Command.php#L525-L613 |
wp-cli/cache-command | src/Cache_Command.php | Cache_Command.add | public function add( $args, $assoc_args ) {
list( $key, $value, $group, $expiration ) = $args;
if ( ! wp_cache_add( $key, $value, $group, $expiration ) ) {
WP_CLI::error( "Could not add object '$key' in group '$group'. Does it already exist?" );
}
WP_CLI::success( "Added object '$key' in group '$group'." );
} | php | public function add( $args, $assoc_args ) {
list( $key, $value, $group, $expiration ) = $args;
if ( ! wp_cache_add( $key, $value, $group, $expiration ) ) {
WP_CLI::error( "Could not add object '$key' in group '$group'. Does it already exist?" );
}
WP_CLI::success( "Added object '$key' in group '$group'." );
} | [
"public",
"function",
"add",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"list",
"(",
"$",
"key",
",",
"$",
"value",
",",
"$",
"group",
",",
"$",
"expiration",
")",
"=",
"$",
"args",
";",
"if",
"(",
"!",
"wp_cache_add",
"(",
"$",
"key",
... | Adds a value to the object cache.
Errors if a value already exists for the key, which means the value can't
be added.
## OPTIONS
<key>
: Cache key.
<value>
: Value to add to the key.
[<group>]
: Method for grouping data within the cache which allows the same key to be used across groups.
---
default: default
---
[<expiration>]
: Define how long to keep the value, in seconds. `0` means as long as possible.
---
default: 0
---
## EXAMPLES
# Add cache.
$ wp cache add my_key my_group my_value 300
Success: Added object 'my_key' in group 'my_value'. | [
"Adds",
"a",
"value",
"to",
"the",
"object",
"cache",
"."
] | train | https://github.com/wp-cli/cache-command/blob/56e2a8186c28bc1edbb8bc1c0f3d3b30fa116ea8/src/Cache_Command.php#L59-L67 |
wp-cli/cache-command | src/Cache_Command.php | Cache_Command.decr | public function decr( $args, $assoc_args ) {
list( $key, $offset, $group ) = $args;
$value = wp_cache_decr( $key, $offset, $group );
if ( false === $value ) {
WP_CLI::error( 'The value was not decremented.' );
}
WP_CLI::print_value( $value, $assoc_args );
} | php | public function decr( $args, $assoc_args ) {
list( $key, $offset, $group ) = $args;
$value = wp_cache_decr( $key, $offset, $group );
if ( false === $value ) {
WP_CLI::error( 'The value was not decremented.' );
}
WP_CLI::print_value( $value, $assoc_args );
} | [
"public",
"function",
"decr",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"list",
"(",
"$",
"key",
",",
"$",
"offset",
",",
"$",
"group",
")",
"=",
"$",
"args",
";",
"$",
"value",
"=",
"wp_cache_decr",
"(",
"$",
"key",
",",
"$",
"offset",... | Decrements a value in the object cache.
Errors if the value can't be decremented.
## OPTIONS
<key>
: Cache key.
[<offset>]
: The amount by which to decrement the item's value.
---
default: 1
---
[<group>]
: Method for grouping data within the cache which allows the same key to be used across groups.
---
default: default
---
## EXAMPLES
# Decrease cache value.
$ wp cache decr my_key 2 my_group
48 | [
"Decrements",
"a",
"value",
"in",
"the",
"object",
"cache",
"."
] | train | https://github.com/wp-cli/cache-command/blob/56e2a8186c28bc1edbb8bc1c0f3d3b30fa116ea8/src/Cache_Command.php#L97-L106 |
wp-cli/cache-command | src/Cache_Command.php | Cache_Command.delete | public function delete( $args, $assoc_args ) {
list( $key, $group ) = $args;
$result = wp_cache_delete( $key, $group );
if ( false === $result ) {
WP_CLI::error( 'The object was not deleted.' );
}
WP_CLI::success( 'Object deleted.' );
} | php | public function delete( $args, $assoc_args ) {
list( $key, $group ) = $args;
$result = wp_cache_delete( $key, $group );
if ( false === $result ) {
WP_CLI::error( 'The object was not deleted.' );
}
WP_CLI::success( 'Object deleted.' );
} | [
"public",
"function",
"delete",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"list",
"(",
"$",
"key",
",",
"$",
"group",
")",
"=",
"$",
"args",
";",
"$",
"result",
"=",
"wp_cache_delete",
"(",
"$",
"key",
",",
"$",
"group",
")",
";",
"if",... | Removes a value from the object cache.
Errors if the value can't be deleted.
## OPTIONS
<key>
: Cache key.
[<group>]
: Method for grouping data within the cache which allows the same key to be used across groups.
---
default: default
---
## EXAMPLES
# Delete cache.
$ wp cache delete my_key my_group
Success: Object deleted. | [
"Removes",
"a",
"value",
"from",
"the",
"object",
"cache",
"."
] | train | https://github.com/wp-cli/cache-command/blob/56e2a8186c28bc1edbb8bc1c0f3d3b30fa116ea8/src/Cache_Command.php#L130-L139 |
wp-cli/cache-command | src/Cache_Command.php | Cache_Command.flush | public function flush( $args, $assoc_args ) {
$value = wp_cache_flush();
if ( false === $value ) {
WP_CLI::error( 'The object cache could not be flushed.' );
}
WP_CLI::success( 'The cache was flushed.' );
} | php | public function flush( $args, $assoc_args ) {
$value = wp_cache_flush();
if ( false === $value ) {
WP_CLI::error( 'The object cache could not be flushed.' );
}
WP_CLI::success( 'The cache was flushed.' );
} | [
"public",
"function",
"flush",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"$",
"value",
"=",
"wp_cache_flush",
"(",
")",
";",
"if",
"(",
"false",
"===",
"$",
"value",
")",
"{",
"WP_CLI",
"::",
"error",
"(",
"'The object cache could not be flushed.... | Flushes the object cache.
For WordPress multisite instances using a persistent object cache,
flushing the object cache will typically flush the cache for all sites.
Beware of the performance impact when flushing the object cache in
production.
Errors if the object cache can't be flushed.
## EXAMPLES
# Flush cache.
$ wp cache flush
Success: The cache was flushed. | [
"Flushes",
"the",
"object",
"cache",
"."
] | train | https://github.com/wp-cli/cache-command/blob/56e2a8186c28bc1edbb8bc1c0f3d3b30fa116ea8/src/Cache_Command.php#L157-L165 |
wp-cli/cache-command | src/Cache_Command.php | Cache_Command.get | public function get( $args, $assoc_args ) {
list( $key, $group ) = $args;
$value = wp_cache_get( $key, $group );
if ( false === $value ) {
WP_CLI::error( "Object with key '$key' and group '$group' not found." );
}
WP_CLI::print_value( $value, $assoc_args );
} | php | public function get( $args, $assoc_args ) {
list( $key, $group ) = $args;
$value = wp_cache_get( $key, $group );
if ( false === $value ) {
WP_CLI::error( "Object with key '$key' and group '$group' not found." );
}
WP_CLI::print_value( $value, $assoc_args );
} | [
"public",
"function",
"get",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"list",
"(",
"$",
"key",
",",
"$",
"group",
")",
"=",
"$",
"args",
";",
"$",
"value",
"=",
"wp_cache_get",
"(",
"$",
"key",
",",
"$",
"group",
")",
";",
"if",
"(",... | Gets a value from the object cache.
Errors if the value doesn't exist.
## OPTIONS
<key>
: Cache key.
[<group>]
: Method for grouping data within the cache which allows the same key to be used across groups.
---
default: default
---
## EXAMPLES
# Get cache.
$ wp cache get my_key my_group
my_value | [
"Gets",
"a",
"value",
"from",
"the",
"object",
"cache",
"."
] | train | https://github.com/wp-cli/cache-command/blob/56e2a8186c28bc1edbb8bc1c0f3d3b30fa116ea8/src/Cache_Command.php#L189-L198 |
wp-cli/cache-command | src/Cache_Command.php | Cache_Command.incr | public function incr( $args, $assoc_args ) {
list( $key, $offset, $group ) = $args;
$value = wp_cache_incr( $key, $offset, $group );
if ( false === $value ) {
WP_CLI::error( 'The value was not incremented.' );
}
WP_CLI::print_value( $value, $assoc_args );
} | php | public function incr( $args, $assoc_args ) {
list( $key, $offset, $group ) = $args;
$value = wp_cache_incr( $key, $offset, $group );
if ( false === $value ) {
WP_CLI::error( 'The value was not incremented.' );
}
WP_CLI::print_value( $value, $assoc_args );
} | [
"public",
"function",
"incr",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"list",
"(",
"$",
"key",
",",
"$",
"offset",
",",
"$",
"group",
")",
"=",
"$",
"args",
";",
"$",
"value",
"=",
"wp_cache_incr",
"(",
"$",
"key",
",",
"$",
"offset",... | Increments a value in the object cache.
Errors if the value can't be incremented.
## OPTIONS
<key>
: Cache key.
[<offset>]
: The amount by which to increment the item's value.
---
default: 1
---
[<group>]
: Method for grouping data within the cache which allows the same key to be used across groups.
---
default: default
---
## EXAMPLES
# Increase cache value.
$ wp cache incr my_key 2 my_group
50 | [
"Increments",
"a",
"value",
"in",
"the",
"object",
"cache",
"."
] | train | https://github.com/wp-cli/cache-command/blob/56e2a8186c28bc1edbb8bc1c0f3d3b30fa116ea8/src/Cache_Command.php#L228-L237 |
wp-cli/cache-command | src/Cache_Command.php | Cache_Command.replace | public function replace( $args, $assoc_args ) {
list( $key, $value, $group, $expiration ) = $args;
$result = wp_cache_replace( $key, $value, $group, $expiration );
if ( false === $result ) {
WP_CLI::error( "Could not replace object '$key' in group '$group'. Does it not exist?" );
}
WP_CLI::success( "Replaced object '$key' in group '$group'." );
} | php | public function replace( $args, $assoc_args ) {
list( $key, $value, $group, $expiration ) = $args;
$result = wp_cache_replace( $key, $value, $group, $expiration );
if ( false === $result ) {
WP_CLI::error( "Could not replace object '$key' in group '$group'. Does it not exist?" );
}
WP_CLI::success( "Replaced object '$key' in group '$group'." );
} | [
"public",
"function",
"replace",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"list",
"(",
"$",
"key",
",",
"$",
"value",
",",
"$",
"group",
",",
"$",
"expiration",
")",
"=",
"$",
"args",
";",
"$",
"result",
"=",
"wp_cache_replace",
"(",
"$"... | Replaces a value in the object cache, if the value already exists.
Errors if the value can't be replaced.
## OPTIONS
<key>
: Cache key.
<value>
: Value to replace.
[<group>]
: Method for grouping data within the cache which allows the same key to be used across groups.
---
default: default
---
[<expiration>]
: Define how long to keep the value, in seconds. `0` means as long as possible.
---
default: 0
---
## EXAMPLES
# Replace cache.
$ wp cache replace my_key new_value my_group
Success: Replaced object 'my_key' in group 'my_group'. | [
"Replaces",
"a",
"value",
"in",
"the",
"object",
"cache",
"if",
"the",
"value",
"already",
"exists",
"."
] | train | https://github.com/wp-cli/cache-command/blob/56e2a8186c28bc1edbb8bc1c0f3d3b30fa116ea8/src/Cache_Command.php#L270-L279 |
wp-cli/cache-command | src/Cache_Command.php | Cache_Command.set | public function set( $args, $assoc_args ) {
list( $key, $value, $group, $expiration ) = $args;
$result = wp_cache_set( $key, $value, $group, $expiration );
if ( false === $result ) {
WP_CLI::error( "Could not add object '$key' in group '$group'." );
}
WP_CLI::success( "Set object '$key' in group '$group'." );
} | php | public function set( $args, $assoc_args ) {
list( $key, $value, $group, $expiration ) = $args;
$result = wp_cache_set( $key, $value, $group, $expiration );
if ( false === $result ) {
WP_CLI::error( "Could not add object '$key' in group '$group'." );
}
WP_CLI::success( "Set object '$key' in group '$group'." );
} | [
"public",
"function",
"set",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"list",
"(",
"$",
"key",
",",
"$",
"value",
",",
"$",
"group",
",",
"$",
"expiration",
")",
"=",
"$",
"args",
";",
"$",
"result",
"=",
"wp_cache_set",
"(",
"$",
"key... | Sets a value to the object cache, regardless of whether it already exists.
Errors if the value can't be set.
## OPTIONS
<key>
: Cache key.
<value>
: Value to set on the key.
[<group>]
: Method for grouping data within the cache which allows the same key to be used across groups.
---
default: default
---
[<expiration>]
: Define how long to keep the value, in seconds. `0` means as long as possible.
---
default: 0
---
## EXAMPLES
# Set cache.
$ wp cache set my_key my_value my_group 300
Success: Set object 'my_key' in group 'my_group'. | [
"Sets",
"a",
"value",
"to",
"the",
"object",
"cache",
"regardless",
"of",
"whether",
"it",
"already",
"exists",
"."
] | train | https://github.com/wp-cli/cache-command/blob/56e2a8186c28bc1edbb8bc1c0f3d3b30fa116ea8/src/Cache_Command.php#L312-L321 |
wp-cli/cache-command | src/Cache_Command.php | Cache_Command.type | public function type( $args, $assoc_args ) {
$message = WP_CLI\Utils\wp_get_cache_type();
WP_CLI::line( $message );
} | php | public function type( $args, $assoc_args ) {
$message = WP_CLI\Utils\wp_get_cache_type();
WP_CLI::line( $message );
} | [
"public",
"function",
"type",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"$",
"message",
"=",
"WP_CLI",
"\\",
"Utils",
"\\",
"wp_get_cache_type",
"(",
")",
";",
"WP_CLI",
"::",
"line",
"(",
"$",
"message",
")",
";",
"}"
] | Attempts to determine which object cache is being used.
Note that the guesses made by this function are based on the
WP_Object_Cache classes that define the 3rd party object cache extension.
Changes to those classes could render problems with this function's
ability to determine which object cache is being used.
## EXAMPLES
# Check cache type.
$ wp cache type
Default | [
"Attempts",
"to",
"determine",
"which",
"object",
"cache",
"is",
"being",
"used",
"."
] | train | https://github.com/wp-cli/cache-command/blob/56e2a8186c28bc1edbb8bc1c0f3d3b30fa116ea8/src/Cache_Command.php#L337-L340 |
burzum/cakephp-file-storage | src/Storage/Listener/LegacyLocalFileStorageListener.php | LegacyLocalFileStorageListener.afterSave | public function afterSave(Event $event, EntityInterface $entity) {
if ($this->_checkEvent($event) && $entity->isNew()) {
$fileField = $this->getConfig('fileField');
$entity['hash'] = $this->getFileHash($entity, $fileField);
$entity['path'] = $this->pathBuilder()->path($entity);
if (!$this->_storeFile($event)) {
return;
}
$event->stopPropagation();
}
} | php | public function afterSave(Event $event, EntityInterface $entity) {
if ($this->_checkEvent($event) && $entity->isNew()) {
$fileField = $this->getConfig('fileField');
$entity['hash'] = $this->getFileHash($entity, $fileField);
$entity['path'] = $this->pathBuilder()->path($entity);
if (!$this->_storeFile($event)) {
return;
}
$event->stopPropagation();
}
} | [
"public",
"function",
"afterSave",
"(",
"Event",
"$",
"event",
",",
"EntityInterface",
"$",
"entity",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_checkEvent",
"(",
"$",
"event",
")",
"&&",
"$",
"entity",
"->",
"isNew",
"(",
")",
")",
"{",
"$",
"fileFie... | Save the file to the storage backend after the record was created.
@param \Cake\Event\Event $event
@param \Cake\Datasource\EntityInterface $entity
@return void | [
"Save",
"the",
"file",
"to",
"the",
"storage",
"backend",
"after",
"the",
"record",
"was",
"created",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Storage/Listener/LegacyLocalFileStorageListener.php#L57-L70 |
burzum/cakephp-file-storage | src/Model/Entity/ImageStorage.php | ImageStorage.imageVersion | public function imageVersion($version, $options = []) {
$options['version'] = $version;
$options['image'] = $this;
$options['hash'] = Configure::read('FileStorage.imageHashes.' . $this->_properties['model'] . '.' . $version);
if (empty($options['hash'])) {
throw new InvalidArgumentException(sprintf('No valid version key (Identifier: `%s` Key: `%s`) passed!', $this->get('model'), $version));
}
$event = $this->dispatchEvent('ImageVersion.getVersions', $options);
return $event->getResult();
} | php | public function imageVersion($version, $options = []) {
$options['version'] = $version;
$options['image'] = $this;
$options['hash'] = Configure::read('FileStorage.imageHashes.' . $this->_properties['model'] . '.' . $version);
if (empty($options['hash'])) {
throw new InvalidArgumentException(sprintf('No valid version key (Identifier: `%s` Key: `%s`) passed!', $this->get('model'), $version));
}
$event = $this->dispatchEvent('ImageVersion.getVersions', $options);
return $event->getResult();
} | [
"public",
"function",
"imageVersion",
"(",
"$",
"version",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"[",
"'version'",
"]",
"=",
"$",
"version",
";",
"$",
"options",
"[",
"'image'",
"]",
"=",
"$",
"this",
";",
"$",
"options",
"[... | Gets the version of an image.
@param string
@param array $options
@return string | [
"Gets",
"the",
"version",
"of",
"an",
"image",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Model/Entity/ImageStorage.php#L23-L35 |
burzum/cakephp-file-storage | src/Shell/ImageVersionShell.php | ImageVersionShell.regenerate | public function regenerate() {
$operations = Configure::read('FileStorage.imageSizes.' . $this->args[0]);
$options = [
'overwrite' => !$this->params['keep-old-versions']
];
if (empty($operations)) {
$this->abort(__d('file_storage', 'Invalid table or version.'));
}
foreach ($operations as $version => $operation) {
try {
$this->_loop($this->command, $this->args[0], [$version => $operation], $options);
} catch (Exception $e) {
$this->abort($e->getMessage());
}
}
} | php | public function regenerate() {
$operations = Configure::read('FileStorage.imageSizes.' . $this->args[0]);
$options = [
'overwrite' => !$this->params['keep-old-versions']
];
if (empty($operations)) {
$this->abort(__d('file_storage', 'Invalid table or version.'));
}
foreach ($operations as $version => $operation) {
try {
$this->_loop($this->command, $this->args[0], [$version => $operation], $options);
} catch (Exception $e) {
$this->abort($e->getMessage());
}
}
} | [
"public",
"function",
"regenerate",
"(",
")",
"{",
"$",
"operations",
"=",
"Configure",
"::",
"read",
"(",
"'FileStorage.imageSizes.'",
".",
"$",
"this",
"->",
"args",
"[",
"0",
"]",
")",
";",
"$",
"options",
"=",
"[",
"'overwrite'",
"=>",
"!",
"$",
"t... | Generate all image versions.
@return void | [
"Generate",
"all",
"image",
"versions",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Shell/ImageVersionShell.php#L175-L192 |
burzum/cakephp-file-storage | src/Shell/ImageVersionShell.php | ImageVersionShell.generate | public function generate($model, $version) {
$operations = Configure::read('FileStorage.imageSizes.' . $model . '.' . $version);
$options = [
'overwrite' => !$this->params['keep-old-versions']
];
if (empty($operations)) {
$this->out(__d('file_storage', 'Invalid table or version.'));
$this->_stop();
}
try {
$this->_loop('generate', $model, [$version => $operations], $options);
} catch (Exception $e) {
$this->abort($e->getMessage());
}
} | php | public function generate($model, $version) {
$operations = Configure::read('FileStorage.imageSizes.' . $model . '.' . $version);
$options = [
'overwrite' => !$this->params['keep-old-versions']
];
if (empty($operations)) {
$this->out(__d('file_storage', 'Invalid table or version.'));
$this->_stop();
}
try {
$this->_loop('generate', $model, [$version => $operations], $options);
} catch (Exception $e) {
$this->abort($e->getMessage());
}
} | [
"public",
"function",
"generate",
"(",
"$",
"model",
",",
"$",
"version",
")",
"{",
"$",
"operations",
"=",
"Configure",
"::",
"read",
"(",
"'FileStorage.imageSizes.'",
".",
"$",
"model",
".",
"'.'",
".",
"$",
"version",
")",
";",
"$",
"options",
"=",
... | Generate a given image version.
@param string $model
@param string $version
@return void | [
"Generate",
"a",
"given",
"image",
"version",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Shell/ImageVersionShell.php#L201-L217 |
burzum/cakephp-file-storage | src/Shell/ImageVersionShell.php | ImageVersionShell.remove | public function remove($model, $version) {
$operations = Configure::read('FileStorage.imageSizes.' . $model . '.' . $version);
if (empty($operations)) {
$this->out(__d('file_storage', 'Invalid table or version.'));
$this->_stop();
}
try {
$this->_loop('remove', $model, [$version => $operations]);
} catch (Exception $e) {
$this->out($e->getMessage());
$this->_stop();
}
} | php | public function remove($model, $version) {
$operations = Configure::read('FileStorage.imageSizes.' . $model . '.' . $version);
if (empty($operations)) {
$this->out(__d('file_storage', 'Invalid table or version.'));
$this->_stop();
}
try {
$this->_loop('remove', $model, [$version => $operations]);
} catch (Exception $e) {
$this->out($e->getMessage());
$this->_stop();
}
} | [
"public",
"function",
"remove",
"(",
"$",
"model",
",",
"$",
"version",
")",
"{",
"$",
"operations",
"=",
"Configure",
"::",
"read",
"(",
"'FileStorage.imageSizes.'",
".",
"$",
"model",
".",
"'.'",
".",
"$",
"version",
")",
";",
"if",
"(",
"empty",
"("... | Remove a given image version.
@param string $model
@param string $version
@return void | [
"Remove",
"a",
"given",
"image",
"version",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Shell/ImageVersionShell.php#L226-L240 |
burzum/cakephp-file-storage | src/Shell/ImageVersionShell.php | ImageVersionShell._loop | protected function _loop($action, $model, $operations = [], $options = []) {
if (!in_array($action, ['generate', 'remove', 'regenerate'])) {
$this->_stop();
}
$totalImageCount = $this->_getCount($model);
if ($totalImageCount === 0) {
$this->out(__d('file_storage', 'No Images for model {0} found', $model));
$this->_stop();
}
$this->out(__d('file_storage', '{0} image file(s) will be processed' . "\n", $totalImageCount));
$offset = 0;
$limit = $this->limit;
do {
$images = $this->_getRecords($model, $limit, $offset);
if (!empty($images)) {
foreach ($images as $image) {
$Storage = StorageManager::get($image->adapter);
if ($Storage === false) {
$this->err(__d('file_storage', 'Cant load adapter config {0} for record {1}', $image->adapter, $image->id));
} else {
$payload = [
'entity' => $image,
'storage' => $Storage,
'operations' => $operations,
'versions' => array_keys($operations),
'table' => $this->Table,
'options' => $options
];
if ($action == 'generate' || $action == 'regenerate') {
$Event = new Event('ImageVersion.createVersion', $this->Table, $payload);
EventManager::instance()->dispatch($Event);
}
if ($action == 'remove') {
$Event = new Event('ImageVersion.removeVersion', $this->Table, $payload);
EventManager::instance()->dispatch($Event);
}
$this->out(__('{0} processed', $image->id));
}
}
}
$offset += $limit;
} while ($images->count() > 0);
} | php | protected function _loop($action, $model, $operations = [], $options = []) {
if (!in_array($action, ['generate', 'remove', 'regenerate'])) {
$this->_stop();
}
$totalImageCount = $this->_getCount($model);
if ($totalImageCount === 0) {
$this->out(__d('file_storage', 'No Images for model {0} found', $model));
$this->_stop();
}
$this->out(__d('file_storage', '{0} image file(s) will be processed' . "\n", $totalImageCount));
$offset = 0;
$limit = $this->limit;
do {
$images = $this->_getRecords($model, $limit, $offset);
if (!empty($images)) {
foreach ($images as $image) {
$Storage = StorageManager::get($image->adapter);
if ($Storage === false) {
$this->err(__d('file_storage', 'Cant load adapter config {0} for record {1}', $image->adapter, $image->id));
} else {
$payload = [
'entity' => $image,
'storage' => $Storage,
'operations' => $operations,
'versions' => array_keys($operations),
'table' => $this->Table,
'options' => $options
];
if ($action == 'generate' || $action == 'regenerate') {
$Event = new Event('ImageVersion.createVersion', $this->Table, $payload);
EventManager::instance()->dispatch($Event);
}
if ($action == 'remove') {
$Event = new Event('ImageVersion.removeVersion', $this->Table, $payload);
EventManager::instance()->dispatch($Event);
}
$this->out(__('{0} processed', $image->id));
}
}
}
$offset += $limit;
} while ($images->count() > 0);
} | [
"protected",
"function",
"_loop",
"(",
"$",
"action",
",",
"$",
"model",
",",
"$",
"operations",
"=",
"[",
"]",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"action",
",",
"[",
"'generate'",
",",
"'remove'",
... | Loops through image records and performs requested operation on them.
@param string $action
@param $model
@param array $operations
@return void | [
"Loops",
"through",
"image",
"records",
"and",
"performs",
"requested",
"operation",
"on",
"them",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Shell/ImageVersionShell.php#L250-L300 |
burzum/cakephp-file-storage | src/Shell/ImageVersionShell.php | ImageVersionShell._getCount | protected function _getCount($identifier, array $extensions = ['jpg', 'png', 'jpeg']) {
return $this->Table
->find()
->where(['model' => $identifier])
->andWhere(['extension IN' => $extensions])
->count();
} | php | protected function _getCount($identifier, array $extensions = ['jpg', 'png', 'jpeg']) {
return $this->Table
->find()
->where(['model' => $identifier])
->andWhere(['extension IN' => $extensions])
->count();
} | [
"protected",
"function",
"_getCount",
"(",
"$",
"identifier",
",",
"array",
"$",
"extensions",
"=",
"[",
"'jpg'",
",",
"'png'",
",",
"'jpeg'",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"Table",
"->",
"find",
"(",
")",
"->",
"where",
"(",
"[",
"'mod... | Gets the amount of images for a model in the DB.
@param string $identifier
@param array $extensions
@return int | [
"Gets",
"the",
"amount",
"of",
"images",
"for",
"a",
"model",
"in",
"the",
"DB",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Shell/ImageVersionShell.php#L309-L315 |
burzum/cakephp-file-storage | src/Shell/ImageVersionShell.php | ImageVersionShell._getRecords | protected function _getRecords($identifier, $limit, $offset, array $extensions = ['jpg', 'png', 'jpeg']) {
return $this->Table
->find()
->where(['model' => $identifier])
->andWhere(['extension IN' => $extensions])
->limit($limit)
->offset($offset)
->all();
} | php | protected function _getRecords($identifier, $limit, $offset, array $extensions = ['jpg', 'png', 'jpeg']) {
return $this->Table
->find()
->where(['model' => $identifier])
->andWhere(['extension IN' => $extensions])
->limit($limit)
->offset($offset)
->all();
} | [
"protected",
"function",
"_getRecords",
"(",
"$",
"identifier",
",",
"$",
"limit",
",",
"$",
"offset",
",",
"array",
"$",
"extensions",
"=",
"[",
"'jpg'",
",",
"'png'",
",",
"'jpeg'",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"Table",
"->",
"find",
... | Gets the chunk of records for the image processing
@param string $identifier
@param int $limit
@param int $offset
@param array $extensions
@return \Cake\Datasource\ResultSetDecorator | [
"Gets",
"the",
"chunk",
"of",
"records",
"for",
"the",
"image",
"processing"
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Shell/ImageVersionShell.php#L326-L334 |
burzum/cakephp-file-storage | src/Storage/Listener/ImageProcessingTrait.php | ImageProcessingTrait.loadImageProcessingFromConfig | public function loadImageProcessingFromConfig() {
$this->_imageVersions = (array)Configure::read('FileStorage.imageSizes');
$this->_imageVersionHashes = StorageUtils::generateHashes('FileStorage', true);
$this->_defaultOutput = (array)Configure::read('FileStorage.defaultOutput');
} | php | public function loadImageProcessingFromConfig() {
$this->_imageVersions = (array)Configure::read('FileStorage.imageSizes');
$this->_imageVersionHashes = StorageUtils::generateHashes('FileStorage', true);
$this->_defaultOutput = (array)Configure::read('FileStorage.defaultOutput');
} | [
"public",
"function",
"loadImageProcessingFromConfig",
"(",
")",
"{",
"$",
"this",
"->",
"_imageVersions",
"=",
"(",
"array",
")",
"Configure",
"::",
"read",
"(",
"'FileStorage.imageSizes'",
")",
";",
"$",
"this",
"->",
"_imageVersionHashes",
"=",
"StorageUtils",
... | Loads the image processing configuration into the class.
@return void | [
"Loads",
"the",
"image",
"processing",
"configuration",
"into",
"the",
"class",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Storage/Listener/ImageProcessingTrait.php#L67-L71 |
burzum/cakephp-file-storage | src/Storage/Listener/ImageProcessingTrait.php | ImageProcessingTrait.imageProcessor | public function imageProcessor(array $config = [], $renew = false) {
if (!empty($this->_imageProcessor) && $renew === false) {
return $this->_imageProcessor;
}
$this->loadImageProcessingFromConfig();
$class = $this->_imageProcessorClass;
$this->_imageProcessor = new $class($config);
return $this->_imageProcessor;
} | php | public function imageProcessor(array $config = [], $renew = false) {
if (!empty($this->_imageProcessor) && $renew === false) {
return $this->_imageProcessor;
}
$this->loadImageProcessingFromConfig();
$class = $this->_imageProcessorClass;
$this->_imageProcessor = new $class($config);
return $this->_imageProcessor;
} | [
"public",
"function",
"imageProcessor",
"(",
"array",
"$",
"config",
"=",
"[",
"]",
",",
"$",
"renew",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"_imageProcessor",
")",
"&&",
"$",
"renew",
"===",
"false",
")",
"{",
"r... | Gets the image processor instance.
@param array $config
@return mixed | [
"Gets",
"the",
"image",
"processor",
"instance",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Storage/Listener/ImageProcessingTrait.php#L79-L88 |
burzum/cakephp-file-storage | src/Storage/Listener/ImageProcessingTrait.php | ImageProcessingTrait._checkImageVersions | protected function _checkImageVersions($identifier, array $versions) {
if (!isset($this->_imageVersions[$identifier])) {
throw new RuntimeException(sprintf('No image version config found for identifier "%s"!', $identifier));
}
foreach ($versions as $version) {
if (!isset($this->_imageVersions[$identifier][$version])) {
throw new RuntimeException(sprintf('Invalid version "%s" for identifier "%s"!', $identifier, $version));
}
}
} | php | protected function _checkImageVersions($identifier, array $versions) {
if (!isset($this->_imageVersions[$identifier])) {
throw new RuntimeException(sprintf('No image version config found for identifier "%s"!', $identifier));
}
foreach ($versions as $version) {
if (!isset($this->_imageVersions[$identifier][$version])) {
throw new RuntimeException(sprintf('Invalid version "%s" for identifier "%s"!', $identifier, $version));
}
}
} | [
"protected",
"function",
"_checkImageVersions",
"(",
"$",
"identifier",
",",
"array",
"$",
"versions",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"_imageVersions",
"[",
"$",
"identifier",
"]",
")",
")",
"{",
"throw",
"new",
"RuntimeExceptio... | Check that the image versions exist before doing something with them.
@throws \RuntimeException
@param string $identifier
@param array $versions
@return void | [
"Check",
"that",
"the",
"image",
"versions",
"exist",
"before",
"doing",
"something",
"with",
"them",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Storage/Listener/ImageProcessingTrait.php#L113-L123 |
burzum/cakephp-file-storage | src/Storage/Listener/ImageProcessingTrait.php | ImageProcessingTrait.createImageVersions | public function createImageVersions(EntityInterface $entity, array $versions, array $options = []) {
$this->_checkImageVersions($entity->get('model'), $versions);
$options += $this->_defaultOutput + [
'overwrite' => true
];
$result = [];
$storage = $this->getStorageAdapter($entity->adapter);
foreach ($this->_imageVersions[$entity->get('model')] as $version => $operations) {
if (!in_array($version, $versions)) {
continue;
}
$saveOptions = $options + ['format' => $entity->extension];
$mimeTypeToFileType = [
'image/jpg' => 'jpeg',
'image/jpeg' => 'jpeg',
'image/png' => 'png',
'image/gif' => 'gif'
];
if (empty($saveOptions['format'])) {
$mime = $entity->get('mime_type');
if (isset($mimeTypeToFileType[$mime])) {
$saveOptions['format'] = $mimeTypeToFileType[$mime];
}
}
if (isset($operations['_output'])) {
$saveOptions = $operations['_output'] + $saveOptions;
unset($operations['_output']);
}
$path = $this->imageVersionPath($entity, $version, 'fullPath', $saveOptions);
try {
if ($options['overwrite'] || !$storage->has($path)) {
unset($saveOptions['overwrite']);
$output = StorageUtils::createTmpFile();
$tmpFile = $this->_tmpFile($storage, $this->pathBuilder()->fullPath($entity));
$this->imageProcessor()->open($tmpFile);
$this->imageProcessor()->batchProcess($output, $operations, $saveOptions);
$storage->write($path, file_get_contents($output), true);
unlink($tmpFile);
unlink($output);
}
$result[$version] = [
'status' => 'success',
'path' => $path,
'hash' => $this->getImageVersionHash($entity->get('model'), $version)
];
} catch (\Exception $e) {
$this->log($e->getMessage(), LogLevel::ERROR, [
'fileStorage'
]);
$result[$version] = [
'status' => 'error',
'error' => $e->getMessage(),
'line' => $e->getLine(),
'file' => $e->getFile()
];
}
}
return $result;
} | php | public function createImageVersions(EntityInterface $entity, array $versions, array $options = []) {
$this->_checkImageVersions($entity->get('model'), $versions);
$options += $this->_defaultOutput + [
'overwrite' => true
];
$result = [];
$storage = $this->getStorageAdapter($entity->adapter);
foreach ($this->_imageVersions[$entity->get('model')] as $version => $operations) {
if (!in_array($version, $versions)) {
continue;
}
$saveOptions = $options + ['format' => $entity->extension];
$mimeTypeToFileType = [
'image/jpg' => 'jpeg',
'image/jpeg' => 'jpeg',
'image/png' => 'png',
'image/gif' => 'gif'
];
if (empty($saveOptions['format'])) {
$mime = $entity->get('mime_type');
if (isset($mimeTypeToFileType[$mime])) {
$saveOptions['format'] = $mimeTypeToFileType[$mime];
}
}
if (isset($operations['_output'])) {
$saveOptions = $operations['_output'] + $saveOptions;
unset($operations['_output']);
}
$path = $this->imageVersionPath($entity, $version, 'fullPath', $saveOptions);
try {
if ($options['overwrite'] || !$storage->has($path)) {
unset($saveOptions['overwrite']);
$output = StorageUtils::createTmpFile();
$tmpFile = $this->_tmpFile($storage, $this->pathBuilder()->fullPath($entity));
$this->imageProcessor()->open($tmpFile);
$this->imageProcessor()->batchProcess($output, $operations, $saveOptions);
$storage->write($path, file_get_contents($output), true);
unlink($tmpFile);
unlink($output);
}
$result[$version] = [
'status' => 'success',
'path' => $path,
'hash' => $this->getImageVersionHash($entity->get('model'), $version)
];
} catch (\Exception $e) {
$this->log($e->getMessage(), LogLevel::ERROR, [
'fileStorage'
]);
$result[$version] = [
'status' => 'error',
'error' => $e->getMessage(),
'line' => $e->getLine(),
'file' => $e->getFile()
];
}
}
return $result;
} | [
"public",
"function",
"createImageVersions",
"(",
"EntityInterface",
"$",
"entity",
",",
"array",
"$",
"versions",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"_checkImageVersions",
"(",
"$",
"entity",
"->",
"get",
"(",
"'mode... | Creates the image versions of an entity.
@param \Cake\Datasource\EntityInterface $entity
@param array $versions Versions array.
@param array $options Imagine save options.
@return array | [
"Creates",
"the",
"image",
"versions",
"of",
"an",
"entity",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Storage/Listener/ImageProcessingTrait.php#L133-L205 |
burzum/cakephp-file-storage | src/Storage/Listener/ImageProcessingTrait.php | ImageProcessingTrait.getAllVersionsKeysForModel | public function getAllVersionsKeysForModel($identifier) {
if (!isset($this->_imageVersions[$identifier])) {
throw new RuntimeException(sprintf('No image config present for identifier "%s"!', $identifier));
}
return array_keys($this->_imageVersions[$identifier]);
} | php | public function getAllVersionsKeysForModel($identifier) {
if (!isset($this->_imageVersions[$identifier])) {
throw new RuntimeException(sprintf('No image config present for identifier "%s"!', $identifier));
}
return array_keys($this->_imageVersions[$identifier]);
} | [
"public",
"function",
"getAllVersionsKeysForModel",
"(",
"$",
"identifier",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"_imageVersions",
"[",
"$",
"identifier",
"]",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"sprintf",
"(",
"'... | Gets all image version config keys for a specific identifier.
@param string $identifier
@throws \RuntimeException
@return array | [
"Gets",
"all",
"image",
"version",
"config",
"keys",
"for",
"a",
"specific",
"identifier",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Storage/Listener/ImageProcessingTrait.php#L261-L267 |
burzum/cakephp-file-storage | src/Storage/Listener/ImageProcessingTrait.php | ImageProcessingTrait.createAllImageVersions | public function createAllImageVersions(EntityInterface $entity, array $options = []) {
return $this->createImageVersions(
$entity,
$this->getAllVersionsKeysForModel($entity->get('model')),
$options
);
} | php | public function createAllImageVersions(EntityInterface $entity, array $options = []) {
return $this->createImageVersions(
$entity,
$this->getAllVersionsKeysForModel($entity->get('model')),
$options
);
} | [
"public",
"function",
"createAllImageVersions",
"(",
"EntityInterface",
"$",
"entity",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"createImageVersions",
"(",
"$",
"entity",
",",
"$",
"this",
"->",
"getAllVersionsKeysFor... | Convenience method to create ALL versions for an entity.
@param \Cake\Datasource\EntityInterface
@return array | [
"Convenience",
"method",
"to",
"create",
"ALL",
"versions",
"for",
"an",
"entity",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Storage/Listener/ImageProcessingTrait.php#L275-L281 |
burzum/cakephp-file-storage | src/Storage/Listener/ImageProcessingTrait.php | ImageProcessingTrait.removeAllImageVersions | public function removeAllImageVersions(EntityInterface $entity, array $options = []) {
return $this->removeImageVersions(
$entity,
$this->getAllVersionsKeysForModel($entity->get('model')),
$options
);
} | php | public function removeAllImageVersions(EntityInterface $entity, array $options = []) {
return $this->removeImageVersions(
$entity,
$this->getAllVersionsKeysForModel($entity->get('model')),
$options
);
} | [
"public",
"function",
"removeAllImageVersions",
"(",
"EntityInterface",
"$",
"entity",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"removeImageVersions",
"(",
"$",
"entity",
",",
"$",
"this",
"->",
"getAllVersionsKeysFor... | Convenience method to delete ALL versions for an entity.
@param \Cake\Datasource\EntityInterface
@return array | [
"Convenience",
"method",
"to",
"delete",
"ALL",
"versions",
"for",
"an",
"entity",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Storage/Listener/ImageProcessingTrait.php#L289-L295 |
burzum/cakephp-file-storage | src/Validation/UploadValidator.php | UploadValidator.isUploadArray | public function isUploadArray($value) {
if (!is_array($value)) {
return false;
}
$requiredKeys = ['name', 'type', 'tmp_name', 'error', 'size'];
$keys = array_keys($value);
foreach ($requiredKeys as $key) {
if (!in_array($key, $keys)) {
return false;
}
}
return true;
} | php | public function isUploadArray($value) {
if (!is_array($value)) {
return false;
}
$requiredKeys = ['name', 'type', 'tmp_name', 'error', 'size'];
$keys = array_keys($value);
foreach ($requiredKeys as $key) {
if (!in_array($key, $keys)) {
return false;
}
}
return true;
} | [
"public",
"function",
"isUploadArray",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"requiredKeys",
"=",
"[",
"'name'",
",",
"'type'",
",",
"'tmp_name'",
",",
"'error'",
... | Validates that a set field / property is a valid upload array.
@deprecated Use \Cake\Utility\Validation::uploadedFile() instead.
@param mixed $value
@return bool | [
"Validates",
"that",
"a",
"set",
"field",
"/",
"property",
"is",
"a",
"valid",
"upload",
"array",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Validation/UploadValidator.php#L72-L85 |
burzum/cakephp-file-storage | src/Validation/UploadValidator.php | UploadValidator.uploadErrors | public function uploadErrors($value, $options = []) {
$defaults = [
'allowNoFileError' => true
];
if (is_array($options)) {
$options = array_merge($defaults, $options);
} else {
$options = $defaults;
}
if (isset($value['error']) && ($value['error'] !== null)) {
switch ($value['error']) {
case UPLOAD_ERR_OK:
return true;
case UPLOAD_ERR_INI_SIZE:
$this->_uploadError = __d('file_storage', 'The uploaded file exceeds limit of %s.', Number::toReadableSize(ini_get('upload_max_filesize')));
return false;
case UPLOAD_ERR_FORM_SIZE:
$this->_uploadError = __d('file_storage', 'The uploaded file is to big, please choose a smaller file or try to compress it.');
return false;
case UPLOAD_ERR_PARTIAL:
$this->_uploadError = __d('file_storage', 'The uploaded file was only partially uploaded.');
return false;
case UPLOAD_ERR_NO_FILE:
if ($options['allowNoFileError'] === false) {
$this->_uploadError = __d('file_storage', 'No file was uploaded.');
return false;
}
return true;
case UPLOAD_ERR_NO_TMP_DIR:
$this->_uploadError = __d('file_storage', 'The remote server has no temporary folder for file uploads. Please contact the site admin.');
return false;
case UPLOAD_ERR_CANT_WRITE:
$this->_uploadError = __d('file_storage', 'Failed to write file to disk. Please contact the site admin.');
return false;
case UPLOAD_ERR_EXTENSION:
$this->_uploadError = __d('file_storage', 'File upload stopped by extension. Please contact the site admin.');
return false;
default:
$this->_uploadError = __d('file_storage', 'Unknown File Error. Please contact the site admin.');
return false;
}
return false;
}
$this->_uploadError = '';
return true;
} | php | public function uploadErrors($value, $options = []) {
$defaults = [
'allowNoFileError' => true
];
if (is_array($options)) {
$options = array_merge($defaults, $options);
} else {
$options = $defaults;
}
if (isset($value['error']) && ($value['error'] !== null)) {
switch ($value['error']) {
case UPLOAD_ERR_OK:
return true;
case UPLOAD_ERR_INI_SIZE:
$this->_uploadError = __d('file_storage', 'The uploaded file exceeds limit of %s.', Number::toReadableSize(ini_get('upload_max_filesize')));
return false;
case UPLOAD_ERR_FORM_SIZE:
$this->_uploadError = __d('file_storage', 'The uploaded file is to big, please choose a smaller file or try to compress it.');
return false;
case UPLOAD_ERR_PARTIAL:
$this->_uploadError = __d('file_storage', 'The uploaded file was only partially uploaded.');
return false;
case UPLOAD_ERR_NO_FILE:
if ($options['allowNoFileError'] === false) {
$this->_uploadError = __d('file_storage', 'No file was uploaded.');
return false;
}
return true;
case UPLOAD_ERR_NO_TMP_DIR:
$this->_uploadError = __d('file_storage', 'The remote server has no temporary folder for file uploads. Please contact the site admin.');
return false;
case UPLOAD_ERR_CANT_WRITE:
$this->_uploadError = __d('file_storage', 'Failed to write file to disk. Please contact the site admin.');
return false;
case UPLOAD_ERR_EXTENSION:
$this->_uploadError = __d('file_storage', 'File upload stopped by extension. Please contact the site admin.');
return false;
default:
$this->_uploadError = __d('file_storage', 'Unknown File Error. Please contact the site admin.');
return false;
}
return false;
}
$this->_uploadError = '';
return true;
} | [
"public",
"function",
"uploadErrors",
"(",
"$",
"value",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'allowNoFileError'",
"=>",
"true",
"]",
";",
"if",
"(",
"is_array",
"(",
"$",
"options",
")",
")",
"{",
"$",
"options",... | Validates the error value that comes with the file input file.
@param array $value
@param array $options
@return bool True on success, if false the error message is set to the models field and also set in $this->_uploadError | [
"Validates",
"the",
"error",
"value",
"that",
"comes",
"with",
"the",
"file",
"input",
"file",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Validation/UploadValidator.php#L94-L150 |
burzum/cakephp-file-storage | src/Storage/Listener/EventFilterTrait.php | EventFilterTrait._getAdapterClassFromConfig | protected function _getAdapterClassFromConfig($configName) {
$config = StorageManager::config($configName);
if (!empty($config['adapterClass'])) {
return $config['adapterClass'];
}
return false;
} | php | protected function _getAdapterClassFromConfig($configName) {
$config = StorageManager::config($configName);
if (!empty($config['adapterClass'])) {
return $config['adapterClass'];
}
return false;
} | [
"protected",
"function",
"_getAdapterClassFromConfig",
"(",
"$",
"configName",
")",
"{",
"$",
"config",
"=",
"StorageManager",
"::",
"config",
"(",
"$",
"configName",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"config",
"[",
"'adapterClass'",
"]",
")",
"... | Gets the adapter class name from the adapter config
@param string $configName Name of the configuration
@return bool|string False if the config is not present | [
"Gets",
"the",
"adapter",
"class",
"name",
"from",
"the",
"adapter",
"config"
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Storage/Listener/EventFilterTrait.php#L104-L111 |
burzum/cakephp-file-storage | src/Storage/DataProcessor/ImageProcessor.php | ImageProcessor.afterStore | public function afterStore(Event $event) {
$this->pathBuilder($event->getSubject()->pathBuilder());
$this->subject = $event->getSubject();
$this->autoProcessImageVersions($event->getData('entity'), 'create');
} | php | public function afterStore(Event $event) {
$this->pathBuilder($event->getSubject()->pathBuilder());
$this->subject = $event->getSubject();
$this->autoProcessImageVersions($event->getData('entity'), 'create');
} | [
"public",
"function",
"afterStore",
"(",
"Event",
"$",
"event",
")",
"{",
"$",
"this",
"->",
"pathBuilder",
"(",
"$",
"event",
"->",
"getSubject",
"(",
")",
"->",
"pathBuilder",
"(",
")",
")",
";",
"$",
"this",
"->",
"subject",
"=",
"$",
"event",
"->... | afterStore
@param \Cake\Event\Event
@return void | [
"afterStore"
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Storage/DataProcessor/ImageProcessor.php#L58-L63 |
burzum/cakephp-file-storage | src/Storage/DataProcessor/ImageProcessor.php | ImageProcessor.autoProcessImageVersions | public function autoProcessImageVersions(EntityInterface $entity, $action) {
if (!in_array($action, ['create', 'remove'])) {
throw new InvalidArgumentException(sprintf('Action was `%s` but must be `create` or `remove`', $action));
}
$this->loadImageProcessingFromConfig();
if (!isset($this->_imageVersions[$entity->model])) {
return false;
}
$method = $action . 'AllImageVersions';
return $this->{$method}($entity);
} | php | public function autoProcessImageVersions(EntityInterface $entity, $action) {
if (!in_array($action, ['create', 'remove'])) {
throw new InvalidArgumentException(sprintf('Action was `%s` but must be `create` or `remove`', $action));
}
$this->loadImageProcessingFromConfig();
if (!isset($this->_imageVersions[$entity->model])) {
return false;
}
$method = $action . 'AllImageVersions';
return $this->{$method}($entity);
} | [
"public",
"function",
"autoProcessImageVersions",
"(",
"EntityInterface",
"$",
"entity",
",",
"$",
"action",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"action",
",",
"[",
"'create'",
",",
"'remove'",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgume... | Convenience method to auto create ALL and auto remove ALL image versions for
an entity.
Call this in your listener after you stored or removed a file that has image
versions. If you need more details in your logic around creating or removing
image versions use the other methods from this trait to implement the checks
and behavior you need.
@param \Cake\Datasource\EntityInterface $entity Entity
@param string $action `create` or `remove` $action Action
@return array | [
"Convenience",
"method",
"to",
"auto",
"create",
"ALL",
"and",
"auto",
"remove",
"ALL",
"image",
"versions",
"for",
"an",
"entity",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Storage/DataProcessor/ImageProcessor.php#L90-L101 |
burzum/cakephp-file-storage | src/Storage/DataProcessor/ImageProcessor.php | ImageProcessor.getImageVersionHash | public function getImageVersionHash($model, $version) {
if (empty($this->_imageVersionHashes[$model][$version])) {
throw new RuntimeException(sprintf('Version "%s" for identifier "%s" does not exist!', $version, $model));
}
return $this->_imageVersionHashes[$model][$version];
} | php | public function getImageVersionHash($model, $version) {
if (empty($this->_imageVersionHashes[$model][$version])) {
throw new RuntimeException(sprintf('Version "%s" for identifier "%s" does not exist!', $version, $model));
}
return $this->_imageVersionHashes[$model][$version];
} | [
"public",
"function",
"getImageVersionHash",
"(",
"$",
"model",
",",
"$",
"version",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"_imageVersionHashes",
"[",
"$",
"model",
"]",
"[",
"$",
"version",
"]",
")",
")",
"{",
"throw",
"new",
"RuntimeE... | Gets the hash of a specific image version for an entity.
@param string $model Model identifier.
@param string $version Version identifier.
@return string | [
"Gets",
"the",
"hash",
"of",
"a",
"specific",
"image",
"version",
"for",
"an",
"entity",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Storage/DataProcessor/ImageProcessor.php#L138-L144 |
burzum/cakephp-file-storage | src/Storage/DataProcessor/ImageProcessor.php | ImageProcessor.createImageVersions | public function createImageVersions(EntityInterface $entity, array $versions, array $options = []) {
$this->_checkImageVersions($entity->model, $versions);
$options += $this->_defaultOutput + [
'overwrite' => true
];
$result = [];
$storage = $this->getStorageAdapter($entity->adapter);
foreach ($this->_imageVersions[$entity->model] as $version => $operations) {
if (!in_array($version, $versions)) {
continue;
}
$saveOptions = $options + ['format' => $entity->extension];
if (isset($operations['_output'])) {
$saveOptions = $operations['_output'] + $saveOptions;
unset($operations['_output']);
}
$path = $this->imageVersionPath($entity, $version, 'fullPath', $saveOptions);
try {
if ($options['overwrite'] || !$storage->has($path)) {
unset($saveOptions['overwrite']);
$output = $this->subject->createTmpFile();
$tmpFile = $this->subject->tmpFile($storage, $this->pathBuilder()->fullPath($entity));
$this->imageProcessor()->open($tmpFile);
$this->imageProcessor()->batchProcess($output, $operations, $saveOptions);
$storage->write($path, file_get_contents($output), true);
unlink($tmpFile);
unlink($output);
}
$result[$version] = [
'status' => 'success',
'path' => $path,
'hash' => $this->getImageVersionHash($entity->model, $version)
];
} catch (\Exception $e) {
$result[$version] = [
'status' => 'error',
'error' => $e->getMessage(),
'line' => $e->getLine(),
'file' => $e->getFile()
];
}
}
return $result;
} | php | public function createImageVersions(EntityInterface $entity, array $versions, array $options = []) {
$this->_checkImageVersions($entity->model, $versions);
$options += $this->_defaultOutput + [
'overwrite' => true
];
$result = [];
$storage = $this->getStorageAdapter($entity->adapter);
foreach ($this->_imageVersions[$entity->model] as $version => $operations) {
if (!in_array($version, $versions)) {
continue;
}
$saveOptions = $options + ['format' => $entity->extension];
if (isset($operations['_output'])) {
$saveOptions = $operations['_output'] + $saveOptions;
unset($operations['_output']);
}
$path = $this->imageVersionPath($entity, $version, 'fullPath', $saveOptions);
try {
if ($options['overwrite'] || !$storage->has($path)) {
unset($saveOptions['overwrite']);
$output = $this->subject->createTmpFile();
$tmpFile = $this->subject->tmpFile($storage, $this->pathBuilder()->fullPath($entity));
$this->imageProcessor()->open($tmpFile);
$this->imageProcessor()->batchProcess($output, $operations, $saveOptions);
$storage->write($path, file_get_contents($output), true);
unlink($tmpFile);
unlink($output);
}
$result[$version] = [
'status' => 'success',
'path' => $path,
'hash' => $this->getImageVersionHash($entity->model, $version)
];
} catch (\Exception $e) {
$result[$version] = [
'status' => 'error',
'error' => $e->getMessage(),
'line' => $e->getLine(),
'file' => $e->getFile()
];
}
}
return $result;
} | [
"public",
"function",
"createImageVersions",
"(",
"EntityInterface",
"$",
"entity",
",",
"array",
"$",
"versions",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"_checkImageVersions",
"(",
"$",
"entity",
"->",
"model",
",",
"$",... | Creates the image versions of an entity.
@param \Cake\Datasource\EntityInterface $entity
@param array $versions Versions array.
@param array $options Imagine save options.
@return array | [
"Creates",
"the",
"image",
"versions",
"of",
"an",
"entity",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Storage/DataProcessor/ImageProcessor.php#L173-L223 |
burzum/cakephp-file-storage | src/Storage/DataProcessor/ImageProcessor.php | ImageProcessor.removeImageVersions | public function removeImageVersions(EntityInterface $entity, array $versions, array $options = []) {
$this->_checkImageVersions($entity->model, $versions);
$result = [];
foreach ($versions as $version) {
$hash = $this->getImageVersionHash($entity->model, $version);
$path = $this->pathBuilder()->fullPath($entity, ['fileSuffix' => '.' . $hash]);
$result[$version] = [
'status' => 'success',
'hash' => $hash,
'path' => $path
];
try {
$this->getStorageAdapter($entity->adapter)->delete($path);
} catch (\Exception $e) {
$result[$version]['status'] = 'error';
$result[$version]['error'] = $e->getMessage();
}
}
return $result;
} | php | public function removeImageVersions(EntityInterface $entity, array $versions, array $options = []) {
$this->_checkImageVersions($entity->model, $versions);
$result = [];
foreach ($versions as $version) {
$hash = $this->getImageVersionHash($entity->model, $version);
$path = $this->pathBuilder()->fullPath($entity, ['fileSuffix' => '.' . $hash]);
$result[$version] = [
'status' => 'success',
'hash' => $hash,
'path' => $path
];
try {
$this->getStorageAdapter($entity->adapter)->delete($path);
} catch (\Exception $e) {
$result[$version]['status'] = 'error';
$result[$version]['error'] = $e->getMessage();
}
}
return $result;
} | [
"public",
"function",
"removeImageVersions",
"(",
"EntityInterface",
"$",
"entity",
",",
"array",
"$",
"versions",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"_checkImageVersions",
"(",
"$",
"entity",
"->",
"model",
",",
"$",... | Removes image versions of an entity.
@param \Cake\Datasource\EntityInterface $entity
@param array List of image version to remove for that entity.
@param array $options
@param array $options
@return array | [
"Removes",
"image",
"versions",
"of",
"an",
"entity",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Storage/DataProcessor/ImageProcessor.php#L234-L255 |
burzum/cakephp-file-storage | src/Storage/DataProcessor/ImageProcessor.php | ImageProcessor.createAllImageVersions | public function createAllImageVersions(EntityInterface $entity, array $options = []) {
return $this->createImageVersions(
$entity,
$this->getAllVersionsKeysForModel($entity->model),
$options
);
} | php | public function createAllImageVersions(EntityInterface $entity, array $options = []) {
return $this->createImageVersions(
$entity,
$this->getAllVersionsKeysForModel($entity->model),
$options
);
} | [
"public",
"function",
"createAllImageVersions",
"(",
"EntityInterface",
"$",
"entity",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"createImageVersions",
"(",
"$",
"entity",
",",
"$",
"this",
"->",
"getAllVersionsKeysFor... | Convenience method to create ALL versions for an entity.
@param \Cake\Datasource\EntityInterface
@return array | [
"Convenience",
"method",
"to",
"create",
"ALL",
"versions",
"for",
"an",
"entity",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Storage/DataProcessor/ImageProcessor.php#L278-L284 |
burzum/cakephp-file-storage | src/Storage/DataProcessor/ImageProcessor.php | ImageProcessor.removeAllImageVersions | public function removeAllImageVersions(EntityInterface $entity, array $options = []) {
return $this->removeImageVersions(
$entity,
$this->getAllVersionsKeysForModel($entity->model),
$options
);
} | php | public function removeAllImageVersions(EntityInterface $entity, array $options = []) {
return $this->removeImageVersions(
$entity,
$this->getAllVersionsKeysForModel($entity->model),
$options
);
} | [
"public",
"function",
"removeAllImageVersions",
"(",
"EntityInterface",
"$",
"entity",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"removeImageVersions",
"(",
"$",
"entity",
",",
"$",
"this",
"->",
"getAllVersionsKeysFor... | Convenience method to delete ALL versions for an entity.
@param \Cake\Datasource\EntityInterface
@return array | [
"Convenience",
"method",
"to",
"delete",
"ALL",
"versions",
"for",
"an",
"entity",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Storage/DataProcessor/ImageProcessor.php#L292-L298 |
burzum/cakephp-file-storage | src/Storage/DataProcessor/ImageProcessor.php | ImageProcessor.imageVersionPath | public function imageVersionPath(EntityInterface $entity, $version, $type = 'fullPath', $options = []) {
if (empty($version)) {
// Temporary fix for GH #116, this should be fixed in the helper and by
// introducing getting an URL by event as well in the long run.
return $this->pathBuilder()->url($entity, $options);
}
$hash = $this->getImageVersionHash($entity->model, $version);
$output = $this->_defaultOutput + ['format' => $entity->extension];
$operations = $this->_imageVersions[$entity->model][$version];
if (isset($operations['_output'])) {
$output = $operations['_output'] + $output;
}
$options += [
'preserveExtension' => false,
'fileSuffix' => '.' . $hash . '.' . $output['format']
];
return $this->pathBuilder()->{$type}($entity, $options);
} | php | public function imageVersionPath(EntityInterface $entity, $version, $type = 'fullPath', $options = []) {
if (empty($version)) {
// Temporary fix for GH #116, this should be fixed in the helper and by
// introducing getting an URL by event as well in the long run.
return $this->pathBuilder()->url($entity, $options);
}
$hash = $this->getImageVersionHash($entity->model, $version);
$output = $this->_defaultOutput + ['format' => $entity->extension];
$operations = $this->_imageVersions[$entity->model][$version];
if (isset($operations['_output'])) {
$output = $operations['_output'] + $output;
}
$options += [
'preserveExtension' => false,
'fileSuffix' => '.' . $hash . '.' . $output['format']
];
return $this->pathBuilder()->{$type}($entity, $options);
} | [
"public",
"function",
"imageVersionPath",
"(",
"EntityInterface",
"$",
"entity",
",",
"$",
"version",
",",
"$",
"type",
"=",
"'fullPath'",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"version",
")",
")",
"{",
"// Tempora... | Generates image version path / url / filename, etc.
@param \Cake\Datasource\EntityInterface $entity Image entity.
@param string $version Version name
@param string $type Path type
@param array $options PathBuilder options
@return string | [
"Generates",
"image",
"version",
"path",
"/",
"url",
"/",
"filename",
"etc",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Storage/DataProcessor/ImageProcessor.php#L309-L330 |
burzum/cakephp-file-storage | src/Shell/Task/ImageTask.php | ImageTask._loop | protected function _loop($identifier, $options, $action) {
$count = $this->_getCount($identifier);
$offset = 0;
$limit = $this->params['limit'];
$this->out(__d('file_storage', '{0} record(s) will be processed.' . "\n", $count));
do {
$records = $this->_getRecords($identifier, $limit, $offset);
if (!empty($records)) {
foreach ($records as $record) {
$method = '_' . $action . 'Image';
try {
$this->{$method}($record, $options);
} catch (StorageException $e) {
$this->err($e->getMessage());
}
}
}
$offset += $limit;
$this->out(__d('file_storage', '{0} of {1} records processed.', [$limit, $count]));
} while ($records->count() > 0);
} | php | protected function _loop($identifier, $options, $action) {
$count = $this->_getCount($identifier);
$offset = 0;
$limit = $this->params['limit'];
$this->out(__d('file_storage', '{0} record(s) will be processed.' . "\n", $count));
do {
$records = $this->_getRecords($identifier, $limit, $offset);
if (!empty($records)) {
foreach ($records as $record) {
$method = '_' . $action . 'Image';
try {
$this->{$method}($record, $options);
} catch (StorageException $e) {
$this->err($e->getMessage());
}
}
}
$offset += $limit;
$this->out(__d('file_storage', '{0} of {1} records processed.', [$limit, $count]));
} while ($records->count() > 0);
} | [
"protected",
"function",
"_loop",
"(",
"$",
"identifier",
",",
"$",
"options",
",",
"$",
"action",
")",
"{",
"$",
"count",
"=",
"$",
"this",
"->",
"_getCount",
"(",
"$",
"identifier",
")",
";",
"$",
"offset",
"=",
"0",
";",
"$",
"limit",
"=",
"$",
... | Loops through image records and performs requested operations on them.
@param string $identifier
@return void | [
"Loops",
"through",
"image",
"records",
"and",
"performs",
"requested",
"operations",
"on",
"them",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Shell/Task/ImageTask.php#L65-L87 |
burzum/cakephp-file-storage | src/Shell/Task/ImageTask.php | ImageTask._removeImage | protected function _removeImage($record, $options) {
$Event = new Event('ImageVersion.removeVersion', $this->Table, [
'entity' => $record,
'operations' => $options
]);
EventManager::instance()->dispatch($Event);
} | php | protected function _removeImage($record, $options) {
$Event = new Event('ImageVersion.removeVersion', $this->Table, [
'entity' => $record,
'operations' => $options
]);
EventManager::instance()->dispatch($Event);
} | [
"protected",
"function",
"_removeImage",
"(",
"$",
"record",
",",
"$",
"options",
")",
"{",
"$",
"Event",
"=",
"new",
"Event",
"(",
"'ImageVersion.removeVersion'",
",",
"$",
"this",
"->",
"Table",
",",
"[",
"'entity'",
"=>",
"$",
"record",
",",
"'operation... | Triggers the event to remove image versions.
@param \Cake\ORM\Entity
@param array
@return void | [
"Triggers",
"the",
"event",
"to",
"remove",
"image",
"versions",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Shell/Task/ImageTask.php#L96-L102 |
burzum/cakephp-file-storage | src/Shell/Task/ImageTask.php | ImageTask._getRecords | public function _getRecords($identifier, $limit, $offset) {
return $this->Table
->find()
->where([$this->Table->alias() . '.model' => $identifier])
->limit($limit)
->offset($offset)
->all();
} | php | public function _getRecords($identifier, $limit, $offset) {
return $this->Table
->find()
->where([$this->Table->alias() . '.model' => $identifier])
->limit($limit)
->offset($offset)
->all();
} | [
"public",
"function",
"_getRecords",
"(",
"$",
"identifier",
",",
"$",
"limit",
",",
"$",
"offset",
")",
"{",
"return",
"$",
"this",
"->",
"Table",
"->",
"find",
"(",
")",
"->",
"where",
"(",
"[",
"$",
"this",
"->",
"Table",
"->",
"alias",
"(",
")"... | Gets the records for the loop.
@param string $identifier
@param int $limit
@param int $offset
@return \Cake\ORM\ResultSet | [
"Gets",
"the",
"records",
"for",
"the",
"loop",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Shell/Task/ImageTask.php#L127-L134 |
burzum/cakephp-file-storage | src/Shell/Task/ImageTask.php | ImageTask._getCount | protected function _getCount($identifier) {
$count = $this->_getCountQuery($identifier)->count();
if ($count === 0) {
$this->out(__d('file_storage', 'No records for identifier "{0}" found.', $identifier));
$this->_stop();
}
return $count;
} | php | protected function _getCount($identifier) {
$count = $this->_getCountQuery($identifier)->count();
if ($count === 0) {
$this->out(__d('file_storage', 'No records for identifier "{0}" found.', $identifier));
$this->_stop();
}
return $count;
} | [
"protected",
"function",
"_getCount",
"(",
"$",
"identifier",
")",
"{",
"$",
"count",
"=",
"$",
"this",
"->",
"_getCountQuery",
"(",
"$",
"identifier",
")",
"->",
"count",
"(",
")",
";",
"if",
"(",
"$",
"count",
"===",
"0",
")",
"{",
"$",
"this",
"... | Gets the amount of records for an identifier in the DB.
@param string $identifier
@return int | [
"Gets",
"the",
"amount",
"of",
"records",
"for",
"an",
"identifier",
"in",
"the",
"DB",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Shell/Task/ImageTask.php#L142-L150 |
burzum/cakephp-file-storage | src/Shell/Task/ImageTask.php | ImageTask._getCountQuery | protected function _getCountQuery($identifier) {
return $this->Table
->find()
->where([
$this->Table->alias() . '.model' => $identifier
]);
} | php | protected function _getCountQuery($identifier) {
return $this->Table
->find()
->where([
$this->Table->alias() . '.model' => $identifier
]);
} | [
"protected",
"function",
"_getCountQuery",
"(",
"$",
"identifier",
")",
"{",
"return",
"$",
"this",
"->",
"Table",
"->",
"find",
"(",
")",
"->",
"where",
"(",
"[",
"$",
"this",
"->",
"Table",
"->",
"alias",
"(",
")",
".",
"'.model'",
"=>",
"$",
"iden... | Gets the query object for the count.
@param string $identifier
@return \Cake\ORM\Query | [
"Gets",
"the",
"query",
"object",
"for",
"the",
"count",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Shell/Task/ImageTask.php#L158-L164 |
burzum/cakephp-file-storage | src/Shell/Task/ImageTask.php | ImageTask.getOptionParser | public function getOptionParser() {
$parser = parent::getOptionParser();
$parser->addOption('model', [
'short' => 'm',
'help' => __('The model to use.'),
'default' => 'Burzum/FileStorage.ImageStorage'
]);
$parser->addOption('limit', [
'short' => 'l',
'help' => __('The limit of records to process in a batch.'),
'default' => 50
]);
$parser->addOption('versions', [
'short' => 's',
'help' => __('The model to use.'),
'default' => 'Burzum/FileStorage.ImageStorage'
])
->addSubcommand('remove', [
'remove' => 'Remove image versions.'
])
->addSubcommand('generate', [
'remove' => 'Generate image versions.'
]);
$parser->addArguments([
'identifier' => ['help' => 'The identifier to process', 'required' => true],
'versions' => ['help' => 'The identifier to process', 'required' => true],
]);
return $parser;
} | php | public function getOptionParser() {
$parser = parent::getOptionParser();
$parser->addOption('model', [
'short' => 'm',
'help' => __('The model to use.'),
'default' => 'Burzum/FileStorage.ImageStorage'
]);
$parser->addOption('limit', [
'short' => 'l',
'help' => __('The limit of records to process in a batch.'),
'default' => 50
]);
$parser->addOption('versions', [
'short' => 's',
'help' => __('The model to use.'),
'default' => 'Burzum/FileStorage.ImageStorage'
])
->addSubcommand('remove', [
'remove' => 'Remove image versions.'
])
->addSubcommand('generate', [
'remove' => 'Generate image versions.'
]);
$parser->addArguments([
'identifier' => ['help' => 'The identifier to process', 'required' => true],
'versions' => ['help' => 'The identifier to process', 'required' => true],
]);
return $parser;
} | [
"public",
"function",
"getOptionParser",
"(",
")",
"{",
"$",
"parser",
"=",
"parent",
"::",
"getOptionParser",
"(",
")",
";",
"$",
"parser",
"->",
"addOption",
"(",
"'model'",
",",
"[",
"'short'",
"=>",
"'m'",
",",
"'help'",
"=>",
"__",
"(",
"'The model ... | {@inheritDoc} | [
"{"
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Shell/Task/ImageTask.php#L169-L201 |
burzum/cakephp-file-storage | src/View/Helper/LegacyImageHelper.php | LegacyImageHelper.imageUrl | public function imageUrl($image, $version = null, $options = []) {
if (empty($image) || empty($image['id'])) {
return false;
}
$eventOptions = [
'hash' => $this->_getHash($version, $image),
'image' => $image,
'version' => $version,
'options' => $options,
'pathType' => 'url'
];
$event = new Event('ImageVersion.getVersions', $this, $eventOptions);
EventManager::instance()->dispatch($event);
if ($event->isStopped()) {
return $this->normalizePath($event->getData('path'));
}
return false;
} | php | public function imageUrl($image, $version = null, $options = []) {
if (empty($image) || empty($image['id'])) {
return false;
}
$eventOptions = [
'hash' => $this->_getHash($version, $image),
'image' => $image,
'version' => $version,
'options' => $options,
'pathType' => 'url'
];
$event = new Event('ImageVersion.getVersions', $this, $eventOptions);
EventManager::instance()->dispatch($event);
if ($event->isStopped()) {
return $this->normalizePath($event->getData('path'));
}
return false;
} | [
"public",
"function",
"imageUrl",
"(",
"$",
"image",
",",
"$",
"version",
"=",
"null",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"image",
")",
"||",
"empty",
"(",
"$",
"image",
"[",
"'id'",
"]",
")",
")",
"{",
... | URL
@param array $image FileStorage array record or whatever else table that matches this helpers needs without the model, we just want the record fields
@param string|null $version Image version string
@param array $options HtmlHelper::image(), 2nd arg options array
@throws \InvalidArgumentException
@return string | [
"URL"
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/View/Helper/LegacyImageHelper.php#L27-L48 |
burzum/cakephp-file-storage | src/Model/Behavior/FileStorageBehavior.php | FileStorageBehavior._isFileUploadPresent | protected function _isFileUploadPresent($entity) {
$field = $this->getConfig('fileField');
if ($this->getConfig('ignoreEmptyFile') === true) {
if (!isset($entity[$field]['error']) || $entity[$field]['error'] === UPLOAD_ERR_NO_FILE) {
return false;
}
}
return true;
} | php | protected function _isFileUploadPresent($entity) {
$field = $this->getConfig('fileField');
if ($this->getConfig('ignoreEmptyFile') === true) {
if (!isset($entity[$field]['error']) || $entity[$field]['error'] === UPLOAD_ERR_NO_FILE) {
return false;
}
}
return true;
} | [
"protected",
"function",
"_isFileUploadPresent",
"(",
"$",
"entity",
")",
"{",
"$",
"field",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'fileField'",
")",
";",
"if",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'ignoreEmptyFile'",
")",
"===",
"true",
")",
... | Checks if a file upload is present.
@param \Cake\Datasource\EntityInterface|array $entity
@return bool | [
"Checks",
"if",
"a",
"file",
"upload",
"is",
"present",
"."
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Model/Behavior/FileStorageBehavior.php#L61-L70 |
burzum/cakephp-file-storage | src/Model/Behavior/FileStorageBehavior.php | FileStorageBehavior.beforeMarshal | public function beforeMarshal(Event $event, ArrayAccess $data) {
if (!$this->_isFileUploadPresent($data)) {
return;
}
$this->_getFileInfoFromUpload($data);
} | php | public function beforeMarshal(Event $event, ArrayAccess $data) {
if (!$this->_isFileUploadPresent($data)) {
return;
}
$this->_getFileInfoFromUpload($data);
} | [
"public",
"function",
"beforeMarshal",
"(",
"Event",
"$",
"event",
",",
"ArrayAccess",
"$",
"data",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"_isFileUploadPresent",
"(",
"$",
"data",
")",
")",
"{",
"return",
";",
"}",
"$",
"this",
"->",
"_getFileIn... | beforeMarshal callback
@param \Cake\Event\Event $event
@param \ArrayAccess $data
@return void | [
"beforeMarshal",
"callback"
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Model/Behavior/FileStorageBehavior.php#L79-L85 |
burzum/cakephp-file-storage | src/Model/Behavior/FileStorageBehavior.php | FileStorageBehavior.beforeSave | public function beforeSave(Event $event, EntityInterface $entity) {
if (!$this->_isFileUploadPresent($entity)) {
$event->stopPropagation();
return;
}
$this->_checkEntityBeforeSave($entity);
$this->dispatchEvent('FileStorage.beforeSave', [
'entity' => $entity,
'storageAdapter' => $this->getStorageAdapter($entity->get('adapter'))
], $this->_table);
} | php | public function beforeSave(Event $event, EntityInterface $entity) {
if (!$this->_isFileUploadPresent($entity)) {
$event->stopPropagation();
return;
}
$this->_checkEntityBeforeSave($entity);
$this->dispatchEvent('FileStorage.beforeSave', [
'entity' => $entity,
'storageAdapter' => $this->getStorageAdapter($entity->get('adapter'))
], $this->_table);
} | [
"public",
"function",
"beforeSave",
"(",
"Event",
"$",
"event",
",",
"EntityInterface",
"$",
"entity",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"_isFileUploadPresent",
"(",
"$",
"entity",
")",
")",
"{",
"$",
"event",
"->",
"stopPropagation",
"(",
")"... | beforeSave callback
@param \Cake\Event\Event $event
@param \Cake\Datasource\EntityInterface $entity
@return void | [
"beforeSave",
"callback"
] | train | https://github.com/burzum/cakephp-file-storage/blob/e0cc17e262ad314a904cf57069f619b9561b48e9/src/Model/Behavior/FileStorageBehavior.php#L94-L107 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.