id
int32
0
241k
repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
29,500
Innmind/Immutable
src/Str.php
Str.matches
public function matches(string $regex): bool { if (\func_num_args() !== 1) { throw new LogicException('Offset is no longer supported'); } return RegExp::of($regex)->matches($this); }
php
public function matches(string $regex): bool { if (\func_num_args() !== 1) { throw new LogicException('Offset is no longer supported'); } return RegExp::of($regex)->matches($this); }
[ "public", "function", "matches", "(", "string", "$", "regex", ")", ":", "bool", "{", "if", "(", "\\", "func_num_args", "(", ")", "!==", "1", ")", "{", "throw", "new", "LogicException", "(", "'Offset is no longer supported'", ")", ";", "}", "return", "RegExp", "::", "of", "(", "$", "regex", ")", "->", "matches", "(", "$", "this", ")", ";", "}" ]
Check if the string match the given regular expression @param string $regex @throws Exception If the regex failed @return bool
[ "Check", "if", "the", "string", "match", "the", "given", "regular", "expression" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L397-L404
29,501
Innmind/Immutable
src/Str.php
Str.pregReplace
public function pregReplace( string $regex, string $replacement, int $limit = -1 ): self { $value = \preg_replace( $regex, $replacement, $this->value, $limit ); if ($value === null) { throw new RegexException('', \preg_last_error()); } return new self($value, $this->encoding); }
php
public function pregReplace( string $regex, string $replacement, int $limit = -1 ): self { $value = \preg_replace( $regex, $replacement, $this->value, $limit ); if ($value === null) { throw new RegexException('', \preg_last_error()); } return new self($value, $this->encoding); }
[ "public", "function", "pregReplace", "(", "string", "$", "regex", ",", "string", "$", "replacement", ",", "int", "$", "limit", "=", "-", "1", ")", ":", "self", "{", "$", "value", "=", "\\", "preg_replace", "(", "$", "regex", ",", "$", "replacement", ",", "$", "this", "->", "value", ",", "$", "limit", ")", ";", "if", "(", "$", "value", "===", "null", ")", "{", "throw", "new", "RegexException", "(", "''", ",", "\\", "preg_last_error", "(", ")", ")", ";", "}", "return", "new", "self", "(", "$", "value", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Replace part of the string by using a regular expression @param string $regex @param string $replacement @param int $limit @throws Exception If the regex failed @return self
[ "Replace", "part", "of", "the", "string", "by", "using", "a", "regular", "expression" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L456-L473
29,502
Innmind/Immutable
src/Str.php
Str.substring
public function substring(int $start, int $length = null): self { if ($this->length() === 0) { return $this; } $sub = \mb_substr($this->value, $start, $length, (string) $this->encoding()); return new self($sub, $this->encoding); }
php
public function substring(int $start, int $length = null): self { if ($this->length() === 0) { return $this; } $sub = \mb_substr($this->value, $start, $length, (string) $this->encoding()); return new self($sub, $this->encoding); }
[ "public", "function", "substring", "(", "int", "$", "start", ",", "int", "$", "length", "=", "null", ")", ":", "self", "{", "if", "(", "$", "this", "->", "length", "(", ")", "===", "0", ")", "{", "return", "$", "this", ";", "}", "$", "sub", "=", "\\", "mb_substr", "(", "$", "this", "->", "value", ",", "$", "start", ",", "$", "length", ",", "(", "string", ")", "$", "this", "->", "encoding", "(", ")", ")", ";", "return", "new", "self", "(", "$", "sub", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Return part of the string @param int $start @param int $length @return self
[ "Return", "part", "of", "the", "string" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L483-L492
29,503
Innmind/Immutable
src/Str.php
Str.camelize
public function camelize(): self { return $this ->pregSplit('/_| /') ->map(function(self $part) { return $part->ucfirst(); }) ->join('') ->toEncoding((string) $this->encoding()); }
php
public function camelize(): self { return $this ->pregSplit('/_| /') ->map(function(self $part) { return $part->ucfirst(); }) ->join('') ->toEncoding((string) $this->encoding()); }
[ "public", "function", "camelize", "(", ")", ":", "self", "{", "return", "$", "this", "->", "pregSplit", "(", "'/_| /'", ")", "->", "map", "(", "function", "(", "self", "$", "part", ")", "{", "return", "$", "part", "->", "ucfirst", "(", ")", ";", "}", ")", "->", "join", "(", "''", ")", "->", "toEncoding", "(", "(", "string", ")", "$", "this", "->", "encoding", "(", ")", ")", ";", "}" ]
Return a CamelCase representation of the string @return self
[ "Return", "a", "CamelCase", "representation", "of", "the", "string" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L555-L564
29,504
Innmind/Immutable
src/Str.php
Str.append
public function append(string $string): self { return new self((string) $this.$string, $this->encoding); }
php
public function append(string $string): self { return new self((string) $this.$string, $this->encoding); }
[ "public", "function", "append", "(", "string", "$", "string", ")", ":", "self", "{", "return", "new", "self", "(", "(", "string", ")", "$", "this", ".", "$", "string", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Append a string at the end of the current one @param string $string @return self
[ "Append", "a", "string", "at", "the", "end", "of", "the", "current", "one" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L573-L576
29,505
Innmind/Immutable
src/Str.php
Str.prepend
public function prepend(string $string): self { return new self($string.(string) $this, $this->encoding); }
php
public function prepend(string $string): self { return new self($string.(string) $this, $this->encoding); }
[ "public", "function", "prepend", "(", "string", "$", "string", ")", ":", "self", "{", "return", "new", "self", "(", "$", "string", ".", "(", "string", ")", "$", "this", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Prepend a string at the beginning of the current one @param string $string @return self
[ "Prepend", "a", "string", "at", "the", "beginning", "of", "the", "current", "one" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L585-L588
29,506
Innmind/Immutable
src/Str.php
Str.rightTrim
public function rightTrim(string $mask = null): self { return new self( $mask === null ? \rtrim((string) $this) : \rtrim((string) $this, $mask), $this->encoding ); }
php
public function rightTrim(string $mask = null): self { return new self( $mask === null ? \rtrim((string) $this) : \rtrim((string) $this, $mask), $this->encoding ); }
[ "public", "function", "rightTrim", "(", "string", "$", "mask", "=", "null", ")", ":", "self", "{", "return", "new", "self", "(", "$", "mask", "===", "null", "?", "\\", "rtrim", "(", "(", "string", ")", "$", "this", ")", ":", "\\", "rtrim", "(", "(", "string", ")", "$", "this", ",", "$", "mask", ")", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Trim the right side of the string @param string $mask @return self
[ "Trim", "the", "right", "side", "of", "the", "string" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L624-L630
29,507
Innmind/Immutable
src/Str.php
Str.leftTrim
public function leftTrim(string $mask = null): self { return new self( $mask === null ? \ltrim((string) $this) : \ltrim((string) $this, $mask), $this->encoding ); }
php
public function leftTrim(string $mask = null): self { return new self( $mask === null ? \ltrim((string) $this) : \ltrim((string) $this, $mask), $this->encoding ); }
[ "public", "function", "leftTrim", "(", "string", "$", "mask", "=", "null", ")", ":", "self", "{", "return", "new", "self", "(", "$", "mask", "===", "null", "?", "\\", "ltrim", "(", "(", "string", ")", "$", "this", ")", ":", "\\", "ltrim", "(", "(", "string", ")", "$", "this", ",", "$", "mask", ")", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Trim the left side of the string @param string $mask @return self
[ "Trim", "the", "left", "side", "of", "the", "string" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L639-L645
29,508
Innmind/Immutable
src/Str.php
Str.contains
public function contains(string $value): bool { try { $this->position($value); return true; } catch (SubstringException $e) { return false; } }
php
public function contains(string $value): bool { try { $this->position($value); return true; } catch (SubstringException $e) { return false; } }
[ "public", "function", "contains", "(", "string", "$", "value", ")", ":", "bool", "{", "try", "{", "$", "this", "->", "position", "(", "$", "value", ")", ";", "return", "true", ";", "}", "catch", "(", "SubstringException", "$", "e", ")", "{", "return", "false", ";", "}", "}" ]
Check if the given string is present in the current one @param string $value @return bool
[ "Check", "if", "the", "given", "string", "is", "present", "in", "the", "current", "one" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L654-L663
29,509
Innmind/Immutable
src/Str.php
Str.endsWith
public function endsWith(string $value): bool { if ($value === '') { return true; } return (string) $this->takeEnd(self::of($value, $this->encoding)->length()) === $value; }
php
public function endsWith(string $value): bool { if ($value === '') { return true; } return (string) $this->takeEnd(self::of($value, $this->encoding)->length()) === $value; }
[ "public", "function", "endsWith", "(", "string", "$", "value", ")", ":", "bool", "{", "if", "(", "$", "value", "===", "''", ")", "{", "return", "true", ";", "}", "return", "(", "string", ")", "$", "this", "->", "takeEnd", "(", "self", "::", "of", "(", "$", "value", ",", "$", "this", "->", "encoding", ")", "->", "length", "(", ")", ")", "===", "$", "value", ";", "}" ]
Check if the current string ends with the given string @param string $value @return bool
[ "Check", "if", "the", "current", "string", "ends", "with", "the", "given", "string" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L692-L699
29,510
Innmind/Immutable
src/Str.php
Str.pregQuote
public function pregQuote(string $delimiter = ''): self { return new self(\preg_quote((string) $this, $delimiter), $this->encoding); }
php
public function pregQuote(string $delimiter = ''): self { return new self(\preg_quote((string) $this, $delimiter), $this->encoding); }
[ "public", "function", "pregQuote", "(", "string", "$", "delimiter", "=", "''", ")", ":", "self", "{", "return", "new", "self", "(", "\\", "preg_quote", "(", "(", "string", ")", "$", "this", ",", "$", "delimiter", ")", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Quote regular expression characters @param string $delimiter @return self
[ "Quote", "regular", "expression", "characters" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L708-L711
29,511
Innmind/Immutable
src/Str.php
Str.pad
private function pad( int $length, string $character = ' ', int $direction = self::PAD_RIGHT ): self { return new self(\str_pad( $this->value, $length, $character, $direction ), $this->encoding); }
php
private function pad( int $length, string $character = ' ', int $direction = self::PAD_RIGHT ): self { return new self(\str_pad( $this->value, $length, $character, $direction ), $this->encoding); }
[ "private", "function", "pad", "(", "int", "$", "length", ",", "string", "$", "character", "=", "' '", ",", "int", "$", "direction", "=", "self", "::", "PAD_RIGHT", ")", ":", "self", "{", "return", "new", "self", "(", "\\", "str_pad", "(", "$", "this", "->", "value", ",", "$", "length", ",", "$", "character", ",", "$", "direction", ")", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Pad the string @param int $length @param string $character @param int $direction @return self
[ "Pad", "the", "string" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L722-L733
29,512
symbiote/silverstripe-content-services
code/content/ContentWriter.php
ContentWriter.getReaderWrapper
protected function getReaderWrapper($content) { if (!$content) { $content = $this->source; } $reader = null; if (is_resource($content)) { $data = null; while (!feof($content)) { $data .= fread($content, 8192); } fclose($content); $reader = new RawContentReader($data); } else if ($content instanceof ContentReader) { $reader = $content; } else if (is_string($content)) { // assumed to be a file if (file_exists($content) && is_readable($content)) { // naughty, but it's the exception that proves the rule... $reader = new FileContentReader($content); } else { $reader = new RawContentReader($content); } } return $reader; }
php
protected function getReaderWrapper($content) { if (!$content) { $content = $this->source; } $reader = null; if (is_resource($content)) { $data = null; while (!feof($content)) { $data .= fread($content, 8192); } fclose($content); $reader = new RawContentReader($data); } else if ($content instanceof ContentReader) { $reader = $content; } else if (is_string($content)) { // assumed to be a file if (file_exists($content) && is_readable($content)) { // naughty, but it's the exception that proves the rule... $reader = new FileContentReader($content); } else { $reader = new RawContentReader($content); } } return $reader; }
[ "protected", "function", "getReaderWrapper", "(", "$", "content", ")", "{", "if", "(", "!", "$", "content", ")", "{", "$", "content", "=", "$", "this", "->", "source", ";", "}", "$", "reader", "=", "null", ";", "if", "(", "is_resource", "(", "$", "content", ")", ")", "{", "$", "data", "=", "null", ";", "while", "(", "!", "feof", "(", "$", "content", ")", ")", "{", "$", "data", ".=", "fread", "(", "$", "content", ",", "8192", ")", ";", "}", "fclose", "(", "$", "content", ")", ";", "$", "reader", "=", "new", "RawContentReader", "(", "$", "data", ")", ";", "}", "else", "if", "(", "$", "content", "instanceof", "ContentReader", ")", "{", "$", "reader", "=", "$", "content", ";", "}", "else", "if", "(", "is_string", "(", "$", "content", ")", ")", "{", "// assumed to be a file", "if", "(", "file_exists", "(", "$", "content", ")", "&&", "is_readable", "(", "$", "content", ")", ")", "{", "// naughty, but it's the exception that proves the rule...", "$", "reader", "=", "new", "FileContentReader", "(", "$", "content", ")", ";", "}", "else", "{", "$", "reader", "=", "new", "RawContentReader", "(", "$", "content", ")", ";", "}", "}", "return", "$", "reader", ";", "}" ]
Get content reader wrapper around a given piece of content @param mixed $content
[ "Get", "content", "reader", "wrapper", "around", "a", "given", "piece", "of", "content" ]
d6dec8da12208d876051aa4329a9b76032172bfa
https://github.com/symbiote/silverstripe-content-services/blob/d6dec8da12208d876051aa4329a9b76032172bfa/code/content/ContentWriter.php#L59-L86
29,513
Innmind/Immutable
src/Type.php
Type.of
public static function of(string $type): SpecificationInterface { if (\function_exists('is_'.$type)) { return new PrimitiveType($type); } if ($type === 'variable') { return new VariableType; } if ($type === 'mixed') { return new MixedType; } return new ClassType($type); }
php
public static function of(string $type): SpecificationInterface { if (\function_exists('is_'.$type)) { return new PrimitiveType($type); } if ($type === 'variable') { return new VariableType; } if ($type === 'mixed') { return new MixedType; } return new ClassType($type); }
[ "public", "static", "function", "of", "(", "string", "$", "type", ")", ":", "SpecificationInterface", "{", "if", "(", "\\", "function_exists", "(", "'is_'", ".", "$", "type", ")", ")", "{", "return", "new", "PrimitiveType", "(", "$", "type", ")", ";", "}", "if", "(", "$", "type", "===", "'variable'", ")", "{", "return", "new", "VariableType", ";", "}", "if", "(", "$", "type", "===", "'mixed'", ")", "{", "return", "new", "MixedType", ";", "}", "return", "new", "ClassType", "(", "$", "type", ")", ";", "}" ]
Build the appropriate specification for the given type @param string $type @return SpecificationInterface
[ "Build", "the", "appropriate", "specification", "for", "the", "given", "type" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Type.php#L22-L37
29,514
Innmind/Immutable
src/Type.php
Type.determine
public static function determine($value): string { $type = \gettype($value); switch ($type) { case 'object': return \get_class($value); case 'integer': return 'int'; case 'boolean': return 'bool'; case 'NULL': return 'null'; case 'double': return 'float'; default: return $type; } }
php
public static function determine($value): string { $type = \gettype($value); switch ($type) { case 'object': return \get_class($value); case 'integer': return 'int'; case 'boolean': return 'bool'; case 'NULL': return 'null'; case 'double': return 'float'; default: return $type; } }
[ "public", "static", "function", "determine", "(", "$", "value", ")", ":", "string", "{", "$", "type", "=", "\\", "gettype", "(", "$", "value", ")", ";", "switch", "(", "$", "type", ")", "{", "case", "'object'", ":", "return", "\\", "get_class", "(", "$", "value", ")", ";", "case", "'integer'", ":", "return", "'int'", ";", "case", "'boolean'", ":", "return", "'bool'", ";", "case", "'NULL'", ":", "return", "'null'", ";", "case", "'double'", ":", "return", "'float'", ";", "default", ":", "return", "$", "type", ";", "}", "}" ]
Return the type of the given value @param mixed $value @return string
[ "Return", "the", "type", "of", "the", "given", "value" ]
e41bc01b13c1b11226e5ac6937bccf3c60813ca9
https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Type.php#L46-L69
29,515
symbiote/silverstripe-content-services
code/content/FileContentReader.php
FileContentReader.read
public function read() { $id = $this->getId(); $path = $this->getPath($id); if (!is_readable($path)) { throw new Exception("Expected path $path is not readable"); } return file_get_contents($path); }
php
public function read() { $id = $this->getId(); $path = $this->getPath($id); if (!is_readable($path)) { throw new Exception("Expected path $path is not readable"); } return file_get_contents($path); }
[ "public", "function", "read", "(", ")", "{", "$", "id", "=", "$", "this", "->", "getId", "(", ")", ";", "$", "path", "=", "$", "this", "->", "getPath", "(", "$", "id", ")", ";", "if", "(", "!", "is_readable", "(", "$", "path", ")", ")", "{", "throw", "new", "Exception", "(", "\"Expected path $path is not readable\"", ")", ";", "}", "return", "file_get_contents", "(", "$", "path", ")", ";", "}" ]
Read content back to the user @return string
[ "Read", "content", "back", "to", "the", "user" ]
d6dec8da12208d876051aa4329a9b76032172bfa
https://github.com/symbiote/silverstripe-content-services/blob/d6dec8da12208d876051aa4329a9b76032172bfa/code/content/FileContentReader.php#L81-L90
29,516
hipchat/hipchat-php
src/HipChat/HipChat.php
HipChat.room_exists
public function room_exists($room_id) { try { $this->get_room($room_id); } catch (HipChat_Exception $e) { if ($e->code === self::STATUS_NOT_FOUND) { return false; } throw $e; } return true; }
php
public function room_exists($room_id) { try { $this->get_room($room_id); } catch (HipChat_Exception $e) { if ($e->code === self::STATUS_NOT_FOUND) { return false; } throw $e; } return true; }
[ "public", "function", "room_exists", "(", "$", "room_id", ")", "{", "try", "{", "$", "this", "->", "get_room", "(", "$", "room_id", ")", ";", "}", "catch", "(", "HipChat_Exception", "$", "e", ")", "{", "if", "(", "$", "e", "->", "code", "===", "self", "::", "STATUS_NOT_FOUND", ")", "{", "return", "false", ";", "}", "throw", "$", "e", ";", "}", "return", "true", ";", "}" ]
Determine if the given room name or room id already exists. @param mixed $room_id @return boolean
[ "Determine", "if", "the", "given", "room", "name", "or", "room", "id", "already", "exists", "." ]
5936c0a48d2d514d94bfc1d774b04c42cd3bc39e
https://github.com/hipchat/hipchat-php/blob/5936c0a48d2d514d94bfc1d774b04c42cd3bc39e/src/HipChat/HipChat.php#L94-L105
29,517
hipchat/hipchat-php
src/HipChat/HipChat.php
HipChat.message_room
public function message_room($room_id, $from, $message, $notify = false, $color = self::COLOR_YELLOW, $message_format = self::FORMAT_HTML) { $args = array( 'room_id' => $room_id, 'from' => $from, 'message' => $message, 'notify' => (int)$notify, 'color' => $color, 'message_format' => $message_format ); $response = $this->make_request('rooms/message', $args, 'POST'); return ($response->status == 'sent'); }
php
public function message_room($room_id, $from, $message, $notify = false, $color = self::COLOR_YELLOW, $message_format = self::FORMAT_HTML) { $args = array( 'room_id' => $room_id, 'from' => $from, 'message' => $message, 'notify' => (int)$notify, 'color' => $color, 'message_format' => $message_format ); $response = $this->make_request('rooms/message', $args, 'POST'); return ($response->status == 'sent'); }
[ "public", "function", "message_room", "(", "$", "room_id", ",", "$", "from", ",", "$", "message", ",", "$", "notify", "=", "false", ",", "$", "color", "=", "self", "::", "COLOR_YELLOW", ",", "$", "message_format", "=", "self", "::", "FORMAT_HTML", ")", "{", "$", "args", "=", "array", "(", "'room_id'", "=>", "$", "room_id", ",", "'from'", "=>", "$", "from", ",", "'message'", "=>", "$", "message", ",", "'notify'", "=>", "(", "int", ")", "$", "notify", ",", "'color'", "=>", "$", "color", ",", "'message_format'", "=>", "$", "message_format", ")", ";", "$", "response", "=", "$", "this", "->", "make_request", "(", "'rooms/message'", ",", "$", "args", ",", "'POST'", ")", ";", "return", "(", "$", "response", "->", "status", "==", "'sent'", ")", ";", "}" ]
Send a message to a room @see http://api.hipchat.com/docs/api/method/rooms/message
[ "Send", "a", "message", "to", "a", "room" ]
5936c0a48d2d514d94bfc1d774b04c42cd3bc39e
https://github.com/hipchat/hipchat-php/blob/5936c0a48d2d514d94bfc1d774b04c42cd3bc39e/src/HipChat/HipChat.php#L122-L135
29,518
hipchat/hipchat-php
src/HipChat/HipChat.php
HipChat.get_rooms_history
public function get_rooms_history($room_id, $date = 'recent') { $response = $this->make_request('rooms/history', array( 'room_id' => $room_id, 'date' => $date )); return $response->messages; }
php
public function get_rooms_history($room_id, $date = 'recent') { $response = $this->make_request('rooms/history', array( 'room_id' => $room_id, 'date' => $date )); return $response->messages; }
[ "public", "function", "get_rooms_history", "(", "$", "room_id", ",", "$", "date", "=", "'recent'", ")", "{", "$", "response", "=", "$", "this", "->", "make_request", "(", "'rooms/history'", ",", "array", "(", "'room_id'", "=>", "$", "room_id", ",", "'date'", "=>", "$", "date", ")", ")", ";", "return", "$", "response", "->", "messages", ";", "}" ]
Get chat history for a room @see https://www.hipchat.com/docs/api/method/rooms/history
[ "Get", "chat", "history", "for", "a", "room" ]
5936c0a48d2d514d94bfc1d774b04c42cd3bc39e
https://github.com/hipchat/hipchat-php/blob/5936c0a48d2d514d94bfc1d774b04c42cd3bc39e/src/HipChat/HipChat.php#L142-L148
29,519
hipchat/hipchat-php
src/HipChat/HipChat.php
HipChat.set_room_topic
public function set_room_topic($room_id, $topic, $from = null) { $args = array( 'room_id' => $room_id, 'topic' => $topic, ); if ($from) { $args['from'] = $from; } $response = $this->make_request('rooms/topic', $args, 'POST'); return ($response->status == 'ok'); }
php
public function set_room_topic($room_id, $topic, $from = null) { $args = array( 'room_id' => $room_id, 'topic' => $topic, ); if ($from) { $args['from'] = $from; } $response = $this->make_request('rooms/topic', $args, 'POST'); return ($response->status == 'ok'); }
[ "public", "function", "set_room_topic", "(", "$", "room_id", ",", "$", "topic", ",", "$", "from", "=", "null", ")", "{", "$", "args", "=", "array", "(", "'room_id'", "=>", "$", "room_id", ",", "'topic'", "=>", "$", "topic", ",", ")", ";", "if", "(", "$", "from", ")", "{", "$", "args", "[", "'from'", "]", "=", "$", "from", ";", "}", "$", "response", "=", "$", "this", "->", "make_request", "(", "'rooms/topic'", ",", "$", "args", ",", "'POST'", ")", ";", "return", "(", "$", "response", "->", "status", "==", "'ok'", ")", ";", "}" ]
Set a room's topic @see http://api.hipchat.com/docs/api/method/rooms/topic
[ "Set", "a", "room", "s", "topic" ]
5936c0a48d2d514d94bfc1d774b04c42cd3bc39e
https://github.com/hipchat/hipchat-php/blob/5936c0a48d2d514d94bfc1d774b04c42cd3bc39e/src/HipChat/HipChat.php#L155-L167
29,520
hipchat/hipchat-php
src/HipChat/HipChat.php
HipChat.create_room
public function create_room($name, $owner_user_id = null, $privacy = null, $topic = null, $guest_access = null) { $args = array( 'name' => $name ); if ($owner_user_id) { $args['owner_user_id'] = $owner_user_id; } if ($privacy) { $args['privacy'] = $privacy; } if ($topic) { $args['topic'] = $topic; } if ($guest_access) { $args['guest_access'] = (int)$guest_access; } // Return the std object return $this->make_request('rooms/create', $args, 'POST'); }
php
public function create_room($name, $owner_user_id = null, $privacy = null, $topic = null, $guest_access = null) { $args = array( 'name' => $name ); if ($owner_user_id) { $args['owner_user_id'] = $owner_user_id; } if ($privacy) { $args['privacy'] = $privacy; } if ($topic) { $args['topic'] = $topic; } if ($guest_access) { $args['guest_access'] = (int)$guest_access; } // Return the std object return $this->make_request('rooms/create', $args, 'POST'); }
[ "public", "function", "create_room", "(", "$", "name", ",", "$", "owner_user_id", "=", "null", ",", "$", "privacy", "=", "null", ",", "$", "topic", "=", "null", ",", "$", "guest_access", "=", "null", ")", "{", "$", "args", "=", "array", "(", "'name'", "=>", "$", "name", ")", ";", "if", "(", "$", "owner_user_id", ")", "{", "$", "args", "[", "'owner_user_id'", "]", "=", "$", "owner_user_id", ";", "}", "if", "(", "$", "privacy", ")", "{", "$", "args", "[", "'privacy'", "]", "=", "$", "privacy", ";", "}", "if", "(", "$", "topic", ")", "{", "$", "args", "[", "'topic'", "]", "=", "$", "topic", ";", "}", "if", "(", "$", "guest_access", ")", "{", "$", "args", "[", "'guest_access'", "]", "=", "(", "int", ")", "$", "guest_access", ";", "}", "// Return the std object", "return", "$", "this", "->", "make_request", "(", "'rooms/create'", ",", "$", "args", ",", "'POST'", ")", ";", "}" ]
Create a room @see http://api.hipchat.com/docs/api/method/rooms/create
[ "Create", "a", "room" ]
5936c0a48d2d514d94bfc1d774b04c42cd3bc39e
https://github.com/hipchat/hipchat-php/blob/5936c0a48d2d514d94bfc1d774b04c42cd3bc39e/src/HipChat/HipChat.php#L174-L197
29,521
hipchat/hipchat-php
src/HipChat/HipChat.php
HipChat.delete_room
public function delete_room($room_id){ $args = array( 'room_id' => $room_id ); $response = $this->make_request('rooms/delete', $args, 'POST'); return ($response->deleted == 'true'); }
php
public function delete_room($room_id){ $args = array( 'room_id' => $room_id ); $response = $this->make_request('rooms/delete', $args, 'POST'); return ($response->deleted == 'true'); }
[ "public", "function", "delete_room", "(", "$", "room_id", ")", "{", "$", "args", "=", "array", "(", "'room_id'", "=>", "$", "room_id", ")", ";", "$", "response", "=", "$", "this", "->", "make_request", "(", "'rooms/delete'", ",", "$", "args", ",", "'POST'", ")", ";", "return", "(", "$", "response", "->", "deleted", "==", "'true'", ")", ";", "}" ]
Delete a room @see http://api.hipchat.com/docs/api/method/rooms/delete
[ "Delete", "a", "room" ]
5936c0a48d2d514d94bfc1d774b04c42cd3bc39e
https://github.com/hipchat/hipchat-php/blob/5936c0a48d2d514d94bfc1d774b04c42cd3bc39e/src/HipChat/HipChat.php#L204-L212
29,522
hipchat/hipchat-php
src/HipChat/HipChat.php
HipChat.create_user
public function create_user($email, $name, $mention_name = null, $title = null, $is_group_admin = 0, $password = null, $timezone = null) { $args = array( 'email' => $email, 'name' => $name, ); if ($mention_name) { $args['mention_name'] = $mention_name; } if ($title) { $args['title'] = $title; } if ($is_group_admin) { $args['is_group_admin'] = (int)$is_group_admin; } if ($password) { $args['password'] = $password; } // @see http://api.hipchat.com/docs/api/timezones if ($timezone) { $args['timezone'] = $timezone; } // Return the std object return $this->make_request('users/create', $args, 'POST'); }
php
public function create_user($email, $name, $mention_name = null, $title = null, $is_group_admin = 0, $password = null, $timezone = null) { $args = array( 'email' => $email, 'name' => $name, ); if ($mention_name) { $args['mention_name'] = $mention_name; } if ($title) { $args['title'] = $title; } if ($is_group_admin) { $args['is_group_admin'] = (int)$is_group_admin; } if ($password) { $args['password'] = $password; } // @see http://api.hipchat.com/docs/api/timezones if ($timezone) { $args['timezone'] = $timezone; } // Return the std object return $this->make_request('users/create', $args, 'POST'); }
[ "public", "function", "create_user", "(", "$", "email", ",", "$", "name", ",", "$", "mention_name", "=", "null", ",", "$", "title", "=", "null", ",", "$", "is_group_admin", "=", "0", ",", "$", "password", "=", "null", ",", "$", "timezone", "=", "null", ")", "{", "$", "args", "=", "array", "(", "'email'", "=>", "$", "email", ",", "'name'", "=>", "$", "name", ",", ")", ";", "if", "(", "$", "mention_name", ")", "{", "$", "args", "[", "'mention_name'", "]", "=", "$", "mention_name", ";", "}", "if", "(", "$", "title", ")", "{", "$", "args", "[", "'title'", "]", "=", "$", "title", ";", "}", "if", "(", "$", "is_group_admin", ")", "{", "$", "args", "[", "'is_group_admin'", "]", "=", "(", "int", ")", "$", "is_group_admin", ";", "}", "if", "(", "$", "password", ")", "{", "$", "args", "[", "'password'", "]", "=", "$", "password", ";", "}", "// @see http://api.hipchat.com/docs/api/timezones", "if", "(", "$", "timezone", ")", "{", "$", "args", "[", "'timezone'", "]", "=", "$", "timezone", ";", "}", "// Return the std object", "return", "$", "this", "->", "make_request", "(", "'users/create'", ",", "$", "args", ",", "'POST'", ")", ";", "}" ]
Create a new user in your group. @see http://api.hipchat.com/docs/api/method/users/create
[ "Create", "a", "new", "user", "in", "your", "group", "." ]
5936c0a48d2d514d94bfc1d774b04c42cd3bc39e
https://github.com/hipchat/hipchat-php/blob/5936c0a48d2d514d94bfc1d774b04c42cd3bc39e/src/HipChat/HipChat.php#L245-L276
29,523
hipchat/hipchat-php
src/HipChat/HipChat.php
HipChat.curl_request
public function curl_request($url, $post_data = null) { if (is_array($post_data)) { $post_data = array_map(array($this, 'sanitize_curl_parameter'), $post_data); } $ch = curl_init($url); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, $this->request_timeout); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->verify_ssl); if (isset($this->proxy)) { curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1); curl_setopt($ch, CURLOPT_PROXY, $this->proxy); } if (is_array($post_data)) { curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); } $response = curl_exec($ch); // make sure we got a real response if (strlen($response) == 0) { $errno = curl_errno($ch); $error = curl_error($ch); throw new HipChat_Exception(self::STATUS_BAD_RESPONSE, "CURL error: $errno - $error", $url); } // make sure we got a 200 $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($code != self::STATUS_OK) { throw new HipChat_Exception($code, "HTTP status code: $code, response=$response", $url); } curl_close($ch); return $response; }
php
public function curl_request($url, $post_data = null) { if (is_array($post_data)) { $post_data = array_map(array($this, 'sanitize_curl_parameter'), $post_data); } $ch = curl_init($url); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, $this->request_timeout); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->verify_ssl); if (isset($this->proxy)) { curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1); curl_setopt($ch, CURLOPT_PROXY, $this->proxy); } if (is_array($post_data)) { curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); } $response = curl_exec($ch); // make sure we got a real response if (strlen($response) == 0) { $errno = curl_errno($ch); $error = curl_error($ch); throw new HipChat_Exception(self::STATUS_BAD_RESPONSE, "CURL error: $errno - $error", $url); } // make sure we got a 200 $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($code != self::STATUS_OK) { throw new HipChat_Exception($code, "HTTP status code: $code, response=$response", $url); } curl_close($ch); return $response; }
[ "public", "function", "curl_request", "(", "$", "url", ",", "$", "post_data", "=", "null", ")", "{", "if", "(", "is_array", "(", "$", "post_data", ")", ")", "{", "$", "post_data", "=", "array_map", "(", "array", "(", "$", "this", ",", "'sanitize_curl_parameter'", ")", ",", "$", "post_data", ")", ";", "}", "$", "ch", "=", "curl_init", "(", "$", "url", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_FOLLOWLOCATION", ",", "1", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_RETURNTRANSFER", ",", "1", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_TIMEOUT", ",", "$", "this", "->", "request_timeout", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_SSL_VERIFYPEER", ",", "$", "this", "->", "verify_ssl", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "proxy", ")", ")", "{", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HTTPPROXYTUNNEL", ",", "1", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_PROXY", ",", "$", "this", "->", "proxy", ")", ";", "}", "if", "(", "is_array", "(", "$", "post_data", ")", ")", "{", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POST", ",", "1", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POSTFIELDS", ",", "$", "post_data", ")", ";", "}", "$", "response", "=", "curl_exec", "(", "$", "ch", ")", ";", "// make sure we got a real response", "if", "(", "strlen", "(", "$", "response", ")", "==", "0", ")", "{", "$", "errno", "=", "curl_errno", "(", "$", "ch", ")", ";", "$", "error", "=", "curl_error", "(", "$", "ch", ")", ";", "throw", "new", "HipChat_Exception", "(", "self", "::", "STATUS_BAD_RESPONSE", ",", "\"CURL error: $errno - $error\"", ",", "$", "url", ")", ";", "}", "// make sure we got a 200", "$", "code", "=", "(", "int", ")", "curl_getinfo", "(", "$", "ch", ",", "CURLINFO_HTTP_CODE", ")", ";", "if", "(", "$", "code", "!=", "self", "::", "STATUS_OK", ")", "{", "throw", "new", "HipChat_Exception", "(", "$", "code", ",", "\"HTTP status code: $code, response=$response\"", ",", "$", "url", ")", ";", "}", "curl_close", "(", "$", "ch", ")", ";", "return", "$", "response", ";", "}" ]
Performs a curl request @param $url URL to hit. @param $post_data Data to send via POST. Leave null for GET request. @throws HipChat_Exception @return string
[ "Performs", "a", "curl", "request" ]
5936c0a48d2d514d94bfc1d774b04c42cd3bc39e
https://github.com/hipchat/hipchat-php/blob/5936c0a48d2d514d94bfc1d774b04c42cd3bc39e/src/HipChat/HipChat.php#L359-L398
29,524
hipchat/hipchat-php
src/HipChat/HipChat.php
HipChat.make_request
public function make_request($api_method, $args = array(), $http_method = 'GET') { $args['format'] = 'json'; $args['auth_token'] = $this->auth_token; $url = "$this->api_target/$this->api_version/$api_method"; $post_data = null; // add args to url for GET if ($http_method == 'GET') { $url .= '?' . http_build_query($args); } else { $post_data = $args; } $response = $this->curl_request($url, $post_data); // make sure response is valid json $response = json_decode($response); if (!$response) { throw new HipChat_Exception(self::STATUS_BAD_RESPONSE, "Invalid JSON received: $response", $url); } return $response; }
php
public function make_request($api_method, $args = array(), $http_method = 'GET') { $args['format'] = 'json'; $args['auth_token'] = $this->auth_token; $url = "$this->api_target/$this->api_version/$api_method"; $post_data = null; // add args to url for GET if ($http_method == 'GET') { $url .= '?' . http_build_query($args); } else { $post_data = $args; } $response = $this->curl_request($url, $post_data); // make sure response is valid json $response = json_decode($response); if (!$response) { throw new HipChat_Exception(self::STATUS_BAD_RESPONSE, "Invalid JSON received: $response", $url); } return $response; }
[ "public", "function", "make_request", "(", "$", "api_method", ",", "$", "args", "=", "array", "(", ")", ",", "$", "http_method", "=", "'GET'", ")", "{", "$", "args", "[", "'format'", "]", "=", "'json'", ";", "$", "args", "[", "'auth_token'", "]", "=", "$", "this", "->", "auth_token", ";", "$", "url", "=", "\"$this->api_target/$this->api_version/$api_method\"", ";", "$", "post_data", "=", "null", ";", "// add args to url for GET", "if", "(", "$", "http_method", "==", "'GET'", ")", "{", "$", "url", ".=", "'?'", ".", "http_build_query", "(", "$", "args", ")", ";", "}", "else", "{", "$", "post_data", "=", "$", "args", ";", "}", "$", "response", "=", "$", "this", "->", "curl_request", "(", "$", "url", ",", "$", "post_data", ")", ";", "// make sure response is valid json", "$", "response", "=", "json_decode", "(", "$", "response", ")", ";", "if", "(", "!", "$", "response", ")", "{", "throw", "new", "HipChat_Exception", "(", "self", "::", "STATUS_BAD_RESPONSE", ",", "\"Invalid JSON received: $response\"", ",", "$", "url", ")", ";", "}", "return", "$", "response", ";", "}" ]
Make an API request using curl @param string $api_method Which API method to hit, like 'rooms/show'. @param array $args Data to send. @param string $http_method HTTP method (GET or POST). @throws HipChat_Exception @return mixed
[ "Make", "an", "API", "request", "using", "curl" ]
5936c0a48d2d514d94bfc1d774b04c42cd3bc39e
https://github.com/hipchat/hipchat-php/blob/5936c0a48d2d514d94bfc1d774b04c42cd3bc39e/src/HipChat/HipChat.php#L429-L453
29,525
symbiote/silverstripe-content-services
code/content/ReaderWriterBase.php
ReaderWriterBase.getContentId
public function getContentId() { if (!$this->id) { throw new Exception("Null content identifier; content must be written before retrieving id"); } return $this->getSourceIdentifier() . ContentService::SEPARATOR . $this->id; }
php
public function getContentId() { if (!$this->id) { throw new Exception("Null content identifier; content must be written before retrieving id"); } return $this->getSourceIdentifier() . ContentService::SEPARATOR . $this->id; }
[ "public", "function", "getContentId", "(", ")", "{", "if", "(", "!", "$", "this", "->", "id", ")", "{", "throw", "new", "Exception", "(", "\"Null content identifier; content must be written before retrieving id\"", ")", ";", "}", "return", "$", "this", "->", "getSourceIdentifier", "(", ")", ".", "ContentService", "::", "SEPARATOR", ".", "$", "this", "->", "id", ";", "}" ]
Get content identifier that can be used to retrieve this content at a later point in timer
[ "Get", "content", "identifier", "that", "can", "be", "used", "to", "retrieve", "this", "content", "at", "a", "later", "point", "in", "timer" ]
d6dec8da12208d876051aa4329a9b76032172bfa
https://github.com/symbiote/silverstripe-content-services/blob/d6dec8da12208d876051aa4329a9b76032172bfa/code/content/ReaderWriterBase.php#L67-L72
29,526
inpsyde/Wonolog
src/Data/FailedLogin.php
FailedLogin.level
public function level() { $this->count_attempts( 300 ); switch ( TRUE ) { case ( $this->attempts > 2 && $this->attempts <= 100 ) : return Logger::NOTICE; case ( $this->attempts > 100 && $this->attempts <= 590 ) : return Logger::WARNING; case ( $this->attempts > 590 && $this->attempts <= 990 ) : return Logger::ERROR; case ( $this->attempts > 990 ) : return Logger::CRITICAL; } return 0; }
php
public function level() { $this->count_attempts( 300 ); switch ( TRUE ) { case ( $this->attempts > 2 && $this->attempts <= 100 ) : return Logger::NOTICE; case ( $this->attempts > 100 && $this->attempts <= 590 ) : return Logger::WARNING; case ( $this->attempts > 590 && $this->attempts <= 990 ) : return Logger::ERROR; case ( $this->attempts > 990 ) : return Logger::CRITICAL; } return 0; }
[ "public", "function", "level", "(", ")", "{", "$", "this", "->", "count_attempts", "(", "300", ")", ";", "switch", "(", "TRUE", ")", "{", "case", "(", "$", "this", "->", "attempts", ">", "2", "&&", "$", "this", "->", "attempts", "<=", "100", ")", ":", "return", "Logger", "::", "NOTICE", ";", "case", "(", "$", "this", "->", "attempts", ">", "100", "&&", "$", "this", "->", "attempts", "<=", "590", ")", ":", "return", "Logger", "::", "WARNING", ";", "case", "(", "$", "this", "->", "attempts", ">", "590", "&&", "$", "this", "->", "attempts", "<=", "990", ")", ":", "return", "Logger", "::", "ERROR", ";", "case", "(", "$", "this", "->", "attempts", ">", "990", ")", ":", "return", "Logger", "::", "CRITICAL", ";", "}", "return", "0", ";", "}" ]
Determine severity of the error based on the number of login attempts in last 5 minutes. @return int
[ "Determine", "severity", "of", "the", "error", "based", "on", "the", "number", "of", "login", "attempts", "in", "last", "5", "minutes", "." ]
87ed9a60c6f5cc3a057db857273dc504efc5ad9f
https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/Data/FailedLogin.php#L60-L76
29,527
inpsyde/Wonolog
src/Data/FailedLogin.php
FailedLogin.sniff_ip
private function sniff_ip() { if ( $this->ip_data ) { return; } if ( PHP_SAPI === 'cli' ) { $this->ip_data = [ '127.0.0.1', 'CLI' ]; return; } $ip_server_keys = [ 'REMOTE_ADDR' => '', 'HTTP_CLIENT_IP' => '', 'HTTP_X_FORWARDED_FOR' => '', ]; $ips = array_intersect_key( $_SERVER, $ip_server_keys ); $this->ip_data = $ips ? [ reset( $ips ), key( $ips ) ] : [ '0.0.0.0', 'Hidden IP' ]; }
php
private function sniff_ip() { if ( $this->ip_data ) { return; } if ( PHP_SAPI === 'cli' ) { $this->ip_data = [ '127.0.0.1', 'CLI' ]; return; } $ip_server_keys = [ 'REMOTE_ADDR' => '', 'HTTP_CLIENT_IP' => '', 'HTTP_X_FORWARDED_FOR' => '', ]; $ips = array_intersect_key( $_SERVER, $ip_server_keys ); $this->ip_data = $ips ? [ reset( $ips ), key( $ips ) ] : [ '0.0.0.0', 'Hidden IP' ]; }
[ "private", "function", "sniff_ip", "(", ")", "{", "if", "(", "$", "this", "->", "ip_data", ")", "{", "return", ";", "}", "if", "(", "PHP_SAPI", "===", "'cli'", ")", "{", "$", "this", "->", "ip_data", "=", "[", "'127.0.0.1'", ",", "'CLI'", "]", ";", "return", ";", "}", "$", "ip_server_keys", "=", "[", "'REMOTE_ADDR'", "=>", "''", ",", "'HTTP_CLIENT_IP'", "=>", "''", ",", "'HTTP_X_FORWARDED_FOR'", "=>", "''", ",", "]", ";", "$", "ips", "=", "array_intersect_key", "(", "$", "_SERVER", ",", "$", "ip_server_keys", ")", ";", "$", "this", "->", "ip_data", "=", "$", "ips", "?", "[", "reset", "(", "$", "ips", ")", ",", "key", "(", "$", "ips", ")", "]", ":", "[", "'0.0.0.0'", ",", "'Hidden IP'", "]", ";", "}" ]
Try to sniff the current client IP.
[ "Try", "to", "sniff", "the", "current", "client", "IP", "." ]
87ed9a60c6f5cc3a057db857273dc504efc5ad9f
https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/Data/FailedLogin.php#L126-L141
29,528
inpsyde/Wonolog
src/Data/FailedLogin.php
FailedLogin.count_attempts
private function count_attempts( $ttl = 300 ) { if ( isset( $this->attempts ) ) { return; } $this->sniff_ip(); $ip = $this->ip_data[ 0 ]; $attempts = get_site_transient( self::TRANSIENT_NAME ); is_array( $attempts ) or $attempts = []; // Seems the first time a failed attempt for this IP if ( ! $attempts || ! array_key_exists( $ip, $attempts ) ) { $attempts[ $ip ] = [ 'count' => 0, 'last_logged' => 0, ]; } $attempts[ $ip ][ 'count' ] ++; $this->attempts_data = $attempts; $count = $attempts[ $ip ][ 'count' ]; $last_logged = $attempts[ $ip ][ 'last_logged' ]; /** * During a brute force attack, logging all the failed attempts can be so expensive to put the server down. * So we log: * * - 3rd attempt * - every 20 when total attempts are > 23 && < 100 (23rd, 43rd...) * - every 100 when total attempts are > 182 && < 1182 (183rd, 283rd...) * - every 200 when total attempts are > 1182 (1183rd, 1383rd...) */ $do_log = $count === 3 || ( $count < 100 && ( $count - $last_logged ) === 20 ) || ( $count < 1000 && ( $count - $last_logged ) === 100 ) || ( ( $count - $last_logged ) === 200 ); $do_log and $attempts[ $ip ][ 'last_logged' ] = $count; set_site_transient( self::TRANSIENT_NAME, $attempts, $ttl ); $this->attempts = $do_log ? $count : 0; }
php
private function count_attempts( $ttl = 300 ) { if ( isset( $this->attempts ) ) { return; } $this->sniff_ip(); $ip = $this->ip_data[ 0 ]; $attempts = get_site_transient( self::TRANSIENT_NAME ); is_array( $attempts ) or $attempts = []; // Seems the first time a failed attempt for this IP if ( ! $attempts || ! array_key_exists( $ip, $attempts ) ) { $attempts[ $ip ] = [ 'count' => 0, 'last_logged' => 0, ]; } $attempts[ $ip ][ 'count' ] ++; $this->attempts_data = $attempts; $count = $attempts[ $ip ][ 'count' ]; $last_logged = $attempts[ $ip ][ 'last_logged' ]; /** * During a brute force attack, logging all the failed attempts can be so expensive to put the server down. * So we log: * * - 3rd attempt * - every 20 when total attempts are > 23 && < 100 (23rd, 43rd...) * - every 100 when total attempts are > 182 && < 1182 (183rd, 283rd...) * - every 200 when total attempts are > 1182 (1183rd, 1383rd...) */ $do_log = $count === 3 || ( $count < 100 && ( $count - $last_logged ) === 20 ) || ( $count < 1000 && ( $count - $last_logged ) === 100 ) || ( ( $count - $last_logged ) === 200 ); $do_log and $attempts[ $ip ][ 'last_logged' ] = $count; set_site_transient( self::TRANSIENT_NAME, $attempts, $ttl ); $this->attempts = $do_log ? $count : 0; }
[ "private", "function", "count_attempts", "(", "$", "ttl", "=", "300", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "attempts", ")", ")", "{", "return", ";", "}", "$", "this", "->", "sniff_ip", "(", ")", ";", "$", "ip", "=", "$", "this", "->", "ip_data", "[", "0", "]", ";", "$", "attempts", "=", "get_site_transient", "(", "self", "::", "TRANSIENT_NAME", ")", ";", "is_array", "(", "$", "attempts", ")", "or", "$", "attempts", "=", "[", "]", ";", "// Seems the first time a failed attempt for this IP", "if", "(", "!", "$", "attempts", "||", "!", "array_key_exists", "(", "$", "ip", ",", "$", "attempts", ")", ")", "{", "$", "attempts", "[", "$", "ip", "]", "=", "[", "'count'", "=>", "0", ",", "'last_logged'", "=>", "0", ",", "]", ";", "}", "$", "attempts", "[", "$", "ip", "]", "[", "'count'", "]", "++", ";", "$", "this", "->", "attempts_data", "=", "$", "attempts", ";", "$", "count", "=", "$", "attempts", "[", "$", "ip", "]", "[", "'count'", "]", ";", "$", "last_logged", "=", "$", "attempts", "[", "$", "ip", "]", "[", "'last_logged'", "]", ";", "/**\n\t\t * During a brute force attack, logging all the failed attempts can be so expensive to put the server down.\n\t\t * So we log:\n\t\t *\n\t\t * - 3rd attempt\n\t\t * - every 20 when total attempts are > 23 && < 100 (23rd, 43rd...)\n\t\t * - every 100 when total attempts are > 182 && < 1182 (183rd, 283rd...)\n\t\t * - every 200 when total attempts are > 1182 (1183rd, 1383rd...)\n\t\t */", "$", "do_log", "=", "$", "count", "===", "3", "||", "(", "$", "count", "<", "100", "&&", "(", "$", "count", "-", "$", "last_logged", ")", "===", "20", ")", "||", "(", "$", "count", "<", "1000", "&&", "(", "$", "count", "-", "$", "last_logged", ")", "===", "100", ")", "||", "(", "(", "$", "count", "-", "$", "last_logged", ")", "===", "200", ")", ";", "$", "do_log", "and", "$", "attempts", "[", "$", "ip", "]", "[", "'last_logged'", "]", "=", "$", "count", ";", "set_site_transient", "(", "self", "::", "TRANSIENT_NAME", ",", "$", "attempts", ",", "$", "ttl", ")", ";", "$", "this", "->", "attempts", "=", "$", "do_log", "?", "$", "count", ":", "0", ";", "}" ]
Determine how many failed login attempts comes from the guessed IP. Use a site transient to count them. @param int $ttl transient time to live in seconds
[ "Determine", "how", "many", "failed", "login", "attempts", "comes", "from", "the", "guessed", "IP", ".", "Use", "a", "site", "transient", "to", "count", "them", "." ]
87ed9a60c6f5cc3a057db857273dc504efc5ad9f
https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/Data/FailedLogin.php#L149-L191
29,529
inpsyde/Wonolog
src/PhpErrorController.php
PhpErrorController.on_exception
public function on_exception( $e ) { // Log the PHP exception. do_action( \Inpsyde\Wonolog\LOG, new Log( $e->getMessage(), Logger::CRITICAL, Channels::PHP_ERROR, [ 'exception' => get_class( $e ), 'file' => $e->getFile(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString(), ] ) ); // after logging let's reset handler and throw the exception restore_exception_handler(); throw $e; }
php
public function on_exception( $e ) { // Log the PHP exception. do_action( \Inpsyde\Wonolog\LOG, new Log( $e->getMessage(), Logger::CRITICAL, Channels::PHP_ERROR, [ 'exception' => get_class( $e ), 'file' => $e->getFile(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString(), ] ) ); // after logging let's reset handler and throw the exception restore_exception_handler(); throw $e; }
[ "public", "function", "on_exception", "(", "$", "e", ")", "{", "// Log the PHP exception.", "do_action", "(", "\\", "Inpsyde", "\\", "Wonolog", "\\", "LOG", ",", "new", "Log", "(", "$", "e", "->", "getMessage", "(", ")", ",", "Logger", "::", "CRITICAL", ",", "Channels", "::", "PHP_ERROR", ",", "[", "'exception'", "=>", "get_class", "(", "$", "e", ")", ",", "'file'", "=>", "$", "e", "->", "getFile", "(", ")", ",", "'line'", "=>", "$", "e", "->", "getLine", "(", ")", ",", "'trace'", "=>", "$", "e", "->", "getTraceAsString", "(", ")", ",", "]", ")", ")", ";", "// after logging let's reset handler and throw the exception", "restore_exception_handler", "(", ")", ";", "throw", "$", "e", ";", "}" ]
Uncaught exception handler. @param \Throwable $e @throws \Throwable
[ "Uncaught", "exception", "handler", "." ]
87ed9a60c6f5cc3a057db857273dc504efc5ad9f
https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/PhpErrorController.php#L96-L117
29,530
inpsyde/Wonolog
src/PhpErrorController.php
PhpErrorController.on_fatal
public function on_fatal() { $last_error = error_get_last(); if ( ! $last_error ) { return; } $error = array_merge( [ 'type' => -1, 'message' => '', 'file' => '', 'line' => 0 ], $last_error ); $fatals = [ E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, ]; if ( in_array( $error[ 'type' ], $fatals, TRUE ) ) { $this->on_error( $error[ 'type' ], $error[ 'message' ], $error[ 'file' ], $error[ 'line' ] ); } }
php
public function on_fatal() { $last_error = error_get_last(); if ( ! $last_error ) { return; } $error = array_merge( [ 'type' => -1, 'message' => '', 'file' => '', 'line' => 0 ], $last_error ); $fatals = [ E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, ]; if ( in_array( $error[ 'type' ], $fatals, TRUE ) ) { $this->on_error( $error[ 'type' ], $error[ 'message' ], $error[ 'file' ], $error[ 'line' ] ); } }
[ "public", "function", "on_fatal", "(", ")", "{", "$", "last_error", "=", "error_get_last", "(", ")", ";", "if", "(", "!", "$", "last_error", ")", "{", "return", ";", "}", "$", "error", "=", "array_merge", "(", "[", "'type'", "=>", "-", "1", ",", "'message'", "=>", "''", ",", "'file'", "=>", "''", ",", "'line'", "=>", "0", "]", ",", "$", "last_error", ")", ";", "$", "fatals", "=", "[", "E_ERROR", ",", "E_PARSE", ",", "E_CORE_ERROR", ",", "E_CORE_WARNING", ",", "E_COMPILE_ERROR", ",", "E_COMPILE_WARNING", ",", "]", ";", "if", "(", "in_array", "(", "$", "error", "[", "'type'", "]", ",", "$", "fatals", ",", "TRUE", ")", ")", "{", "$", "this", "->", "on_error", "(", "$", "error", "[", "'type'", "]", ",", "$", "error", "[", "'message'", "]", ",", "$", "error", "[", "'file'", "]", ",", "$", "error", "[", "'line'", "]", ")", ";", "}", "}" ]
Checks for a fatal error, work-around for `set_error_handler` not working with fatal errors.
[ "Checks", "for", "a", "fatal", "error", "work", "-", "around", "for", "set_error_handler", "not", "working", "with", "fatal", "errors", "." ]
87ed9a60c6f5cc3a057db857273dc504efc5ad9f
https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/PhpErrorController.php#L122-L143
29,531
inpsyde/Wonolog
src/HookListener/QueryErrorsListener.php
QueryErrorsListener.update
public function update( array $args ) { $wp = $args ? reset( $args ) : NULL; if ( ! $wp instanceof \WP ) { return new NullLog(); } $error = []; isset( $wp->query_vars[ 'error' ] ) and $error[] = $wp->query_vars[ 'error' ]; is_404() and $error[] = '404 Page not found'; if ( empty( $error ) ) { return new NullLog(); } $url = filter_var( add_query_arg( [] ), FILTER_SANITIZE_URL ); $message = "Error on frontend request for url {$url}."; $context = [ 'error' => $error, 'query_vars' => $wp->query_vars, 'matched_rule' => $wp->matched_rule, ]; return new Debug( $message, Channels::HTTP, $context ); }
php
public function update( array $args ) { $wp = $args ? reset( $args ) : NULL; if ( ! $wp instanceof \WP ) { return new NullLog(); } $error = []; isset( $wp->query_vars[ 'error' ] ) and $error[] = $wp->query_vars[ 'error' ]; is_404() and $error[] = '404 Page not found'; if ( empty( $error ) ) { return new NullLog(); } $url = filter_var( add_query_arg( [] ), FILTER_SANITIZE_URL ); $message = "Error on frontend request for url {$url}."; $context = [ 'error' => $error, 'query_vars' => $wp->query_vars, 'matched_rule' => $wp->matched_rule, ]; return new Debug( $message, Channels::HTTP, $context ); }
[ "public", "function", "update", "(", "array", "$", "args", ")", "{", "$", "wp", "=", "$", "args", "?", "reset", "(", "$", "args", ")", ":", "NULL", ";", "if", "(", "!", "$", "wp", "instanceof", "\\", "WP", ")", "{", "return", "new", "NullLog", "(", ")", ";", "}", "$", "error", "=", "[", "]", ";", "isset", "(", "$", "wp", "->", "query_vars", "[", "'error'", "]", ")", "and", "$", "error", "[", "]", "=", "$", "wp", "->", "query_vars", "[", "'error'", "]", ";", "is_404", "(", ")", "and", "$", "error", "[", "]", "=", "'404 Page not found'", ";", "if", "(", "empty", "(", "$", "error", ")", ")", "{", "return", "new", "NullLog", "(", ")", ";", "}", "$", "url", "=", "filter_var", "(", "add_query_arg", "(", "[", "]", ")", ",", "FILTER_SANITIZE_URL", ")", ";", "$", "message", "=", "\"Error on frontend request for url {$url}.\"", ";", "$", "context", "=", "[", "'error'", "=>", "$", "error", ",", "'query_vars'", "=>", "$", "wp", "->", "query_vars", ",", "'matched_rule'", "=>", "$", "wp", "->", "matched_rule", ",", "]", ";", "return", "new", "Debug", "(", "$", "message", ",", "Channels", "::", "HTTP", ",", "$", "context", ")", ";", "}" ]
Checks frontend request for any errors and log them. @param $args @return LogDataInterface @wp-hook wp
[ "Checks", "frontend", "request", "for", "any", "errors", "and", "log", "them", "." ]
87ed9a60c6f5cc3a057db857273dc504efc5ad9f
https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/HookListener/QueryErrorsListener.php#L43-L68
29,532
inpsyde/Wonolog
src/HookListener/HookListenersRegistry.php
HookListenersRegistry.initialize
public static function initialize() { $instance = new static(); /** * Fires right before hook listeners are registered. * * @param HookListenersRegistry $registry */ do_action( self::ACTION_REGISTER, $instance ); array_walk( $instance->listeners, function ( HookListenerInterface $listener ) use ( $instance ) { /** * Filters whether to enable the hook listener. * * @param bool $enable * @param HookListenerInterface $listener */ if ( apply_filters( self::FILTER_ENABLED, TRUE, $listener ) ) { $hooks = (array) $listener->listen_to(); array_walk( $hooks, [ $instance, 'listen_hook' ], $listener ); } } ); unset( $instance->listeners ); $instance->listeners = []; }
php
public static function initialize() { $instance = new static(); /** * Fires right before hook listeners are registered. * * @param HookListenersRegistry $registry */ do_action( self::ACTION_REGISTER, $instance ); array_walk( $instance->listeners, function ( HookListenerInterface $listener ) use ( $instance ) { /** * Filters whether to enable the hook listener. * * @param bool $enable * @param HookListenerInterface $listener */ if ( apply_filters( self::FILTER_ENABLED, TRUE, $listener ) ) { $hooks = (array) $listener->listen_to(); array_walk( $hooks, [ $instance, 'listen_hook' ], $listener ); } } ); unset( $instance->listeners ); $instance->listeners = []; }
[ "public", "static", "function", "initialize", "(", ")", "{", "$", "instance", "=", "new", "static", "(", ")", ";", "/**\n\t\t * Fires right before hook listeners are registered.\n\t\t *\n\t\t * @param HookListenersRegistry $registry\n\t\t */", "do_action", "(", "self", "::", "ACTION_REGISTER", ",", "$", "instance", ")", ";", "array_walk", "(", "$", "instance", "->", "listeners", ",", "function", "(", "HookListenerInterface", "$", "listener", ")", "use", "(", "$", "instance", ")", "{", "/**\n\t\t\t\t * Filters whether to enable the hook listener.\n\t\t\t\t *\n\t\t\t\t * @param bool $enable\n\t\t\t\t * @param HookListenerInterface $listener\n\t\t\t\t */", "if", "(", "apply_filters", "(", "self", "::", "FILTER_ENABLED", ",", "TRUE", ",", "$", "listener", ")", ")", "{", "$", "hooks", "=", "(", "array", ")", "$", "listener", "->", "listen_to", "(", ")", ";", "array_walk", "(", "$", "hooks", ",", "[", "$", "instance", ",", "'listen_hook'", "]", ",", "$", "listener", ")", ";", "}", "}", ")", ";", "unset", "(", "$", "instance", "->", "listeners", ")", ";", "$", "instance", "->", "listeners", "=", "[", "]", ";", "}" ]
Initialize the class, fire an hook to allow listener registration and adds the hook that will make log happen
[ "Initialize", "the", "class", "fire", "an", "hook", "to", "allow", "listener", "registration", "and", "adds", "the", "hook", "that", "will", "make", "log", "happen" ]
87ed9a60c6f5cc3a057db857273dc504efc5ad9f
https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/HookListener/HookListenersRegistry.php#L35-L65
29,533
inpsyde/Wonolog
src/Data/HookLogFactory.php
HookLogFactory.extract_log_objects_in_args
private function extract_log_objects_in_args( array $args, $hook_level ) { $logs = []; foreach ( $args as $arg ) { if ( $arg instanceof LogDataInterface ) { $logs[] = $this->maybe_raise_level( $hook_level, $arg ); } } return $logs; }
php
private function extract_log_objects_in_args( array $args, $hook_level ) { $logs = []; foreach ( $args as $arg ) { if ( $arg instanceof LogDataInterface ) { $logs[] = $this->maybe_raise_level( $hook_level, $arg ); } } return $logs; }
[ "private", "function", "extract_log_objects_in_args", "(", "array", "$", "args", ",", "$", "hook_level", ")", "{", "$", "logs", "=", "[", "]", ";", "foreach", "(", "$", "args", "as", "$", "arg", ")", "{", "if", "(", "$", "arg", "instanceof", "LogDataInterface", ")", "{", "$", "logs", "[", "]", "=", "$", "this", "->", "maybe_raise_level", "(", "$", "hook_level", ",", "$", "arg", ")", ";", "}", "}", "return", "$", "logs", ";", "}" ]
If one or more LogData objects are passed as argument, extract all of them and return remaining objects. @param array $args @param int $hook_level @return LogDataInterface[]
[ "If", "one", "or", "more", "LogData", "objects", "are", "passed", "as", "argument", "extract", "all", "of", "them", "and", "return", "remaining", "objects", "." ]
87ed9a60c6f5cc3a057db857273dc504efc5ad9f
https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/Data/HookLogFactory.php#L83-L94
29,534
inpsyde/Wonolog
src/HookListener/CronDebugListener.php
CronDebugListener.cron_action_profile
private function cron_action_profile() { if ( ! defined( 'DOING_CRON' ) || ! DOING_CRON ) { return; } $hook = current_filter(); if ( ! isset( $this->done[ $hook ] ) ) { $this->done[ $hook ][ 'start' ] = microtime( TRUE ); return; } if ( ! isset( $this->done[ $hook ][ 'duration' ] ) ) { $duration = number_format( microtime( TRUE ) - $this->done[ $hook ][ 'start' ], 2 ); $this->done[ $hook ][ 'duration' ] = $duration . ' s'; // Log the cron action performed. do_action( \Inpsyde\Wonolog\LOG, new Info( "Cron action \"{$hook}\" performed.", Channels::DEBUG, $this->done[ $hook ] ) ); } }
php
private function cron_action_profile() { if ( ! defined( 'DOING_CRON' ) || ! DOING_CRON ) { return; } $hook = current_filter(); if ( ! isset( $this->done[ $hook ] ) ) { $this->done[ $hook ][ 'start' ] = microtime( TRUE ); return; } if ( ! isset( $this->done[ $hook ][ 'duration' ] ) ) { $duration = number_format( microtime( TRUE ) - $this->done[ $hook ][ 'start' ], 2 ); $this->done[ $hook ][ 'duration' ] = $duration . ' s'; // Log the cron action performed. do_action( \Inpsyde\Wonolog\LOG, new Info( "Cron action \"{$hook}\" performed.", Channels::DEBUG, $this->done[ $hook ] ) ); } }
[ "private", "function", "cron_action_profile", "(", ")", "{", "if", "(", "!", "defined", "(", "'DOING_CRON'", ")", "||", "!", "DOING_CRON", ")", "{", "return", ";", "}", "$", "hook", "=", "current_filter", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "done", "[", "$", "hook", "]", ")", ")", "{", "$", "this", "->", "done", "[", "$", "hook", "]", "[", "'start'", "]", "=", "microtime", "(", "TRUE", ")", ";", "return", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "done", "[", "$", "hook", "]", "[", "'duration'", "]", ")", ")", "{", "$", "duration", "=", "number_format", "(", "microtime", "(", "TRUE", ")", "-", "$", "this", "->", "done", "[", "$", "hook", "]", "[", "'start'", "]", ",", "2", ")", ";", "$", "this", "->", "done", "[", "$", "hook", "]", "[", "'duration'", "]", "=", "$", "duration", ".", "' s'", ";", "// Log the cron action performed.", "do_action", "(", "\\", "Inpsyde", "\\", "Wonolog", "\\", "LOG", ",", "new", "Info", "(", "\"Cron action \\\"{$hook}\\\" performed.\"", ",", "Channels", "::", "DEBUG", ",", "$", "this", "->", "done", "[", "$", "hook", "]", ")", ")", ";", "}", "}" ]
Run before and after that any cron action ran, logging it and its performance.
[ "Run", "before", "and", "after", "that", "any", "cron", "action", "ran", "logging", "it", "and", "its", "performance", "." ]
87ed9a60c6f5cc3a057db857273dc504efc5ad9f
https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/HookListener/CronDebugListener.php#L139-L164
29,535
inpsyde/Wonolog
src/Controller.php
Controller.setup
public function setup( $priority = 100 ) { if ( did_action( self::ACTION_SETUP ) ) { return $this; } // We use WONOLOG_DISABLE instead of WONOLOG_ENABLE so that not defined (default) means enabled. $disable_by_env = filter_var( getenv( 'WONOLOG_DISABLE' ), FILTER_VALIDATE_BOOLEAN ); /** * Filters whether to completely disable Wonolog. * * @param bool $disable */ if ( apply_filters( self::FILTER_DISABLE, $disable_by_env ) ) { return $this; } /** * Fires right before Wonolog is set up. */ do_action( self::ACTION_SETUP ); $processor_registry = new ProcessorsRegistry(); $handlers_registry = new HandlersRegistry( $processor_registry ); $subscriber = new LogActionSubscriber( new Channels( $handlers_registry, $processor_registry ) ); $listener = [ $subscriber, 'listen' ]; add_action( LOG, $listener, $priority, PHP_INT_MAX ); foreach ( Logger::getLevels() as $level => $level_code ) { // $level_code is from 100 (DEBUG) to 600 (EMERGENCY) this makes hook priority based on level priority add_action( LOG . '.' . strtolower( $level ), $listener, $priority + ( 601 - $level_code ), PHP_INT_MAX ); } add_action( 'muplugins_loaded', [ HookListenersRegistry::class, 'initialize' ], PHP_INT_MAX ); /** * Fires right after Wonolog has been set up. */ do_action( self::ACTION_LOADED ); return $this; }
php
public function setup( $priority = 100 ) { if ( did_action( self::ACTION_SETUP ) ) { return $this; } // We use WONOLOG_DISABLE instead of WONOLOG_ENABLE so that not defined (default) means enabled. $disable_by_env = filter_var( getenv( 'WONOLOG_DISABLE' ), FILTER_VALIDATE_BOOLEAN ); /** * Filters whether to completely disable Wonolog. * * @param bool $disable */ if ( apply_filters( self::FILTER_DISABLE, $disable_by_env ) ) { return $this; } /** * Fires right before Wonolog is set up. */ do_action( self::ACTION_SETUP ); $processor_registry = new ProcessorsRegistry(); $handlers_registry = new HandlersRegistry( $processor_registry ); $subscriber = new LogActionSubscriber( new Channels( $handlers_registry, $processor_registry ) ); $listener = [ $subscriber, 'listen' ]; add_action( LOG, $listener, $priority, PHP_INT_MAX ); foreach ( Logger::getLevels() as $level => $level_code ) { // $level_code is from 100 (DEBUG) to 600 (EMERGENCY) this makes hook priority based on level priority add_action( LOG . '.' . strtolower( $level ), $listener, $priority + ( 601 - $level_code ), PHP_INT_MAX ); } add_action( 'muplugins_loaded', [ HookListenersRegistry::class, 'initialize' ], PHP_INT_MAX ); /** * Fires right after Wonolog has been set up. */ do_action( self::ACTION_LOADED ); return $this; }
[ "public", "function", "setup", "(", "$", "priority", "=", "100", ")", "{", "if", "(", "did_action", "(", "self", "::", "ACTION_SETUP", ")", ")", "{", "return", "$", "this", ";", "}", "// We use WONOLOG_DISABLE instead of WONOLOG_ENABLE so that not defined (default) means enabled.", "$", "disable_by_env", "=", "filter_var", "(", "getenv", "(", "'WONOLOG_DISABLE'", ")", ",", "FILTER_VALIDATE_BOOLEAN", ")", ";", "/**\n\t\t * Filters whether to completely disable Wonolog.\n\t\t *\n\t\t * @param bool $disable\n\t\t */", "if", "(", "apply_filters", "(", "self", "::", "FILTER_DISABLE", ",", "$", "disable_by_env", ")", ")", "{", "return", "$", "this", ";", "}", "/**\n\t\t * Fires right before Wonolog is set up.\n\t\t */", "do_action", "(", "self", "::", "ACTION_SETUP", ")", ";", "$", "processor_registry", "=", "new", "ProcessorsRegistry", "(", ")", ";", "$", "handlers_registry", "=", "new", "HandlersRegistry", "(", "$", "processor_registry", ")", ";", "$", "subscriber", "=", "new", "LogActionSubscriber", "(", "new", "Channels", "(", "$", "handlers_registry", ",", "$", "processor_registry", ")", ")", ";", "$", "listener", "=", "[", "$", "subscriber", ",", "'listen'", "]", ";", "add_action", "(", "LOG", ",", "$", "listener", ",", "$", "priority", ",", "PHP_INT_MAX", ")", ";", "foreach", "(", "Logger", "::", "getLevels", "(", ")", "as", "$", "level", "=>", "$", "level_code", ")", "{", "// $level_code is from 100 (DEBUG) to 600 (EMERGENCY) this makes hook priority based on level priority", "add_action", "(", "LOG", ".", "'.'", ".", "strtolower", "(", "$", "level", ")", ",", "$", "listener", ",", "$", "priority", "+", "(", "601", "-", "$", "level_code", ")", ",", "PHP_INT_MAX", ")", ";", "}", "add_action", "(", "'muplugins_loaded'", ",", "[", "HookListenersRegistry", "::", "class", ",", "'initialize'", "]", ",", "PHP_INT_MAX", ")", ";", "/**\n\t\t * Fires right after Wonolog has been set up.\n\t\t */", "do_action", "(", "self", "::", "ACTION_LOADED", ")", ";", "return", "$", "this", ";", "}" ]
Initialize Wonolog. @param int $priority @return Controller
[ "Initialize", "Wonolog", "." ]
87ed9a60c6f5cc3a057db857273dc504efc5ad9f
https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/Controller.php#L41-L84
29,536
inpsyde/Wonolog
src/Controller.php
Controller.log_php_errors
public function log_php_errors( $error_types = NULL ) { static $done = FALSE; if ( $done ) { return $this; } $done = TRUE; is_int( $error_types ) or $error_types = E_ALL | E_STRICT; $controller = new PhpErrorController(); register_shutdown_function( [ $controller, 'on_fatal', ] ); set_error_handler( [ $controller, 'on_error' ], $error_types ); set_exception_handler( [ $controller, 'on_exception', ] ); // Ensure that channel Channels::PHP_ERROR error is there add_filter( Channels::FILTER_CHANNELS, function ( array $channels ) { $channels[] = Channels::PHP_ERROR; return $channels; }, PHP_INT_MAX ); return $this; }
php
public function log_php_errors( $error_types = NULL ) { static $done = FALSE; if ( $done ) { return $this; } $done = TRUE; is_int( $error_types ) or $error_types = E_ALL | E_STRICT; $controller = new PhpErrorController(); register_shutdown_function( [ $controller, 'on_fatal', ] ); set_error_handler( [ $controller, 'on_error' ], $error_types ); set_exception_handler( [ $controller, 'on_exception', ] ); // Ensure that channel Channels::PHP_ERROR error is there add_filter( Channels::FILTER_CHANNELS, function ( array $channels ) { $channels[] = Channels::PHP_ERROR; return $channels; }, PHP_INT_MAX ); return $this; }
[ "public", "function", "log_php_errors", "(", "$", "error_types", "=", "NULL", ")", "{", "static", "$", "done", "=", "FALSE", ";", "if", "(", "$", "done", ")", "{", "return", "$", "this", ";", "}", "$", "done", "=", "TRUE", ";", "is_int", "(", "$", "error_types", ")", "or", "$", "error_types", "=", "E_ALL", "|", "E_STRICT", ";", "$", "controller", "=", "new", "PhpErrorController", "(", ")", ";", "register_shutdown_function", "(", "[", "$", "controller", ",", "'on_fatal'", ",", "]", ")", ";", "set_error_handler", "(", "[", "$", "controller", ",", "'on_error'", "]", ",", "$", "error_types", ")", ";", "set_exception_handler", "(", "[", "$", "controller", ",", "'on_exception'", ",", "]", ")", ";", "// Ensure that channel Channels::PHP_ERROR error is there", "add_filter", "(", "Channels", "::", "FILTER_CHANNELS", ",", "function", "(", "array", "$", "channels", ")", "{", "$", "channels", "[", "]", "=", "Channels", "::", "PHP_ERROR", ";", "return", "$", "channels", ";", "}", ",", "PHP_INT_MAX", ")", ";", "return", "$", "this", ";", "}" ]
Tell Wonolog to use the PHP errors handler. @param int|null $error_types bitmask of error types constants, default to E_ALL | E_STRICT @return Controller
[ "Tell", "Wonolog", "to", "use", "the", "PHP", "errors", "handler", "." ]
87ed9a60c6f5cc3a057db857273dc504efc5ad9f
https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/Controller.php#L93-L121
29,537
inpsyde/Wonolog
src/Controller.php
Controller.use_default_handler
public function use_default_handler( HandlerInterface $handler = NULL ) { static $done = FALSE; if ( $done ) { return $this; } $done = TRUE; add_action( HandlersRegistry::ACTION_REGISTER, function ( HandlersRegistry $registry ) use ( $handler ) { $handler = DefaultHandlerFactory::with_default_handler( $handler ) ->create_default_handler(); $registry->add_handler( $handler, HandlersRegistry::DEFAULT_NAME ); }, 1 ); return $this; }
php
public function use_default_handler( HandlerInterface $handler = NULL ) { static $done = FALSE; if ( $done ) { return $this; } $done = TRUE; add_action( HandlersRegistry::ACTION_REGISTER, function ( HandlersRegistry $registry ) use ( $handler ) { $handler = DefaultHandlerFactory::with_default_handler( $handler ) ->create_default_handler(); $registry->add_handler( $handler, HandlersRegistry::DEFAULT_NAME ); }, 1 ); return $this; }
[ "public", "function", "use_default_handler", "(", "HandlerInterface", "$", "handler", "=", "NULL", ")", "{", "static", "$", "done", "=", "FALSE", ";", "if", "(", "$", "done", ")", "{", "return", "$", "this", ";", "}", "$", "done", "=", "TRUE", ";", "add_action", "(", "HandlersRegistry", "::", "ACTION_REGISTER", ",", "function", "(", "HandlersRegistry", "$", "registry", ")", "use", "(", "$", "handler", ")", "{", "$", "handler", "=", "DefaultHandlerFactory", "::", "with_default_handler", "(", "$", "handler", ")", "->", "create_default_handler", "(", ")", ";", "$", "registry", "->", "add_handler", "(", "$", "handler", ",", "HandlersRegistry", "::", "DEFAULT_NAME", ")", ";", "}", ",", "1", ")", ";", "return", "$", "this", ";", "}" ]
Tell Wonolog to use a default handler that can be passed as argument or build using settings customizable via hooks. @param HandlerInterface $handler @return Controller
[ "Tell", "Wonolog", "to", "use", "a", "default", "handler", "that", "can", "be", "passed", "as", "argument", "or", "build", "using", "settings", "customizable", "via", "hooks", "." ]
87ed9a60c6f5cc3a057db857273dc504efc5ad9f
https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/Controller.php#L131-L153
29,538
inpsyde/Wonolog
src/Controller.php
Controller.use_handler
public function use_handler( HandlerInterface $handler, array $channels = [], $handler_id = NULL ) { add_action( HandlersRegistry::ACTION_REGISTER, function ( HandlersRegistry $registry ) use ( $handler_id, $handler ) { $registry->add_handler( $handler, $handler_id ); }, 1 ); ( $handler_id === null ) and $handler_id = $handler; add_action( Channels::ACTION_LOGGER, function ( Logger $logger, HandlersRegistry $handlers ) use ( $handler_id, $channels ) { if ( $channels === [] || in_array( $logger->getName(), $channels, TRUE ) ) { $logger->pushHandler( $handlers->find( $handler_id ) ); } }, 10, 2 ); return $this; }
php
public function use_handler( HandlerInterface $handler, array $channels = [], $handler_id = NULL ) { add_action( HandlersRegistry::ACTION_REGISTER, function ( HandlersRegistry $registry ) use ( $handler_id, $handler ) { $registry->add_handler( $handler, $handler_id ); }, 1 ); ( $handler_id === null ) and $handler_id = $handler; add_action( Channels::ACTION_LOGGER, function ( Logger $logger, HandlersRegistry $handlers ) use ( $handler_id, $channels ) { if ( $channels === [] || in_array( $logger->getName(), $channels, TRUE ) ) { $logger->pushHandler( $handlers->find( $handler_id ) ); } }, 10, 2 ); return $this; }
[ "public", "function", "use_handler", "(", "HandlerInterface", "$", "handler", ",", "array", "$", "channels", "=", "[", "]", ",", "$", "handler_id", "=", "NULL", ")", "{", "add_action", "(", "HandlersRegistry", "::", "ACTION_REGISTER", ",", "function", "(", "HandlersRegistry", "$", "registry", ")", "use", "(", "$", "handler_id", ",", "$", "handler", ")", "{", "$", "registry", "->", "add_handler", "(", "$", "handler", ",", "$", "handler_id", ")", ";", "}", ",", "1", ")", ";", "(", "$", "handler_id", "===", "null", ")", "and", "$", "handler_id", "=", "$", "handler", ";", "add_action", "(", "Channels", "::", "ACTION_LOGGER", ",", "function", "(", "Logger", "$", "logger", ",", "HandlersRegistry", "$", "handlers", ")", "use", "(", "$", "handler_id", ",", "$", "channels", ")", "{", "if", "(", "$", "channels", "===", "[", "]", "||", "in_array", "(", "$", "logger", "->", "getName", "(", ")", ",", "$", "channels", ",", "TRUE", ")", ")", "{", "$", "logger", "->", "pushHandler", "(", "$", "handlers", "->", "find", "(", "$", "handler_id", ")", ")", ";", "}", "}", ",", "10", ",", "2", ")", ";", "return", "$", "this", ";", "}" ]
Tell Wonolog to make given handler available to loggers with given id. If one or more channels are passed, the handler will be attached to related Monolog loggers. @param HandlerInterface $handler @param string[] $channels @param string|NULL $handler_id @return Controller
[ "Tell", "Wonolog", "to", "make", "given", "handler", "available", "to", "loggers", "with", "given", "id", ".", "If", "one", "or", "more", "channels", "are", "passed", "the", "handler", "will", "be", "attached", "to", "related", "Monolog", "loggers", "." ]
87ed9a60c6f5cc3a057db857273dc504efc5ad9f
https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/Controller.php#L165-L191
29,539
inpsyde/Wonolog
src/Controller.php
Controller.use_default_processor
public function use_default_processor( callable $processor = null ) { static $done = FALSE; if ( $done ) { return $this; } $done = TRUE; add_action( ProcessorsRegistry::ACTION_REGISTER, function ( ProcessorsRegistry $registry ) use ($processor) { $processor or $processor = new WpContextProcessor(); $registry->add_processor( $processor, ProcessorsRegistry::DEFAULT_NAME ); } ); return $this; }
php
public function use_default_processor( callable $processor = null ) { static $done = FALSE; if ( $done ) { return $this; } $done = TRUE; add_action( ProcessorsRegistry::ACTION_REGISTER, function ( ProcessorsRegistry $registry ) use ($processor) { $processor or $processor = new WpContextProcessor(); $registry->add_processor( $processor, ProcessorsRegistry::DEFAULT_NAME ); } ); return $this; }
[ "public", "function", "use_default_processor", "(", "callable", "$", "processor", "=", "null", ")", "{", "static", "$", "done", "=", "FALSE", ";", "if", "(", "$", "done", ")", "{", "return", "$", "this", ";", "}", "$", "done", "=", "TRUE", ";", "add_action", "(", "ProcessorsRegistry", "::", "ACTION_REGISTER", ",", "function", "(", "ProcessorsRegistry", "$", "registry", ")", "use", "(", "$", "processor", ")", "{", "$", "processor", "or", "$", "processor", "=", "new", "WpContextProcessor", "(", ")", ";", "$", "registry", "->", "add_processor", "(", "$", "processor", ",", "ProcessorsRegistry", "::", "DEFAULT_NAME", ")", ";", "}", ")", ";", "return", "$", "this", ";", "}" ]
Tell Wonolog to use default log processor. @param callable $processor @return Controller
[ "Tell", "Wonolog", "to", "use", "default", "log", "processor", "." ]
87ed9a60c6f5cc3a057db857273dc504efc5ad9f
https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/Controller.php#L200-L219
29,540
inpsyde/Wonolog
src/Controller.php
Controller.use_default_hook_listeners
public function use_default_hook_listeners() { static $done = FALSE; if ( $done ) { return $this; } $done = TRUE; add_action( HookListenersRegistry::ACTION_REGISTER, function ( HookListenersRegistry $registry ) { $registry ->register_listener( new HookListener\DbErrorListener() ) ->register_listener( new HookListener\FailedLoginListener() ) ->register_listener( new HookListener\HttpApiListener() ) ->register_listener( new HookListener\MailerListener() ) ->register_listener( new HookListener\QueryErrorsListener() ) ->register_listener( new HookListener\CronDebugListener() ) ->register_listener( new HookListener\WpDieHandlerListener() ); } ); return $this; }
php
public function use_default_hook_listeners() { static $done = FALSE; if ( $done ) { return $this; } $done = TRUE; add_action( HookListenersRegistry::ACTION_REGISTER, function ( HookListenersRegistry $registry ) { $registry ->register_listener( new HookListener\DbErrorListener() ) ->register_listener( new HookListener\FailedLoginListener() ) ->register_listener( new HookListener\HttpApiListener() ) ->register_listener( new HookListener\MailerListener() ) ->register_listener( new HookListener\QueryErrorsListener() ) ->register_listener( new HookListener\CronDebugListener() ) ->register_listener( new HookListener\WpDieHandlerListener() ); } ); return $this; }
[ "public", "function", "use_default_hook_listeners", "(", ")", "{", "static", "$", "done", "=", "FALSE", ";", "if", "(", "$", "done", ")", "{", "return", "$", "this", ";", "}", "$", "done", "=", "TRUE", ";", "add_action", "(", "HookListenersRegistry", "::", "ACTION_REGISTER", ",", "function", "(", "HookListenersRegistry", "$", "registry", ")", "{", "$", "registry", "->", "register_listener", "(", "new", "HookListener", "\\", "DbErrorListener", "(", ")", ")", "->", "register_listener", "(", "new", "HookListener", "\\", "FailedLoginListener", "(", ")", ")", "->", "register_listener", "(", "new", "HookListener", "\\", "HttpApiListener", "(", ")", ")", "->", "register_listener", "(", "new", "HookListener", "\\", "MailerListener", "(", ")", ")", "->", "register_listener", "(", "new", "HookListener", "\\", "QueryErrorsListener", "(", ")", ")", "->", "register_listener", "(", "new", "HookListener", "\\", "CronDebugListener", "(", ")", ")", "->", "register_listener", "(", "new", "HookListener", "\\", "WpDieHandlerListener", "(", ")", ")", ";", "}", ")", ";", "return", "$", "this", ";", "}" ]
Tell Wonolog to use all default hook listeners. @return Controller
[ "Tell", "Wonolog", "to", "use", "all", "default", "hook", "listeners", "." ]
87ed9a60c6f5cc3a057db857273dc504efc5ad9f
https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/Controller.php#L310-L335
29,541
inpsyde/Wonolog
src/Controller.php
Controller.use_hook_listener
public function use_hook_listener( HookListenerInterface $listener ) { add_action( HookListenersRegistry::ACTION_REGISTER, function ( HookListenersRegistry $registry ) use ( $listener ) { $registry->register_listener( $listener ); } ); return $this; }
php
public function use_hook_listener( HookListenerInterface $listener ) { add_action( HookListenersRegistry::ACTION_REGISTER, function ( HookListenersRegistry $registry ) use ( $listener ) { $registry->register_listener( $listener ); } ); return $this; }
[ "public", "function", "use_hook_listener", "(", "HookListenerInterface", "$", "listener", ")", "{", "add_action", "(", "HookListenersRegistry", "::", "ACTION_REGISTER", ",", "function", "(", "HookListenersRegistry", "$", "registry", ")", "use", "(", "$", "listener", ")", "{", "$", "registry", "->", "register_listener", "(", "$", "listener", ")", ";", "}", ")", ";", "return", "$", "this", ";", "}" ]
Tell Wonolog to use given hook listener. @param HookListenerInterface $listener @return Controller
[ "Tell", "Wonolog", "to", "use", "given", "hook", "listener", "." ]
87ed9a60c6f5cc3a057db857273dc504efc5ad9f
https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/Controller.php#L344-L355
29,542
inpsyde/Wonolog
src/Handler/DefaultHandlerFactory.php
DefaultHandlerFactory.maybe_create_htaccess
private function maybe_create_htaccess( $folder ) { if ( ! $folder || ! is_dir( $folder ) || ! is_writable( $folder ) || file_exists( "{$folder}/.htaccess" ) || ! defined( 'WP_CONTENT_DIR' ) ) { return $folder; } $target_dir = realpath( $folder ); $content_dir = realpath( WP_CONTENT_DIR ); // Sorry, we can't allow logs to be put straight in content folder. That's too dangerous. if ( $target_dir === $content_dir ) { $target_dir .= DIRECTORY_SEPARATOR . 'wonolog'; } // If target dir is outside content dir, its security is up to user. if ( strpos( $target_dir, $content_dir ) !== 0 ) { return $target_dir; } // Let's disable error reporting: too much file operations which might fail, nothing can log them, and package // is fully functional even if failing happens. Silence looks like best option here. set_error_handler( '__return_true' ); $handle = fopen( "{$folder}/.htaccess", 'w' ); if ( $handle && flock( $handle, LOCK_EX ) ) { $htaccess = <<<'HTACCESS' <IfModule mod_authz_core.c> Require all denied </IfModule> <IfModule !mod_authz_core.c> Deny from all </IfModule> HTACCESS; if ( fwrite( $handle, $htaccess ) ) { flock( $handle, LOCK_UN ); chmod( "{$folder}/.htaccess", 0444 ); } } fclose( $handle ); restore_error_handler(); return $target_dir; }
php
private function maybe_create_htaccess( $folder ) { if ( ! $folder || ! is_dir( $folder ) || ! is_writable( $folder ) || file_exists( "{$folder}/.htaccess" ) || ! defined( 'WP_CONTENT_DIR' ) ) { return $folder; } $target_dir = realpath( $folder ); $content_dir = realpath( WP_CONTENT_DIR ); // Sorry, we can't allow logs to be put straight in content folder. That's too dangerous. if ( $target_dir === $content_dir ) { $target_dir .= DIRECTORY_SEPARATOR . 'wonolog'; } // If target dir is outside content dir, its security is up to user. if ( strpos( $target_dir, $content_dir ) !== 0 ) { return $target_dir; } // Let's disable error reporting: too much file operations which might fail, nothing can log them, and package // is fully functional even if failing happens. Silence looks like best option here. set_error_handler( '__return_true' ); $handle = fopen( "{$folder}/.htaccess", 'w' ); if ( $handle && flock( $handle, LOCK_EX ) ) { $htaccess = <<<'HTACCESS' <IfModule mod_authz_core.c> Require all denied </IfModule> <IfModule !mod_authz_core.c> Deny from all </IfModule> HTACCESS; if ( fwrite( $handle, $htaccess ) ) { flock( $handle, LOCK_UN ); chmod( "{$folder}/.htaccess", 0444 ); } } fclose( $handle ); restore_error_handler(); return $target_dir; }
[ "private", "function", "maybe_create_htaccess", "(", "$", "folder", ")", "{", "if", "(", "!", "$", "folder", "||", "!", "is_dir", "(", "$", "folder", ")", "||", "!", "is_writable", "(", "$", "folder", ")", "||", "file_exists", "(", "\"{$folder}/.htaccess\"", ")", "||", "!", "defined", "(", "'WP_CONTENT_DIR'", ")", ")", "{", "return", "$", "folder", ";", "}", "$", "target_dir", "=", "realpath", "(", "$", "folder", ")", ";", "$", "content_dir", "=", "realpath", "(", "WP_CONTENT_DIR", ")", ";", "// Sorry, we can't allow logs to be put straight in content folder. That's too dangerous.", "if", "(", "$", "target_dir", "===", "$", "content_dir", ")", "{", "$", "target_dir", ".=", "DIRECTORY_SEPARATOR", ".", "'wonolog'", ";", "}", "// If target dir is outside content dir, its security is up to user.", "if", "(", "strpos", "(", "$", "target_dir", ",", "$", "content_dir", ")", "!==", "0", ")", "{", "return", "$", "target_dir", ";", "}", "// Let's disable error reporting: too much file operations which might fail, nothing can log them, and package", "// is fully functional even if failing happens. Silence looks like best option here.", "set_error_handler", "(", "'__return_true'", ")", ";", "$", "handle", "=", "fopen", "(", "\"{$folder}/.htaccess\"", ",", "'w'", ")", ";", "if", "(", "$", "handle", "&&", "flock", "(", "$", "handle", ",", "LOCK_EX", ")", ")", "{", "$", "htaccess", "=", " <<<'HTACCESS'\n<IfModule mod_authz_core.c>\n\tRequire all denied\n</IfModule>\n<IfModule !mod_authz_core.c>\n\tDeny from all\n</IfModule>\nHTACCESS", ";", "if", "(", "fwrite", "(", "$", "handle", ",", "$", "htaccess", ")", ")", "{", "flock", "(", "$", "handle", ",", "LOCK_UN", ")", ";", "chmod", "(", "\"{$folder}/.htaccess\"", ",", "0444", ")", ";", "}", "}", "fclose", "(", "$", "handle", ")", ";", "restore_error_handler", "(", ")", ";", "return", "$", "target_dir", ";", "}" ]
When the log root folder is inside WordPress content folder, the logs are going to be publicly accessible, and that is in best case a privacy leakage issue, in worst case a security threat. We try to write an .htaccess file to prevent access to them. This guarantees nothing, because .htaccess can be ignored depending web server in use and its configuration, but at least we tried. To configure a custom log folder outside content folder is also highly recommended in documentation. @param string $folder @return string
[ "When", "the", "log", "root", "folder", "is", "inside", "WordPress", "content", "folder", "the", "logs", "are", "going", "to", "be", "publicly", "accessible", "and", "that", "is", "in", "best", "case", "a", "privacy", "leakage", "issue", "in", "worst", "case", "a", "security", "threat", ".", "We", "try", "to", "write", "an", ".", "htaccess", "file", "to", "prevent", "access", "to", "them", ".", "This", "guarantees", "nothing", "because", ".", "htaccess", "can", "be", "ignored", "depending", "web", "server", "in", "use", "and", "its", "configuration", "but", "at", "least", "we", "tried", ".", "To", "configure", "a", "custom", "log", "folder", "outside", "content", "folder", "is", "also", "highly", "recommended", "in", "documentation", "." ]
87ed9a60c6f5cc3a057db857273dc504efc5ad9f
https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/Handler/DefaultHandlerFactory.php#L173-L225
29,543
inpsyde/Wonolog
src/HookListener/HttpApiListener.php
HttpApiListener.log_http_error
private function log_http_error( $data, $context, $class, array $args = [], $url = '' ) { $msg = 'WP HTTP API Error'; $response = is_array( $data ) && isset( $data[ 'response' ] ) && is_array( $data[ 'response' ] ) ? shortcode_atts( [ 'message' => '', 'code' => '', 'body' => '' ], $data[ 'response' ] ) : [ 'message' => '', 'code' => '', 'body' => '' ]; if ( is_wp_error( $data ) ) { $msg .= ': ' . $data->get_error_message(); } elseif ( is_string( $response[ 'message' ] ) && $response[ 'message' ] ) { $msg .= ': ' . $response[ 'message' ]; } $log_context = [ 'transport' => $class, 'context' => $context, 'query_args' => $args, 'url' => $url, ]; if ( $response[ 'body' ] && is_string( $response[ 'body' ] ) ) { $log_context[ 'response_body' ] = strlen( $response[ 'body' ] ) <= 300 ? $response[ 'body' ] : substr( $response[ 'body' ], 0, 300 ) . '...'; } if ( array_key_exists( 'code', $response ) && is_scalar( $response[ 'code' ] ) ) { $msg .= " - Response code: {$response[ 'code' ]}"; ( is_array( $data ) && ! empty( $data[ 'headers' ] ) ) and $log_context[ 'headers' ] = $data[ 'headers' ]; } return new Error( rtrim( $msg, '.' ) . '.', Channels::HTTP, $log_context ); }
php
private function log_http_error( $data, $context, $class, array $args = [], $url = '' ) { $msg = 'WP HTTP API Error'; $response = is_array( $data ) && isset( $data[ 'response' ] ) && is_array( $data[ 'response' ] ) ? shortcode_atts( [ 'message' => '', 'code' => '', 'body' => '' ], $data[ 'response' ] ) : [ 'message' => '', 'code' => '', 'body' => '' ]; if ( is_wp_error( $data ) ) { $msg .= ': ' . $data->get_error_message(); } elseif ( is_string( $response[ 'message' ] ) && $response[ 'message' ] ) { $msg .= ': ' . $response[ 'message' ]; } $log_context = [ 'transport' => $class, 'context' => $context, 'query_args' => $args, 'url' => $url, ]; if ( $response[ 'body' ] && is_string( $response[ 'body' ] ) ) { $log_context[ 'response_body' ] = strlen( $response[ 'body' ] ) <= 300 ? $response[ 'body' ] : substr( $response[ 'body' ], 0, 300 ) . '...'; } if ( array_key_exists( 'code', $response ) && is_scalar( $response[ 'code' ] ) ) { $msg .= " - Response code: {$response[ 'code' ]}"; ( is_array( $data ) && ! empty( $data[ 'headers' ] ) ) and $log_context[ 'headers' ] = $data[ 'headers' ]; } return new Error( rtrim( $msg, '.' ) . '.', Channels::HTTP, $log_context ); }
[ "private", "function", "log_http_error", "(", "$", "data", ",", "$", "context", ",", "$", "class", ",", "array", "$", "args", "=", "[", "]", ",", "$", "url", "=", "''", ")", "{", "$", "msg", "=", "'WP HTTP API Error'", ";", "$", "response", "=", "is_array", "(", "$", "data", ")", "&&", "isset", "(", "$", "data", "[", "'response'", "]", ")", "&&", "is_array", "(", "$", "data", "[", "'response'", "]", ")", "?", "shortcode_atts", "(", "[", "'message'", "=>", "''", ",", "'code'", "=>", "''", ",", "'body'", "=>", "''", "]", ",", "$", "data", "[", "'response'", "]", ")", ":", "[", "'message'", "=>", "''", ",", "'code'", "=>", "''", ",", "'body'", "=>", "''", "]", ";", "if", "(", "is_wp_error", "(", "$", "data", ")", ")", "{", "$", "msg", ".=", "': '", ".", "$", "data", "->", "get_error_message", "(", ")", ";", "}", "elseif", "(", "is_string", "(", "$", "response", "[", "'message'", "]", ")", "&&", "$", "response", "[", "'message'", "]", ")", "{", "$", "msg", ".=", "': '", ".", "$", "response", "[", "'message'", "]", ";", "}", "$", "log_context", "=", "[", "'transport'", "=>", "$", "class", ",", "'context'", "=>", "$", "context", ",", "'query_args'", "=>", "$", "args", ",", "'url'", "=>", "$", "url", ",", "]", ";", "if", "(", "$", "response", "[", "'body'", "]", "&&", "is_string", "(", "$", "response", "[", "'body'", "]", ")", ")", "{", "$", "log_context", "[", "'response_body'", "]", "=", "strlen", "(", "$", "response", "[", "'body'", "]", ")", "<=", "300", "?", "$", "response", "[", "'body'", "]", ":", "substr", "(", "$", "response", "[", "'body'", "]", ",", "0", ",", "300", ")", ".", "'...'", ";", "}", "if", "(", "array_key_exists", "(", "'code'", ",", "$", "response", ")", "&&", "is_scalar", "(", "$", "response", "[", "'code'", "]", ")", ")", "{", "$", "msg", ".=", "\" - Response code: {$response[ 'code' ]}\"", ";", "(", "is_array", "(", "$", "data", ")", "&&", "!", "empty", "(", "$", "data", "[", "'headers'", "]", ")", ")", "and", "$", "log_context", "[", "'headers'", "]", "=", "$", "data", "[", "'headers'", "]", ";", "}", "return", "new", "Error", "(", "rtrim", "(", "$", "msg", ",", "'.'", ")", ".", "'.'", ",", "Channels", "::", "HTTP", ",", "$", "log_context", ")", ";", "}" ]
Log any error for HTTP API. @param \WP_Error|array $data @param string $context @param string $class @param array $args @param string $url @return Error
[ "Log", "any", "error", "for", "HTTP", "API", "." ]
87ed9a60c6f5cc3a057db857273dc504efc5ad9f
https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/HookListener/HttpApiListener.php#L169-L201
29,544
phpsci/phpsci
src/PHPSci/Utils/ValidationUtils.php
ValidationUtils.check_X_y
public static function check_X_y(\CArray $X, \CArray $y, bool $accept_sparse=false, bool $copy=False, bool $force_all_finite=True, bool $ensure_2d=True, bool $allow_nd=False, bool $multi_output=False, int $ensure_min_samples=1, int $ensure_min_features=1, bool $y_numeric=False, $estimator=null) { return [$X, $y]; }
php
public static function check_X_y(\CArray $X, \CArray $y, bool $accept_sparse=false, bool $copy=False, bool $force_all_finite=True, bool $ensure_2d=True, bool $allow_nd=False, bool $multi_output=False, int $ensure_min_samples=1, int $ensure_min_features=1, bool $y_numeric=False, $estimator=null) { return [$X, $y]; }
[ "public", "static", "function", "check_X_y", "(", "\\", "CArray", "$", "X", ",", "\\", "CArray", "$", "y", ",", "bool", "$", "accept_sparse", "=", "false", ",", "bool", "$", "copy", "=", "False", ",", "bool", "$", "force_all_finite", "=", "True", ",", "bool", "$", "ensure_2d", "=", "True", ",", "bool", "$", "allow_nd", "=", "False", ",", "bool", "$", "multi_output", "=", "False", ",", "int", "$", "ensure_min_samples", "=", "1", ",", "int", "$", "ensure_min_features", "=", "1", ",", "bool", "$", "y_numeric", "=", "False", ",", "$", "estimator", "=", "null", ")", "{", "return", "[", "$", "X", ",", "$", "y", "]", ";", "}" ]
Input validation for standard estimators. @param \CArray $X @param \CArray $y @param bool $accept_sparse @param bool $copy @param bool $force_all_finite @param bool $ensure_2d @param bool $allow_nd @param bool $multi_output @param int $ensure_min_samples @param int $ensure_min_features @param bool $y_numeric @param bool $warn_on_dtype @param null $estimator @return array
[ "Input", "validation", "for", "standard", "estimators", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Utils/ValidationUtils.php#L32-L38
29,545
phpsci/phpsci
src/PHPSci/Utils/DatasetUtils.php
DatasetUtils.make_dataset
public static function make_dataset(\CArray $X, \CArray $y, $sample_weight, $random_state=null) : array { $seed = rand(0, 10); $dataset = new ArrayDataset($X, $y, $sample_weight, $seed); $intercept_decay = 1.0; return [$dataset, $intercept_decay]; }
php
public static function make_dataset(\CArray $X, \CArray $y, $sample_weight, $random_state=null) : array { $seed = rand(0, 10); $dataset = new ArrayDataset($X, $y, $sample_weight, $seed); $intercept_decay = 1.0; return [$dataset, $intercept_decay]; }
[ "public", "static", "function", "make_dataset", "(", "\\", "CArray", "$", "X", ",", "\\", "CArray", "$", "y", ",", "$", "sample_weight", ",", "$", "random_state", "=", "null", ")", ":", "array", "{", "$", "seed", "=", "rand", "(", "0", ",", "10", ")", ";", "$", "dataset", "=", "new", "ArrayDataset", "(", "$", "X", ",", "$", "y", ",", "$", "sample_weight", ",", "$", "seed", ")", ";", "$", "intercept_decay", "=", "1.0", ";", "return", "[", "$", "dataset", ",", "$", "intercept_decay", "]", ";", "}" ]
Create ``Dataset`` abstraction for sparse and dense inputs. This also returns the ``intercept_decay`` which is different for sparse datasets. @param \CArray $X @param \CArray $y @param $sample_weight @param null $random_state @return array
[ "Create", "Dataset", "abstraction", "for", "sparse", "and", "dense", "inputs", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Utils/DatasetUtils.php#L23-L29
29,546
phpsci/phpsci
src/PHPSci/Kernel/CArray/Wrapper.php
Wrapper.add
public static function add(\CArray $a, \CArray $b): \CArray { return parent::add($a, $b); }
php
public static function add(\CArray $a, \CArray $b): \CArray { return parent::add($a, $b); }
[ "public", "static", "function", "add", "(", "\\", "CArray", "$", "a", ",", "\\", "CArray", "$", "b", ")", ":", "\\", "CArray", "{", "return", "parent", "::", "add", "(", "$", "a", ",", "$", "b", ")", ";", "}" ]
Add arguments element-wise. @param \CArray $a Target CArray a @param \CArray $b Target CArray b @return \CArray The sum of $a and $b, element-wise.
[ "Add", "arguments", "element", "-", "wise", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Kernel/CArray/Wrapper.php#L36-L39
29,547
phpsci/phpsci
src/PHPSci/Kernel/CArray/Wrapper.php
Wrapper.subtract
public static function subtract(\CArray $a, \CArray $b): \CArray { return parent::subtract($a, $b); }
php
public static function subtract(\CArray $a, \CArray $b): \CArray { return parent::subtract($a, $b); }
[ "public", "static", "function", "subtract", "(", "\\", "CArray", "$", "a", ",", "\\", "CArray", "$", "b", ")", ":", "\\", "CArray", "{", "return", "parent", "::", "subtract", "(", "$", "a", ",", "$", "b", ")", ";", "}" ]
Subtract two CArrays, element-wise. @param \CArray $a Target CArray $a @param \CArray $b Target CArray $b @return \CArray The difference of $a and $b, element-wise.
[ "Subtract", "two", "CArrays", "element", "-", "wise", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Kernel/CArray/Wrapper.php#L49-L52
29,548
phpsci/phpsci
src/PHPSci/Kernel/CArray/Wrapper.php
Wrapper.sum
public static function sum(\CArray $a, int $axis = null): \CArray { if (!isset($axis)) { return parent::sum($a); } return parent::sum($a, $axis); }
php
public static function sum(\CArray $a, int $axis = null): \CArray { if (!isset($axis)) { return parent::sum($a); } return parent::sum($a, $axis); }
[ "public", "static", "function", "sum", "(", "\\", "CArray", "$", "a", ",", "int", "$", "axis", "=", "null", ")", ":", "\\", "CArray", "{", "if", "(", "!", "isset", "(", "$", "axis", ")", ")", "{", "return", "parent", "::", "sum", "(", "$", "a", ")", ";", "}", "return", "parent", "::", "sum", "(", "$", "a", ",", "$", "axis", ")", ";", "}" ]
Sum of target CArray elements over a given axis. @param \CArray $a Target CArray @param int $axis (Optional) Axis or axes along which a sum is performed. Defaults to null. @return \CArray An CArray with the same shape as $a, with the specified axis removed.
[ "Sum", "of", "target", "CArray", "elements", "over", "a", "given", "axis", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Kernel/CArray/Wrapper.php#L63-L70
29,549
phpsci/phpsci
src/PHPSci/Kernel/CArray/Wrapper.php
Wrapper.eye
public static function eye(int $x, int $y, int $k = 0): \CArray { return parent::eye($x, $y, $k); }
php
public static function eye(int $x, int $y, int $k = 0): \CArray { return parent::eye($x, $y, $k); }
[ "public", "static", "function", "eye", "(", "int", "$", "x", ",", "int", "$", "y", ",", "int", "$", "k", "=", "0", ")", ":", "\\", "CArray", "{", "return", "parent", "::", "eye", "(", "$", "x", ",", "$", "y", ",", "$", "k", ")", ";", "}" ]
Return CArray filled with zeros and ones in the diagonal provided diagonal index. @param int $x Number of rows (2-D) or width (1-D) @param int $y Number of cols (2-D) or 0 (1-D) @param int $k (Optional) Diagonal Index. Defaults to 0. @return \CArray
[ "Return", "CArray", "filled", "with", "zeros", "and", "ones", "in", "the", "diagonal", "provided", "diagonal", "index", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Kernel/CArray/Wrapper.php#L286-L289
29,550
phpsci/phpsci
src/PHPSci/Kernel/CArray/Wrapper.php
Wrapper.ones
public static function ones(int $x, int $y): \CArray { return parent::ones($x, $y); }
php
public static function ones(int $x, int $y): \CArray { return parent::ones($x, $y); }
[ "public", "static", "function", "ones", "(", "int", "$", "x", ",", "int", "$", "y", ")", ":", "\\", "CArray", "{", "return", "parent", "::", "ones", "(", "$", "x", ",", "$", "y", ")", ";", "}" ]
Return new CArray with same shape as target CArray filled with zeros. @param int $x Number of rows (2-D) or width (1-D) @param int $y Number of cols (2-D) or 0 (1-D) @return \CArray CArray with shape ($x, $y) filled with ones.
[ "Return", "new", "CArray", "with", "same", "shape", "as", "target", "CArray", "filled", "with", "zeros", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Kernel/CArray/Wrapper.php#L313-L316
29,551
phpsci/phpsci
src/PHPSci/Kernel/CArray/Wrapper.php
Wrapper.full
public static function full($num, int $x, int $y): \CArray { return parent::full($num, $x, $y); }
php
public static function full($num, int $x, int $y): \CArray { return parent::full($num, $x, $y); }
[ "public", "static", "function", "full", "(", "$", "num", ",", "int", "$", "x", ",", "int", "$", "y", ")", ":", "\\", "CArray", "{", "return", "parent", "::", "full", "(", "$", "num", ",", "$", "x", ",", "$", "y", ")", ";", "}" ]
Return new CArray filled with user provided number. @param double $num Number to fill the new CArray @param int $x Number of rows (2-D) or width (1-D) @param int $y Number of cols (2-D) or 0 (1-D) @return \CArray New CArray with shape ($x, $y) filled with $num
[ "Return", "new", "CArray", "filled", "with", "user", "provided", "number", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Kernel/CArray/Wrapper.php#L365-L368
29,552
phpsci/phpsci
src/PHPSci/Kernel/CArray/Wrapper.php
Wrapper.arange
public static function arange($stop, $start, $step): \CArray { return parent::arange($stop, $start, $step); }
php
public static function arange($stop, $start, $step): \CArray { return parent::arange($stop, $start, $step); }
[ "public", "static", "function", "arange", "(", "$", "stop", ",", "$", "start", ",", "$", "step", ")", ":", "\\", "CArray", "{", "return", "parent", "::", "arange", "(", "$", "stop", ",", "$", "start", ",", "$", "step", ")", ";", "}" ]
CArray with evenly spaced values within a given interval. @param $stop End of interval @param $start (Optional) Start of interval. Default is 0. @param $step (Optional) Spacing between values. Default is 1. @return \CArray CArray with evenly spaced values.
[ "CArray", "with", "evenly", "spaced", "values", "within", "a", "given", "interval", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Kernel/CArray/Wrapper.php#L419-L422
29,553
phpsci/phpsci
src/PHPSci/Kernel/CArray/Wrapper.php
Wrapper.linspace
public static function linspace($start, $stop, int $num): \CArray { return parent::linspace($start, $stop, $num); }
php
public static function linspace($start, $stop, int $num): \CArray { return parent::linspace($start, $stop, $num); }
[ "public", "static", "function", "linspace", "(", "$", "start", ",", "$", "stop", ",", "int", "$", "num", ")", ":", "\\", "CArray", "{", "return", "parent", "::", "linspace", "(", "$", "start", ",", "$", "stop", ",", "$", "num", ")", ";", "}" ]
CArray with evenly spaced numbers over a specified interval. @param $start The starting value of the sequence. @param $stop The end value of the sequence @param int $num Number of samples to generate. Default is 50. @return \CArray
[ "CArray", "with", "evenly", "spaced", "numbers", "over", "a", "specified", "interval", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Kernel/CArray/Wrapper.php#L433-L436
29,554
phpsci/phpsci
src/PHPSci/Kernel/CArray/Wrapper.php
Wrapper.logspace
public static function logspace($start, $stop, int $num, $base): \CArray { return parent::logspace($start, $stop, $num, $base); }
php
public static function logspace($start, $stop, int $num, $base): \CArray { return parent::logspace($start, $stop, $num, $base); }
[ "public", "static", "function", "logspace", "(", "$", "start", ",", "$", "stop", ",", "int", "$", "num", ",", "$", "base", ")", ":", "\\", "CArray", "{", "return", "parent", "::", "logspace", "(", "$", "start", ",", "$", "stop", ",", "$", "num", ",", "$", "base", ")", ";", "}" ]
CArray with numbers spaced evenly on a log scale. @param $start The starting value of the sequence. @param $stop The final value of the sequence @param int $num (optional) Number of samples to generate. Default is 50. @param $base (optional) The base of the log space. @return \CArray $num samples, equally spaced on a log scale.
[ "CArray", "with", "numbers", "spaced", "evenly", "on", "a", "log", "scale", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Kernel/CArray/Wrapper.php#L448-L451
29,555
phpsci/phpsci
src/PHPSci/Kernel/CArray/Wrapper.php
Wrapper.matmul
public static function matmul(\CArray $a, \CArray $b): \CArray { return parent::matmul($a, $b); }
php
public static function matmul(\CArray $a, \CArray $b): \CArray { return parent::matmul($a, $b); }
[ "public", "static", "function", "matmul", "(", "\\", "CArray", "$", "a", ",", "\\", "CArray", "$", "b", ")", ":", "\\", "CArray", "{", "return", "parent", "::", "matmul", "(", "$", "a", ",", "$", "b", ")", ";", "}" ]
Matrix product of two CArrays. - If both arguments are 2-D they are multiplied like conventional matrices. - If the first argument is 1-D, it is promoted to a matrix by prepending a 1 to its dimensions. After matrix multiplication the prepended 1 is removed. - If the second argument is 1-D, it is promoted to a matrix by appending a 1 to its dimensions. After matrix multiplication the appended 1 is removed. Multiplication by a scalar is not allowed. @param \CArray $a Target $a CArray @param \CArray $b Target $b CArray @return \CArray Dot product of $a and $b. If both are 1D, them a 0 dimensional (scalar) CArray will be returned
[ "Matrix", "product", "of", "two", "CArrays", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Kernel/CArray/Wrapper.php#L483-L486
29,556
phpsci/phpsci
src/PHPSci/Kernel/CArray/Wrapper.php
Wrapper.inner
public static function inner(\CArray $a, \CArray $b): \CArray { return parent::inner($a, $b); }
php
public static function inner(\CArray $a, \CArray $b): \CArray { return parent::inner($a, $b); }
[ "public", "static", "function", "inner", "(", "\\", "CArray", "$", "a", ",", "\\", "CArray", "$", "b", ")", ":", "\\", "CArray", "{", "return", "parent", "::", "inner", "(", "$", "a", ",", "$", "b", ")", ";", "}" ]
Inner product of two CArrays. If 1D - Ordinary inner product of vectors If 2D - Sum product over the last axes. @param \CArray $a Target $a CArray - Last Dimension must match $b @param \CArray $b Target $b CArray - Last Dimension must match $a @return \CArray Inner product of $a and $b
[ "Inner", "product", "of", "two", "CArrays", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Kernel/CArray/Wrapper.php#L499-L502
29,557
phpsci/phpsci
src/PHPSci/Kernel/CArray/Wrapper.php
Wrapper.solve
public static function solve(\CArray $a, \CArray $b): \CArray { return parent::solve($a, $b); }
php
public static function solve(\CArray $a, \CArray $b): \CArray { return parent::solve($a, $b); }
[ "public", "static", "function", "solve", "(", "\\", "CArray", "$", "a", ",", "\\", "CArray", "$", "b", ")", ":", "\\", "CArray", "{", "return", "parent", "::", "solve", "(", "$", "a", ",", "$", "b", ")", ";", "}" ]
Solve a linear matrix equation @param \CArray $a Coefficient CArray @param \CArray $b Ordinate CArray @return \CArray Solution of the system $a x = $b. Returned shape is same as $b.
[ "Solve", "a", "linear", "matrix", "equation" ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Kernel/CArray/Wrapper.php#L561-L564
29,558
phpsci/phpsci
src/PHPSci/NaiveBayes/GaussianNB.php
GaussianNB.fit
public function fit(\CArray $X, \CArray $y, \CArray $sample_weight = null) { list($X, $y) = ValidationUtils::check_X_y($X, $y); return $this->_partial_fit($X, $y, CArray::unique($y), true, $sample_weight); }
php
public function fit(\CArray $X, \CArray $y, \CArray $sample_weight = null) { list($X, $y) = ValidationUtils::check_X_y($X, $y); return $this->_partial_fit($X, $y, CArray::unique($y), true, $sample_weight); }
[ "public", "function", "fit", "(", "\\", "CArray", "$", "X", ",", "\\", "CArray", "$", "y", ",", "\\", "CArray", "$", "sample_weight", "=", "null", ")", "{", "list", "(", "$", "X", ",", "$", "y", ")", "=", "ValidationUtils", "::", "check_X_y", "(", "$", "X", ",", "$", "y", ")", ";", "return", "$", "this", "->", "_partial_fit", "(", "$", "X", ",", "$", "y", ",", "CArray", "::", "unique", "(", "$", "y", ")", ",", "true", ",", "$", "sample_weight", ")", ";", "}" ]
Fit Gaussian Naive Bayes according to X, y @param \CArray $X @param \CArray $y @param \CArray|null $sample_weight @return void @throws \PHPSci\Exceptions\ValueErrorException
[ "Fit", "Gaussian", "Naive", "Bayes", "according", "to", "X", "y" ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/NaiveBayes/GaussianNB.php#L195-L199
29,559
phpsci/phpsci
src/PHPSci/Utils/MulticlassUtils.php
MulticlassUtils._check_partial_fit_first_call
public static function _check_partial_fit_first_call(Classifier $clf, \CArray $classes = null) { if($clf->classes_() == null && !isset($classes) ) { throw new ValueErrorException("classes must be passed on the first call to partial_fit."); } if(isset($classes)) { if($clf->classes_()) { } else { $clf->classes_(CArray::unique($classes)); return true; } } # classes is None and clf.classes_ has already previously been set: # nothing to do return false; }
php
public static function _check_partial_fit_first_call(Classifier $clf, \CArray $classes = null) { if($clf->classes_() == null && !isset($classes) ) { throw new ValueErrorException("classes must be passed on the first call to partial_fit."); } if(isset($classes)) { if($clf->classes_()) { } else { $clf->classes_(CArray::unique($classes)); return true; } } # classes is None and clf.classes_ has already previously been set: # nothing to do return false; }
[ "public", "static", "function", "_check_partial_fit_first_call", "(", "Classifier", "$", "clf", ",", "\\", "CArray", "$", "classes", "=", "null", ")", "{", "if", "(", "$", "clf", "->", "classes_", "(", ")", "==", "null", "&&", "!", "isset", "(", "$", "classes", ")", ")", "{", "throw", "new", "ValueErrorException", "(", "\"classes must be passed on the first call to partial_fit.\"", ")", ";", "}", "if", "(", "isset", "(", "$", "classes", ")", ")", "{", "if", "(", "$", "clf", "->", "classes_", "(", ")", ")", "{", "}", "else", "{", "$", "clf", "->", "classes_", "(", "CArray", "::", "unique", "(", "$", "classes", ")", ")", ";", "return", "true", ";", "}", "}", "# classes is None and clf.classes_ has already previously been set:", "# nothing to do", "return", "false", ";", "}" ]
Private helper function for factorizing common classes param logic Estimators that implement the ``partial_fit`` API need to be provided with the list of possible classes at the first call to partial_fit. Subsequent calls to partial_fit should check that ``classes`` is still consistent with a previous value of ``clf.classes_`` when provided. This function returns True if it detects that this was the first call to ``partial_fit`` on ``clf``. In that case the ``classes_`` attribute is also set on ``clf``. @see https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/multiclass.py @param Classifier $clf @param \CArray|null $classes @return bool @throws ValueErrorException
[ "Private", "helper", "function", "for", "factorizing", "common", "classes", "param", "logic" ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Utils/MulticlassUtils.php#L34-L51
29,560
phpsci/phpsci
src/PHPSci/Utils/Datasets/SequentialDataset.php
SequentialDataset.next
public function next(\CArray $x_data_ptr = null, int $x_ind_ptr = null, int $nnz = null, float $y, float $sample_weight = null) { $current_index = $this->_get_next_index(); return $this->_sample($x_data_ptr, $x_ind_ptr, $nnz, $y, $sample_weight, $current_index); }
php
public function next(\CArray $x_data_ptr = null, int $x_ind_ptr = null, int $nnz = null, float $y, float $sample_weight = null) { $current_index = $this->_get_next_index(); return $this->_sample($x_data_ptr, $x_ind_ptr, $nnz, $y, $sample_weight, $current_index); }
[ "public", "function", "next", "(", "\\", "CArray", "$", "x_data_ptr", "=", "null", ",", "int", "$", "x_ind_ptr", "=", "null", ",", "int", "$", "nnz", "=", "null", ",", "float", "$", "y", ",", "float", "$", "sample_weight", "=", "null", ")", "{", "$", "current_index", "=", "$", "this", "->", "_get_next_index", "(", ")", ";", "return", "$", "this", "->", "_sample", "(", "$", "x_data_ptr", ",", "$", "x_ind_ptr", ",", "$", "nnz", ",", "$", "y", ",", "$", "sample_weight", ",", "$", "current_index", ")", ";", "}" ]
Get the next example ``x`` from the dataset. This method gets the next sample looping sequentially over all samples. The order can be shuffled with the method ``shuffle``. Shuffling once before iterating over all samples corresponds to a random draw without replacement. It is used for instance in SGD solver. @param \CArray $x_data_ptr A pointer to the double array which holds the feature values of the next example. @param int $x_ind_ptr A pointer to the int array which holds the feature indices of the next example. @param int $nnz A pointer to an int holding the number of non-zero values of the next example. @param float $y The target value of the next example. @param float $sample_weight The weight of the next example.
[ "Get", "the", "next", "example", "x", "from", "the", "dataset", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Utils/Datasets/SequentialDataset.php#L106-L110
29,561
phpsci/phpsci
src/PHPSci/NaiveBayes/BaseNaiveBayes.php
BaseNaiveBayes.predict
public function predict(\CArray $X) { $predicted_classes = []; $jll = $this->_joint_log_likelihood($X); $predictions = CArray::toArray(CArray::argmax($jll, 1)); foreach($predictions as $pred) { $predicted_classes[] = $this->classes_[[(int)$pred]]; } return $predicted_classes; }
php
public function predict(\CArray $X) { $predicted_classes = []; $jll = $this->_joint_log_likelihood($X); $predictions = CArray::toArray(CArray::argmax($jll, 1)); foreach($predictions as $pred) { $predicted_classes[] = $this->classes_[[(int)$pred]]; } return $predicted_classes; }
[ "public", "function", "predict", "(", "\\", "CArray", "$", "X", ")", "{", "$", "predicted_classes", "=", "[", "]", ";", "$", "jll", "=", "$", "this", "->", "_joint_log_likelihood", "(", "$", "X", ")", ";", "$", "predictions", "=", "CArray", "::", "toArray", "(", "CArray", "::", "argmax", "(", "$", "jll", ",", "1", ")", ")", ";", "foreach", "(", "$", "predictions", "as", "$", "pred", ")", "{", "$", "predicted_classes", "[", "]", "=", "$", "this", "->", "classes_", "[", "[", "(", "int", ")", "$", "pred", "]", "]", ";", "}", "return", "$", "predicted_classes", ";", "}" ]
Perform classification on an array of test vectors X. @param \CArray $X @return void
[ "Perform", "classification", "on", "an", "array", "of", "test", "vectors", "X", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/NaiveBayes/BaseNaiveBayes.php#L28-L37
29,562
phpsci/phpsci
src/PHPSci/Utils/WeightUtils.php
WeightUtils.compute_class_weight
public static function compute_class_weight(\CArray $class_weight = null, \CArray $classes, \CArray $y) : \CArray { if(CArray::unique($y)->x - CArray::unique($classes)->x) { throw new ValueErrorException("classes should include all valid labels that can be in y"); } if(!isset($class_weight) || $class_weight->x == 0) { # uniform class weights $weight = CArray::ones($classes->x, 0); } return $weight; }
php
public static function compute_class_weight(\CArray $class_weight = null, \CArray $classes, \CArray $y) : \CArray { if(CArray::unique($y)->x - CArray::unique($classes)->x) { throw new ValueErrorException("classes should include all valid labels that can be in y"); } if(!isset($class_weight) || $class_weight->x == 0) { # uniform class weights $weight = CArray::ones($classes->x, 0); } return $weight; }
[ "public", "static", "function", "compute_class_weight", "(", "\\", "CArray", "$", "class_weight", "=", "null", ",", "\\", "CArray", "$", "classes", ",", "\\", "CArray", "$", "y", ")", ":", "\\", "CArray", "{", "if", "(", "CArray", "::", "unique", "(", "$", "y", ")", "->", "x", "-", "CArray", "::", "unique", "(", "$", "classes", ")", "->", "x", ")", "{", "throw", "new", "ValueErrorException", "(", "\"classes should include all valid labels that can be in y\"", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "class_weight", ")", "||", "$", "class_weight", "->", "x", "==", "0", ")", "{", "# uniform class weights", "$", "weight", "=", "CArray", "::", "ones", "(", "$", "classes", "->", "x", ",", "0", ")", ";", "}", "return", "$", "weight", ";", "}" ]
Estimate class weights for unbalanced datasets. @see https://github.com/scikit-learn/scikit-learn/blob/a7e17117bb15eb3f51ebccc1bd53e42fcb4e6cd8/sklearn/utils/class_weight.py#L9 @param \CArray $class_weight @param \CArray $classes @param \CArray $y @return \CArray|void @throws ValueErrorException
[ "Estimate", "class", "weights", "for", "unbalanced", "datasets", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Utils/WeightUtils.php#L24-L35
29,563
phpsci/phpsci
src/PHPSci/Plot/Plotter.php
Plotter.drawLabels
private function drawLabels() { $min_value = CArray::amin($this->data[0]); $max_value = CArray::amax($this->data[0]); $left = CArray::toArray( CArray::linspace($min_value, 0, 5, false) ); $right = CArray::toArray( CArray::linspace(0, $max_value, 5) ); # Remove 0 so it don't repeat array_shift($right); $bottom_values = array_merge( $left, $right ); $padding = CArray::toArray( CArray::linspace($this->grid_padding, $this->gridWidth(), count($bottom_values)) ); foreach($bottom_values as $k => $value) { $this->addLine( $padding[$k] + ($this->grid_padding/2), $this->height - $this->grid_padding, $padding[$k] + ($this->grid_padding/2), $this->height - ($this->grid_padding/1.5) ); $this->addText( $value, $padding[$k] + ($this->grid_padding/2.5), $this->height - ($this->grid_padding/2) ); } $min_value = CArray::amin($this->data[1]); $max_value = CArray::amax($this->data[1]); $side_values = CArray::toArray( CArray::linspace($min_value, $max_value, 6, false) ); $padding = CArray::toArray( CArray::linspace($this->gridHeight(), $this->grid_padding, count($side_values)) ); foreach($side_values as $k => $value) { $this->addLine( $this->grid_padding, $padding[$k] + ($this->grid_padding/2), ($this->grid_padding/1.5), $padding[$k] + ($this->grid_padding/2) ); $this->addText( round($value, 2), $this->grid_padding * 0.2, $padding[$k] + ($this->grid_padding/2.5) ); } }
php
private function drawLabels() { $min_value = CArray::amin($this->data[0]); $max_value = CArray::amax($this->data[0]); $left = CArray::toArray( CArray::linspace($min_value, 0, 5, false) ); $right = CArray::toArray( CArray::linspace(0, $max_value, 5) ); # Remove 0 so it don't repeat array_shift($right); $bottom_values = array_merge( $left, $right ); $padding = CArray::toArray( CArray::linspace($this->grid_padding, $this->gridWidth(), count($bottom_values)) ); foreach($bottom_values as $k => $value) { $this->addLine( $padding[$k] + ($this->grid_padding/2), $this->height - $this->grid_padding, $padding[$k] + ($this->grid_padding/2), $this->height - ($this->grid_padding/1.5) ); $this->addText( $value, $padding[$k] + ($this->grid_padding/2.5), $this->height - ($this->grid_padding/2) ); } $min_value = CArray::amin($this->data[1]); $max_value = CArray::amax($this->data[1]); $side_values = CArray::toArray( CArray::linspace($min_value, $max_value, 6, false) ); $padding = CArray::toArray( CArray::linspace($this->gridHeight(), $this->grid_padding, count($side_values)) ); foreach($side_values as $k => $value) { $this->addLine( $this->grid_padding, $padding[$k] + ($this->grid_padding/2), ($this->grid_padding/1.5), $padding[$k] + ($this->grid_padding/2) ); $this->addText( round($value, 2), $this->grid_padding * 0.2, $padding[$k] + ($this->grid_padding/2.5) ); } }
[ "private", "function", "drawLabels", "(", ")", "{", "$", "min_value", "=", "CArray", "::", "amin", "(", "$", "this", "->", "data", "[", "0", "]", ")", ";", "$", "max_value", "=", "CArray", "::", "amax", "(", "$", "this", "->", "data", "[", "0", "]", ")", ";", "$", "left", "=", "CArray", "::", "toArray", "(", "CArray", "::", "linspace", "(", "$", "min_value", ",", "0", ",", "5", ",", "false", ")", ")", ";", "$", "right", "=", "CArray", "::", "toArray", "(", "CArray", "::", "linspace", "(", "0", ",", "$", "max_value", ",", "5", ")", ")", ";", "# Remove 0 so it don't repeat", "array_shift", "(", "$", "right", ")", ";", "$", "bottom_values", "=", "array_merge", "(", "$", "left", ",", "$", "right", ")", ";", "$", "padding", "=", "CArray", "::", "toArray", "(", "CArray", "::", "linspace", "(", "$", "this", "->", "grid_padding", ",", "$", "this", "->", "gridWidth", "(", ")", ",", "count", "(", "$", "bottom_values", ")", ")", ")", ";", "foreach", "(", "$", "bottom_values", "as", "$", "k", "=>", "$", "value", ")", "{", "$", "this", "->", "addLine", "(", "$", "padding", "[", "$", "k", "]", "+", "(", "$", "this", "->", "grid_padding", "/", "2", ")", ",", "$", "this", "->", "height", "-", "$", "this", "->", "grid_padding", ",", "$", "padding", "[", "$", "k", "]", "+", "(", "$", "this", "->", "grid_padding", "/", "2", ")", ",", "$", "this", "->", "height", "-", "(", "$", "this", "->", "grid_padding", "/", "1.5", ")", ")", ";", "$", "this", "->", "addText", "(", "$", "value", ",", "$", "padding", "[", "$", "k", "]", "+", "(", "$", "this", "->", "grid_padding", "/", "2.5", ")", ",", "$", "this", "->", "height", "-", "(", "$", "this", "->", "grid_padding", "/", "2", ")", ")", ";", "}", "$", "min_value", "=", "CArray", "::", "amin", "(", "$", "this", "->", "data", "[", "1", "]", ")", ";", "$", "max_value", "=", "CArray", "::", "amax", "(", "$", "this", "->", "data", "[", "1", "]", ")", ";", "$", "side_values", "=", "CArray", "::", "toArray", "(", "CArray", "::", "linspace", "(", "$", "min_value", ",", "$", "max_value", ",", "6", ",", "false", ")", ")", ";", "$", "padding", "=", "CArray", "::", "toArray", "(", "CArray", "::", "linspace", "(", "$", "this", "->", "gridHeight", "(", ")", ",", "$", "this", "->", "grid_padding", ",", "count", "(", "$", "side_values", ")", ")", ")", ";", "foreach", "(", "$", "side_values", "as", "$", "k", "=>", "$", "value", ")", "{", "$", "this", "->", "addLine", "(", "$", "this", "->", "grid_padding", ",", "$", "padding", "[", "$", "k", "]", "+", "(", "$", "this", "->", "grid_padding", "/", "2", ")", ",", "(", "$", "this", "->", "grid_padding", "/", "1.5", ")", ",", "$", "padding", "[", "$", "k", "]", "+", "(", "$", "this", "->", "grid_padding", "/", "2", ")", ")", ";", "$", "this", "->", "addText", "(", "round", "(", "$", "value", ",", "2", ")", ",", "$", "this", "->", "grid_padding", "*", "0.2", ",", "$", "padding", "[", "$", "k", "]", "+", "(", "$", "this", "->", "grid_padding", "/", "2.5", ")", ")", ";", "}", "}" ]
Draw Y Bottom Labels
[ "Draw", "Y", "Bottom", "Labels" ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Plot/Plotter.php#L167-L233
29,564
phpsci/phpsci
src/PHPSci/Plot/Plotter.php
Plotter.addDot
public function addDot($x, $y, $w, $h, $rgb = [0, 0, 255]) { // choose a color for the ellipse $ellipseColor = imagecolorallocate($this->image(), $rgb[0], $rgb[1], $rgb[2]); // draw the blue ellipse imagefilledellipse($this->image(), $x, $y, $w, $h, $ellipseColor); }
php
public function addDot($x, $y, $w, $h, $rgb = [0, 0, 255]) { // choose a color for the ellipse $ellipseColor = imagecolorallocate($this->image(), $rgb[0], $rgb[1], $rgb[2]); // draw the blue ellipse imagefilledellipse($this->image(), $x, $y, $w, $h, $ellipseColor); }
[ "public", "function", "addDot", "(", "$", "x", ",", "$", "y", ",", "$", "w", ",", "$", "h", ",", "$", "rgb", "=", "[", "0", ",", "0", ",", "255", "]", ")", "{", "// choose a color for the ellipse", "$", "ellipseColor", "=", "imagecolorallocate", "(", "$", "this", "->", "image", "(", ")", ",", "$", "rgb", "[", "0", "]", ",", "$", "rgb", "[", "1", "]", ",", "$", "rgb", "[", "2", "]", ")", ";", "// draw the blue ellipse", "imagefilledellipse", "(", "$", "this", "->", "image", "(", ")", ",", "$", "x", ",", "$", "y", ",", "$", "w", ",", "$", "h", ",", "$", "ellipseColor", ")", ";", "}" ]
Add dot to image @param $x @param $y @param $w @param $h @param array $rgb
[ "Add", "dot", "to", "image" ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Plot/Plotter.php#L278-L284
29,565
phpsci/phpsci
src/PHPSci/Plot/Plotter.php
Plotter.addRectangle
public function addRectangle($x1, $y1, $x2, $y2, $colors = [0, 0, 0]) { $color = imagecolorallocate($this->image(), $colors[0], $colors[1], $colors[2]); imagerectangle ( $this->image() , $x1 , $y1 , $x2 , $y2 , $color ); }
php
public function addRectangle($x1, $y1, $x2, $y2, $colors = [0, 0, 0]) { $color = imagecolorallocate($this->image(), $colors[0], $colors[1], $colors[2]); imagerectangle ( $this->image() , $x1 , $y1 , $x2 , $y2 , $color ); }
[ "public", "function", "addRectangle", "(", "$", "x1", ",", "$", "y1", ",", "$", "x2", ",", "$", "y2", ",", "$", "colors", "=", "[", "0", ",", "0", ",", "0", "]", ")", "{", "$", "color", "=", "imagecolorallocate", "(", "$", "this", "->", "image", "(", ")", ",", "$", "colors", "[", "0", "]", ",", "$", "colors", "[", "1", "]", ",", "$", "colors", "[", "2", "]", ")", ";", "imagerectangle", "(", "$", "this", "->", "image", "(", ")", ",", "$", "x1", ",", "$", "y1", ",", "$", "x2", ",", "$", "y2", ",", "$", "color", ")", ";", "}" ]
Add Rectangle to Graph @param $x1 @param $y1 @param $x2 @param $y2 @param array $colors
[ "Add", "Rectangle", "to", "Graph" ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Plot/Plotter.php#L294-L298
29,566
phpsci/phpsci
src/PHPSci/Plot/Plotter.php
Plotter.generateGrid
private function generateGrid() { $this->addRectangle( $this->grid_padding, ($this->height-$this->grid_padding), ($this->width-$this->grid_padding), $this->grid_padding ); }
php
private function generateGrid() { $this->addRectangle( $this->grid_padding, ($this->height-$this->grid_padding), ($this->width-$this->grid_padding), $this->grid_padding ); }
[ "private", "function", "generateGrid", "(", ")", "{", "$", "this", "->", "addRectangle", "(", "$", "this", "->", "grid_padding", ",", "(", "$", "this", "->", "height", "-", "$", "this", "->", "grid_padding", ")", ",", "(", "$", "this", "->", "width", "-", "$", "this", "->", "grid_padding", ")", ",", "$", "this", "->", "grid_padding", ")", ";", "}" ]
Generate Graph Grid
[ "Generate", "Graph", "Grid" ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Plot/Plotter.php#L303-L311
29,567
polyfony-inc/polyfony
Private/Polyfony/Query/Convert.php
Convert.valueFromDatabase
public static function valueFromDatabase($column_name, $raw_value, $get_it_raw=false) { // if we want the raw result ok, but exclude arrays that can never be gotten raw if($get_it_raw === true && substr($column_name,-6,6) != '_array') { // return as is $value = $raw_value; } // if the column_name contains an array elseif(substr($column_name,-6,6) == '_array') { // decode the array $value = json_decode($raw_value,true); } // if the column_name contains a size value elseif(substr($column_name,-5,5) == '_size') { // convert to human size $value = \Polyfony\Format::size($raw_value); } // if the column_name contains a datetime elseif(substr($column_name,-9,9) == '_datetime') { // if the value is set $value = date('d/m/Y H:i', $raw_value); } // if the column_name contains a date elseif( substr($column_name,-5,5) == '_date' || substr($column_name,-3,3) == '_at' || substr($column_name,-3,3) == '_on' ) { // if the value is set $value = date('d/m/Y', $raw_value); } // not a magic column name else { // we secure it against XSS $value = \Polyfony\Format::htmlSafe($raw_value); } // return the converted (or not) value return $value; }
php
public static function valueFromDatabase($column_name, $raw_value, $get_it_raw=false) { // if we want the raw result ok, but exclude arrays that can never be gotten raw if($get_it_raw === true && substr($column_name,-6,6) != '_array') { // return as is $value = $raw_value; } // if the column_name contains an array elseif(substr($column_name,-6,6) == '_array') { // decode the array $value = json_decode($raw_value,true); } // if the column_name contains a size value elseif(substr($column_name,-5,5) == '_size') { // convert to human size $value = \Polyfony\Format::size($raw_value); } // if the column_name contains a datetime elseif(substr($column_name,-9,9) == '_datetime') { // if the value is set $value = date('d/m/Y H:i', $raw_value); } // if the column_name contains a date elseif( substr($column_name,-5,5) == '_date' || substr($column_name,-3,3) == '_at' || substr($column_name,-3,3) == '_on' ) { // if the value is set $value = date('d/m/Y', $raw_value); } // not a magic column name else { // we secure it against XSS $value = \Polyfony\Format::htmlSafe($raw_value); } // return the converted (or not) value return $value; }
[ "public", "static", "function", "valueFromDatabase", "(", "$", "column_name", ",", "$", "raw_value", ",", "$", "get_it_raw", "=", "false", ")", "{", "// if we want the raw result ok, but exclude arrays that can never be gotten raw", "if", "(", "$", "get_it_raw", "===", "true", "&&", "substr", "(", "$", "column_name", ",", "-", "6", ",", "6", ")", "!=", "'_array'", ")", "{", "// return as is", "$", "value", "=", "$", "raw_value", ";", "}", "// if the column_name contains an array", "elseif", "(", "substr", "(", "$", "column_name", ",", "-", "6", ",", "6", ")", "==", "'_array'", ")", "{", "// decode the array", "$", "value", "=", "json_decode", "(", "$", "raw_value", ",", "true", ")", ";", "}", "// if the column_name contains a size value", "elseif", "(", "substr", "(", "$", "column_name", ",", "-", "5", ",", "5", ")", "==", "'_size'", ")", "{", "// convert to human size", "$", "value", "=", "\\", "Polyfony", "\\", "Format", "::", "size", "(", "$", "raw_value", ")", ";", "}", "// if the column_name contains a datetime", "elseif", "(", "substr", "(", "$", "column_name", ",", "-", "9", ",", "9", ")", "==", "'_datetime'", ")", "{", "// if the value is set", "$", "value", "=", "date", "(", "'d/m/Y H:i'", ",", "$", "raw_value", ")", ";", "}", "// if the column_name contains a date", "elseif", "(", "substr", "(", "$", "column_name", ",", "-", "5", ",", "5", ")", "==", "'_date'", "||", "substr", "(", "$", "column_name", ",", "-", "3", ",", "3", ")", "==", "'_at'", "||", "substr", "(", "$", "column_name", ",", "-", "3", ",", "3", ")", "==", "'_on'", ")", "{", "// if the value is set", "$", "value", "=", "date", "(", "'d/m/Y'", ",", "$", "raw_value", ")", ";", "}", "// not a magic column name", "else", "{", "// we secure it against XSS", "$", "value", "=", "\\", "Polyfony", "\\", "Format", "::", "htmlSafe", "(", "$", "raw_value", ")", ";", "}", "// return the converted (or not) value", "return", "$", "value", ";", "}" ]
convert a value comming from the database, to its original type
[ "convert", "a", "value", "comming", "from", "the", "database", "to", "its", "original", "type" ]
76dac2f4141c8f480370236295c07dfa52e5c589
https://github.com/polyfony-inc/polyfony/blob/76dac2f4141c8f480370236295c07dfa52e5c589/Private/Polyfony/Query/Convert.php#L9-L48
29,568
polyfony-inc/polyfony
Private/Polyfony/Query/Convert.php
Convert.columnToPlaceholder
public static function columnToPlaceholder( string $quote_symbol, string $column, $allow_wildcard = false ) :array { // apply the secure regex for the column name $column = preg_replace(($allow_wildcard ? '/[^a-zA-Z0-9_\.\*]/' : '/[^a-zA-Z0-9_\.]/'), '', $column); // cleanup the placeholder $placeholder = str_replace(['.', '*'], '_', strtolower($column)); // return cleaned column return([$quote_symbol . $column . $quote_symbol, $placeholder]); }
php
public static function columnToPlaceholder( string $quote_symbol, string $column, $allow_wildcard = false ) :array { // apply the secure regex for the column name $column = preg_replace(($allow_wildcard ? '/[^a-zA-Z0-9_\.\*]/' : '/[^a-zA-Z0-9_\.]/'), '', $column); // cleanup the placeholder $placeholder = str_replace(['.', '*'], '_', strtolower($column)); // return cleaned column return([$quote_symbol . $column . $quote_symbol, $placeholder]); }
[ "public", "static", "function", "columnToPlaceholder", "(", "string", "$", "quote_symbol", ",", "string", "$", "column", ",", "$", "allow_wildcard", "=", "false", ")", ":", "array", "{", "// apply the secure regex for the column name", "$", "column", "=", "preg_replace", "(", "(", "$", "allow_wildcard", "?", "'/[^a-zA-Z0-9_\\.\\*]/'", ":", "'/[^a-zA-Z0-9_\\.]/'", ")", ",", "''", ",", "$", "column", ")", ";", "// cleanup the placeholder", "$", "placeholder", "=", "str_replace", "(", "[", "'.'", ",", "'*'", "]", ",", "'_'", ",", "strtolower", "(", "$", "column", ")", ")", ";", "// return cleaned column", "return", "(", "[", "$", "quote_symbol", ".", "$", "column", ".", "$", "quote_symbol", ",", "$", "placeholder", "]", ")", ";", "}" ]
get a column placeholder to build queries with
[ "get", "a", "column", "placeholder", "to", "build", "queries", "with" ]
76dac2f4141c8f480370236295c07dfa52e5c589
https://github.com/polyfony-inc/polyfony/blob/76dac2f4141c8f480370236295c07dfa52e5c589/Private/Polyfony/Query/Convert.php#L98-L109
29,569
ventoviro/windwalker-core
src/Core/Cache/CacheManager.php
CacheManager.getCache
public function getCache( string $name = 'windwalker', string $storage = 'array', string $serializer = 'php', array $options = [] ): CacheInterface { $config = $this->config; $debug = $config->get('system.debug', false); $enabled = $config->get('cache.enabled', false); $forceEnabled = $options['force_enabled'] ?? false; if (!$forceEnabled && ($debug || !$enabled) && !$this->ignoreGlobal) { $storage = 'null'; $serializer = 'raw'; } return $this->create($name, $storage, $serializer, $options); }
php
public function getCache( string $name = 'windwalker', string $storage = 'array', string $serializer = 'php', array $options = [] ): CacheInterface { $config = $this->config; $debug = $config->get('system.debug', false); $enabled = $config->get('cache.enabled', false); $forceEnabled = $options['force_enabled'] ?? false; if (!$forceEnabled && ($debug || !$enabled) && !$this->ignoreGlobal) { $storage = 'null'; $serializer = 'raw'; } return $this->create($name, $storage, $serializer, $options); }
[ "public", "function", "getCache", "(", "string", "$", "name", "=", "'windwalker'", ",", "string", "$", "storage", "=", "'array'", ",", "string", "$", "serializer", "=", "'php'", ",", "array", "$", "options", "=", "[", "]", ")", ":", "CacheInterface", "{", "$", "config", "=", "$", "this", "->", "config", ";", "$", "debug", "=", "$", "config", "->", "get", "(", "'system.debug'", ",", "false", ")", ";", "$", "enabled", "=", "$", "config", "->", "get", "(", "'cache.enabled'", ",", "false", ")", ";", "$", "forceEnabled", "=", "$", "options", "[", "'force_enabled'", "]", "??", "false", ";", "if", "(", "!", "$", "forceEnabled", "&&", "(", "$", "debug", "||", "!", "$", "enabled", ")", "&&", "!", "$", "this", "->", "ignoreGlobal", ")", "{", "$", "storage", "=", "'null'", ";", "$", "serializer", "=", "'raw'", ";", "}", "return", "$", "this", "->", "create", "(", "$", "name", ",", "$", "storage", ",", "$", "serializer", ",", "$", "options", ")", ";", "}" ]
Create cache object. @param string $name @param string $storage @param string $serializer @param array $options @return CacheInterface @throws \ReflectionException @throws \Windwalker\DI\Exception\DependencyResolutionException @deprecated Use getCacheInstance() instead.
[ "Create", "cache", "object", "." ]
0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074
https://github.com/ventoviro/windwalker-core/blob/0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074/src/Core/Cache/CacheManager.php#L132-L151
29,570
ventoviro/windwalker-core
src/Core/Cache/CacheManager.php
CacheManager.ignoreGlobal
public function ignoreGlobal(?bool $bool = null): bool { if ($bool === null) { return $this->ignoreGlobal; } $this->ignoreGlobal = (bool) $bool; return $bool; }
php
public function ignoreGlobal(?bool $bool = null): bool { if ($bool === null) { return $this->ignoreGlobal; } $this->ignoreGlobal = (bool) $bool; return $bool; }
[ "public", "function", "ignoreGlobal", "(", "?", "bool", "$", "bool", "=", "null", ")", ":", "bool", "{", "if", "(", "$", "bool", "===", "null", ")", "{", "return", "$", "this", "->", "ignoreGlobal", ";", "}", "$", "this", "->", "ignoreGlobal", "=", "(", "bool", ")", "$", "bool", ";", "return", "$", "bool", ";", "}" ]
Method to get property IgnoreGlobal @param boolean $bool @return boolean
[ "Method", "to", "get", "property", "IgnoreGlobal" ]
0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074
https://github.com/ventoviro/windwalker-core/blob/0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074/src/Core/Cache/CacheManager.php#L333-L342
29,571
polyfony-inc/polyfony
Private/Polyfony/Query/Conditions.php
Conditions.where
public function where(array $conditions) { // for each provided strict condition foreach($conditions as $column => $value) { // secure the column name list( $column, $placeholder ) = Convert::columnToPlaceholder($this->Quote ,$column); // save the condition $this->Conditions[] = "{$this->Operator} ( {$column} = :{$placeholder} )"; // save the value $this->Values[":{$placeholder}"] = $value; } // return self to the next method return $this; }
php
public function where(array $conditions) { // for each provided strict condition foreach($conditions as $column => $value) { // secure the column name list( $column, $placeholder ) = Convert::columnToPlaceholder($this->Quote ,$column); // save the condition $this->Conditions[] = "{$this->Operator} ( {$column} = :{$placeholder} )"; // save the value $this->Values[":{$placeholder}"] = $value; } // return self to the next method return $this; }
[ "public", "function", "where", "(", "array", "$", "conditions", ")", "{", "// for each provided strict condition", "foreach", "(", "$", "conditions", "as", "$", "column", "=>", "$", "value", ")", "{", "// secure the column name", "list", "(", "$", "column", ",", "$", "placeholder", ")", "=", "Convert", "::", "columnToPlaceholder", "(", "$", "this", "->", "Quote", ",", "$", "column", ")", ";", "// save the condition", "$", "this", "->", "Conditions", "[", "]", "=", "\"{$this->Operator} ( {$column} = :{$placeholder} )\"", ";", "// save the value", "$", "this", "->", "Values", "[", "\":{$placeholder}\"", "]", "=", "$", "value", ";", "}", "// return self to the next method", "return", "$", "this", ";", "}" ]
add a condition
[ "add", "a", "condition" ]
76dac2f4141c8f480370236295c07dfa52e5c589
https://github.com/polyfony-inc/polyfony/blob/76dac2f4141c8f480370236295c07dfa52e5c589/Private/Polyfony/Query/Conditions.php#L9-L24
29,572
polyfony-inc/polyfony
Private/Polyfony/Query/Conditions.php
Conditions.whereEmpty
public function whereEmpty($conditions) { // if provided conditions are an array if(is_array($conditions)) { // for each condition foreach($conditions as $column) { // add the condition $this->whereEmpty($column); } } else { // secure the column name list( $column, $placeholder ) = Convert::columnToPlaceholder($this->Quote ,$conditions); // save the condition $this->Conditions[] = "{$this->Operator} ( {$column} == :empty_{$placeholder} OR {$column} IS NULL )"; // add the empty value $this->Values[":empty_{$placeholder}"] = ''; } // return self to the next method return $this; }
php
public function whereEmpty($conditions) { // if provided conditions are an array if(is_array($conditions)) { // for each condition foreach($conditions as $column) { // add the condition $this->whereEmpty($column); } } else { // secure the column name list( $column, $placeholder ) = Convert::columnToPlaceholder($this->Quote ,$conditions); // save the condition $this->Conditions[] = "{$this->Operator} ( {$column} == :empty_{$placeholder} OR {$column} IS NULL )"; // add the empty value $this->Values[":empty_{$placeholder}"] = ''; } // return self to the next method return $this; }
[ "public", "function", "whereEmpty", "(", "$", "conditions", ")", "{", "// if provided conditions are an array", "if", "(", "is_array", "(", "$", "conditions", ")", ")", "{", "// for each condition", "foreach", "(", "$", "conditions", "as", "$", "column", ")", "{", "// add the condition", "$", "this", "->", "whereEmpty", "(", "$", "column", ")", ";", "}", "}", "else", "{", "// secure the column name", "list", "(", "$", "column", ",", "$", "placeholder", ")", "=", "Convert", "::", "columnToPlaceholder", "(", "$", "this", "->", "Quote", ",", "$", "conditions", ")", ";", "// save the condition", "$", "this", "->", "Conditions", "[", "]", "=", "\"{$this->Operator} ( {$column} == :empty_{$placeholder} OR {$column} IS NULL )\"", ";", "// add the empty value", "$", "this", "->", "Values", "[", "\":empty_{$placeholder}\"", "]", "=", "''", ";", "}", "// return self to the next method", "return", "$", "this", ";", "}" ]
we are still supporting NON-array parameter, this will be removed at some point in time
[ "we", "are", "still", "supporting", "NON", "-", "array", "parameter", "this", "will", "be", "removed", "at", "some", "point", "in", "time" ]
76dac2f4141c8f480370236295c07dfa52e5c589
https://github.com/polyfony-inc/polyfony/blob/76dac2f4141c8f480370236295c07dfa52e5c589/Private/Polyfony/Query/Conditions.php#L185-L207
29,573
polyfony-inc/polyfony
Private/Polyfony/Security.php
Security.disconnect
public static function disconnect() :void { // first authenticate self::enforce(); // then close the session self::$_account->closeSession(); // and redirect to the exit route or fallback to the login route Response::setRedirect(Config::get('router', 'exit_route') ?: Config::get('router', 'login_route')); // render the response Response::render(); }
php
public static function disconnect() :void { // first authenticate self::enforce(); // then close the session self::$_account->closeSession(); // and redirect to the exit route or fallback to the login route Response::setRedirect(Config::get('router', 'exit_route') ?: Config::get('router', 'login_route')); // render the response Response::render(); }
[ "public", "static", "function", "disconnect", "(", ")", ":", "void", "{", "// first authenticate", "self", "::", "enforce", "(", ")", ";", "// then close the session", "self", "::", "$", "_account", "->", "closeSession", "(", ")", ";", "// and redirect to the exit route or fallback to the login route", "Response", "::", "setRedirect", "(", "Config", "::", "get", "(", "'router'", ",", "'exit_route'", ")", "?", ":", "Config", "::", "get", "(", "'router'", ",", "'login_route'", ")", ")", ";", "// render the response", "Response", "::", "render", "(", ")", ";", "}" ]
authenticate then close the session
[ "authenticate", "then", "close", "the", "session" ]
76dac2f4141c8f480370236295c07dfa52e5c589
https://github.com/polyfony-inc/polyfony/blob/76dac2f4141c8f480370236295c07dfa52e5c589/Private/Polyfony/Security.php#L49-L63
29,574
polyfony-inc/polyfony
Private/Polyfony/Security.php
Security.authenticate
protected static function authenticate() :void { // if we did not authenticate before if(!self::$_account) { // search for an enabled account with that session key and a non expired session $account = \Models\Accounts::getFirstEnabledWithNonExpiredSession( // the session key Cook::get(Config::get('security', 'cookie')) ); // if the cookie session key doesn't match any existing account session, we deny access $account ?: self::refuse( 'Your session is no longer valid', 403, true); // if the stored key and dynamically generated mismatch, we deny access $account->hasMatchingDynamicKey() ?: self::refuse( 'Your signature has changed since your last visit, please log-in again', 403, true); // if account has expired, we deny access !$account->hasItsValidityExpired() ?: self::refuse( "Your account has expired, it was valid until {$account->get('account_expiration_date')}", 403, true); // update our credentials self::$_account = $account; // set access as granted self::$_granted = true; } }
php
protected static function authenticate() :void { // if we did not authenticate before if(!self::$_account) { // search for an enabled account with that session key and a non expired session $account = \Models\Accounts::getFirstEnabledWithNonExpiredSession( // the session key Cook::get(Config::get('security', 'cookie')) ); // if the cookie session key doesn't match any existing account session, we deny access $account ?: self::refuse( 'Your session is no longer valid', 403, true); // if the stored key and dynamically generated mismatch, we deny access $account->hasMatchingDynamicKey() ?: self::refuse( 'Your signature has changed since your last visit, please log-in again', 403, true); // if account has expired, we deny access !$account->hasItsValidityExpired() ?: self::refuse( "Your account has expired, it was valid until {$account->get('account_expiration_date')}", 403, true); // update our credentials self::$_account = $account; // set access as granted self::$_granted = true; } }
[ "protected", "static", "function", "authenticate", "(", ")", ":", "void", "{", "// if we did not authenticate before", "if", "(", "!", "self", "::", "$", "_account", ")", "{", "// search for an enabled account with that session key and a non expired session", "$", "account", "=", "\\", "Models", "\\", "Accounts", "::", "getFirstEnabledWithNonExpiredSession", "(", "// the session key", "Cook", "::", "get", "(", "Config", "::", "get", "(", "'security'", ",", "'cookie'", ")", ")", ")", ";", "// if the cookie session key doesn't match any existing account session, we deny access", "$", "account", "?", ":", "self", "::", "refuse", "(", "'Your session is no longer valid'", ",", "403", ",", "true", ")", ";", "// if the stored key and dynamically generated mismatch, we deny access", "$", "account", "->", "hasMatchingDynamicKey", "(", ")", "?", ":", "self", "::", "refuse", "(", "'Your signature has changed since your last visit, please log-in again'", ",", "403", ",", "true", ")", ";", "// if account has expired, we deny access", "!", "$", "account", "->", "hasItsValidityExpired", "(", ")", "?", ":", "self", "::", "refuse", "(", "\"Your account has expired, it was valid until {$account->get('account_expiration_date')}\"", ",", "403", ",", "true", ")", ";", "// update our credentials", "self", "::", "$", "_account", "=", "$", "account", ";", "// set access as granted", "self", "::", "$", "_granted", "=", "true", ";", "}", "}" ]
internal authentication method that will grant access based on an existing session
[ "internal", "authentication", "method", "that", "will", "grant", "access", "based", "on", "an", "existing", "session" ]
76dac2f4141c8f480370236295c07dfa52e5c589
https://github.com/polyfony-inc/polyfony/blob/76dac2f4141c8f480370236295c07dfa52e5c589/Private/Polyfony/Security.php#L66-L94
29,575
polyfony-inc/polyfony
Private/Polyfony/Security.php
Security.login
protected static function login() :void { // look for users with this login $account = \Models\Accounts::getFirstEnabledWithLogin( Request::post( Config::get('security', 'login') ) ); // if the account does not exist/is not found if(!$account) { // we deny access self::refuse('Account does not exist or is disabled'); } // if the account has been forced by that ip recently if($account->hasFailedLoginAttemptsRecentFrom(self::getSafeRemoteAddress())) { // extend the lock on the account $account->extendLoginBan(); // refuse access self::refuse('Please wait '.Config::get('security', 'waiting_duration').' seconds before trying again'); } // if the account has expired if($account->hasItsValidityExpired()) { // register that failure $account->registerFailedLoginAttemptFrom(self::getSafeRemoteAddress(), self::getSafeUserAgent()); // refuse access self::refuse("Your account has expired, it was valid until {$account->get('account_expiration_date')}"); } // if the posted password doesn't match the account's password if(!$account->hasThisPassword(Request::post(Config::get('security', 'password')))) { // register that failure $account->registerFailedLoginAttemptFrom(self::getSafeRemoteAddress(), self::getSafeUserAgent()); // refuse access self::refuse('Wrong password'); } // if we failed to open a session if(!$account->tryOpeningSession()) { // we report that something is wrong self::refuse('Your session failed to open, make sure your browser accepts cookies', 500); } // then session has been opened else { // log the loggin action Logger::info("Account {$account->get('login')} has logged in"); // put the user inside of us self::$_account = $account; // set the most basic authentication block as being true/passed self::$_granted = true; // if we have an url in the session, redirect to it (and remove it) !Session::has('previously_requested_url') ?: self::redirectToThePreviouslyRequestedUrl(); } }
php
protected static function login() :void { // look for users with this login $account = \Models\Accounts::getFirstEnabledWithLogin( Request::post( Config::get('security', 'login') ) ); // if the account does not exist/is not found if(!$account) { // we deny access self::refuse('Account does not exist or is disabled'); } // if the account has been forced by that ip recently if($account->hasFailedLoginAttemptsRecentFrom(self::getSafeRemoteAddress())) { // extend the lock on the account $account->extendLoginBan(); // refuse access self::refuse('Please wait '.Config::get('security', 'waiting_duration').' seconds before trying again'); } // if the account has expired if($account->hasItsValidityExpired()) { // register that failure $account->registerFailedLoginAttemptFrom(self::getSafeRemoteAddress(), self::getSafeUserAgent()); // refuse access self::refuse("Your account has expired, it was valid until {$account->get('account_expiration_date')}"); } // if the posted password doesn't match the account's password if(!$account->hasThisPassword(Request::post(Config::get('security', 'password')))) { // register that failure $account->registerFailedLoginAttemptFrom(self::getSafeRemoteAddress(), self::getSafeUserAgent()); // refuse access self::refuse('Wrong password'); } // if we failed to open a session if(!$account->tryOpeningSession()) { // we report that something is wrong self::refuse('Your session failed to open, make sure your browser accepts cookies', 500); } // then session has been opened else { // log the loggin action Logger::info("Account {$account->get('login')} has logged in"); // put the user inside of us self::$_account = $account; // set the most basic authentication block as being true/passed self::$_granted = true; // if we have an url in the session, redirect to it (and remove it) !Session::has('previously_requested_url') ?: self::redirectToThePreviouslyRequestedUrl(); } }
[ "protected", "static", "function", "login", "(", ")", ":", "void", "{", "// look for users with this login", "$", "account", "=", "\\", "Models", "\\", "Accounts", "::", "getFirstEnabledWithLogin", "(", "Request", "::", "post", "(", "Config", "::", "get", "(", "'security'", ",", "'login'", ")", ")", ")", ";", "// if the account does not exist/is not found", "if", "(", "!", "$", "account", ")", "{", "// we deny access", "self", "::", "refuse", "(", "'Account does not exist or is disabled'", ")", ";", "}", "// if the account has been forced by that ip recently", "if", "(", "$", "account", "->", "hasFailedLoginAttemptsRecentFrom", "(", "self", "::", "getSafeRemoteAddress", "(", ")", ")", ")", "{", "// extend the lock on the account", "$", "account", "->", "extendLoginBan", "(", ")", ";", "// refuse access", "self", "::", "refuse", "(", "'Please wait '", ".", "Config", "::", "get", "(", "'security'", ",", "'waiting_duration'", ")", ".", "' seconds before trying again'", ")", ";", "}", "// if the account has expired", "if", "(", "$", "account", "->", "hasItsValidityExpired", "(", ")", ")", "{", "// register that failure", "$", "account", "->", "registerFailedLoginAttemptFrom", "(", "self", "::", "getSafeRemoteAddress", "(", ")", ",", "self", "::", "getSafeUserAgent", "(", ")", ")", ";", "// refuse access", "self", "::", "refuse", "(", "\"Your account has expired, it was valid until {$account->get('account_expiration_date')}\"", ")", ";", "}", "// if the posted password doesn't match the account's password", "if", "(", "!", "$", "account", "->", "hasThisPassword", "(", "Request", "::", "post", "(", "Config", "::", "get", "(", "'security'", ",", "'password'", ")", ")", ")", ")", "{", "// register that failure", "$", "account", "->", "registerFailedLoginAttemptFrom", "(", "self", "::", "getSafeRemoteAddress", "(", ")", ",", "self", "::", "getSafeUserAgent", "(", ")", ")", ";", "// refuse access", "self", "::", "refuse", "(", "'Wrong password'", ")", ";", "}", "// if we failed to open a session", "if", "(", "!", "$", "account", "->", "tryOpeningSession", "(", ")", ")", "{", "// we report that something is wrong", "self", "::", "refuse", "(", "'Your session failed to open, make sure your browser accepts cookies'", ",", "500", ")", ";", "}", "// then session has been opened", "else", "{", "// log the loggin action", "Logger", "::", "info", "(", "\"Account {$account->get('login')} has logged in\"", ")", ";", "// put the user inside of us", "self", "::", "$", "_account", "=", "$", "account", ";", "// set the most basic authentication block as being true/passed", "self", "::", "$", "_granted", "=", "true", ";", "// if we have an url in the session, redirect to it (and remove it)", "!", "Session", "::", "has", "(", "'previously_requested_url'", ")", "?", ":", "self", "::", "redirectToThePreviouslyRequestedUrl", "(", ")", ";", "}", "}" ]
internal login method that will open a session
[ "internal", "login", "method", "that", "will", "open", "a", "session" ]
76dac2f4141c8f480370236295c07dfa52e5c589
https://github.com/polyfony-inc/polyfony/blob/76dac2f4141c8f480370236295c07dfa52e5c589/Private/Polyfony/Security.php#L97-L146
29,576
polyfony-inc/polyfony
Private/Polyfony/Security.php
Security.getSignature
public static function getSignature($mixed) :string { // compute a hash with (the provided string + salt + user agent + remote ip) return(hash(Config::get('security','algo'), self::getSafeUserAgent() . self::getSafeRemoteAddress() . Config::get('security','salt') . is_string($mixed) ? $mixed : json_encode($mixed) )); }
php
public static function getSignature($mixed) :string { // compute a hash with (the provided string + salt + user agent + remote ip) return(hash(Config::get('security','algo'), self::getSafeUserAgent() . self::getSafeRemoteAddress() . Config::get('security','salt') . is_string($mixed) ? $mixed : json_encode($mixed) )); }
[ "public", "static", "function", "getSignature", "(", "$", "mixed", ")", ":", "string", "{", "// compute a hash with (the provided string + salt + user agent + remote ip)", "return", "(", "hash", "(", "Config", "::", "get", "(", "'security'", ",", "'algo'", ")", ",", "self", "::", "getSafeUserAgent", "(", ")", ".", "self", "::", "getSafeRemoteAddress", "(", ")", ".", "Config", "::", "get", "(", "'security'", ",", "'salt'", ")", ".", "is_string", "(", "$", "mixed", ")", "?", "$", "mixed", ":", "json_encode", "(", "$", "mixed", ")", ")", ")", ";", "}" ]
internal method for generating unique signatures
[ "internal", "method", "for", "generating", "unique", "signatures" ]
76dac2f4141c8f480370236295c07dfa52e5c589
https://github.com/polyfony-inc/polyfony/blob/76dac2f4141c8f480370236295c07dfa52e5c589/Private/Polyfony/Security.php#L172-L178
29,577
locomotivemtl/charcoal-ui
src/Charcoal/Ui/Layout/LayoutTrait.php
LayoutTrait.setStructure
public function setStructure(array $layouts) { $computedLayouts = []; foreach ($layouts as $l) { $loop = isset($l['loop']) ? (int)$l['loop'] : 1; unset($l['loop']); for ($i=0; $i<$loop; $i++) { $computedLayouts[] = $l; } } $this->structure = $computedLayouts; return $this; }
php
public function setStructure(array $layouts) { $computedLayouts = []; foreach ($layouts as $l) { $loop = isset($l['loop']) ? (int)$l['loop'] : 1; unset($l['loop']); for ($i=0; $i<$loop; $i++) { $computedLayouts[] = $l; } } $this->structure = $computedLayouts; return $this; }
[ "public", "function", "setStructure", "(", "array", "$", "layouts", ")", "{", "$", "computedLayouts", "=", "[", "]", ";", "foreach", "(", "$", "layouts", "as", "$", "l", ")", "{", "$", "loop", "=", "isset", "(", "$", "l", "[", "'loop'", "]", ")", "?", "(", "int", ")", "$", "l", "[", "'loop'", "]", ":", "1", ";", "unset", "(", "$", "l", "[", "'loop'", "]", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "loop", ";", "$", "i", "++", ")", "{", "$", "computedLayouts", "[", "]", "=", "$", "l", ";", "}", "}", "$", "this", "->", "structure", "=", "$", "computedLayouts", ";", "return", "$", "this", ";", "}" ]
Prepare the layouts configuration in a simpler, ready, data structure. This function goes through the layout options to expand loops into extra layout data... @param array $layouts The original layout data, typically from configuration. @return array Computed layouts, ready for looping
[ "Prepare", "the", "layouts", "configuration", "in", "a", "simpler", "ready", "data", "structure", "." ]
0070f35d89ea24ae93720734d261c02a10e218b6
https://github.com/locomotivemtl/charcoal-ui/blob/0070f35d89ea24ae93720734d261c02a10e218b6/src/Charcoal/Ui/Layout/LayoutTrait.php#L54-L68
29,578
locomotivemtl/charcoal-ui
src/Charcoal/Ui/Layout/LayoutTrait.php
LayoutTrait.rowIndex
public function rowIndex($position = null) { if ($position === null) { $position = $this->position(); } $i = 0; $p = 0; foreach ($this->structure as $row_ident => $row) { $numCells = count($row['columns']); $p += $numCells; if ($p > $position) { return $i; } $i++; } return null; }
php
public function rowIndex($position = null) { if ($position === null) { $position = $this->position(); } $i = 0; $p = 0; foreach ($this->structure as $row_ident => $row) { $numCells = count($row['columns']); $p += $numCells; if ($p > $position) { return $i; } $i++; } return null; }
[ "public", "function", "rowIndex", "(", "$", "position", "=", "null", ")", "{", "if", "(", "$", "position", "===", "null", ")", "{", "$", "position", "=", "$", "this", "->", "position", "(", ")", ";", "}", "$", "i", "=", "0", ";", "$", "p", "=", "0", ";", "foreach", "(", "$", "this", "->", "structure", "as", "$", "row_ident", "=>", "$", "row", ")", "{", "$", "numCells", "=", "count", "(", "$", "row", "[", "'columns'", "]", ")", ";", "$", "p", "+=", "$", "numCells", ";", "if", "(", "$", "p", ">", "$", "position", ")", "{", "return", "$", "i", ";", "}", "$", "i", "++", ";", "}", "return", "null", ";", "}" ]
Get the row index at a certain position @param integer $position Optional. Forced position. @return integer|null
[ "Get", "the", "row", "index", "at", "a", "certain", "position" ]
0070f35d89ea24ae93720734d261c02a10e218b6
https://github.com/locomotivemtl/charcoal-ui/blob/0070f35d89ea24ae93720734d261c02a10e218b6/src/Charcoal/Ui/Layout/LayoutTrait.php#L95-L112
29,579
locomotivemtl/charcoal-ui
src/Charcoal/Ui/Layout/LayoutTrait.php
LayoutTrait.rowData
public function rowData($position = null) { if ($position === null) { $position = $this->position(); } $rowIndex = $this->rowIndex($position); if (isset($this->structure[$rowIndex])) { return $this->structure[$rowIndex]; } else { return null; } }
php
public function rowData($position = null) { if ($position === null) { $position = $this->position(); } $rowIndex = $this->rowIndex($position); if (isset($this->structure[$rowIndex])) { return $this->structure[$rowIndex]; } else { return null; } }
[ "public", "function", "rowData", "(", "$", "position", "=", "null", ")", "{", "if", "(", "$", "position", "===", "null", ")", "{", "$", "position", "=", "$", "this", "->", "position", "(", ")", ";", "}", "$", "rowIndex", "=", "$", "this", "->", "rowIndex", "(", "$", "position", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "structure", "[", "$", "rowIndex", "]", ")", ")", "{", "return", "$", "this", "->", "structure", "[", "$", "rowIndex", "]", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Get the row information If no `$position` is specified, then the current position will be used. @param integer $position Optional. Forced position. @return array|null
[ "Get", "the", "row", "information" ]
0070f35d89ea24ae93720734d261c02a10e218b6
https://github.com/locomotivemtl/charcoal-ui/blob/0070f35d89ea24ae93720734d261c02a10e218b6/src/Charcoal/Ui/Layout/LayoutTrait.php#L122-L134
29,580
locomotivemtl/charcoal-ui
src/Charcoal/Ui/Layout/LayoutTrait.php
LayoutTrait.rowNumCells
public function rowNumCells($position = null) { if ($position === null) { $position = $this->position(); } // Get the data ta position $row = $this->rowData($position); $numCells = isset($row['columns']) ? count($row['columns']) : null; return $numCells; }
php
public function rowNumCells($position = null) { if ($position === null) { $position = $this->position(); } // Get the data ta position $row = $this->rowData($position); $numCells = isset($row['columns']) ? count($row['columns']) : null; return $numCells; }
[ "public", "function", "rowNumCells", "(", "$", "position", "=", "null", ")", "{", "if", "(", "$", "position", "===", "null", ")", "{", "$", "position", "=", "$", "this", "->", "position", "(", ")", ";", "}", "// Get the data ta position", "$", "row", "=", "$", "this", "->", "rowData", "(", "$", "position", ")", ";", "$", "numCells", "=", "isset", "(", "$", "row", "[", "'columns'", "]", ")", "?", "count", "(", "$", "row", "[", "'columns'", "]", ")", ":", "null", ";", "return", "$", "numCells", ";", "}" ]
Get the number of cells at current position This can be different than the number of columns, in case @param integer $position Optional. Forced position. @return integer
[ "Get", "the", "number", "of", "cells", "at", "current", "position" ]
0070f35d89ea24ae93720734d261c02a10e218b6
https://github.com/locomotivemtl/charcoal-ui/blob/0070f35d89ea24ae93720734d261c02a10e218b6/src/Charcoal/Ui/Layout/LayoutTrait.php#L164-L174
29,581
locomotivemtl/charcoal-ui
src/Charcoal/Ui/Layout/LayoutTrait.php
LayoutTrait.cellRowIndex
public function cellRowIndex($position = null) { if ($position === null) { $position = $this->position(); } $first = $this->rowFirstCellIndex($position); return ($position - $first); }
php
public function cellRowIndex($position = null) { if ($position === null) { $position = $this->position(); } $first = $this->rowFirstCellIndex($position); return ($position - $first); }
[ "public", "function", "cellRowIndex", "(", "$", "position", "=", "null", ")", "{", "if", "(", "$", "position", "===", "null", ")", "{", "$", "position", "=", "$", "this", "->", "position", "(", ")", ";", "}", "$", "first", "=", "$", "this", "->", "rowFirstCellIndex", "(", "$", "position", ")", ";", "return", "(", "$", "position", "-", "$", "first", ")", ";", "}" ]
Get the cell index in the current row @param integer $position Optional. Forced position. @return integer
[ "Get", "the", "cell", "index", "in", "the", "current", "row" ]
0070f35d89ea24ae93720734d261c02a10e218b6
https://github.com/locomotivemtl/charcoal-ui/blob/0070f35d89ea24ae93720734d261c02a10e218b6/src/Charcoal/Ui/Layout/LayoutTrait.php#L217-L225
29,582
locomotivemtl/charcoal-ui
src/Charcoal/Ui/Layout/LayoutTrait.php
LayoutTrait.numCellsTotal
public function numCellsTotal() { $numCells = 0; foreach ($this->structure as $row) { $rowCols = isset($row['columns']) ? count($row['columns']) : 0; $numCells += $rowCols; } return $numCells; }
php
public function numCellsTotal() { $numCells = 0; foreach ($this->structure as $row) { $rowCols = isset($row['columns']) ? count($row['columns']) : 0; $numCells += $rowCols; } return $numCells; }
[ "public", "function", "numCellsTotal", "(", ")", "{", "$", "numCells", "=", "0", ";", "foreach", "(", "$", "this", "->", "structure", "as", "$", "row", ")", "{", "$", "rowCols", "=", "isset", "(", "$", "row", "[", "'columns'", "]", ")", "?", "count", "(", "$", "row", "[", "'columns'", "]", ")", ":", "0", ";", "$", "numCells", "+=", "$", "rowCols", ";", "}", "return", "$", "numCells", ";", "}" ]
Get the total number of cells, in all rows @return integer
[ "Get", "the", "total", "number", "of", "cells", "in", "all", "rows" ]
0070f35d89ea24ae93720734d261c02a10e218b6
https://github.com/locomotivemtl/charcoal-ui/blob/0070f35d89ea24ae93720734d261c02a10e218b6/src/Charcoal/Ui/Layout/LayoutTrait.php#L232-L240
29,583
acdh-oeaw/repo-php-util
src/acdhOeaw/fedora/dissemination/parameter/UriPart.php
UriPart.transform
public function transform(string $value, string ...$parts): string { $value = parse_url($value); $toUnset = ['scheme', 'host', 'port', 'user', 'pass', 'path', 'query', 'fragment']; $toUnset = array_intersect(array_diff($toUnset, $parts), array_keys($value)); foreach ($toUnset as $i) { unset($value[$i]); } $scheme = isset($value['scheme']) ? $value['scheme'] . '://' : ''; $host = isset($value['host']) ? $value['host'] : ''; $port = isset($value['port']) ? ':' . $value['port'] : ''; $user = isset($value['user']) ? $value['user'] : ''; $pass = isset($value['pass']) ? ':' . $value['pass'] : ''; $pass = ($user || $pass) ? "$pass@" : ''; $path = isset($value['path']) ? $value['path'] : ''; $query = isset($value['query']) ? '?' . $value['query'] : ''; $fragment = isset($value['fragment']) ? '#' . $value['fragment'] : ''; return $scheme . $user . $pass . $host . $port . $path . $query . $fragment; }
php
public function transform(string $value, string ...$parts): string { $value = parse_url($value); $toUnset = ['scheme', 'host', 'port', 'user', 'pass', 'path', 'query', 'fragment']; $toUnset = array_intersect(array_diff($toUnset, $parts), array_keys($value)); foreach ($toUnset as $i) { unset($value[$i]); } $scheme = isset($value['scheme']) ? $value['scheme'] . '://' : ''; $host = isset($value['host']) ? $value['host'] : ''; $port = isset($value['port']) ? ':' . $value['port'] : ''; $user = isset($value['user']) ? $value['user'] : ''; $pass = isset($value['pass']) ? ':' . $value['pass'] : ''; $pass = ($user || $pass) ? "$pass@" : ''; $path = isset($value['path']) ? $value['path'] : ''; $query = isset($value['query']) ? '?' . $value['query'] : ''; $fragment = isset($value['fragment']) ? '#' . $value['fragment'] : ''; return $scheme . $user . $pass . $host . $port . $path . $query . $fragment; }
[ "public", "function", "transform", "(", "string", "$", "value", ",", "string", "...", "$", "parts", ")", ":", "string", "{", "$", "value", "=", "parse_url", "(", "$", "value", ")", ";", "$", "toUnset", "=", "[", "'scheme'", ",", "'host'", ",", "'port'", ",", "'user'", ",", "'pass'", ",", "'path'", ",", "'query'", ",", "'fragment'", "]", ";", "$", "toUnset", "=", "array_intersect", "(", "array_diff", "(", "$", "toUnset", ",", "$", "parts", ")", ",", "array_keys", "(", "$", "value", ")", ")", ";", "foreach", "(", "$", "toUnset", "as", "$", "i", ")", "{", "unset", "(", "$", "value", "[", "$", "i", "]", ")", ";", "}", "$", "scheme", "=", "isset", "(", "$", "value", "[", "'scheme'", "]", ")", "?", "$", "value", "[", "'scheme'", "]", ".", "'://'", ":", "''", ";", "$", "host", "=", "isset", "(", "$", "value", "[", "'host'", "]", ")", "?", "$", "value", "[", "'host'", "]", ":", "''", ";", "$", "port", "=", "isset", "(", "$", "value", "[", "'port'", "]", ")", "?", "':'", ".", "$", "value", "[", "'port'", "]", ":", "''", ";", "$", "user", "=", "isset", "(", "$", "value", "[", "'user'", "]", ")", "?", "$", "value", "[", "'user'", "]", ":", "''", ";", "$", "pass", "=", "isset", "(", "$", "value", "[", "'pass'", "]", ")", "?", "':'", ".", "$", "value", "[", "'pass'", "]", ":", "''", ";", "$", "pass", "=", "(", "$", "user", "||", "$", "pass", ")", "?", "\"$pass@\"", ":", "''", ";", "$", "path", "=", "isset", "(", "$", "value", "[", "'path'", "]", ")", "?", "$", "value", "[", "'path'", "]", ":", "''", ";", "$", "query", "=", "isset", "(", "$", "value", "[", "'query'", "]", ")", "?", "'?'", ".", "$", "value", "[", "'query'", "]", ":", "''", ";", "$", "fragment", "=", "isset", "(", "$", "value", "[", "'fragment'", "]", ")", "?", "'#'", ".", "$", "value", "[", "'fragment'", "]", ":", "''", ";", "return", "$", "scheme", ".", "$", "user", ".", "$", "pass", ".", "$", "host", ".", "$", "port", ".", "$", "path", ".", "$", "query", ".", "$", "fragment", ";", "}" ]
Extracts given URL parts. @param string $value URL to be transformed @param ... $parts parts to be extracted. One of: scheme (e.g. "https", "ftp", etc.), host, port, user, pass, path, query, fragment (part of the URL following #) @return string
[ "Extracts", "given", "URL", "parts", "." ]
e22c7cd2613f3c8daf0deee879896d9cd7f61b41
https://github.com/acdh-oeaw/repo-php-util/blob/e22c7cd2613f3c8daf0deee879896d9cd7f61b41/src/acdhOeaw/fedora/dissemination/parameter/UriPart.php#L55-L75
29,584
Blobfolio/blob-common
lib/blobfolio/common/file.php
file.data_uri
public static function data_uri(string $path) { ref\cast::string($path, true); ref\file::path($path, true); if ((false !== $path) && @\is_file($path)) { $content = \base64_encode(@\file_get_contents($path)); $finfo = mime::finfo($path); return "data:{$finfo['mime']};base64,{$content}"; } return false; }
php
public static function data_uri(string $path) { ref\cast::string($path, true); ref\file::path($path, true); if ((false !== $path) && @\is_file($path)) { $content = \base64_encode(@\file_get_contents($path)); $finfo = mime::finfo($path); return "data:{$finfo['mime']};base64,{$content}"; } return false; }
[ "public", "static", "function", "data_uri", "(", "string", "$", "path", ")", "{", "ref", "\\", "cast", "::", "string", "(", "$", "path", ",", "true", ")", ";", "ref", "\\", "file", "::", "path", "(", "$", "path", ",", "true", ")", ";", "if", "(", "(", "false", "!==", "$", "path", ")", "&&", "@", "\\", "is_file", "(", "$", "path", ")", ")", "{", "$", "content", "=", "\\", "base64_encode", "(", "@", "\\", "file_get_contents", "(", "$", "path", ")", ")", ";", "$", "finfo", "=", "mime", "::", "finfo", "(", "$", "path", ")", ";", "return", "\"data:{$finfo['mime']};base64,{$content}\"", ";", "}", "return", "false", ";", "}" ]
Get Data-URI From File @param string $path Path. @return string|bool Data-URI or false.
[ "Get", "Data", "-", "URI", "From", "File" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/file.php#L170-L182
29,585
Blobfolio/blob-common
lib/blobfolio/common/file.php
file.empty_dir
public static function empty_dir(string $path) { if (! @\is_readable($path) || ! @\is_dir($path)) { return false; } // Scan all files in dir. if ($handle = @\opendir($path)) { while (false !== ($file = @\readdir($handle))) { // Anything but a dot === not empty. if (('.' !== $file) && ('..' !== $file)) { return false; } } \closedir($handle); return true; } return false; }
php
public static function empty_dir(string $path) { if (! @\is_readable($path) || ! @\is_dir($path)) { return false; } // Scan all files in dir. if ($handle = @\opendir($path)) { while (false !== ($file = @\readdir($handle))) { // Anything but a dot === not empty. if (('.' !== $file) && ('..' !== $file)) { return false; } } \closedir($handle); return true; } return false; }
[ "public", "static", "function", "empty_dir", "(", "string", "$", "path", ")", "{", "if", "(", "!", "@", "\\", "is_readable", "(", "$", "path", ")", "||", "!", "@", "\\", "is_dir", "(", "$", "path", ")", ")", "{", "return", "false", ";", "}", "// Scan all files in dir.", "if", "(", "$", "handle", "=", "@", "\\", "opendir", "(", "$", "path", ")", ")", "{", "while", "(", "false", "!==", "(", "$", "file", "=", "@", "\\", "readdir", "(", "$", "handle", ")", ")", ")", "{", "// Anything but a dot === not empty.", "if", "(", "(", "'.'", "!==", "$", "file", ")", "&&", "(", "'..'", "!==", "$", "file", ")", ")", "{", "return", "false", ";", "}", "}", "\\", "closedir", "(", "$", "handle", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Is Directory Empty? @param string $path Path. @return bool True/false.
[ "Is", "Directory", "Empty?" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/file.php#L205-L223
29,586
Blobfolio/blob-common
lib/blobfolio/common/file.php
file.mkdir
public static function mkdir(string $path, $chmod=null) { // Figure out a good default CHMOD. if (! $chmod || ! \is_numeric($chmod)) { $chmod = (\fileperms(__DIR__) & 0777 | 0755); } // Sanitize the path. ref\file::path($path, false); if (! $path || (false !== \strpos($path, '://'))) { return false; } // We only need to proceed if the path doesn't exist. if (! @\is_dir($path)) { ref\file::untrailingslash($path); // Figure out where we need to begin. $base = \dirname($path); while ($base && ('.' !== $base) && ! @\is_dir($base)) { $base = \dirname($base); } // Make it. if (! @\mkdir($path, 0777, true)) { return false; } // Fix permissions. if ($path !== $base) { // If we fell deep enough that base became relative, // let's move it back. if (! $base || ('.' === $base)) { $base = __DIR__; } // Base should be inside path. If not, something weird // has happened. if (0 !== mb::strpos($path, $base)) { return true; } $path = mb::substr($path, mb::strlen($base), null); ref\file::unleadingslash($path); $parts = \explode('/', $path); $path = $base; // Loop through each subdirectory to set the appropriate // permissions. foreach ($parts as $v) { $path .= ('/' === \substr($path, -1)) ? $v : "/$v"; if (! @\chmod($path, $chmod)) { return true; } } } else { @\chmod($path, $chmod); } } return true; }
php
public static function mkdir(string $path, $chmod=null) { // Figure out a good default CHMOD. if (! $chmod || ! \is_numeric($chmod)) { $chmod = (\fileperms(__DIR__) & 0777 | 0755); } // Sanitize the path. ref\file::path($path, false); if (! $path || (false !== \strpos($path, '://'))) { return false; } // We only need to proceed if the path doesn't exist. if (! @\is_dir($path)) { ref\file::untrailingslash($path); // Figure out where we need to begin. $base = \dirname($path); while ($base && ('.' !== $base) && ! @\is_dir($base)) { $base = \dirname($base); } // Make it. if (! @\mkdir($path, 0777, true)) { return false; } // Fix permissions. if ($path !== $base) { // If we fell deep enough that base became relative, // let's move it back. if (! $base || ('.' === $base)) { $base = __DIR__; } // Base should be inside path. If not, something weird // has happened. if (0 !== mb::strpos($path, $base)) { return true; } $path = mb::substr($path, mb::strlen($base), null); ref\file::unleadingslash($path); $parts = \explode('/', $path); $path = $base; // Loop through each subdirectory to set the appropriate // permissions. foreach ($parts as $v) { $path .= ('/' === \substr($path, -1)) ? $v : "/$v"; if (! @\chmod($path, $chmod)) { return true; } } } else { @\chmod($path, $chmod); } } return true; }
[ "public", "static", "function", "mkdir", "(", "string", "$", "path", ",", "$", "chmod", "=", "null", ")", "{", "// Figure out a good default CHMOD.", "if", "(", "!", "$", "chmod", "||", "!", "\\", "is_numeric", "(", "$", "chmod", ")", ")", "{", "$", "chmod", "=", "(", "\\", "fileperms", "(", "__DIR__", ")", "&", "0777", "|", "0755", ")", ";", "}", "// Sanitize the path.", "ref", "\\", "file", "::", "path", "(", "$", "path", ",", "false", ")", ";", "if", "(", "!", "$", "path", "||", "(", "false", "!==", "\\", "strpos", "(", "$", "path", ",", "'://'", ")", ")", ")", "{", "return", "false", ";", "}", "// We only need to proceed if the path doesn't exist.", "if", "(", "!", "@", "\\", "is_dir", "(", "$", "path", ")", ")", "{", "ref", "\\", "file", "::", "untrailingslash", "(", "$", "path", ")", ";", "// Figure out where we need to begin.", "$", "base", "=", "\\", "dirname", "(", "$", "path", ")", ";", "while", "(", "$", "base", "&&", "(", "'.'", "!==", "$", "base", ")", "&&", "!", "@", "\\", "is_dir", "(", "$", "base", ")", ")", "{", "$", "base", "=", "\\", "dirname", "(", "$", "base", ")", ";", "}", "// Make it.", "if", "(", "!", "@", "\\", "mkdir", "(", "$", "path", ",", "0777", ",", "true", ")", ")", "{", "return", "false", ";", "}", "// Fix permissions.", "if", "(", "$", "path", "!==", "$", "base", ")", "{", "// If we fell deep enough that base became relative,", "// let's move it back.", "if", "(", "!", "$", "base", "||", "(", "'.'", "===", "$", "base", ")", ")", "{", "$", "base", "=", "__DIR__", ";", "}", "// Base should be inside path. If not, something weird", "// has happened.", "if", "(", "0", "!==", "mb", "::", "strpos", "(", "$", "path", ",", "$", "base", ")", ")", "{", "return", "true", ";", "}", "$", "path", "=", "mb", "::", "substr", "(", "$", "path", ",", "mb", "::", "strlen", "(", "$", "base", ")", ",", "null", ")", ";", "ref", "\\", "file", "::", "unleadingslash", "(", "$", "path", ")", ";", "$", "parts", "=", "\\", "explode", "(", "'/'", ",", "$", "path", ")", ";", "$", "path", "=", "$", "base", ";", "// Loop through each subdirectory to set the appropriate", "// permissions.", "foreach", "(", "$", "parts", "as", "$", "v", ")", "{", "$", "path", ".=", "(", "'/'", "===", "\\", "substr", "(", "$", "path", ",", "-", "1", ")", ")", "?", "$", "v", ":", "\"/$v\"", ";", "if", "(", "!", "@", "\\", "chmod", "(", "$", "path", ",", "$", "chmod", ")", ")", "{", "return", "true", ";", "}", "}", "}", "else", "{", "@", "\\", "chmod", "(", "$", "path", ",", "$", "chmod", ")", ";", "}", "}", "return", "true", ";", "}" ]
Resursively Make Directory PHP's mkdir function can be recursive, but the permissions are only set correctly on the innermost folder created. @param string $path Path. @param int $chmod CHMOD. @return bool True/false.
[ "Resursively", "Make", "Directory" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/file.php#L352-L413
29,587
Blobfolio/blob-common
lib/blobfolio/common/file.php
file.readfile_chunked
public static function readfile_chunked(string $file, bool $retbytes=true) { if (! $file || ! @\is_file($file)) { return false; } $buffer = ''; $cnt = 0; $chunk_size = 1024 * 1024; if (false === ($handle = @\fopen($file, 'rb'))) { return false; } while (! @\feof($handle)) { $buffer = @\fread($handle, $chunk_size); echo $buffer; \ob_flush(); \flush(); if ($retbytes) { $cnt += \strlen($buffer); } } $status = @\fclose($handle); // Return number of bytes delivered like readfile() does. if ($retbytes && $status) { return $cnt; } return $status; }
php
public static function readfile_chunked(string $file, bool $retbytes=true) { if (! $file || ! @\is_file($file)) { return false; } $buffer = ''; $cnt = 0; $chunk_size = 1024 * 1024; if (false === ($handle = @\fopen($file, 'rb'))) { return false; } while (! @\feof($handle)) { $buffer = @\fread($handle, $chunk_size); echo $buffer; \ob_flush(); \flush(); if ($retbytes) { $cnt += \strlen($buffer); } } $status = @\fclose($handle); // Return number of bytes delivered like readfile() does. if ($retbytes && $status) { return $cnt; } return $status; }
[ "public", "static", "function", "readfile_chunked", "(", "string", "$", "file", ",", "bool", "$", "retbytes", "=", "true", ")", "{", "if", "(", "!", "$", "file", "||", "!", "@", "\\", "is_file", "(", "$", "file", ")", ")", "{", "return", "false", ";", "}", "$", "buffer", "=", "''", ";", "$", "cnt", "=", "0", ";", "$", "chunk_size", "=", "1024", "*", "1024", ";", "if", "(", "false", "===", "(", "$", "handle", "=", "@", "\\", "fopen", "(", "$", "file", ",", "'rb'", ")", ")", ")", "{", "return", "false", ";", "}", "while", "(", "!", "@", "\\", "feof", "(", "$", "handle", ")", ")", "{", "$", "buffer", "=", "@", "\\", "fread", "(", "$", "handle", ",", "$", "chunk_size", ")", ";", "echo", "$", "buffer", ";", "\\", "ob_flush", "(", ")", ";", "\\", "flush", "(", ")", ";", "if", "(", "$", "retbytes", ")", "{", "$", "cnt", "+=", "\\", "strlen", "(", "$", "buffer", ")", ";", "}", "}", "$", "status", "=", "@", "\\", "fclose", "(", "$", "handle", ")", ";", "// Return number of bytes delivered like readfile() does.", "if", "(", "$", "retbytes", "&&", "$", "status", ")", "{", "return", "$", "cnt", ";", "}", "return", "$", "status", ";", "}" ]
Read File in Chunks This greatly reduces overhead if serving files through a PHP gateway script. @param string $file Path. @param bool $retbytes Return bytes served like `readfile()`. @return mixed Bytes served or status.
[ "Read", "File", "in", "Chunks" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/file.php#L437-L468
29,588
Blobfolio/blob-common
lib/blobfolio/common/file.php
file.rmdir
public static function rmdir(string $path) { ref\file::path($path, true); if (! $path || ! @\is_readable($path) || ! @\is_dir($path)) { return false; } // Scan all files in dir. if ($handle = @\opendir($path)) { while (false !== ($entry = @\readdir($handle))) { // Anything but a dot === not empty. if (('.' === $entry) || ('..' === $entry)) { continue; } $file = "{$path}{$entry}"; // Delete files. if (@\is_file($file)) { @\unlink($file); } // Recursively delete directories. else { static::rmdir($file); } } \closedir($handle); } if (static::empty_dir($path)) { @\rmdir($path); } return ! @\file_exists($path); }
php
public static function rmdir(string $path) { ref\file::path($path, true); if (! $path || ! @\is_readable($path) || ! @\is_dir($path)) { return false; } // Scan all files in dir. if ($handle = @\opendir($path)) { while (false !== ($entry = @\readdir($handle))) { // Anything but a dot === not empty. if (('.' === $entry) || ('..' === $entry)) { continue; } $file = "{$path}{$entry}"; // Delete files. if (@\is_file($file)) { @\unlink($file); } // Recursively delete directories. else { static::rmdir($file); } } \closedir($handle); } if (static::empty_dir($path)) { @\rmdir($path); } return ! @\file_exists($path); }
[ "public", "static", "function", "rmdir", "(", "string", "$", "path", ")", "{", "ref", "\\", "file", "::", "path", "(", "$", "path", ",", "true", ")", ";", "if", "(", "!", "$", "path", "||", "!", "@", "\\", "is_readable", "(", "$", "path", ")", "||", "!", "@", "\\", "is_dir", "(", "$", "path", ")", ")", "{", "return", "false", ";", "}", "// Scan all files in dir.", "if", "(", "$", "handle", "=", "@", "\\", "opendir", "(", "$", "path", ")", ")", "{", "while", "(", "false", "!==", "(", "$", "entry", "=", "@", "\\", "readdir", "(", "$", "handle", ")", ")", ")", "{", "// Anything but a dot === not empty.", "if", "(", "(", "'.'", "===", "$", "entry", ")", "||", "(", "'..'", "===", "$", "entry", ")", ")", "{", "continue", ";", "}", "$", "file", "=", "\"{$path}{$entry}\"", ";", "// Delete files.", "if", "(", "@", "\\", "is_file", "(", "$", "file", ")", ")", "{", "@", "\\", "unlink", "(", "$", "file", ")", ";", "}", "// Recursively delete directories.", "else", "{", "static", "::", "rmdir", "(", "$", "file", ")", ";", "}", "}", "\\", "closedir", "(", "$", "handle", ")", ";", "}", "if", "(", "static", "::", "empty_dir", "(", "$", "path", ")", ")", "{", "@", "\\", "rmdir", "(", "$", "path", ")", ";", "}", "return", "!", "@", "\\", "file_exists", "(", "$", "path", ")", ";", "}" ]
Recursively Remove A Directory @param string $path Path. @return bool True/false.
[ "Recursively", "Remove", "A", "Directory" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/file.php#L501-L534
29,589
locomotivemtl/charcoal-ui
src/Charcoal/Ui/Form/FormTrait.php
FormTrait.setGroups
public function setGroups(array $groups) { $this->groups = []; foreach ($groups as $groupIdent => $group) { $this->addGroup($groupIdent, $group); } return $this; }
php
public function setGroups(array $groups) { $this->groups = []; foreach ($groups as $groupIdent => $group) { $this->addGroup($groupIdent, $group); } return $this; }
[ "public", "function", "setGroups", "(", "array", "$", "groups", ")", "{", "$", "this", "->", "groups", "=", "[", "]", ";", "foreach", "(", "$", "groups", "as", "$", "groupIdent", "=>", "$", "group", ")", "{", "$", "this", "->", "addGroup", "(", "$", "groupIdent", ",", "$", "group", ")", ";", "}", "return", "$", "this", ";", "}" ]
Set the object's form groups. @param array $groups A collection of group structures. @return FormInterface Chainable
[ "Set", "the", "object", "s", "form", "groups", "." ]
0070f35d89ea24ae93720734d261c02a10e218b6
https://github.com/locomotivemtl/charcoal-ui/blob/0070f35d89ea24ae93720734d261c02a10e218b6/src/Charcoal/Ui/Form/FormTrait.php#L227-L236
29,590
locomotivemtl/charcoal-ui
src/Charcoal/Ui/Form/FormTrait.php
FormTrait.addGroup
public function addGroup($groupIdent, $group) { if ($group === false || $group === null) { return $this; } $group = $this->parseFormGroup($groupIdent, $group); if (isset($group['ident'])) { $groupIdent = $group['ident']; } $this->groups[$groupIdent] = $group; return $this; }
php
public function addGroup($groupIdent, $group) { if ($group === false || $group === null) { return $this; } $group = $this->parseFormGroup($groupIdent, $group); if (isset($group['ident'])) { $groupIdent = $group['ident']; } $this->groups[$groupIdent] = $group; return $this; }
[ "public", "function", "addGroup", "(", "$", "groupIdent", ",", "$", "group", ")", "{", "if", "(", "$", "group", "===", "false", "||", "$", "group", "===", "null", ")", "{", "return", "$", "this", ";", "}", "$", "group", "=", "$", "this", "->", "parseFormGroup", "(", "$", "groupIdent", ",", "$", "group", ")", ";", "if", "(", "isset", "(", "$", "group", "[", "'ident'", "]", ")", ")", "{", "$", "groupIdent", "=", "$", "group", "[", "'ident'", "]", ";", "}", "$", "this", "->", "groups", "[", "$", "groupIdent", "]", "=", "$", "group", ";", "return", "$", "this", ";", "}" ]
Add a form group. @param string $groupIdent The group identifier. @param array|FormGroupInterface $group The group object or structure. @throws InvalidArgumentException If the identifier is not a string or the group is invalid. @return FormInterface Chainable
[ "Add", "a", "form", "group", "." ]
0070f35d89ea24ae93720734d261c02a10e218b6
https://github.com/locomotivemtl/charcoal-ui/blob/0070f35d89ea24ae93720734d261c02a10e218b6/src/Charcoal/Ui/Form/FormTrait.php#L284-L299
29,591
locomotivemtl/charcoal-ui
src/Charcoal/Ui/Form/FormTrait.php
FormTrait.groups
public function groups(callable $groupCallback = null) { $groups = $this->groups; uasort($groups, [ $this, 'sortItemsByPriority' ]); $groupCallback = (isset($groupCallback) ? $groupCallback : $this->groupCallback); $groups = $this->finalizeFormGroups($groups); $i = 1; foreach ($groups as $group) { if ($groupCallback) { $groupCallback($group); } $GLOBALS['widget_template'] = $group->template(); if (!$this->selectedFormGroup() && $this->isTabbable()) { $group->setIsHidden(false); if ($i > 1) { $group->setIsHidden(true); } } $i++; yield $group; $GLOBALS['widget_template'] = ''; } }
php
public function groups(callable $groupCallback = null) { $groups = $this->groups; uasort($groups, [ $this, 'sortItemsByPriority' ]); $groupCallback = (isset($groupCallback) ? $groupCallback : $this->groupCallback); $groups = $this->finalizeFormGroups($groups); $i = 1; foreach ($groups as $group) { if ($groupCallback) { $groupCallback($group); } $GLOBALS['widget_template'] = $group->template(); if (!$this->selectedFormGroup() && $this->isTabbable()) { $group->setIsHidden(false); if ($i > 1) { $group->setIsHidden(true); } } $i++; yield $group; $GLOBALS['widget_template'] = ''; } }
[ "public", "function", "groups", "(", "callable", "$", "groupCallback", "=", "null", ")", "{", "$", "groups", "=", "$", "this", "->", "groups", ";", "uasort", "(", "$", "groups", ",", "[", "$", "this", ",", "'sortItemsByPriority'", "]", ")", ";", "$", "groupCallback", "=", "(", "isset", "(", "$", "groupCallback", ")", "?", "$", "groupCallback", ":", "$", "this", "->", "groupCallback", ")", ";", "$", "groups", "=", "$", "this", "->", "finalizeFormGroups", "(", "$", "groups", ")", ";", "$", "i", "=", "1", ";", "foreach", "(", "$", "groups", "as", "$", "group", ")", "{", "if", "(", "$", "groupCallback", ")", "{", "$", "groupCallback", "(", "$", "group", ")", ";", "}", "$", "GLOBALS", "[", "'widget_template'", "]", "=", "$", "group", "->", "template", "(", ")", ";", "if", "(", "!", "$", "this", "->", "selectedFormGroup", "(", ")", "&&", "$", "this", "->", "isTabbable", "(", ")", ")", "{", "$", "group", "->", "setIsHidden", "(", "false", ")", ";", "if", "(", "$", "i", ">", "1", ")", "{", "$", "group", "->", "setIsHidden", "(", "true", ")", ";", "}", "}", "$", "i", "++", ";", "yield", "$", "group", ";", "$", "GLOBALS", "[", "'widget_template'", "]", "=", "''", ";", "}", "}" ]
Retrieve the form groups. @param callable $groupCallback Optional callback applied to each form group. @return FormGroupInterface[]|Generator
[ "Retrieve", "the", "form", "groups", "." ]
0070f35d89ea24ae93720734d261c02a10e218b6
https://github.com/locomotivemtl/charcoal-ui/blob/0070f35d89ea24ae93720734d261c02a10e218b6/src/Charcoal/Ui/Form/FormTrait.php#L404-L433
29,592
locomotivemtl/charcoal-ui
src/Charcoal/Ui/Form/FormTrait.php
FormTrait.setGroupDisplayMode
public function setGroupDisplayMode($mode) { if (!is_string($mode)) { throw new InvalidArgumentException( 'Display mode must be a string' ); } if ($mode === 'tabs') { $mode = 'tab'; } $this->groupDisplayMode = $mode; return $this; }
php
public function setGroupDisplayMode($mode) { if (!is_string($mode)) { throw new InvalidArgumentException( 'Display mode must be a string' ); } if ($mode === 'tabs') { $mode = 'tab'; } $this->groupDisplayMode = $mode; return $this; }
[ "public", "function", "setGroupDisplayMode", "(", "$", "mode", ")", "{", "if", "(", "!", "is_string", "(", "$", "mode", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Display mode must be a string'", ")", ";", "}", "if", "(", "$", "mode", "===", "'tabs'", ")", "{", "$", "mode", "=", "'tab'", ";", "}", "$", "this", "->", "groupDisplayMode", "=", "$", "mode", ";", "return", "$", "this", ";", "}" ]
Set the widget's content group display mode. Currently only supports "tab". @param string $mode Group display mode. @throws InvalidArgumentException If the display mode is not a string. @return ObjectFormWidget Chainable.
[ "Set", "the", "widget", "s", "content", "group", "display", "mode", "." ]
0070f35d89ea24ae93720734d261c02a10e218b6
https://github.com/locomotivemtl/charcoal-ui/blob/0070f35d89ea24ae93720734d261c02a10e218b6/src/Charcoal/Ui/Form/FormTrait.php#L558-L573
29,593
diff-sniffer/core
src/Runner.php
Runner.run
public function run(Changeset $changeset) { $diff = new Diff($changeset->getDiff()); if (!count($diff)) { return 0; } $reporter = new Reporter($diff, $this->config); $runner = new BaseRunner(); $runner->config = $this->config; $runner->reporter = $reporter; $runner->init(); $it = new Iterator($diff, $changeset, $runner->ruleset, $this->config); /** @var File $file */ foreach ($it as $file) { $runner->processFile($file); } $reporter->printReports(); return (int) ($reporter->totalErrors || $reporter->totalWarnings); }
php
public function run(Changeset $changeset) { $diff = new Diff($changeset->getDiff()); if (!count($diff)) { return 0; } $reporter = new Reporter($diff, $this->config); $runner = new BaseRunner(); $runner->config = $this->config; $runner->reporter = $reporter; $runner->init(); $it = new Iterator($diff, $changeset, $runner->ruleset, $this->config); /** @var File $file */ foreach ($it as $file) { $runner->processFile($file); } $reporter->printReports(); return (int) ($reporter->totalErrors || $reporter->totalWarnings); }
[ "public", "function", "run", "(", "Changeset", "$", "changeset", ")", "{", "$", "diff", "=", "new", "Diff", "(", "$", "changeset", "->", "getDiff", "(", ")", ")", ";", "if", "(", "!", "count", "(", "$", "diff", ")", ")", "{", "return", "0", ";", "}", "$", "reporter", "=", "new", "Reporter", "(", "$", "diff", ",", "$", "this", "->", "config", ")", ";", "$", "runner", "=", "new", "BaseRunner", "(", ")", ";", "$", "runner", "->", "config", "=", "$", "this", "->", "config", ";", "$", "runner", "->", "reporter", "=", "$", "reporter", ";", "$", "runner", "->", "init", "(", ")", ";", "$", "it", "=", "new", "Iterator", "(", "$", "diff", ",", "$", "changeset", ",", "$", "runner", "->", "ruleset", ",", "$", "this", "->", "config", ")", ";", "/** @var File $file */", "foreach", "(", "$", "it", "as", "$", "file", ")", "{", "$", "runner", "->", "processFile", "(", "$", "file", ")", ";", "}", "$", "reporter", "->", "printReports", "(", ")", ";", "return", "(", "int", ")", "(", "$", "reporter", "->", "totalErrors", "||", "$", "reporter", "->", "totalWarnings", ")", ";", "}" ]
Runs CodeSniffer against specified changeset @param Changeset $changeset Changeset instance @return int @throws DeepExitException @throws Exception
[ "Runs", "CodeSniffer", "against", "specified", "changeset" ]
583369a5f5c91496862f6bdf60b69565da4bc05d
https://github.com/diff-sniffer/core/blob/583369a5f5c91496862f6bdf60b69565da4bc05d/src/Runner.php#L34-L59
29,594
Blobfolio/blob-common
wp/lib/blobcommon.php
blobcommon.get_release_info
protected static function get_release_info(string $key, $template) { // PHP 5.6.0 compatibility has been dropped, so nobody can // update until they update PHP. if (\version_compare(\PHP_VERSION, '7.2.0') < 0) { return false; } // Already pulled it? if (isset(static::$_release[$key])) { return static::$_release[$key]; } // WordPress hides relevant functionality in this file. require_once \ABSPATH . 'wp-admin/includes/plugin.php'; $uri = \get_file_data( \BLOBCOMMON_INDEX, array('json'=>$key), 'plugin' ); $uri = $uri['json']; r_sanitize::url($uri); if (! $uri) { static::$_release[$key] = false; return static::$_release[$key]; } // Cache this to the transient table for a little bit. $transient_key = 'blob-common_remote_' . \md5($uri . $key); if (false !== (static::$_release[$key] = \get_transient($transient_key))) { return static::$_release[$key]; } // Read the file. $response = \wp_remote_get($uri); if (200 !== \wp_remote_retrieve_response_code($response)) { static::$_release[$key] = false; return static::$_release[$key]; } // Decode the JSON. static::$_release[$key] = data::json_decode_array( \wp_remote_retrieve_body($response), $template ); // Add the URI we discovered, just in case. static::$_release[$key]['json_uri'] = $uri; // Cache it for a while. \set_transient($transient_key, static::$_release[$key], \HOUR_IN_SECONDS); // And we're done. return static::$_release[$key]; }
php
protected static function get_release_info(string $key, $template) { // PHP 5.6.0 compatibility has been dropped, so nobody can // update until they update PHP. if (\version_compare(\PHP_VERSION, '7.2.0') < 0) { return false; } // Already pulled it? if (isset(static::$_release[$key])) { return static::$_release[$key]; } // WordPress hides relevant functionality in this file. require_once \ABSPATH . 'wp-admin/includes/plugin.php'; $uri = \get_file_data( \BLOBCOMMON_INDEX, array('json'=>$key), 'plugin' ); $uri = $uri['json']; r_sanitize::url($uri); if (! $uri) { static::$_release[$key] = false; return static::$_release[$key]; } // Cache this to the transient table for a little bit. $transient_key = 'blob-common_remote_' . \md5($uri . $key); if (false !== (static::$_release[$key] = \get_transient($transient_key))) { return static::$_release[$key]; } // Read the file. $response = \wp_remote_get($uri); if (200 !== \wp_remote_retrieve_response_code($response)) { static::$_release[$key] = false; return static::$_release[$key]; } // Decode the JSON. static::$_release[$key] = data::json_decode_array( \wp_remote_retrieve_body($response), $template ); // Add the URI we discovered, just in case. static::$_release[$key]['json_uri'] = $uri; // Cache it for a while. \set_transient($transient_key, static::$_release[$key], \HOUR_IN_SECONDS); // And we're done. return static::$_release[$key]; }
[ "protected", "static", "function", "get_release_info", "(", "string", "$", "key", ",", "$", "template", ")", "{", "// PHP 5.6.0 compatibility has been dropped, so nobody can", "// update until they update PHP.", "if", "(", "\\", "version_compare", "(", "\\", "PHP_VERSION", ",", "'7.2.0'", ")", "<", "0", ")", "{", "return", "false", ";", "}", "// Already pulled it?", "if", "(", "isset", "(", "static", "::", "$", "_release", "[", "$", "key", "]", ")", ")", "{", "return", "static", "::", "$", "_release", "[", "$", "key", "]", ";", "}", "// WordPress hides relevant functionality in this file.", "require_once", "\\", "ABSPATH", ".", "'wp-admin/includes/plugin.php'", ";", "$", "uri", "=", "\\", "get_file_data", "(", "\\", "BLOBCOMMON_INDEX", ",", "array", "(", "'json'", "=>", "$", "key", ")", ",", "'plugin'", ")", ";", "$", "uri", "=", "$", "uri", "[", "'json'", "]", ";", "r_sanitize", "::", "url", "(", "$", "uri", ")", ";", "if", "(", "!", "$", "uri", ")", "{", "static", "::", "$", "_release", "[", "$", "key", "]", "=", "false", ";", "return", "static", "::", "$", "_release", "[", "$", "key", "]", ";", "}", "// Cache this to the transient table for a little bit.", "$", "transient_key", "=", "'blob-common_remote_'", ".", "\\", "md5", "(", "$", "uri", ".", "$", "key", ")", ";", "if", "(", "false", "!==", "(", "static", "::", "$", "_release", "[", "$", "key", "]", "=", "\\", "get_transient", "(", "$", "transient_key", ")", ")", ")", "{", "return", "static", "::", "$", "_release", "[", "$", "key", "]", ";", "}", "// Read the file.", "$", "response", "=", "\\", "wp_remote_get", "(", "$", "uri", ")", ";", "if", "(", "200", "!==", "\\", "wp_remote_retrieve_response_code", "(", "$", "response", ")", ")", "{", "static", "::", "$", "_release", "[", "$", "key", "]", "=", "false", ";", "return", "static", "::", "$", "_release", "[", "$", "key", "]", ";", "}", "// Decode the JSON.", "static", "::", "$", "_release", "[", "$", "key", "]", "=", "data", "::", "json_decode_array", "(", "\\", "wp_remote_retrieve_body", "(", "$", "response", ")", ",", "$", "template", ")", ";", "// Add the URI we discovered, just in case.", "static", "::", "$", "_release", "[", "$", "key", "]", "[", "'json_uri'", "]", "=", "$", "uri", ";", "// Cache it for a while.", "\\", "set_transient", "(", "$", "transient_key", ",", "static", "::", "$", "_release", "[", "$", "key", "]", ",", "\\", "HOUR_IN_SECONDS", ")", ";", "// And we're done.", "return", "static", "::", "$", "_release", "[", "$", "key", "]", ";", "}" ]
Parse Release File Both the plugin and library have JSON files containing release information. These files tell WordPress whether or not an update is available, and where to find it. @param string $key Header key containing JSON URI. @param array $template Data template. @return array Info.
[ "Parse", "Release", "File" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/wp/lib/blobcommon.php#L188-L242
29,595
Blobfolio/blob-common
wp/lib/blobcommon.php
blobcommon.check_plugin
protected static function check_plugin($key=null) { if (\is_null(static::$_plugin)) { // Pull the remote info and store it for later. if (false === ($remote = static::get_release_info('Info URI', static::PLUGIN_TEMPLATE))) { static::$_plugin = false; return static::$_plugin; } // Use the main plugin headers as the basis. static::$_plugin = \get_plugin_data(\BLOBCOMMON_INDEX, false, false); // And add in what we pulled remotely. static::$_plugin['InfoURI'] = $remote['json_uri']; static::$_plugin['DownloadVersion'] = $remote['Version']; static::$_plugin['DownloadURI'] = $remote['DownloadURI']; } // Requesting just one key? if (! \is_null($key)) { return \array_key_exists($key, static::$_plugin) ? static::$_plugin[$key] : false; } // Send everything! return static::$_plugin; }
php
protected static function check_plugin($key=null) { if (\is_null(static::$_plugin)) { // Pull the remote info and store it for later. if (false === ($remote = static::get_release_info('Info URI', static::PLUGIN_TEMPLATE))) { static::$_plugin = false; return static::$_plugin; } // Use the main plugin headers as the basis. static::$_plugin = \get_plugin_data(\BLOBCOMMON_INDEX, false, false); // And add in what we pulled remotely. static::$_plugin['InfoURI'] = $remote['json_uri']; static::$_plugin['DownloadVersion'] = $remote['Version']; static::$_plugin['DownloadURI'] = $remote['DownloadURI']; } // Requesting just one key? if (! \is_null($key)) { return \array_key_exists($key, static::$_plugin) ? static::$_plugin[$key] : false; } // Send everything! return static::$_plugin; }
[ "protected", "static", "function", "check_plugin", "(", "$", "key", "=", "null", ")", "{", "if", "(", "\\", "is_null", "(", "static", "::", "$", "_plugin", ")", ")", "{", "// Pull the remote info and store it for later.", "if", "(", "false", "===", "(", "$", "remote", "=", "static", "::", "get_release_info", "(", "'Info URI'", ",", "static", "::", "PLUGIN_TEMPLATE", ")", ")", ")", "{", "static", "::", "$", "_plugin", "=", "false", ";", "return", "static", "::", "$", "_plugin", ";", "}", "// Use the main plugin headers as the basis.", "static", "::", "$", "_plugin", "=", "\\", "get_plugin_data", "(", "\\", "BLOBCOMMON_INDEX", ",", "false", ",", "false", ")", ";", "// And add in what we pulled remotely.", "static", "::", "$", "_plugin", "[", "'InfoURI'", "]", "=", "$", "remote", "[", "'json_uri'", "]", ";", "static", "::", "$", "_plugin", "[", "'DownloadVersion'", "]", "=", "$", "remote", "[", "'Version'", "]", ";", "static", "::", "$", "_plugin", "[", "'DownloadURI'", "]", "=", "$", "remote", "[", "'DownloadURI'", "]", ";", "}", "// Requesting just one key?", "if", "(", "!", "\\", "is_null", "(", "$", "key", ")", ")", "{", "return", "\\", "array_key_exists", "(", "$", "key", ",", "static", "::", "$", "_plugin", ")", "?", "static", "::", "$", "_plugin", "[", "$", "key", "]", ":", "false", ";", "}", "// Send everything!", "return", "static", "::", "$", "_plugin", ";", "}" ]
Check Plugin Info Unlike with the Phar library, this function only gathers the release information. Downloads are handled some other way. @param string $key Key. @return mixed Details, detail, false.
[ "Check", "Plugin", "Info" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/wp/lib/blobcommon.php#L339-L363
29,596
ventoviro/windwalker-core
src/Core/Composer/StarterInstaller.php
StarterInstaller.rootInstall
public static function rootInstall(Event $event) { include getcwd() . '/vendor/autoload.php'; $io = $event->getIO(); static::genSecretCode($io); static::genSecretConfig($io); // Complete $io->write('Install complete.'); }
php
public static function rootInstall(Event $event) { include getcwd() . '/vendor/autoload.php'; $io = $event->getIO(); static::genSecretCode($io); static::genSecretConfig($io); // Complete $io->write('Install complete.'); }
[ "public", "static", "function", "rootInstall", "(", "Event", "$", "event", ")", "{", "include", "getcwd", "(", ")", ".", "'/vendor/autoload.php'", ";", "$", "io", "=", "$", "event", "->", "getIO", "(", ")", ";", "static", "::", "genSecretCode", "(", "$", "io", ")", ";", "static", "::", "genSecretConfig", "(", "$", "io", ")", ";", "// Complete", "$", "io", "->", "write", "(", "'Install complete.'", ")", ";", "}" ]
Do install. @param Event $event The command event. @return void
[ "Do", "install", "." ]
0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074
https://github.com/ventoviro/windwalker-core/blob/0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074/src/Core/Composer/StarterInstaller.php#L31-L43
29,597
ventoviro/windwalker-core
src/Core/Composer/StarterInstaller.php
StarterInstaller.genSecretCode
protected static function genSecretCode(IOInterface $io) { $file = getcwd() . '/etc/conf/system.php'; $config = file_get_contents($file); $hash = 'Windwalker-' . hrtime(true); $salt = $io->ask("\nSalt to generate secret [{$hash}]: ", $hash); $config = str_replace('This-token-is-not-safe', md5(hrtime(true) . $salt), $config); file_put_contents($file, $config); $io->write('Auto created secret key.'); }
php
protected static function genSecretCode(IOInterface $io) { $file = getcwd() . '/etc/conf/system.php'; $config = file_get_contents($file); $hash = 'Windwalker-' . hrtime(true); $salt = $io->ask("\nSalt to generate secret [{$hash}]: ", $hash); $config = str_replace('This-token-is-not-safe', md5(hrtime(true) . $salt), $config); file_put_contents($file, $config); $io->write('Auto created secret key.'); }
[ "protected", "static", "function", "genSecretCode", "(", "IOInterface", "$", "io", ")", "{", "$", "file", "=", "getcwd", "(", ")", ".", "'/etc/conf/system.php'", ";", "$", "config", "=", "file_get_contents", "(", "$", "file", ")", ";", "$", "hash", "=", "'Windwalker-'", ".", "hrtime", "(", "true", ")", ";", "$", "salt", "=", "$", "io", "->", "ask", "(", "\"\\nSalt to generate secret [{$hash}]: \"", ",", "$", "hash", ")", ";", "$", "config", "=", "str_replace", "(", "'This-token-is-not-safe'", ",", "md5", "(", "hrtime", "(", "true", ")", ".", "$", "salt", ")", ",", "$", "config", ")", ";", "file_put_contents", "(", "$", "file", ",", "$", "config", ")", ";", "$", "io", "->", "write", "(", "'Auto created secret key.'", ")", ";", "}" ]
Generate secret code. @param IOInterface $io @return void
[ "Generate", "secret", "code", "." ]
0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074
https://github.com/ventoviro/windwalker-core/blob/0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074/src/Core/Composer/StarterInstaller.php#L52-L67
29,598
ventoviro/windwalker-core
src/Debugger/View/Database/DatabaseHtmlView.php
DatabaseHtmlView.highlightQuery
public function highlightQuery($query) { $newlineKeywords = '#\b(FROM|LEFT|INNER|OUTER|WHERE|SET|VALUES|ORDER|GROUP|HAVING|LIMIT|ON|AND|CASE)\b#i'; $query = htmlspecialchars($query, ENT_QUOTES); $query = preg_replace($newlineKeywords, '<br />&#160;&#160;\\0', $query); $regex = [ '/(=)/' => '<strong class="text-error">$1</strong>', // All uppercase words have a special meaning. '/(?<!\w|>)([A-Z_]{2,})(?!\w)/x' => '<span class="text-info">$1</span>', ]; $query = preg_replace(array_keys($regex), array_values($regex), $query); $query = str_replace('*', '<strong style="color: red;">*</strong>', $query); return $query; }
php
public function highlightQuery($query) { $newlineKeywords = '#\b(FROM|LEFT|INNER|OUTER|WHERE|SET|VALUES|ORDER|GROUP|HAVING|LIMIT|ON|AND|CASE)\b#i'; $query = htmlspecialchars($query, ENT_QUOTES); $query = preg_replace($newlineKeywords, '<br />&#160;&#160;\\0', $query); $regex = [ '/(=)/' => '<strong class="text-error">$1</strong>', // All uppercase words have a special meaning. '/(?<!\w|>)([A-Z_]{2,})(?!\w)/x' => '<span class="text-info">$1</span>', ]; $query = preg_replace(array_keys($regex), array_values($regex), $query); $query = str_replace('*', '<strong style="color: red;">*</strong>', $query); return $query; }
[ "public", "function", "highlightQuery", "(", "$", "query", ")", "{", "$", "newlineKeywords", "=", "'#\\b(FROM|LEFT|INNER|OUTER|WHERE|SET|VALUES|ORDER|GROUP|HAVING|LIMIT|ON|AND|CASE)\\b#i'", ";", "$", "query", "=", "htmlspecialchars", "(", "$", "query", ",", "ENT_QUOTES", ")", ";", "$", "query", "=", "preg_replace", "(", "$", "newlineKeywords", ",", "'<br />&#160;&#160;\\\\0'", ",", "$", "query", ")", ";", "$", "regex", "=", "[", "'/(=)/'", "=>", "'<strong class=\"text-error\">$1</strong>'", ",", "// All uppercase words have a special meaning.", "'/(?<!\\w|>)([A-Z_]{2,})(?!\\w)/x'", "=>", "'<span class=\"text-info\">$1</span>'", ",", "]", ";", "$", "query", "=", "preg_replace", "(", "array_keys", "(", "$", "regex", ")", ",", "array_values", "(", "$", "regex", ")", ",", "$", "query", ")", ";", "$", "query", "=", "str_replace", "(", "'*'", ",", "'<strong style=\"color: red;\">*</strong>'", ",", "$", "query", ")", ";", "return", "$", "query", ";", "}" ]
Simple highlight for SQL queries. @param string $query The query to highlight. @return string Highlighted query string.
[ "Simple", "highlight", "for", "SQL", "queries", "." ]
0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074
https://github.com/ventoviro/windwalker-core/blob/0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074/src/Debugger/View/Database/DatabaseHtmlView.php#L50-L72
29,599
secucard/secucard-connect-php-sdk
src/SecucardConnect/Product/Services/IdentResultsService.php
IdentResultsService.getListByRequestIds
public function getListByRequestIds($ids) { $parts = []; foreach ($ids as $id) { $parts[] = 'request.id:' . $id; } $qp = new QueryParams(); $qp->query = join(' OR ', $parts); return $this->getList($qp); }
php
public function getListByRequestIds($ids) { $parts = []; foreach ($ids as $id) { $parts[] = 'request.id:' . $id; } $qp = new QueryParams(); $qp->query = join(' OR ', $parts); return $this->getList($qp); }
[ "public", "function", "getListByRequestIds", "(", "$", "ids", ")", "{", "$", "parts", "=", "[", "]", ";", "foreach", "(", "$", "ids", "as", "$", "id", ")", "{", "$", "parts", "[", "]", "=", "'request.id:'", ".", "$", "id", ";", "}", "$", "qp", "=", "new", "QueryParams", "(", ")", ";", "$", "qp", "->", "query", "=", "join", "(", "' OR '", ",", "$", "parts", ")", ";", "return", "$", "this", "->", "getList", "(", "$", "qp", ")", ";", "}" ]
Returns an array of IdentResult instances for a given array of IdentRequest ids. @param array $ids The request ids. @return BaseCollection The obtained results. @throws ClientError @throws GuzzleException @throws ApiError @throws AuthError
[ "Returns", "an", "array", "of", "IdentResult", "instances", "for", "a", "given", "array", "of", "IdentRequest", "ids", "." ]
d990686095e4e02d0924fc12b9bf60140fe8efab
https://github.com/secucard/secucard-connect-php-sdk/blob/d990686095e4e02d0924fc12b9bf60140fe8efab/src/SecucardConnect/Product/Services/IdentResultsService.php#L30-L39