repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
mirko-pagliai/me-cms
src/Utility/Sitemap.php
Sitemap.staticPages
public static function staticPages() { if (!getConfig('sitemap.static_pages')) { return []; } return array_map(function (Entity $page) { return self::parse(['_name' => 'page', $page->slug], ['lastmod' => $page->modified]); }, StaticPage::all()); }
php
public static function staticPages() { if (!getConfig('sitemap.static_pages')) { return []; } return array_map(function (Entity $page) { return self::parse(['_name' => 'page', $page->slug], ['lastmod' => $page->modified]); }, StaticPage::all()); }
[ "public", "static", "function", "staticPages", "(", ")", "{", "if", "(", "!", "getConfig", "(", "'sitemap.static_pages'", ")", ")", "{", "return", "[", "]", ";", "}", "return", "array_map", "(", "function", "(", "Entity", "$", "page", ")", "{", "return",...
Returns static pages urls @return array @uses MeCms\Utility\SitemapBuilder::parse() @uses MeCms\Utility\StaticPage::all()
[ "Returns", "static", "pages", "urls" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Utility/Sitemap.php#L246-L255
train
s9e/RegexpBuilder
src/Passes/Recurse.php
Recurse.recurseString
protected function recurseString(array $string) { $isOptional = $this->isOptional; foreach ($string as $k => $element) { if (is_array($element)) { $string[$k] = $this->runner->run($element); } } $this->isOptional = $isOptional; return $string; }
php
protected function recurseString(array $string) { $isOptional = $this->isOptional; foreach ($string as $k => $element) { if (is_array($element)) { $string[$k] = $this->runner->run($element); } } $this->isOptional = $isOptional; return $string; }
[ "protected", "function", "recurseString", "(", "array", "$", "string", ")", "{", "$", "isOptional", "=", "$", "this", "->", "isOptional", ";", "foreach", "(", "$", "string", "as", "$", "k", "=>", "$", "element", ")", "{", "if", "(", "is_array", "(", ...
Recurse into given string and run all passes on each element @param array $string @return array
[ "Recurse", "into", "given", "string", "and", "run", "all", "passes", "on", "each", "element" ]
59d0167a909659d718f53964f7653d2c83a5f8fe
https://github.com/s9e/RegexpBuilder/blob/59d0167a909659d718f53964f7653d2c83a5f8fe/src/Passes/Recurse.php#L44-L57
train
locomotivemtl/charcoal-email
src/Charcoal/Email/Script/ProcessQueueScript.php
ProcessQueueScript.run
public function run(RequestInterface $request, ResponseInterface $response) { // Unused parameter unset($request); // Lock script, to ensure it can not be run twice at the same time (before previous instance is done). $this->startLock(); $climate = $this->climate(); $processedCallback = function($success, $failures, $skipped) use ($climate) { if (!empty($success)) { $climate->green()->out(sprintf('%s emails were successfully sent.', count($success))); } if (!empty($failures)) { $climate->red()->out(sprintf('%s emails were not successfully sent', count($failures))); } if (!empty($skipped)) { $climate->dim()->out(sprintf('%s emails were skipped.', count($skipped))); } }; $queueManager = new EmailQueueManager([ 'logger' => $this->logger, 'queue_item_factory' => $this->queueItemFactory ]); $queueManager->setProcessedCallback($processedCallback); $queueManager->processQueue(); $this->stopLock(); return $response; }
php
public function run(RequestInterface $request, ResponseInterface $response) { // Unused parameter unset($request); // Lock script, to ensure it can not be run twice at the same time (before previous instance is done). $this->startLock(); $climate = $this->climate(); $processedCallback = function($success, $failures, $skipped) use ($climate) { if (!empty($success)) { $climate->green()->out(sprintf('%s emails were successfully sent.', count($success))); } if (!empty($failures)) { $climate->red()->out(sprintf('%s emails were not successfully sent', count($failures))); } if (!empty($skipped)) { $climate->dim()->out(sprintf('%s emails were skipped.', count($skipped))); } }; $queueManager = new EmailQueueManager([ 'logger' => $this->logger, 'queue_item_factory' => $this->queueItemFactory ]); $queueManager->setProcessedCallback($processedCallback); $queueManager->processQueue(); $this->stopLock(); return $response; }
[ "public", "function", "run", "(", "RequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", ")", "{", "// Unused parameter", "unset", "(", "$", "request", ")", ";", "// Lock script, to ensure it can not be run twice at the same time (before previous inst...
Process all messages currently in queue. @param RequestInterface $request A PSR-7 compatible Request instance. @param ResponseInterface $response A PSR-7 compatible Response instance. @return ResponseInterface
[ "Process", "all", "messages", "currently", "in", "queue", "." ]
99ccabcd0a91802e308177e0b6b626eaf0f940da
https://github.com/locomotivemtl/charcoal-email/blob/99ccabcd0a91802e308177e0b6b626eaf0f940da/src/Charcoal/Email/Script/ProcessQueueScript.php#L50-L84
train
waynestate/waynestate-api-php
src/Connector.php
Connector.ensureSslEndpoint
protected function ensureSslEndpoint($url) { // If the endpoint isn't on SSL if (substr($url, 0, 5) != 'https') { // Force an SSL endpoint $endpoint = parse_url($url); $url = 'https://' . $endpoint['host'] . $endpoint['path']; } // SSL already enabled return $url; }
php
protected function ensureSslEndpoint($url) { // If the endpoint isn't on SSL if (substr($url, 0, 5) != 'https') { // Force an SSL endpoint $endpoint = parse_url($url); $url = 'https://' . $endpoint['host'] . $endpoint['path']; } // SSL already enabled return $url; }
[ "protected", "function", "ensureSslEndpoint", "(", "$", "url", ")", "{", "// If the endpoint isn't on SSL", "if", "(", "substr", "(", "$", "url", ",", "0", ",", "5", ")", "!=", "'https'", ")", "{", "// Force an SSL endpoint", "$", "endpoint", "=", "parse_url",...
Ensure the endpoint is SSL @param $url @return string
[ "Ensure", "the", "endpoint", "is", "SSL" ]
7f81f2286a352cbd6089751fa5ad7817cc95463f
https://github.com/waynestate/waynestate-api-php/blob/7f81f2286a352cbd6089751fa5ad7817cc95463f/src/Connector.php#L109-L120
train
waynestate/waynestate-api-php
src/Connector.php
Connector.Cache
protected function Cache($action, $filename, $data = '', $max_age = '') { if (!is_dir($this->cache_dir)) { return ''; } // Set the full path $cache_file = $this->cache_dir . $filename; $cache = ''; if ($action == 'get') { // Clear the file stats clearstatcache(); if (is_file($cache_file) && $max_age != '') { // Make sure $max_age is negitive if (is_string($max_age) && substr($max_age, 0, 1) != '-') { $max_age = '-' . $max_age; } // Make sure $max_age is an INT if (!is_int($max_age)) { $max_age = strtotime($max_age); } // Test to see if the file is still fresh enough if (filemtime($cache_file) >= date($max_age)) { $cache = file_get_contents($cache_file); } } } else { if (is_writable($this->cache_dir)) { // Serialize the Fields $store = serialize($data); //Open and Write the File $fp = fopen($cache_file, "w"); fwrite($fp, $store); fclose($fp); chmod($cache_file, 0770); $cache = strlen($store); } } return $cache; }
php
protected function Cache($action, $filename, $data = '', $max_age = '') { if (!is_dir($this->cache_dir)) { return ''; } // Set the full path $cache_file = $this->cache_dir . $filename; $cache = ''; if ($action == 'get') { // Clear the file stats clearstatcache(); if (is_file($cache_file) && $max_age != '') { // Make sure $max_age is negitive if (is_string($max_age) && substr($max_age, 0, 1) != '-') { $max_age = '-' . $max_age; } // Make sure $max_age is an INT if (!is_int($max_age)) { $max_age = strtotime($max_age); } // Test to see if the file is still fresh enough if (filemtime($cache_file) >= date($max_age)) { $cache = file_get_contents($cache_file); } } } else { if (is_writable($this->cache_dir)) { // Serialize the Fields $store = serialize($data); //Open and Write the File $fp = fopen($cache_file, "w"); fwrite($fp, $store); fclose($fp); chmod($cache_file, 0770); $cache = strlen($store); } } return $cache; }
[ "protected", "function", "Cache", "(", "$", "action", ",", "$", "filename", ",", "$", "data", "=", "''", ",", "$", "max_age", "=", "''", ")", "{", "if", "(", "!", "is_dir", "(", "$", "this", "->", "cache_dir", ")", ")", "{", "return", "''", ";", ...
Get or Set Cache @param string $action (ex. "get" or "set") @param string $filename @param mixed $data @param string $max_age @return string
[ "Get", "or", "Set", "Cache" ]
7f81f2286a352cbd6089751fa5ad7817cc95463f
https://github.com/waynestate/waynestate-api-php/blob/7f81f2286a352cbd6089751fa5ad7817cc95463f/src/Connector.php#L286-L333
train
waynestate/waynestate-api-php
src/Connector.php
Connector.getEndpoint
protected function getEndpoint() { // If force production is in effect if ($this->force_production) { $this->force_production = false; return $this->endpoints['production']; } // Return the active endpoint return $this->endpoints[$this->active_endpoint]; }
php
protected function getEndpoint() { // If force production is in effect if ($this->force_production) { $this->force_production = false; return $this->endpoints['production']; } // Return the active endpoint return $this->endpoints[$this->active_endpoint]; }
[ "protected", "function", "getEndpoint", "(", ")", "{", "// If force production is in effect", "if", "(", "$", "this", "->", "force_production", ")", "{", "$", "this", "->", "force_production", "=", "false", ";", "return", "$", "this", "->", "endpoints", "[", "...
Get the current active endpoint @return mixed
[ "Get", "the", "current", "active", "endpoint" ]
7f81f2286a352cbd6089751fa5ad7817cc95463f
https://github.com/waynestate/waynestate-api-php/blob/7f81f2286a352cbd6089751fa5ad7817cc95463f/src/Connector.php#L349-L359
train
waynestate/waynestate-api-php
src/Connector.php
Connector.addEndpoint
protected function addEndpoint($name, $url) { // Add or modify the endpoint URL $this->endpoints[$name] = $this->ensureSslEndpoint($url); $this->active_endpoint = $name; // Return boolean if endpoint has been added successfully return array_key_exists($name, $this->endpoints); }
php
protected function addEndpoint($name, $url) { // Add or modify the endpoint URL $this->endpoints[$name] = $this->ensureSslEndpoint($url); $this->active_endpoint = $name; // Return boolean if endpoint has been added successfully return array_key_exists($name, $this->endpoints); }
[ "protected", "function", "addEndpoint", "(", "$", "name", ",", "$", "url", ")", "{", "// Add or modify the endpoint URL", "$", "this", "->", "endpoints", "[", "$", "name", "]", "=", "$", "this", "->", "ensureSslEndpoint", "(", "$", "url", ")", ";", "$", ...
Add a user defined endpoint @param $name @param $url @return bool
[ "Add", "a", "user", "defined", "endpoint" ]
7f81f2286a352cbd6089751fa5ad7817cc95463f
https://github.com/waynestate/waynestate-api-php/blob/7f81f2286a352cbd6089751fa5ad7817cc95463f/src/Connector.php#L368-L376
train
unikent/lib-php-readinglists
src/Item.php
Item.get_resource_url
public function get_resource_url() { $info = $this->data[$this->url]; if (!isset($info['http://purl.org/vocab/resourcelist/schema#resource'])) { return null; } return $info['http://purl.org/vocab/resourcelist/schema#resource'][0]['value']; }
php
public function get_resource_url() { $info = $this->data[$this->url]; if (!isset($info['http://purl.org/vocab/resourcelist/schema#resource'])) { return null; } return $info['http://purl.org/vocab/resourcelist/schema#resource'][0]['value']; }
[ "public", "function", "get_resource_url", "(", ")", "{", "$", "info", "=", "$", "this", "->", "data", "[", "$", "this", "->", "url", "]", ";", "if", "(", "!", "isset", "(", "$", "info", "[", "'http://purl.org/vocab/resourcelist/schema#resource'", "]", ")",...
Returns the resource list URL.
[ "Returns", "the", "resource", "list", "URL", "." ]
e14bfaee0ec52319c3f95a0599d01222948b6d76
https://github.com/unikent/lib-php-readinglists/blob/e14bfaee0ec52319c3f95a0599d01222948b6d76/src/Item.php#L54-L61
train
unikent/lib-php-readinglists
src/Item.php
Item.get_values
private function get_values($scheme) { $resourceurl = $this->get_resource_url(); if (!$resourceurl) { return array(); } $info = $this->data[$resourceurl]; if (!isset($info[$scheme])) { return array(); } $values = array(); foreach ($info[$scheme] as $k => $v) { $values[$k] = $v['value']; } return $values; }
php
private function get_values($scheme) { $resourceurl = $this->get_resource_url(); if (!$resourceurl) { return array(); } $info = $this->data[$resourceurl]; if (!isset($info[$scheme])) { return array(); } $values = array(); foreach ($info[$scheme] as $k => $v) { $values[$k] = $v['value']; } return $values; }
[ "private", "function", "get_values", "(", "$", "scheme", ")", "{", "$", "resourceurl", "=", "$", "this", "->", "get_resource_url", "(", ")", ";", "if", "(", "!", "$", "resourceurl", ")", "{", "return", "array", "(", ")", ";", "}", "$", "info", "=", ...
Returns a value from the resource metadata. @internal
[ "Returns", "a", "value", "from", "the", "resource", "metadata", "." ]
e14bfaee0ec52319c3f95a0599d01222948b6d76
https://github.com/unikent/lib-php-readinglists/blob/e14bfaee0ec52319c3f95a0599d01222948b6d76/src/Item.php#L67-L84
train
unikent/lib-php-readinglists
src/Item.php
Item.get_authors
public function get_authors() { $authors = array(); $url = $this->get_value('http://purl.org/ontology/bibo/authorList'); $info = $this->data[$url]; foreach ($info as $k => $v) { if (strpos($k, '#type') !== false) { continue; } $authors[] = $this->get_author($v[0]['value']); } return $authors; }
php
public function get_authors() { $authors = array(); $url = $this->get_value('http://purl.org/ontology/bibo/authorList'); $info = $this->data[$url]; foreach ($info as $k => $v) { if (strpos($k, '#type') !== false) { continue; } $authors[] = $this->get_author($v[0]['value']); } return $authors; }
[ "public", "function", "get_authors", "(", ")", "{", "$", "authors", "=", "array", "(", ")", ";", "$", "url", "=", "$", "this", "->", "get_value", "(", "'http://purl.org/ontology/bibo/authorList'", ")", ";", "$", "info", "=", "$", "this", "->", "data", "[...
Returns the authors of the item.
[ "Returns", "the", "authors", "of", "the", "item", "." ]
e14bfaee0ec52319c3f95a0599d01222948b6d76
https://github.com/unikent/lib-php-readinglists/blob/e14bfaee0ec52319c3f95a0599d01222948b6d76/src/Item.php#L150-L164
train
unikent/lib-php-readinglists
src/Item.php
Item.get_publisher
public function get_publisher() { $url = $this->get_value('http://purl.org/dc/terms/publisher'); if (!$url) { return; } $info = $this->data[$url]; return $info['http://xmlns.com/foaf/0.1/name'][0]['value']; }
php
public function get_publisher() { $url = $this->get_value('http://purl.org/dc/terms/publisher'); if (!$url) { return; } $info = $this->data[$url]; return $info['http://xmlns.com/foaf/0.1/name'][0]['value']; }
[ "public", "function", "get_publisher", "(", ")", "{", "$", "url", "=", "$", "this", "->", "get_value", "(", "'http://purl.org/dc/terms/publisher'", ")", ";", "if", "(", "!", "$", "url", ")", "{", "return", ";", "}", "$", "info", "=", "$", "this", "->",...
Returns the name of a publisher.
[ "Returns", "the", "name", "of", "a", "publisher", "." ]
e14bfaee0ec52319c3f95a0599d01222948b6d76
https://github.com/unikent/lib-php-readinglists/blob/e14bfaee0ec52319c3f95a0599d01222948b6d76/src/Item.php#L169-L177
train
froq/froq-view
src/View.php
View.setFileHead
public function setFileHead(): void { // check local service file $this->fileHead = $this->prepareFilePath('head', false); if (!file_exists($this->fileHead)) { // look up for default file $this->fileHead = $this->prepareDefaultFilePath('head'); } }
php
public function setFileHead(): void { // check local service file $this->fileHead = $this->prepareFilePath('head', false); if (!file_exists($this->fileHead)) { // look up for default file $this->fileHead = $this->prepareDefaultFilePath('head'); } }
[ "public", "function", "setFileHead", "(", ")", ":", "void", "{", "// check local service file", "$", "this", "->", "fileHead", "=", "$", "this", "->", "prepareFilePath", "(", "'head'", ",", "false", ")", ";", "if", "(", "!", "file_exists", "(", "$", "this"...
Set file head. @return void
[ "Set", "file", "head", "." ]
aeb774c02339287946a221ee871bd1e1db87c69a
https://github.com/froq/froq-view/blob/aeb774c02339287946a221ee871bd1e1db87c69a/src/View.php#L160-L168
train
froq/froq-view
src/View.php
View.setFileFoot
public function setFileFoot(): void { // check local service file $this->fileFoot = $this->prepareFilePath('foot', false); if (!file_exists($this->fileFoot)) { // look up for default file $this->fileFoot = $this->prepareDefaultFilePath('foot'); } }
php
public function setFileFoot(): void { // check local service file $this->fileFoot = $this->prepareFilePath('foot', false); if (!file_exists($this->fileFoot)) { // look up for default file $this->fileFoot = $this->prepareDefaultFilePath('foot'); } }
[ "public", "function", "setFileFoot", "(", ")", ":", "void", "{", "// check local service file", "$", "this", "->", "fileFoot", "=", "$", "this", "->", "prepareFilePath", "(", "'foot'", ",", "false", ")", ";", "if", "(", "!", "file_exists", "(", "$", "this"...
Set file foot. @return void
[ "Set", "file", "foot", "." ]
aeb774c02339287946a221ee871bd1e1db87c69a
https://github.com/froq/froq-view/blob/aeb774c02339287946a221ee871bd1e1db87c69a/src/View.php#L174-L182
train
froq/froq-view
src/View.php
View.prepareFilePath
private function prepareFilePath(string $file, bool $fileCheck = true): string { $file = str_replace(["\0", "\r", "\n"], '', trim($file)); if ($file == '') { throw new ViewException('No valid file given'); } // custom if ($file[0] == '.') { $fileCheck = false; if (!file_exists($file)) { throw new ViewException("Custom view file '{$file}' not found"); } } elseif ($file[0] == '@') { // custom in default view folder $file = sprintf('%s/app/service/_default/view/%s.php', APP_DIR, substr($file, 1)); $fileCheck = false; if (!file_exists($file)) { throw new ViewException("Default view file '{$file}' not found"); } } else { $file = sprintf('%s/app/service/%s/view/%s.php', APP_DIR, $this->service->getName(), $file); } if ($fileCheck && !file_exists($file)) { // look up default folder if ($this->service->isDefaultService()) { $file = sprintf('%s/app/service/_default/%s/view/%s', APP_DIR, $this->service->getName(), basename($file)); } if (!file_exists($file)) { throw new ViewException("View file '{$file}' not found"); } } return $file; }
php
private function prepareFilePath(string $file, bool $fileCheck = true): string { $file = str_replace(["\0", "\r", "\n"], '', trim($file)); if ($file == '') { throw new ViewException('No valid file given'); } // custom if ($file[0] == '.') { $fileCheck = false; if (!file_exists($file)) { throw new ViewException("Custom view file '{$file}' not found"); } } elseif ($file[0] == '@') { // custom in default view folder $file = sprintf('%s/app/service/_default/view/%s.php', APP_DIR, substr($file, 1)); $fileCheck = false; if (!file_exists($file)) { throw new ViewException("Default view file '{$file}' not found"); } } else { $file = sprintf('%s/app/service/%s/view/%s.php', APP_DIR, $this->service->getName(), $file); } if ($fileCheck && !file_exists($file)) { // look up default folder if ($this->service->isDefaultService()) { $file = sprintf('%s/app/service/_default/%s/view/%s', APP_DIR, $this->service->getName(), basename($file)); } if (!file_exists($file)) { throw new ViewException("View file '{$file}' not found"); } } return $file; }
[ "private", "function", "prepareFilePath", "(", "string", "$", "file", ",", "bool", "$", "fileCheck", "=", "true", ")", ":", "string", "{", "$", "file", "=", "str_replace", "(", "[", "\"\\0\"", ",", "\"\\r\"", ",", "\"\\n\"", "]", ",", "''", ",", "trim"...
Prepare file path. @param string $file @param bool $fileCheck @return string @throws froq\view\ViewException
[ "Prepare", "file", "path", "." ]
aeb774c02339287946a221ee871bd1e1db87c69a
https://github.com/froq/froq-view/blob/aeb774c02339287946a221ee871bd1e1db87c69a/src/View.php#L271-L308
train
froq/froq-view
src/View.php
View.prepareDefaultFilePath
private function prepareDefaultFilePath(string $file, bool $fileCheck = true): string { $file = sprintf('%s/app/service/_default/view/%s.php', APP_DIR, $file); if ($fileCheck && !file_exists($file)) { throw new ViewException("View file '{$file}' not found"); } return $file; }
php
private function prepareDefaultFilePath(string $file, bool $fileCheck = true): string { $file = sprintf('%s/app/service/_default/view/%s.php', APP_DIR, $file); if ($fileCheck && !file_exists($file)) { throw new ViewException("View file '{$file}' not found"); } return $file; }
[ "private", "function", "prepareDefaultFilePath", "(", "string", "$", "file", ",", "bool", "$", "fileCheck", "=", "true", ")", ":", "string", "{", "$", "file", "=", "sprintf", "(", "'%s/app/service/_default/view/%s.php'", ",", "APP_DIR", ",", "$", "file", ")", ...
Prepare default file path. @param string $file @param bool $fileCheck @return string @throws froq\view\ViewException
[ "Prepare", "default", "file", "path", "." ]
aeb774c02339287946a221ee871bd1e1db87c69a
https://github.com/froq/froq-view/blob/aeb774c02339287946a221ee871bd1e1db87c69a/src/View.php#L317-L325
train
krixon/datetime
src/DateTimeCalculator.php
DateTimeCalculator.clear
public function clear() { $this->date = $this->base->toInternalDateTime(); $this->calendar = $this->createCalendar($this->locale); if (null === $this->locale) { $this->calendar->setFirstDayOfWeek(\IntlCalendar::DOW_MONDAY); } }
php
public function clear() { $this->date = $this->base->toInternalDateTime(); $this->calendar = $this->createCalendar($this->locale); if (null === $this->locale) { $this->calendar->setFirstDayOfWeek(\IntlCalendar::DOW_MONDAY); } }
[ "public", "function", "clear", "(", ")", "{", "$", "this", "->", "date", "=", "$", "this", "->", "base", "->", "toInternalDateTime", "(", ")", ";", "$", "this", "->", "calendar", "=", "$", "this", "->", "createCalendar", "(", "$", "this", "->", "loca...
Clears the current calculation and returns to the base date.
[ "Clears", "the", "current", "calculation", "and", "returns", "to", "the", "base", "date", "." ]
9a39084119bbfae2cf6e22d794aa04dd79344ce0
https://github.com/krixon/datetime/blob/9a39084119bbfae2cf6e22d794aa04dd79344ce0/src/DateTimeCalculator.php#L108-L116
train
s9e/RegexpBuilder
src/Output/BaseImplementation.php
BaseImplementation.validate
protected function validate($value) { if ($value < $this->minValue || $value > $this->maxValue) { throw new InvalidArgumentException('Value ' . $value . ' is out of bounds (' . $this->minValue . '..' . $this->maxValue . ')'); } }
php
protected function validate($value) { if ($value < $this->minValue || $value > $this->maxValue) { throw new InvalidArgumentException('Value ' . $value . ' is out of bounds (' . $this->minValue . '..' . $this->maxValue . ')'); } }
[ "protected", "function", "validate", "(", "$", "value", ")", "{", "if", "(", "$", "value", "<", "$", "this", "->", "minValue", "||", "$", "value", ">", "$", "this", "->", "maxValue", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Value '", ...
Validate given value @param integer $value @return void
[ "Validate", "given", "value" ]
59d0167a909659d718f53964f7653d2c83a5f8fe
https://github.com/s9e/RegexpBuilder/blob/59d0167a909659d718f53964f7653d2c83a5f8fe/src/Output/BaseImplementation.php#L47-L53
train
mirko-pagliai/me-cms
src/View/View/AppView.php
AppView.setBlocks
protected function setBlocks() { //Sets the "theme color" (the toolbar color for some mobile browser) if (getConfig('default.toolbar_color')) { $this->Html->meta('theme-color', getConfig('default.toolbar_color')); } //Sets the meta tag for RSS posts if (getConfig('default.rss_meta')) { $this->Html->meta(__d('me_cms', 'Latest posts'), '/posts/rss', ['type' => 'rss']); } //Sets scripts for Google Analytics if (getConfig('default.analytics')) { echo $this->Library->analytics(getConfig('default.analytics')); } //Sets scripts for Shareaholic if (getConfig('shareaholic.site_id')) { echo $this->Library->shareaholic(getConfig('shareaholic.site_id')); } //Sets some Facebook's tags $this->Html->meta(['content' => $this->getTitleForLayout(), 'property' => 'og:title']); $this->Html->meta(['content' => Router::url(null, true), 'property' => 'og:url']); //Sets the app ID for Facebook if (getConfig('default.facebook_app_id')) { $this->Html->meta([ 'content' => getConfig('default.facebook_app_id'), 'property' => 'fb:app_id', ]); } }
php
protected function setBlocks() { //Sets the "theme color" (the toolbar color for some mobile browser) if (getConfig('default.toolbar_color')) { $this->Html->meta('theme-color', getConfig('default.toolbar_color')); } //Sets the meta tag for RSS posts if (getConfig('default.rss_meta')) { $this->Html->meta(__d('me_cms', 'Latest posts'), '/posts/rss', ['type' => 'rss']); } //Sets scripts for Google Analytics if (getConfig('default.analytics')) { echo $this->Library->analytics(getConfig('default.analytics')); } //Sets scripts for Shareaholic if (getConfig('shareaholic.site_id')) { echo $this->Library->shareaholic(getConfig('shareaholic.site_id')); } //Sets some Facebook's tags $this->Html->meta(['content' => $this->getTitleForLayout(), 'property' => 'og:title']); $this->Html->meta(['content' => Router::url(null, true), 'property' => 'og:url']); //Sets the app ID for Facebook if (getConfig('default.facebook_app_id')) { $this->Html->meta([ 'content' => getConfig('default.facebook_app_id'), 'property' => 'fb:app_id', ]); } }
[ "protected", "function", "setBlocks", "(", ")", "{", "//Sets the \"theme color\" (the toolbar color for some mobile browser)", "if", "(", "getConfig", "(", "'default.toolbar_color'", ")", ")", "{", "$", "this", "->", "Html", "->", "meta", "(", "'theme-color'", ",", "g...
Internal method to set some blocks @return void @uses $userbar @uses MeCms\View\View::getTitleForLayout() @uses MeTools\View\Helper\HtmlHelper::meta() @uses MeTools\View\Helper\LibraryHelper::analytics() @uses MeTools\View\Helper\LibraryHelper::shareaholic()
[ "Internal", "method", "to", "set", "some", "blocks" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/View/View/AppView.php#L39-L72
train
mirko-pagliai/me-cms
src/View/View/AppView.php
AppView.userbar
public function userbar($content = null) { if (!$content) { return $this->userbar; } $this->userbar = array_merge($this->userbar, (array)$content); }
php
public function userbar($content = null) { if (!$content) { return $this->userbar; } $this->userbar = array_merge($this->userbar, (array)$content); }
[ "public", "function", "userbar", "(", "$", "content", "=", "null", ")", "{", "if", "(", "!", "$", "content", ")", "{", "return", "$", "this", "->", "userbar", ";", "}", "$", "this", "->", "userbar", "=", "array_merge", "(", "$", "this", "->", "user...
Sets one or more userbar contents. @param string|array|null $content Contents. It can be a string or an array of contents. If `null`, returns an array of current contents @return array|void @uses $userbar
[ "Sets", "one", "or", "more", "userbar", "contents", "." ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/View/View/AppView.php#L124-L131
train
ommu/mod-core
controllers/ModuleController.php
ModuleController.updateModule
public function updateModule() { $this->moduleHandle->cacheModuleConfig(); //oke $this->moduleHandle->setModules(); //oke $this->moduleHandle->updateModuleAddon(); }
php
public function updateModule() { $this->moduleHandle->cacheModuleConfig(); //oke $this->moduleHandle->setModules(); //oke $this->moduleHandle->updateModuleAddon(); }
[ "public", "function", "updateModule", "(", ")", "{", "$", "this", "->", "moduleHandle", "->", "cacheModuleConfig", "(", ")", ";", "//oke\r", "$", "this", "->", "moduleHandle", "->", "setModules", "(", ")", ";", "//oke\r", "$", "this", "->", "moduleHandle", ...
Cache module, update and install to file
[ "Cache", "module", "update", "and", "install", "to", "file" ]
68c90e76440e74ee93bcf82905a54d86c941b771
https://github.com/ommu/mod-core/blob/68c90e76440e74ee93bcf82905a54d86c941b771/controllers/ModuleController.php#L91-L96
train
mirko-pagliai/me-cms
src/Controller/Admin/PagesCategoriesController.php
PagesCategoriesController.add
public function add() { $category = $this->PagesCategories->newEntity(); if ($this->request->is('post')) { $category = $this->PagesCategories->patchEntity($category, $this->request->getData()); if ($this->PagesCategories->save($category)) { $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); } $this->Flash->error(I18N_OPERATION_NOT_OK); } $this->set(compact('category')); }
php
public function add() { $category = $this->PagesCategories->newEntity(); if ($this->request->is('post')) { $category = $this->PagesCategories->patchEntity($category, $this->request->getData()); if ($this->PagesCategories->save($category)) { $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); } $this->Flash->error(I18N_OPERATION_NOT_OK); } $this->set(compact('category')); }
[ "public", "function", "add", "(", ")", "{", "$", "category", "=", "$", "this", "->", "PagesCategories", "->", "newEntity", "(", ")", ";", "if", "(", "$", "this", "->", "request", "->", "is", "(", "'post'", ")", ")", "{", "$", "category", "=", "$", ...
Adds pages category @return \Cake\Network\Response|null|void
[ "Adds", "pages", "category" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/Admin/PagesCategoriesController.php#L83-L100
train
mirko-pagliai/me-cms
src/Controller/Admin/PagesCategoriesController.php
PagesCategoriesController.edit
public function edit($id = null) { $category = $this->PagesCategories->get($id); if ($this->request->is(['patch', 'post', 'put'])) { $category = $this->PagesCategories->patchEntity($category, $this->request->getData()); if ($this->PagesCategories->save($category)) { $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); } $this->Flash->error(I18N_OPERATION_NOT_OK); } $this->set(compact('category')); }
php
public function edit($id = null) { $category = $this->PagesCategories->get($id); if ($this->request->is(['patch', 'post', 'put'])) { $category = $this->PagesCategories->patchEntity($category, $this->request->getData()); if ($this->PagesCategories->save($category)) { $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); } $this->Flash->error(I18N_OPERATION_NOT_OK); } $this->set(compact('category')); }
[ "public", "function", "edit", "(", "$", "id", "=", "null", ")", "{", "$", "category", "=", "$", "this", "->", "PagesCategories", "->", "get", "(", "$", "id", ")", ";", "if", "(", "$", "this", "->", "request", "->", "is", "(", "[", "'patch'", ",",...
Edits pages category @param string $id Pages category ID @return \Cake\Network\Response|null|void
[ "Edits", "pages", "category" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/Admin/PagesCategoriesController.php#L107-L124
train
mirko-pagliai/me-cms
src/Controller/Admin/PagesCategoriesController.php
PagesCategoriesController.delete
public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $category = $this->PagesCategories->get($id); //Before deleting, it checks if the category has some pages if (!$category->page_count) { $this->PagesCategories->deleteOrFail($category); $this->Flash->success(I18N_OPERATION_OK); } else { $this->Flash->alert(I18N_BEFORE_DELETE); } return $this->redirect(['action' => 'index']); }
php
public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $category = $this->PagesCategories->get($id); //Before deleting, it checks if the category has some pages if (!$category->page_count) { $this->PagesCategories->deleteOrFail($category); $this->Flash->success(I18N_OPERATION_OK); } else { $this->Flash->alert(I18N_BEFORE_DELETE); } return $this->redirect(['action' => 'index']); }
[ "public", "function", "delete", "(", "$", "id", "=", "null", ")", "{", "$", "this", "->", "request", "->", "allowMethod", "(", "[", "'post'", ",", "'delete'", "]", ")", ";", "$", "category", "=", "$", "this", "->", "PagesCategories", "->", "get", "("...
Deletes pages category @param string $id Pages category ID @return \Cake\Network\Response|null
[ "Deletes", "pages", "category" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/Admin/PagesCategoriesController.php#L130-L145
train
mirko-pagliai/me-cms
src/Model/Validation/PostValidator.php
PostValidator.validTags
public function validTags($value) { $validator = new TagValidator; $messages = []; foreach ($value as $tag) { $errors = $validator->errors($tag); if (!empty($errors['tag'])) { foreach ($errors['tag'] as $error) { $messages[] = __d('me_cms', 'Tag "{0}": {1}', $tag['tag'], lcfirst($error)); } } } return empty($messages) ?: implode(PHP_EOL, $messages); }
php
public function validTags($value) { $validator = new TagValidator; $messages = []; foreach ($value as $tag) { $errors = $validator->errors($tag); if (!empty($errors['tag'])) { foreach ($errors['tag'] as $error) { $messages[] = __d('me_cms', 'Tag "{0}": {1}', $tag['tag'], lcfirst($error)); } } } return empty($messages) ?: implode(PHP_EOL, $messages); }
[ "public", "function", "validTags", "(", "$", "value", ")", "{", "$", "validator", "=", "new", "TagValidator", ";", "$", "messages", "=", "[", "]", ";", "foreach", "(", "$", "value", "as", "$", "tag", ")", "{", "$", "errors", "=", "$", "validator", ...
Tags validation method. It uses the `TagValidator` and checks its rules on each tag and returns `true` on success or a string with all a string with all errors found (separated by `PHP_EOL`) on failure. @param string $value Field value @return bool|string `true` on success or an error message on failure @since 2.26.1 @uses \MeCms\Model\Validation\TagValidator
[ "Tags", "validation", "method", "." ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Model/Validation/PostValidator.php#L73-L89
train
s9e/RegexpBuilder
src/Runner.php
Runner.run
public function run(array $strings) { foreach ($this->passes as $pass) { $strings = $pass->run($strings); } return $strings; }
php
public function run(array $strings) { foreach ($this->passes as $pass) { $strings = $pass->run($strings); } return $strings; }
[ "public", "function", "run", "(", "array", "$", "strings", ")", "{", "foreach", "(", "$", "this", "->", "passes", "as", "$", "pass", ")", "{", "$", "strings", "=", "$", "pass", "->", "run", "(", "$", "strings", ")", ";", "}", "return", "$", "stri...
Run all passes on the list of strings @param array[] $strings @return array[]
[ "Run", "all", "passes", "on", "the", "list", "of", "strings" ]
59d0167a909659d718f53964f7653d2c83a5f8fe
https://github.com/s9e/RegexpBuilder/blob/59d0167a909659d718f53964f7653d2c83a5f8fe/src/Runner.php#L36-L44
train
PitonCMS/Engine
app/Models/PageElementMediaMapper.php
PageElementMediaMapper.findElementsByPageId
public function findElementsByPageId($pageId) { $this->makeSelect(); $this->sql .= ' and page_element.page_id = ? order by block_key, element_sort'; $this->bindValues[] = $pageId; return $this->find(); }
php
public function findElementsByPageId($pageId) { $this->makeSelect(); $this->sql .= ' and page_element.page_id = ? order by block_key, element_sort'; $this->bindValues[] = $pageId; return $this->find(); }
[ "public", "function", "findElementsByPageId", "(", "$", "pageId", ")", "{", "$", "this", "->", "makeSelect", "(", ")", ";", "$", "this", "->", "sql", ".=", "' and page_element.page_id = ? order by block_key, element_sort'", ";", "$", "this", "->", "bindValues", "[...
Find Elements by Page ID @param int $pageId Page ID @return mixed Array or null
[ "Find", "Elements", "by", "Page", "ID" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Models/PageElementMediaMapper.php#L34-L41
train
gregorybesson/PlaygroundUser
src/Service/Provider.php
Provider.getUserProviderMapper
public function getUserProviderMapper() { if ($this->userProviderMapper == null) { $this->userProviderMapper = $this->getServiceManager()->get('playgrounduser_userprovider_mapper'); } return $this->userProviderMapper; }
php
public function getUserProviderMapper() { if ($this->userProviderMapper == null) { $this->userProviderMapper = $this->getServiceManager()->get('playgrounduser_userprovider_mapper'); } return $this->userProviderMapper; }
[ "public", "function", "getUserProviderMapper", "(", ")", "{", "if", "(", "$", "this", "->", "userProviderMapper", "==", "null", ")", "{", "$", "this", "->", "userProviderMapper", "=", "$", "this", "->", "getServiceManager", "(", ")", "->", "get", "(", "'pl...
Retourne le modele de userProviderMapper @return \PlaygroundUser\Mapper\UserProviderMapper
[ "Retourne", "le", "modele", "de", "userProviderMapper" ]
b07c9969b5da1c173001fbba343f0a006d87eb8e
https://github.com/gregorybesson/PlaygroundUser/blob/b07c9969b5da1c173001fbba343f0a006d87eb8e/src/Service/Provider.php#L92-L99
train
gregorybesson/PlaygroundUser
src/Service/Provider.php
Provider.getHybridAuth
public function getHybridAuth() { if ($this->hybridAuth == null) { $this->hybridAuth = $this->getServiceManager()->get('HybridAuth'); } return $this->hybridAuth; }
php
public function getHybridAuth() { if ($this->hybridAuth == null) { $this->hybridAuth = $this->getServiceManager()->get('HybridAuth'); } return $this->hybridAuth; }
[ "public", "function", "getHybridAuth", "(", ")", "{", "if", "(", "$", "this", "->", "hybridAuth", "==", "null", ")", "{", "$", "this", "->", "hybridAuth", "=", "$", "this", "->", "getServiceManager", "(", ")", "->", "get", "(", "'HybridAuth'", ")", ";"...
Retourne l'objet HybridAuth @return \Hybrid_Auth
[ "Retourne", "l", "objet", "HybridAuth" ]
b07c9969b5da1c173001fbba343f0a006d87eb8e
https://github.com/gregorybesson/PlaygroundUser/blob/b07c9969b5da1c173001fbba343f0a006d87eb8e/src/Service/Provider.php#L105-L112
train
gregorybesson/PlaygroundUser
src/Service/Provider.php
Provider.getSocialConfig
public function getSocialConfig() { if ($this->SocialConfig == null) { $this->SocialConfig = $this->getServiceManager()->get('SocialConfig'); } return $this->SocialConfig; }
php
public function getSocialConfig() { if ($this->SocialConfig == null) { $this->SocialConfig = $this->getServiceManager()->get('SocialConfig'); } return $this->SocialConfig; }
[ "public", "function", "getSocialConfig", "(", ")", "{", "if", "(", "$", "this", "->", "SocialConfig", "==", "null", ")", "{", "$", "this", "->", "SocialConfig", "=", "$", "this", "->", "getServiceManager", "(", ")", "->", "get", "(", "'SocialConfig'", ")...
Retourne la configuration des providers @return multitype:
[ "Retourne", "la", "configuration", "des", "providers" ]
b07c9969b5da1c173001fbba343f0a006d87eb8e
https://github.com/gregorybesson/PlaygroundUser/blob/b07c9969b5da1c173001fbba343f0a006d87eb8e/src/Service/Provider.php#L118-L125
train
gregorybesson/PlaygroundUser
src/Service/Provider.php
Provider.getInfoMe
public function getInfoMe($socialnetworktype, $options = array()) { $infoMe = null; $provider = ucfirst(strtolower($socialnetworktype)); if (is_string($socialnetworktype)) { try { $adapter = $this->getHybridAuth()->authenticate($provider); if ($adapter->isConnected()) { $infoMe = $adapter->getUserProfile(); } } catch (\Exception $ex) { // The following retry is efficient in case a user previously registered on his social account // with the app has unsubsribed from the app // cf http://hybridauth.sourceforge.net/userguide/HybridAuth_Sessions.html if (($ex->getCode() == 6) || ($ex->getCode() == 7)) { // Réinitialiser la session HybridAuth $this->getHybridAuth()->getAdapter($provider)->logout(); // Essayer de se connecter à nouveau $adapter = $this->getHybridAuth()->authenticate($provider); if ($adapter->isConnected()) { $infoMe = $adapter->getUserProfile(); } } else { // $authEvent->setCode(\Zend\Authentication\Result::FAILURE) // ->setMessages(array('Invalid provider')); // $this->setSatisfied(false); return null; } } } return $infoMe; }
php
public function getInfoMe($socialnetworktype, $options = array()) { $infoMe = null; $provider = ucfirst(strtolower($socialnetworktype)); if (is_string($socialnetworktype)) { try { $adapter = $this->getHybridAuth()->authenticate($provider); if ($adapter->isConnected()) { $infoMe = $adapter->getUserProfile(); } } catch (\Exception $ex) { // The following retry is efficient in case a user previously registered on his social account // with the app has unsubsribed from the app // cf http://hybridauth.sourceforge.net/userguide/HybridAuth_Sessions.html if (($ex->getCode() == 6) || ($ex->getCode() == 7)) { // Réinitialiser la session HybridAuth $this->getHybridAuth()->getAdapter($provider)->logout(); // Essayer de se connecter à nouveau $adapter = $this->getHybridAuth()->authenticate($provider); if ($adapter->isConnected()) { $infoMe = $adapter->getUserProfile(); } } else { // $authEvent->setCode(\Zend\Authentication\Result::FAILURE) // ->setMessages(array('Invalid provider')); // $this->setSatisfied(false); return null; } } } return $infoMe; }
[ "public", "function", "getInfoMe", "(", "$", "socialnetworktype", ",", "$", "options", "=", "array", "(", ")", ")", "{", "$", "infoMe", "=", "null", ";", "$", "provider", "=", "ucfirst", "(", "strtolower", "(", "$", "socialnetworktype", ")", ")", ";", ...
Retourne mes infos @param string $socialnetworktype @param array $options @return NULL|\Hybrid_User_Profile
[ "Retourne", "mes", "infos" ]
b07c9969b5da1c173001fbba343f0a006d87eb8e
https://github.com/gregorybesson/PlaygroundUser/blob/b07c9969b5da1c173001fbba343f0a006d87eb8e/src/Service/Provider.php#L133-L167
train
gregorybesson/PlaygroundUser
src/Entity/Team.php
Team.addUsers
public function addUsers(ArrayCollection $users) { foreach ($users as $user) { $user->addTeam($this); $this->users->add($user); } }
php
public function addUsers(ArrayCollection $users) { foreach ($users as $user) { $user->addTeam($this); $this->users->add($user); } }
[ "public", "function", "addUsers", "(", "ArrayCollection", "$", "users", ")", "{", "foreach", "(", "$", "users", "as", "$", "user", ")", "{", "$", "user", "->", "addTeam", "(", "$", "this", ")", ";", "$", "this", "->", "users", "->", "add", "(", "$"...
Add users to the team. @param ArrayCollection $users @return void
[ "Add", "users", "to", "the", "team", "." ]
b07c9969b5da1c173001fbba343f0a006d87eb8e
https://github.com/gregorybesson/PlaygroundUser/blob/b07c9969b5da1c173001fbba343f0a006d87eb8e/src/Entity/Team.php#L186-L192
train
gregorybesson/PlaygroundUser
src/Entity/Team.php
Team.removeUsers
public function removeUsers(ArrayCollection $users) { foreach ($users as $user) { $user->removeTeam($this); $this->users->removeElement($user); } }
php
public function removeUsers(ArrayCollection $users) { foreach ($users as $user) { $user->removeTeam($this); $this->users->removeElement($user); } }
[ "public", "function", "removeUsers", "(", "ArrayCollection", "$", "users", ")", "{", "foreach", "(", "$", "users", "as", "$", "user", ")", "{", "$", "user", "->", "removeTeam", "(", "$", "this", ")", ";", "$", "this", "->", "users", "->", "removeElemen...
Remove users from the team. @param ArrayCollection $users @return void
[ "Remove", "users", "from", "the", "team", "." ]
b07c9969b5da1c173001fbba343f0a006d87eb8e
https://github.com/gregorybesson/PlaygroundUser/blob/b07c9969b5da1c173001fbba343f0a006d87eb8e/src/Entity/Team.php#L201-L207
train
nails/module-auth
auth/controllers/MfaDevice.php
MfaDevice.index
public function index() { // Validates the request token and generates a new one for the next request $this->validateToken(); // -------------------------------------------------------------------------- // Has this user already set up an MFA? $oAuthModel = Factory::model('Auth', 'nails/module-auth'); $oMfaDevice = $oAuthModel->mfaDeviceSecretGet($this->mfaUser->id); if ($oMfaDevice) { $this->requestCode(); } else { $this->setupDevice(); } }
php
public function index() { // Validates the request token and generates a new one for the next request $this->validateToken(); // -------------------------------------------------------------------------- // Has this user already set up an MFA? $oAuthModel = Factory::model('Auth', 'nails/module-auth'); $oMfaDevice = $oAuthModel->mfaDeviceSecretGet($this->mfaUser->id); if ($oMfaDevice) { $this->requestCode(); } else { $this->setupDevice(); } }
[ "public", "function", "index", "(", ")", "{", "// Validates the request token and generates a new one for the next request", "$", "this", "->", "validateToken", "(", ")", ";", "// --------------------------------------------------------------------------", "// Has this user already s...
Remaps requests to the correct method @throws \Nails\Common\Exception\FactoryException
[ "Remaps", "requests", "to", "the", "correct", "method" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/auth/controllers/MfaDevice.php#L39-L55
train
nails/module-auth
auth/controllers/MfaDevice.php
MfaDevice.setupDevice
protected function setupDevice() { $oSession = Factory::service('Session', 'nails/module-auth'); $oAuthModel = Factory::model('Auth', 'nails/module-auth'); $oInput = Factory::service('Input'); if ($oInput->post()) { $oFormValidation = Factory::service('FormValidation'); $oFormValidation->set_rules('mfa_secret', '', 'required'); $oFormValidation->set_rules('mfa_code', '', 'required'); $oFormValidation->set_message('required', lang('fv_required')); if ($oFormValidation->run()) { $sSecret = $oInput->post('mfa_secret'); $sMfaCode = $oInput->post('mfa_code'); // Verify the inout if ($oAuthModel->mfaDeviceSecretValidate($this->mfaUser->id, $sSecret, $sMfaCode)) { // Codes have been validated and saved to the DB, sign the user in and move on $sStatus = 'success'; $sMessage = '<strong>Multi Factor Authentication Enabled!</strong><br />You successfully '; $sMessage .= 'associated an MFA device with your account. You will be required to use it '; $sMessage .= 'the next time you log in.'; $oSession->setFlashData($sStatus, $sMessage); $this->loginUser(); } else { $this->data['error'] = 'Sorry, that code failed to validate. Please try again.'; } } else { $this->data['error'] = lang('fv_there_were_errors'); } } // Generate the secret $this->data['secret'] = $oAuthModel->mfaDeviceSecretGenerate( $this->mfaUser->id, $oInput->post('mfa_secret', true) ); if (!$this->data['secret']) { $sStatus = 'error'; $sMessage = '<Strong>Sorry,</strong> it has not been possible to get an MFA device set up for this user. '; $sMessage .= $oAuthModel->lastError(); $oSession->setFlashData($sStatus, $sMessage); if ($this->returnTo) { redirect('auth/login?return_to=' . $this->returnTo); } else { redirect('auth/login'); } } // -------------------------------------------------------------------------- $this->data['page']->title = 'Set up a new MFA device'; $this->loadStyles(NAILS_APP_PATH . 'application/modules/auth/views/mfa/device/setup.php'); Factory::service('View') ->load([ 'structure/header/blank', 'auth/mfa/device/setup', 'structure/footer/blank', ]); }
php
protected function setupDevice() { $oSession = Factory::service('Session', 'nails/module-auth'); $oAuthModel = Factory::model('Auth', 'nails/module-auth'); $oInput = Factory::service('Input'); if ($oInput->post()) { $oFormValidation = Factory::service('FormValidation'); $oFormValidation->set_rules('mfa_secret', '', 'required'); $oFormValidation->set_rules('mfa_code', '', 'required'); $oFormValidation->set_message('required', lang('fv_required')); if ($oFormValidation->run()) { $sSecret = $oInput->post('mfa_secret'); $sMfaCode = $oInput->post('mfa_code'); // Verify the inout if ($oAuthModel->mfaDeviceSecretValidate($this->mfaUser->id, $sSecret, $sMfaCode)) { // Codes have been validated and saved to the DB, sign the user in and move on $sStatus = 'success'; $sMessage = '<strong>Multi Factor Authentication Enabled!</strong><br />You successfully '; $sMessage .= 'associated an MFA device with your account. You will be required to use it '; $sMessage .= 'the next time you log in.'; $oSession->setFlashData($sStatus, $sMessage); $this->loginUser(); } else { $this->data['error'] = 'Sorry, that code failed to validate. Please try again.'; } } else { $this->data['error'] = lang('fv_there_were_errors'); } } // Generate the secret $this->data['secret'] = $oAuthModel->mfaDeviceSecretGenerate( $this->mfaUser->id, $oInput->post('mfa_secret', true) ); if (!$this->data['secret']) { $sStatus = 'error'; $sMessage = '<Strong>Sorry,</strong> it has not been possible to get an MFA device set up for this user. '; $sMessage .= $oAuthModel->lastError(); $oSession->setFlashData($sStatus, $sMessage); if ($this->returnTo) { redirect('auth/login?return_to=' . $this->returnTo); } else { redirect('auth/login'); } } // -------------------------------------------------------------------------- $this->data['page']->title = 'Set up a new MFA device'; $this->loadStyles(NAILS_APP_PATH . 'application/modules/auth/views/mfa/device/setup.php'); Factory::service('View') ->load([ 'structure/header/blank', 'auth/mfa/device/setup', 'structure/footer/blank', ]); }
[ "protected", "function", "setupDevice", "(", ")", "{", "$", "oSession", "=", "Factory", "::", "service", "(", "'Session'", ",", "'nails/module-auth'", ")", ";", "$", "oAuthModel", "=", "Factory", "::", "model", "(", "'Auth'", ",", "'nails/module-auth'", ")", ...
Sets up a new MFA device @throws \Nails\Common\Exception\FactoryException
[ "Sets", "up", "a", "new", "MFA", "device" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/auth/controllers/MfaDevice.php#L64-L137
train
nails/module-auth
auth/controllers/MfaDevice.php
MfaDevice.requestCode
protected function requestCode() { $oInput = Factory::service('Input'); if ($oInput->post()) { $oFormValidation = Factory::service('FormValidation'); $oFormValidation->set_rules('mfa_code', '', 'required'); $oFormValidation->set_message('required', lang('fv_required')); if ($oFormValidation->run()) { $oAuthModel = Factory::model('Auth', 'nails/module-auth'); $sMfaCode = $oInput->post('mfa_code'); // Verify the inout if ($oAuthModel->mfaDeviceCodeValidate($this->mfaUser->id, $sMfaCode)) { $this->loginUser(); } else { $this->data['error'] = 'Sorry, that code failed to validate. Please try again. '; $this->data['error'] .= $oAuthModel->lastError(); } } else { $this->data['error'] = lang('fv_there_were_errors'); } } // -------------------------------------------------------------------------- $this->data['page']->title = 'Enter your Code'; $this->loadStyles(NAILS_APP_PATH . 'application/modules/auth/views/mfa/device/ask.php'); Factory::service('View') ->load([ 'structure/header/blank', 'auth/mfa/device/ask', 'structure/footer/blank', ]); }
php
protected function requestCode() { $oInput = Factory::service('Input'); if ($oInput->post()) { $oFormValidation = Factory::service('FormValidation'); $oFormValidation->set_rules('mfa_code', '', 'required'); $oFormValidation->set_message('required', lang('fv_required')); if ($oFormValidation->run()) { $oAuthModel = Factory::model('Auth', 'nails/module-auth'); $sMfaCode = $oInput->post('mfa_code'); // Verify the inout if ($oAuthModel->mfaDeviceCodeValidate($this->mfaUser->id, $sMfaCode)) { $this->loginUser(); } else { $this->data['error'] = 'Sorry, that code failed to validate. Please try again. '; $this->data['error'] .= $oAuthModel->lastError(); } } else { $this->data['error'] = lang('fv_there_were_errors'); } } // -------------------------------------------------------------------------- $this->data['page']->title = 'Enter your Code'; $this->loadStyles(NAILS_APP_PATH . 'application/modules/auth/views/mfa/device/ask.php'); Factory::service('View') ->load([ 'structure/header/blank', 'auth/mfa/device/ask', 'structure/footer/blank', ]); }
[ "protected", "function", "requestCode", "(", ")", "{", "$", "oInput", "=", "Factory", "::", "service", "(", "'Input'", ")", ";", "if", "(", "$", "oInput", "->", "post", "(", ")", ")", "{", "$", "oFormValidation", "=", "Factory", "::", "service", "(", ...
Requests a code from the user @throws \Nails\Common\Exception\FactoryException
[ "Requests", "a", "code", "from", "the", "user" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/auth/controllers/MfaDevice.php#L146-L184
train
ekowabaka/clearice
src/argparser/ArgumentParser.php
ArgumentParser.addToOptionCache
private function addToOptionCache(string $identifier, $option) : void { if (!isset($option[$identifier])) { return; } $cacheKey = "${option['command']}${option[$identifier]}"; if (!isset($this->optionsCache[$cacheKey])) { $this->optionsCache[$cacheKey] = $option; } else { throw new OptionExistsException( "An argument option with $identifier {$option['command']} {$option[$identifier]} already exists." ); } }
php
private function addToOptionCache(string $identifier, $option) : void { if (!isset($option[$identifier])) { return; } $cacheKey = "${option['command']}${option[$identifier]}"; if (!isset($this->optionsCache[$cacheKey])) { $this->optionsCache[$cacheKey] = $option; } else { throw new OptionExistsException( "An argument option with $identifier {$option['command']} {$option[$identifier]} already exists." ); } }
[ "private", "function", "addToOptionCache", "(", "string", "$", "identifier", ",", "$", "option", ")", ":", "void", "{", "if", "(", "!", "isset", "(", "$", "option", "[", "$", "identifier", "]", ")", ")", "{", "return", ";", "}", "$", "cacheKey", "=",...
Add an option to the option cache for easy access through associative arrays. The option cache associates arguments with their options. @param string $identifier @param mixed $option @throws OptionExistsException
[ "Add", "an", "option", "to", "the", "option", "cache", "for", "easy", "access", "through", "associative", "arrays", ".", "The", "option", "cache", "associates", "arguments", "with", "their", "options", "." ]
8762c8a75e62df5c1a5505f2c78d6809ab5b3658
https://github.com/ekowabaka/clearice/blob/8762c8a75e62df5c1a5505f2c78d6809ab5b3658/src/argparser/ArgumentParser.php#L92-L105
train
ekowabaka/clearice
src/argparser/ArgumentParser.php
ArgumentParser.addOption
public function addOption(array $option): void { $this->validator->validateOption($option, $this->commands); $option['command'] = $option['command'] ?? ''; $option['repeats'] = $option['repeats'] ?? false; $this->options[] = $option; $this->addToOptionCache('name', $option); $this->addToOptionCache('short_name', $option); }
php
public function addOption(array $option): void { $this->validator->validateOption($option, $this->commands); $option['command'] = $option['command'] ?? ''; $option['repeats'] = $option['repeats'] ?? false; $this->options[] = $option; $this->addToOptionCache('name', $option); $this->addToOptionCache('short_name', $option); }
[ "public", "function", "addOption", "(", "array", "$", "option", ")", ":", "void", "{", "$", "this", "->", "validator", "->", "validateOption", "(", "$", "option", ",", "$", "this", "->", "commands", ")", ";", "$", "option", "[", "'command'", "]", "=", ...
Add an option to be parsed. Arguments are presented as a structured array with the following possible keys. name: The name of the option prefixed with a double dash -- short_name: A shorter single character option prefixed with a single dash - type: Required for all options that take values. An option specified without a type is considered to be a boolean flag. repeats: A boolean value that states whether the option can be repeated or not. Repeatable options are returned as arrays. default: A default value for the option. help: A help message for the option @param array $option @throws OptionExistsException @throws InvalidArgumentDescriptionException @throws UnknownCommandException
[ "Add", "an", "option", "to", "be", "parsed", ".", "Arguments", "are", "presented", "as", "a", "structured", "array", "with", "the", "following", "possible", "keys", "." ]
8762c8a75e62df5c1a5505f2c78d6809ab5b3658
https://github.com/ekowabaka/clearice/blob/8762c8a75e62df5c1a5505f2c78d6809ab5b3658/src/argparser/ArgumentParser.php#L143-L151
train
ekowabaka/clearice
src/argparser/ArgumentParser.php
ArgumentParser.parseShortArgument
private function parseShortArgument($command, $arguments, &$argPointer, &$output) { $argument = $arguments[$argPointer]; $option = $this->retrieveOptionFromCache($command, substr($argument, 1, 1)); $value = true; if (isset($option['type'])) { if (substr($argument, 2) != "") { $value = substr($argument, 2); } else { $value = $this->getNextValueOrFail($arguments, $argPointer, $option['name']); } } $this->assignValue($option, $output, $option['name'], $value); }
php
private function parseShortArgument($command, $arguments, &$argPointer, &$output) { $argument = $arguments[$argPointer]; $option = $this->retrieveOptionFromCache($command, substr($argument, 1, 1)); $value = true; if (isset($option['type'])) { if (substr($argument, 2) != "") { $value = substr($argument, 2); } else { $value = $this->getNextValueOrFail($arguments, $argPointer, $option['name']); } } $this->assignValue($option, $output, $option['name'], $value); }
[ "private", "function", "parseShortArgument", "(", "$", "command", ",", "$", "arguments", ",", "&", "$", "argPointer", ",", "&", "$", "output", ")", "{", "$", "argument", "=", "$", "arguments", "[", "$", "argPointer", "]", ";", "$", "option", "=", "$", ...
Parse a short argument that is prefixed with a single dash '-' @param $command @param $arguments @param $argPointer @throws InvalidValueException @throws InvalidArgumentException
[ "Parse", "a", "short", "argument", "that", "is", "prefixed", "with", "a", "single", "dash", "-" ]
8762c8a75e62df5c1a5505f2c78d6809ab5b3658
https://github.com/ekowabaka/clearice/blob/8762c8a75e62df5c1a5505f2c78d6809ab5b3658/src/argparser/ArgumentParser.php#L204-L219
train
ekowabaka/clearice
src/argparser/ArgumentParser.php
ArgumentParser.parse
public function parse($arguments = null) { try{ global $argv; $arguments = $arguments ?? $argv; $argPointer = 1; $parsed = []; $this->name = $this->name ?? $arguments[0]; $this->parseCommand($arguments, $argPointer, $parsed); $this->parseArgumentArray($arguments, $argPointer, $parsed); $this->maybeShowHelp($parsed); $this->validator->validateArguments($this->options, $parsed); $this->fillInDefaults($parsed); $parsed['__executed'] = $this->name; return $parsed; } catch (HelpMessageRequestedException $exception) { $this->programControl->quit(); } catch (InvalidArgumentException $exception) { print $exception->getMessage() . PHP_EOL; $this->programControl->quit(); } }
php
public function parse($arguments = null) { try{ global $argv; $arguments = $arguments ?? $argv; $argPointer = 1; $parsed = []; $this->name = $this->name ?? $arguments[0]; $this->parseCommand($arguments, $argPointer, $parsed); $this->parseArgumentArray($arguments, $argPointer, $parsed); $this->maybeShowHelp($parsed); $this->validator->validateArguments($this->options, $parsed); $this->fillInDefaults($parsed); $parsed['__executed'] = $this->name; return $parsed; } catch (HelpMessageRequestedException $exception) { $this->programControl->quit(); } catch (InvalidArgumentException $exception) { print $exception->getMessage() . PHP_EOL; $this->programControl->quit(); } }
[ "public", "function", "parse", "(", "$", "arguments", "=", "null", ")", "{", "try", "{", "global", "$", "argv", ";", "$", "arguments", "=", "$", "arguments", "??", "$", "argv", ";", "$", "argPointer", "=", "1", ";", "$", "parsed", "=", "[", "]", ...
Parses command line arguments and return a structured array of options and their associated values. @param array $arguments An optional array of arguments that would be parsed instead of those passed to the CLI. @return array @throws InvalidValueException
[ "Parses", "command", "line", "arguments", "and", "return", "a", "structured", "array", "of", "options", "and", "their", "associated", "values", "." ]
8762c8a75e62df5c1a5505f2c78d6809ab5b3658
https://github.com/ekowabaka/clearice/blob/8762c8a75e62df5c1a5505f2c78d6809ab5b3658/src/argparser/ArgumentParser.php#L293-L314
train
ekowabaka/clearice
src/argparser/ArgumentParser.php
ArgumentParser.enableHelp
public function enableHelp(string $description = null, string $footer = null, string $name = null) : void { $this->name = $name; $this->description = $description; $this->footer = $footer; $this->helpEnabled = true; $this->addOption(['name' => 'help', 'short_name' => 'h', 'help' => "display this help message"]); foreach($this->commands as $command) { $this->addOption(['name' => 'help', 'help' => 'display this help message', 'command' => $command['name']]); } }
php
public function enableHelp(string $description = null, string $footer = null, string $name = null) : void { $this->name = $name; $this->description = $description; $this->footer = $footer; $this->helpEnabled = true; $this->addOption(['name' => 'help', 'short_name' => 'h', 'help' => "display this help message"]); foreach($this->commands as $command) { $this->addOption(['name' => 'help', 'help' => 'display this help message', 'command' => $command['name']]); } }
[ "public", "function", "enableHelp", "(", "string", "$", "description", "=", "null", ",", "string", "$", "footer", "=", "null", ",", "string", "$", "name", "=", "null", ")", ":", "void", "{", "$", "this", "->", "name", "=", "$", "name", ";", "$", "t...
Enables help messages so they show automatically. This method also allows you to optionally pass the name of the application, a description header for the help message and a footer. @param string $name The name of the application binary @param string $description A description to be displayed on top of the help message @param string $footer A footer message to be displayed after the help message @throws InvalidArgumentDescriptionException @throws OptionExistsException @throws UnknownCommandException
[ "Enables", "help", "messages", "so", "they", "show", "automatically", ".", "This", "method", "also", "allows", "you", "to", "optionally", "pass", "the", "name", "of", "the", "application", "a", "description", "header", "for", "the", "help", "message", "and", ...
8762c8a75e62df5c1a5505f2c78d6809ab5b3658
https://github.com/ekowabaka/clearice/blob/8762c8a75e62df5c1a5505f2c78d6809ab5b3658/src/argparser/ArgumentParser.php#L329-L339
train
mirko-pagliai/me-cms
src/Controller/PagesController.php
PagesController.view
public function view($slug = null) { //Checks if there exists a static page $static = StaticPage::get($slug); if ($static) { $page = new Entity(array_merge([ 'category' => new Entity(['slug' => null, 'title' => null]), 'title' => StaticPage::title($slug), 'subtitle' => null, ], compact('slug'))); $this->set(compact('page')); return $this->render($static); } $slug = rtrim($slug, '/'); $page = $this->Pages->findActiveBySlug($slug) ->contain([$this->Pages->Categories->getAlias() => ['fields' => ['title', 'slug']]]) ->cache(sprintf('view_%s', md5($slug)), $this->Pages->getCacheName()) ->firstOrFail(); $this->set(compact('page')); }
php
public function view($slug = null) { //Checks if there exists a static page $static = StaticPage::get($slug); if ($static) { $page = new Entity(array_merge([ 'category' => new Entity(['slug' => null, 'title' => null]), 'title' => StaticPage::title($slug), 'subtitle' => null, ], compact('slug'))); $this->set(compact('page')); return $this->render($static); } $slug = rtrim($slug, '/'); $page = $this->Pages->findActiveBySlug($slug) ->contain([$this->Pages->Categories->getAlias() => ['fields' => ['title', 'slug']]]) ->cache(sprintf('view_%s', md5($slug)), $this->Pages->getCacheName()) ->firstOrFail(); $this->set(compact('page')); }
[ "public", "function", "view", "(", "$", "slug", "=", "null", ")", "{", "//Checks if there exists a static page", "$", "static", "=", "StaticPage", "::", "get", "(", "$", "slug", ")", ";", "if", "(", "$", "static", ")", "{", "$", "page", "=", "new", "En...
Views page. It first checks if there's a static page, using all the passed arguments. Otherwise, it checks for the page in the database, using that slug. Static pages must be located in `APP/View/StaticPages/`. @param string $slug Page slug @return \Cake\Network\Response|void @uses MeCms\Utility\StaticPage::get() @uses MeCms\Utility\StaticPage::title()
[ "Views", "page", "." ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/PagesController.php#L55-L79
train
mirko-pagliai/me-cms
src/Controller/PagesController.php
PagesController.preview
public function preview($slug = null) { $page = $this->Pages->findPendingBySlug($slug) ->contain([$this->Pages->Categories->getAlias() => ['fields' => ['title', 'slug']]]) ->firstOrFail(); $this->set(compact('page')); $this->render('view'); }
php
public function preview($slug = null) { $page = $this->Pages->findPendingBySlug($slug) ->contain([$this->Pages->Categories->getAlias() => ['fields' => ['title', 'slug']]]) ->firstOrFail(); $this->set(compact('page')); $this->render('view'); }
[ "public", "function", "preview", "(", "$", "slug", "=", "null", ")", "{", "$", "page", "=", "$", "this", "->", "Pages", "->", "findPendingBySlug", "(", "$", "slug", ")", "->", "contain", "(", "[", "$", "this", "->", "Pages", "->", "Categories", "->",...
Preview for pages. It uses the `view` template. @param string $slug Page slug @return void
[ "Preview", "for", "pages", ".", "It", "uses", "the", "view", "template", "." ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/PagesController.php#L87-L95
train
mirko-pagliai/me-cms
src/Utility/SitemapBuilder.php
SitemapBuilder.getMethods
protected static function getMethods($plugin) { //Sets the class name $class = App::classname($plugin . '.Sitemap', 'Utility'); //Gets all methods from the `Sitemap` class of the plugin $methods = get_child_methods($class); if (empty($methods)) { return []; } return collection($methods)->map(function ($method) use ($class) { return array_merge(compact('class'), ['name' => $method]); })->toList(); }
php
protected static function getMethods($plugin) { //Sets the class name $class = App::classname($plugin . '.Sitemap', 'Utility'); //Gets all methods from the `Sitemap` class of the plugin $methods = get_child_methods($class); if (empty($methods)) { return []; } return collection($methods)->map(function ($method) use ($class) { return array_merge(compact('class'), ['name' => $method]); })->toList(); }
[ "protected", "static", "function", "getMethods", "(", "$", "plugin", ")", "{", "//Sets the class name", "$", "class", "=", "App", "::", "classname", "(", "$", "plugin", ".", "'.Sitemap'", ",", "'Utility'", ")", ";", "//Gets all methods from the `Sitemap` class of th...
Internal method to get methods from `Sitemap` classes @param string $plugin Plugin @return array Array with classes and methods names
[ "Internal", "method", "to", "get", "methods", "from", "Sitemap", "classes" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Utility/SitemapBuilder.php#L30-L45
train
PitonCMS/Engine
app/Library/Twig/Base.php
Base.pathFor
public function pathFor($name, $data = [], $queryParams = []) { // The `pathfor('showPage', {'url': 'home'})` route should be an alias for `pathFor('home')` if ($name === 'showPage' && isset($data['url']) && $data['url'] === 'home') { $name = 'home'; unset($data['url']); } return $this->container->router->pathFor($name, $data, $queryParams); }
php
public function pathFor($name, $data = [], $queryParams = []) { // The `pathfor('showPage', {'url': 'home'})` route should be an alias for `pathFor('home')` if ($name === 'showPage' && isset($data['url']) && $data['url'] === 'home') { $name = 'home'; unset($data['url']); } return $this->container->router->pathFor($name, $data, $queryParams); }
[ "public", "function", "pathFor", "(", "$", "name", ",", "$", "data", "=", "[", "]", ",", "$", "queryParams", "=", "[", "]", ")", "{", "// The `pathfor('showPage', {'url': 'home'})` route should be an alias for `pathFor('home')`", "if", "(", "$", "name", "===", "'s...
Get Path for Named Route @param string $name Name of the route @param array $data Associative array to assign to route segments @param array $queryParams Query string parameters @return string The desired route path without the domain, but does include the basePath
[ "Get", "Path", "for", "Named", "Route" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Library/Twig/Base.php#L124-L133
train
PitonCMS/Engine
app/Library/Twig/Base.php
Base.getMediaPath
public function getMediaPath($fileName) { // If this is an external link to a media file, just return string if (stripos($fileName, 'http') === 0 || empty($fileName)) { return $fileName; } return ($this->container->filePath)($fileName) . $fileName; }
php
public function getMediaPath($fileName) { // If this is an external link to a media file, just return string if (stripos($fileName, 'http') === 0 || empty($fileName)) { return $fileName; } return ($this->container->filePath)($fileName) . $fileName; }
[ "public", "function", "getMediaPath", "(", "$", "fileName", ")", "{", "// If this is an external link to a media file, just return string", "if", "(", "stripos", "(", "$", "fileName", ",", "'http'", ")", "===", "0", "||", "empty", "(", "$", "fileName", ")", ")", ...
Get Media Path @param string $fileName Media file name to parse @return string
[ "Get", "Media", "Path" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Library/Twig/Base.php#L210-L218
train
mirko-pagliai/me-cms
src/Controller/Admin/SystemsController.php
SystemsController.browser
public function browser() { //Gets the type from the query and the supported types from configuration $type = $this->request->getQuery('type'); $types = $this->KcFinder->getTypes(); //If there's only one type, it automatically sets the query value if (!$type && count($types) < 2) { $type = array_key_first($types); $this->request = $this->request->withQueryParams(compact('type')); } //Checks the type, then sets the KCFinder path if ($type && array_key_exists($type, $types)) { //Sets locale $locale = substr(I18n::getLocale(), 0, 2); $locale = empty($locale) ? 'en' : $locale; $this->set('kcfinder', sprintf('%s/kcfinder/browse.php?lang=%s&type=%s', Router::url('/vendor', true), $locale, $type)); } $this->set('types', array_combine(array_keys($types), array_keys($types))); }
php
public function browser() { //Gets the type from the query and the supported types from configuration $type = $this->request->getQuery('type'); $types = $this->KcFinder->getTypes(); //If there's only one type, it automatically sets the query value if (!$type && count($types) < 2) { $type = array_key_first($types); $this->request = $this->request->withQueryParams(compact('type')); } //Checks the type, then sets the KCFinder path if ($type && array_key_exists($type, $types)) { //Sets locale $locale = substr(I18n::getLocale(), 0, 2); $locale = empty($locale) ? 'en' : $locale; $this->set('kcfinder', sprintf('%s/kcfinder/browse.php?lang=%s&type=%s', Router::url('/vendor', true), $locale, $type)); } $this->set('types', array_combine(array_keys($types), array_keys($types))); }
[ "public", "function", "browser", "(", ")", "{", "//Gets the type from the query and the supported types from configuration", "$", "type", "=", "$", "this", "->", "request", "->", "getQuery", "(", "'type'", ")", ";", "$", "types", "=", "$", "this", "->", "KcFinder"...
Media browser with KCFinder. The KCFinder component is loaded by the `initialize()` method. @return void @uses MeCms\Controller\Component\KcFinderComponent::getTypes()
[ "Media", "browser", "with", "KCFinder", "." ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/Admin/SystemsController.php#L71-L93
train
drdplusinfo/health
DrdPlus/Health/Health.php
Health.healFreshOrdinaryWounds
public function healFreshOrdinaryWounds(HealingPower $healingPower, WoundBoundary $woundBoundary): int { $this->checkIfNeedsToRollAgainstMalusFirst(); // can heal new and ordinary wounds only, up to limit by current treatment boundary $healedAmount = 0; $remainingHealUpToWounds = $healingPower->getHealUpToWounds(); foreach ($this->getUnhealedFreshOrdinaryWounds() as $newOrdinaryWound) { // wound is set as old internally, ALL OF THEM, even if no healing left $currentlyRegenerated = $newOrdinaryWound->heal($remainingHealUpToWounds); $remainingHealUpToWounds -= $currentlyRegenerated; $healedAmount += $currentlyRegenerated; } $this->treatmentBoundary = TreatmentBoundary::getIt($this->getUnhealedWoundsSum()); $this->resolveMalusAfterHeal($healedAmount, $woundBoundary); return $healedAmount; }
php
public function healFreshOrdinaryWounds(HealingPower $healingPower, WoundBoundary $woundBoundary): int { $this->checkIfNeedsToRollAgainstMalusFirst(); // can heal new and ordinary wounds only, up to limit by current treatment boundary $healedAmount = 0; $remainingHealUpToWounds = $healingPower->getHealUpToWounds(); foreach ($this->getUnhealedFreshOrdinaryWounds() as $newOrdinaryWound) { // wound is set as old internally, ALL OF THEM, even if no healing left $currentlyRegenerated = $newOrdinaryWound->heal($remainingHealUpToWounds); $remainingHealUpToWounds -= $currentlyRegenerated; $healedAmount += $currentlyRegenerated; } $this->treatmentBoundary = TreatmentBoundary::getIt($this->getUnhealedWoundsSum()); $this->resolveMalusAfterHeal($healedAmount, $woundBoundary); return $healedAmount; }
[ "public", "function", "healFreshOrdinaryWounds", "(", "HealingPower", "$", "healingPower", ",", "WoundBoundary", "$", "woundBoundary", ")", ":", "int", "{", "$", "this", "->", "checkIfNeedsToRollAgainstMalusFirst", "(", ")", ";", "// can heal new and ordinary wounds only,...
Also sets treatment boundary to unhealed wounds after. Even if the heal itself heals nothing! @param HealingPower $healingPower @param WoundBoundary $woundBoundary @return int amount of actually healed points of wounds @throws \DrdPlus\Health\Exceptions\NeedsToRollAgainstMalusFromWoundsFirst
[ "Also", "sets", "treatment", "boundary", "to", "unhealed", "wounds", "after", ".", "Even", "if", "the", "heal", "itself", "heals", "nothing!" ]
f8dee76ddf651367afbbaab6f30376fc80f97001
https://github.com/drdplusinfo/health/blob/f8dee76ddf651367afbbaab6f30376fc80f97001/DrdPlus/Health/Health.php#L214-L230
train
drdplusinfo/health
DrdPlus/Health/Health.php
Health.regenerate
public function regenerate(HealingPower $healingPower, WoundBoundary $woundBoundary): int { $this->checkIfNeedsToRollAgainstMalusFirst(); // every wound becomes old after this $regeneratedAmount = 0; $remainingHealUpToWounds = $healingPower->getHealUpToWounds(); foreach ($this->getUnhealedWounds() as $unhealedWound) { // wound is set as old internally, ALL OF THEM, even if no healing left $currentlyRegenerated = $unhealedWound->heal($remainingHealUpToWounds); $remainingHealUpToWounds -= $currentlyRegenerated; $regeneratedAmount += $currentlyRegenerated; } $this->treatmentBoundary = TreatmentBoundary::getIt($this->getUnhealedWoundsSum()); $this->resolveMalusAfterHeal($regeneratedAmount, $woundBoundary); return $regeneratedAmount; }
php
public function regenerate(HealingPower $healingPower, WoundBoundary $woundBoundary): int { $this->checkIfNeedsToRollAgainstMalusFirst(); // every wound becomes old after this $regeneratedAmount = 0; $remainingHealUpToWounds = $healingPower->getHealUpToWounds(); foreach ($this->getUnhealedWounds() as $unhealedWound) { // wound is set as old internally, ALL OF THEM, even if no healing left $currentlyRegenerated = $unhealedWound->heal($remainingHealUpToWounds); $remainingHealUpToWounds -= $currentlyRegenerated; $regeneratedAmount += $currentlyRegenerated; } $this->treatmentBoundary = TreatmentBoundary::getIt($this->getUnhealedWoundsSum()); $this->resolveMalusAfterHeal($regeneratedAmount, $woundBoundary); return $regeneratedAmount; }
[ "public", "function", "regenerate", "(", "HealingPower", "$", "healingPower", ",", "WoundBoundary", "$", "woundBoundary", ")", ":", "int", "{", "$", "this", "->", "checkIfNeedsToRollAgainstMalusFirst", "(", ")", ";", "// every wound becomes old after this", "$", "rege...
Regenerate any wound, both ordinary and serious, both new and old, by natural or unnatural way. @param HealingPower $healingPower @param WoundBoundary $woundBoundary @return int actually regenerated amount @throws \DrdPlus\Health\Exceptions\NeedsToRollAgainstMalusFromWoundsFirst
[ "Regenerate", "any", "wound", "both", "ordinary", "and", "serious", "both", "new", "and", "old", "by", "natural", "or", "unnatural", "way", "." ]
f8dee76ddf651367afbbaab6f30376fc80f97001
https://github.com/drdplusinfo/health/blob/f8dee76ddf651367afbbaab6f30376fc80f97001/DrdPlus/Health/Health.php#L319-L334
train
drdplusinfo/health
DrdPlus/Health/Health.php
Health.getUnhealedFreshOrdinaryWoundsSum
public function getUnhealedFreshOrdinaryWoundsSum(): int { return \array_sum( \array_map( function (OrdinaryWound $ordinaryWound) { return $ordinaryWound->getValue(); }, $this->getUnhealedFreshOrdinaryWounds() ) ); }
php
public function getUnhealedFreshOrdinaryWoundsSum(): int { return \array_sum( \array_map( function (OrdinaryWound $ordinaryWound) { return $ordinaryWound->getValue(); }, $this->getUnhealedFreshOrdinaryWounds() ) ); }
[ "public", "function", "getUnhealedFreshOrdinaryWoundsSum", "(", ")", ":", "int", "{", "return", "\\", "array_sum", "(", "\\", "array_map", "(", "function", "(", "OrdinaryWound", "$", "ordinaryWound", ")", "{", "return", "$", "ordinaryWound", "->", "getValue", "(...
Usable for info about amount of wounds which can be healed by basic healing @return int
[ "Usable", "for", "info", "about", "amount", "of", "wounds", "which", "can", "be", "healed", "by", "basic", "healing" ]
f8dee76ddf651367afbbaab6f30376fc80f97001
https://github.com/drdplusinfo/health/blob/f8dee76ddf651367afbbaab6f30376fc80f97001/DrdPlus/Health/Health.php#L341-L351
train
drdplusinfo/health
DrdPlus/Health/Health.php
Health.getUnhealedFreshSeriousWoundsSum
public function getUnhealedFreshSeriousWoundsSum(): int { return \array_sum( \array_map( function (SeriousWound $seriousWound) { return $seriousWound->getValue(); }, $this->getUnhealedFreshSeriousWounds() ) ); }
php
public function getUnhealedFreshSeriousWoundsSum(): int { return \array_sum( \array_map( function (SeriousWound $seriousWound) { return $seriousWound->getValue(); }, $this->getUnhealedFreshSeriousWounds() ) ); }
[ "public", "function", "getUnhealedFreshSeriousWoundsSum", "(", ")", ":", "int", "{", "return", "\\", "array_sum", "(", "\\", "array_map", "(", "function", "(", "SeriousWound", "$", "seriousWound", ")", "{", "return", "$", "seriousWound", "->", "getValue", "(", ...
Usable for info about amount of wounds which can be healed by treatment @return int
[ "Usable", "for", "info", "about", "amount", "of", "wounds", "which", "can", "be", "healed", "by", "treatment" ]
f8dee76ddf651367afbbaab6f30376fc80f97001
https://github.com/drdplusinfo/health/blob/f8dee76ddf651367afbbaab6f30376fc80f97001/DrdPlus/Health/Health.php#L358-L368
train
TuumPHP/Respond
src/Controller/Matcher.php
Matcher.identifier
public static function identifier(array $match) { $name = $match[1]; // this should be the matched name. if($name === '*') { return '(?P<pathInfo>.*)'; } $type = '[-_0-9a-zA-Z]'; if (strpos($name, ':') !== false) { list($name, $type) = explode(':', $name, 2); if(isset(self::$types[$type])) { $type = self::$types[$type]; } } return "(?P<{$name}>{$type}+)"; }
php
public static function identifier(array $match) { $name = $match[1]; // this should be the matched name. if($name === '*') { return '(?P<pathInfo>.*)'; } $type = '[-_0-9a-zA-Z]'; if (strpos($name, ':') !== false) { list($name, $type) = explode(':', $name, 2); if(isset(self::$types[$type])) { $type = self::$types[$type]; } } return "(?P<{$name}>{$type}+)"; }
[ "public", "static", "function", "identifier", "(", "array", "$", "match", ")", "{", "$", "name", "=", "$", "match", "[", "1", "]", ";", "// this should be the matched name.", "if", "(", "$", "name", "===", "'*'", ")", "{", "return", "'(?P<pathInfo>.*)'", "...
a callback method for converting identifier in route pattern to regex's one. i.e. {id} -> (?P<id>[\w]}). @param array $match @return string
[ "a", "callback", "method", "for", "converting", "identifier", "in", "route", "pattern", "to", "regex", "s", "one", "." ]
5861ec0bffc97c500d88bf307a53277f1c2fe12f
https://github.com/TuumPHP/Respond/blob/5861ec0bffc97c500d88bf307a53277f1c2fe12f/src/Controller/Matcher.php#L115-L129
train
Nekland/Tools
src/Utils/Tempfile/TemporaryFile.php
TemporaryFile.remove
public function remove() { if ($this->removed) { return; } if (!\unlink($this->file)) { throw new RuntimeException(sprintf('Impossible to remove file "%s"', $this->file)); } $this->removed = true; }
php
public function remove() { if ($this->removed) { return; } if (!\unlink($this->file)) { throw new RuntimeException(sprintf('Impossible to remove file "%s"', $this->file)); } $this->removed = true; }
[ "public", "function", "remove", "(", ")", "{", "if", "(", "$", "this", "->", "removed", ")", "{", "return", ";", "}", "if", "(", "!", "\\", "unlink", "(", "$", "this", "->", "file", ")", ")", "{", "throw", "new", "RuntimeException", "(", "sprintf",...
Removes the temporary file. Please consider unset the object instead.
[ "Removes", "the", "temporary", "file", ".", "Please", "consider", "unset", "the", "object", "instead", "." ]
b3f05e5cf2291271e21397060069221a2b65d201
https://github.com/Nekland/Tools/blob/b3f05e5cf2291271e21397060069221a2b65d201/src/Utils/Tempfile/TemporaryFile.php#L107-L118
train
nails/module-auth
src/Model/User/Password.php
Password.isCorrect
public function isCorrect($iUserId, $sPassword) { if (empty($iUserId) || empty($sPassword)) { return false; } // -------------------------------------------------------------------------- $oDb = Factory::service('Database'); $oDb->select('u.password, u.password_engine, u.salt'); $oDb->where('u.id', $iUserId); $oDb->limit(1); $oResult = $oDb->get(NAILS_DB_PREFIX . 'user u'); // -------------------------------------------------------------------------- if ($oResult->num_rows() !== 1) { return false; } // -------------------------------------------------------------------------- /** * @todo: use the appropriate driver to determine password correctness, but * for now, do it the old way */ $sHash = sha1(sha1($sPassword) . $oResult->row()->salt); return $oResult->row()->password === $sHash; }
php
public function isCorrect($iUserId, $sPassword) { if (empty($iUserId) || empty($sPassword)) { return false; } // -------------------------------------------------------------------------- $oDb = Factory::service('Database'); $oDb->select('u.password, u.password_engine, u.salt'); $oDb->where('u.id', $iUserId); $oDb->limit(1); $oResult = $oDb->get(NAILS_DB_PREFIX . 'user u'); // -------------------------------------------------------------------------- if ($oResult->num_rows() !== 1) { return false; } // -------------------------------------------------------------------------- /** * @todo: use the appropriate driver to determine password correctness, but * for now, do it the old way */ $sHash = sha1(sha1($sPassword) . $oResult->row()->salt); return $oResult->row()->password === $sHash; }
[ "public", "function", "isCorrect", "(", "$", "iUserId", ",", "$", "sPassword", ")", "{", "if", "(", "empty", "(", "$", "iUserId", ")", "||", "empty", "(", "$", "sPassword", ")", ")", "{", "return", "false", ";", "}", "// -----------------------------------...
Determines whether a password is correct for a particular user. @param int $iUserId The user ID to check for @param string $sPassword The raw, unencrypted password to check @return boolean
[ "Determines", "whether", "a", "password", "is", "correct", "for", "a", "particular", "user", "." ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User/Password.php#L67-L97
train
nails/module-auth
src/Model/User/Password.php
Password.isExpired
public function isExpired($iUserId) { if (empty($iUserId)) { return false; } $oDb = Factory::service('Database'); $oDb->select('u.password_changed,ug.password_rules'); $oDb->where('u.id', $iUserId); $oDb->join(NAILS_DB_PREFIX . 'user_group ug', 'ug.id = u.group_id'); $oDb->limit(1); $oResult = $oDb->get(NAILS_DB_PREFIX . 'user u'); if ($oResult->num_rows() !== 1) { return false; } // Decode the password rules $oGroupPwRules = json_decode($oResult->row()->password_rules); if (empty($oGroupPwRules->expiresAfter)) { return false; } $sChanged = $oResult->row()->password_changed; if (is_null($sChanged)) { return true; } else { $oThen = new \DateTime($sChanged); $oNow = new \DateTime(); $oInterval = $oNow->diff($oThen); return $oInterval->days >= $oGroupPwRules->expiresAfter; } }
php
public function isExpired($iUserId) { if (empty($iUserId)) { return false; } $oDb = Factory::service('Database'); $oDb->select('u.password_changed,ug.password_rules'); $oDb->where('u.id', $iUserId); $oDb->join(NAILS_DB_PREFIX . 'user_group ug', 'ug.id = u.group_id'); $oDb->limit(1); $oResult = $oDb->get(NAILS_DB_PREFIX . 'user u'); if ($oResult->num_rows() !== 1) { return false; } // Decode the password rules $oGroupPwRules = json_decode($oResult->row()->password_rules); if (empty($oGroupPwRules->expiresAfter)) { return false; } $sChanged = $oResult->row()->password_changed; if (is_null($sChanged)) { return true; } else { $oThen = new \DateTime($sChanged); $oNow = new \DateTime(); $oInterval = $oNow->diff($oThen); return $oInterval->days >= $oGroupPwRules->expiresAfter; } }
[ "public", "function", "isExpired", "(", "$", "iUserId", ")", "{", "if", "(", "empty", "(", "$", "iUserId", ")", ")", "{", "return", "false", ";", "}", "$", "oDb", "=", "Factory", "::", "service", "(", "'Database'", ")", ";", "$", "oDb", "->", "sele...
Determines whether a user's password has expired @param integer $iUserId The user ID to check @return boolean
[ "Determines", "whether", "a", "user", "s", "password", "has", "expired" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User/Password.php#L108-L146
train
nails/module-auth
src/Model/User/Password.php
Password.expiresAfter
public function expiresAfter($iGroupId) { if (empty($iGroupId)) { return null; } $oDb = Factory::service('Database'); $oDb->select('password_rules'); $oDb->where('id', $iGroupId); $oDb->limit(1); $oResult = $oDb->get(NAILS_DB_PREFIX . 'user_group'); if ($oResult->num_rows() !== 1) { return null; } // Decode the password rules $oGroupPwRules = json_decode($oResult->row()->password_rules); return empty($oGroupPwRules->expiresAfter) ? null : $oGroupPwRules->expiresAfter; }
php
public function expiresAfter($iGroupId) { if (empty($iGroupId)) { return null; } $oDb = Factory::service('Database'); $oDb->select('password_rules'); $oDb->where('id', $iGroupId); $oDb->limit(1); $oResult = $oDb->get(NAILS_DB_PREFIX . 'user_group'); if ($oResult->num_rows() !== 1) { return null; } // Decode the password rules $oGroupPwRules = json_decode($oResult->row()->password_rules); return empty($oGroupPwRules->expiresAfter) ? null : $oGroupPwRules->expiresAfter; }
[ "public", "function", "expiresAfter", "(", "$", "iGroupId", ")", "{", "if", "(", "empty", "(", "$", "iGroupId", ")", ")", "{", "return", "null", ";", "}", "$", "oDb", "=", "Factory", "::", "service", "(", "'Database'", ")", ";", "$", "oDb", "->", "...
Returns how many days a password is valid for @param $iGroupId @return null
[ "Returns", "how", "many", "days", "a", "password", "is", "valid", "for" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User/Password.php#L157-L177
train
nails/module-auth
src/Model/User/Password.php
Password.generateHash
public function generateHash($iGroupId, $sPassword) { if (empty($sPassword)) { $this->setError('No password to hash'); return false; } // -------------------------------------------------------------------------- // Check password satisfies password rules $aPwRules = $this->getRules($iGroupId); // Long enough? if (!empty($aPwRules['min']) && strlen($sPassword) < $aPwRules['min']) { $this->setError('Password is too short.'); return false; } // Too long? if (!empty($aPwRules['max']) && strlen($sPassword) > $aPwRules['max']) { $this->setError('Password is too long.'); return false; } // Satisfies all the requirements $aFailedRequirements = []; if (!empty($aPwRules['requirements'])) { foreach ($aPwRules['requirements'] as $sRequirement => $bValue) { switch ($sRequirement) { case 'symbol': if (!$this->strContainsFromCharset($sPassword, 'symbol')) { $aFailedRequirements[] = 'a symbol'; } break; case 'number': if (!$this->strContainsFromCharset($sPassword, 'number')) { $aFailedRequirements[] = 'a number'; } break; case 'lower_alpha': if (!$this->strContainsFromCharset($sPassword, 'lower_alpha')) { $aFailedRequirements[] = 'a lowercase letter'; } break; case 'upper_alpha': if (!$this->strContainsFromCharset($sPassword, 'upper_alpha')) { $aFailedRequirements[] = 'an uppercase letter'; } break; } } } if (!empty($aFailedRequirements)) { $sError = 'Password must contain ' . implode(', ', $aFailedRequirements) . '.'; $sError = str_lreplace(', ', ' and ', $sError); $this->setError($sError); return false; } // Not be a banned password? if (!empty($aPwRules['banned'])) { foreach ($aPwRules['banned'] as $sStr) { if (trim(strtolower($sPassword)) == strtolower($sStr)) { $this->setError('Password cannot be "' . $sStr . '"'); return false; } } } // -------------------------------------------------------------------------- // Password is valid, generate hash object return $this->generateHashObject($sPassword); }
php
public function generateHash($iGroupId, $sPassword) { if (empty($sPassword)) { $this->setError('No password to hash'); return false; } // -------------------------------------------------------------------------- // Check password satisfies password rules $aPwRules = $this->getRules($iGroupId); // Long enough? if (!empty($aPwRules['min']) && strlen($sPassword) < $aPwRules['min']) { $this->setError('Password is too short.'); return false; } // Too long? if (!empty($aPwRules['max']) && strlen($sPassword) > $aPwRules['max']) { $this->setError('Password is too long.'); return false; } // Satisfies all the requirements $aFailedRequirements = []; if (!empty($aPwRules['requirements'])) { foreach ($aPwRules['requirements'] as $sRequirement => $bValue) { switch ($sRequirement) { case 'symbol': if (!$this->strContainsFromCharset($sPassword, 'symbol')) { $aFailedRequirements[] = 'a symbol'; } break; case 'number': if (!$this->strContainsFromCharset($sPassword, 'number')) { $aFailedRequirements[] = 'a number'; } break; case 'lower_alpha': if (!$this->strContainsFromCharset($sPassword, 'lower_alpha')) { $aFailedRequirements[] = 'a lowercase letter'; } break; case 'upper_alpha': if (!$this->strContainsFromCharset($sPassword, 'upper_alpha')) { $aFailedRequirements[] = 'an uppercase letter'; } break; } } } if (!empty($aFailedRequirements)) { $sError = 'Password must contain ' . implode(', ', $aFailedRequirements) . '.'; $sError = str_lreplace(', ', ' and ', $sError); $this->setError($sError); return false; } // Not be a banned password? if (!empty($aPwRules['banned'])) { foreach ($aPwRules['banned'] as $sStr) { if (trim(strtolower($sPassword)) == strtolower($sStr)) { $this->setError('Password cannot be "' . $sStr . '"'); return false; } } } // -------------------------------------------------------------------------- // Password is valid, generate hash object return $this->generateHashObject($sPassword); }
[ "public", "function", "generateHash", "(", "$", "iGroupId", ",", "$", "sPassword", ")", "{", "if", "(", "empty", "(", "$", "sPassword", ")", ")", "{", "$", "this", "->", "setError", "(", "'No password to hash'", ")", ";", "return", "false", ";", "}", "...
Create a password hash, checks to ensure a password is strong enough according to the password rules defined by the app. @param integer $iGroupId The group who's rules to fetch @param string $sPassword The raw, unencrypted password @return mixed stdClass on success, false on failure
[ "Create", "a", "password", "hash", "checks", "to", "ensure", "a", "password", "is", "strong", "enough", "according", "to", "the", "password", "rules", "defined", "by", "the", "app", "." ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User/Password.php#L190-L267
train
nails/module-auth
src/Model/User/Password.php
Password.strContainsFromCharset
private function strContainsFromCharset($sStr, $sCharset) { if (empty($this->aCharset[$sCharset])) { return true; } return preg_match('/[' . preg_quote($this->aCharset[$sCharset], '/') . ']/', $sStr); }
php
private function strContainsFromCharset($sStr, $sCharset) { if (empty($this->aCharset[$sCharset])) { return true; } return preg_match('/[' . preg_quote($this->aCharset[$sCharset], '/') . ']/', $sStr); }
[ "private", "function", "strContainsFromCharset", "(", "$", "sStr", ",", "$", "sCharset", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "aCharset", "[", "$", "sCharset", "]", ")", ")", "{", "return", "true", ";", "}", "return", "preg_match", "("...
Determines whether a string contains any of the characters from a defined charset. @param string $sStr The string to analyse @param string $sCharset The charset to test against @return boolean
[ "Determines", "whether", "a", "string", "contains", "any", "of", "the", "characters", "from", "a", "defined", "charset", "." ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User/Password.php#L279-L286
train
nails/module-auth
src/Model/User/Password.php
Password.generateHashObject
public function generateHashObject($sPassword) { $sSalt = $this->salt(); // -------------------------------------------------------------------------- $oOut = new \stdClass(); $oOut->password = sha1(sha1($sPassword) . $sSalt); $oOut->password_md5 = md5($oOut->password); $oOut->salt = $sSalt; $oOut->engine = 'NAILS_1'; return $oOut; }
php
public function generateHashObject($sPassword) { $sSalt = $this->salt(); // -------------------------------------------------------------------------- $oOut = new \stdClass(); $oOut->password = sha1(sha1($sPassword) . $sSalt); $oOut->password_md5 = md5($oOut->password); $oOut->salt = $sSalt; $oOut->engine = 'NAILS_1'; return $oOut; }
[ "public", "function", "generateHashObject", "(", "$", "sPassword", ")", "{", "$", "sSalt", "=", "$", "this", "->", "salt", "(", ")", ";", "// --------------------------------------------------------------------------", "$", "oOut", "=", "new", "\\", "stdClass", "(",...
Generates a password hash, no strength checks @param string $sPassword The password to generate the hash for @return \stdClass
[ "Generates", "a", "password", "hash", "no", "strength", "checks" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User/Password.php#L309-L322
train
nails/module-auth
src/Model/User/Password.php
Password.generate
public function generate($iGroupId) { $aPwRules = $this->getRules($iGroupId); $aPwOut = []; // -------------------------------------------------------------------------- /** * We're generating a password, define all the charsets to use, at the very * ;east have the lower_alpha charset. */ $aCharsets = []; $aCharsets[] = $this->aCharset['lower_alpha']; if (!empty($aPwRules['requirements'])) { foreach ($aPwRules['requirements'] as $sRequirement => $bValue) { switch ($sRequirement) { case 'symbol': $aCharsets[] = $this->aCharset['symbol']; break; case 'number': $aCharsets[] = $this->aCharset['number']; break; case 'upper_alpha': $aCharsets[] = $this->aCharset['upper_alpha']; break; } } } // -------------------------------------------------------------------------- // Work out the min length $iMin = getFromArray('min', $aPwRules); if (empty($iMin)) { $iMin = 8; } // Work out the max length $iMax = getFromArray('max', $aPwRules); if (empty($iMax) || $iMin > $iMax) { $iMax = $iMin + count($aCharsets) * 2; } // -------------------------------------------------------------------------- // We now have a max_length and all our chars, generate password! $bPwValid = true; do { do { foreach ($aCharsets as $sCharset) { $sCharacter = rand(0, strlen($sCharset) - 1); $aPwOut[] = $sCharset[$sCharacter]; } } while (count($aPwOut) < $iMax); // Check password isn't a prohibited string if (!empty($aPwRules['banned'])) { foreach ($aPwRules['banned'] as $sString) { if (strtolower(implode('', $aPwOut)) == strtolower($sString)) { $bPwValid = false; break; } } } } while (!$bPwValid); // -------------------------------------------------------------------------- // Shuffle the string and return shuffle($aPwOut); return implode('', $aPwOut); }
php
public function generate($iGroupId) { $aPwRules = $this->getRules($iGroupId); $aPwOut = []; // -------------------------------------------------------------------------- /** * We're generating a password, define all the charsets to use, at the very * ;east have the lower_alpha charset. */ $aCharsets = []; $aCharsets[] = $this->aCharset['lower_alpha']; if (!empty($aPwRules['requirements'])) { foreach ($aPwRules['requirements'] as $sRequirement => $bValue) { switch ($sRequirement) { case 'symbol': $aCharsets[] = $this->aCharset['symbol']; break; case 'number': $aCharsets[] = $this->aCharset['number']; break; case 'upper_alpha': $aCharsets[] = $this->aCharset['upper_alpha']; break; } } } // -------------------------------------------------------------------------- // Work out the min length $iMin = getFromArray('min', $aPwRules); if (empty($iMin)) { $iMin = 8; } // Work out the max length $iMax = getFromArray('max', $aPwRules); if (empty($iMax) || $iMin > $iMax) { $iMax = $iMin + count($aCharsets) * 2; } // -------------------------------------------------------------------------- // We now have a max_length and all our chars, generate password! $bPwValid = true; do { do { foreach ($aCharsets as $sCharset) { $sCharacter = rand(0, strlen($sCharset) - 1); $aPwOut[] = $sCharset[$sCharacter]; } } while (count($aPwOut) < $iMax); // Check password isn't a prohibited string if (!empty($aPwRules['banned'])) { foreach ($aPwRules['banned'] as $sString) { if (strtolower(implode('', $aPwOut)) == strtolower($sString)) { $bPwValid = false; break; } } } } while (!$bPwValid); // -------------------------------------------------------------------------- // Shuffle the string and return shuffle($aPwOut); return implode('', $aPwOut); }
[ "public", "function", "generate", "(", "$", "iGroupId", ")", "{", "$", "aPwRules", "=", "$", "this", "->", "getRules", "(", "$", "iGroupId", ")", ";", "$", "aPwOut", "=", "[", "]", ";", "// --------------------------------------------------------------------------...
Generates a password which is sufficiently secure according to the app's password rules @param integer $iGroupId The group who's rules to fetch @return string
[ "Generates", "a", "password", "which", "is", "sufficiently", "secure", "according", "to", "the", "app", "s", "password", "rules" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User/Password.php#L333-L410
train
nails/module-auth
src/Model/User/Password.php
Password.getRules
protected function getRules($iGroupId) { $sCacheKey = 'password-rules-' . $iGroupId; $aCacheResult = $this->getCache($sCacheKey); if (!empty($aCacheResult)) { return $aCacheResult; } $oDb = Factory::service('Database'); $oDb->select('password_rules'); $oDb->where('id', $iGroupId); $oResult = $oDb->get(NAILS_DB_PREFIX . 'user_group'); if ($oResult->num_rows() === 0) { return []; } $oPwRules = json_decode($oResult->row()->password_rules); $aOut = []; $aOut['min'] = !empty($oPwRules->min) ? $oPwRules->min : null; $aOut['max'] = !empty($oPwRules->max) ? $oPwRules->max : null; $aOut['expiresAfter'] = !empty($oPwRules->expiresAfter) ? $oPwRules->expiresAfter : null; $aOut['requirements'] = !empty($oPwRules->requirements) ? $oPwRules->requirements : []; $aOut['banned'] = !empty($oPwRules->banned) ? $oPwRules->banned : []; $this->setCache($sCacheKey, $aOut); return $aOut; }
php
protected function getRules($iGroupId) { $sCacheKey = 'password-rules-' . $iGroupId; $aCacheResult = $this->getCache($sCacheKey); if (!empty($aCacheResult)) { return $aCacheResult; } $oDb = Factory::service('Database'); $oDb->select('password_rules'); $oDb->where('id', $iGroupId); $oResult = $oDb->get(NAILS_DB_PREFIX . 'user_group'); if ($oResult->num_rows() === 0) { return []; } $oPwRules = json_decode($oResult->row()->password_rules); $aOut = []; $aOut['min'] = !empty($oPwRules->min) ? $oPwRules->min : null; $aOut['max'] = !empty($oPwRules->max) ? $oPwRules->max : null; $aOut['expiresAfter'] = !empty($oPwRules->expiresAfter) ? $oPwRules->expiresAfter : null; $aOut['requirements'] = !empty($oPwRules->requirements) ? $oPwRules->requirements : []; $aOut['banned'] = !empty($oPwRules->banned) ? $oPwRules->banned : []; $this->setCache($sCacheKey, $aOut); return $aOut; }
[ "protected", "function", "getRules", "(", "$", "iGroupId", ")", "{", "$", "sCacheKey", "=", "'password-rules-'", ".", "$", "iGroupId", ";", "$", "aCacheResult", "=", "$", "this", "->", "getCache", "(", "$", "sCacheKey", ")", ";", "if", "(", "!", "empty",...
Returns the app's raw password rules as an array @param integer $iGroupId The group who's rules to fetch @return array
[ "Returns", "the", "app", "s", "raw", "password", "rules", "as", "an", "array" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User/Password.php#L421-L450
train
nails/module-auth
src/Model/User/Password.php
Password.getRulesAsString
public function getRulesAsString($iGroupId) { $aRules = $this->getRulesAsArray($iGroupId); if (empty($aRules)) { return ''; } $sStr = 'Passwords must ' . strtolower(implode(', ', $aRules)) . '.'; return str_lreplace(', ', ' and ', $sStr); }
php
public function getRulesAsString($iGroupId) { $aRules = $this->getRulesAsArray($iGroupId); if (empty($aRules)) { return ''; } $sStr = 'Passwords must ' . strtolower(implode(', ', $aRules)) . '.'; return str_lreplace(', ', ' and ', $sStr); }
[ "public", "function", "getRulesAsString", "(", "$", "iGroupId", ")", "{", "$", "aRules", "=", "$", "this", "->", "getRulesAsArray", "(", "$", "iGroupId", ")", ";", "if", "(", "empty", "(", "$", "aRules", ")", ")", "{", "return", "''", ";", "}", "$", ...
Returns the app's password rules as a formatted string @param integer $iGroupId The group who's rules to fetch @return string
[ "Returns", "the", "app", "s", "password", "rules", "as", "a", "formatted", "string" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User/Password.php#L461-L471
train
nails/module-auth
src/Model/User/Password.php
Password.getRulesAsArray
public function getRulesAsArray($iGroupId) { $aRules = $this->getRules($iGroupId); $aOut = []; if (!empty($aRules['min'])) { $aOut[] = 'Have at least ' . $aRules['min'] . ' characters'; } if (!empty($aRules['max'])) { $aOut[] = 'Have at most ' . $aRules['max'] . ' characters'; } if (!empty($aRules['requirements'])) { foreach ($aRules['requirements'] as $sKey => $bValue) { switch ($sKey) { case 'symbol': $aOut[] = 'Contain a symbol'; break; case 'lower_alpha': $aOut[] = 'Contain a lowercase letter'; break; case 'upper_alpha': $aOut[] = 'Contain an upper case letter'; break; case 'number': $aOut[] = 'Contain a number'; break; } } } return $aOut; }
php
public function getRulesAsArray($iGroupId) { $aRules = $this->getRules($iGroupId); $aOut = []; if (!empty($aRules['min'])) { $aOut[] = 'Have at least ' . $aRules['min'] . ' characters'; } if (!empty($aRules['max'])) { $aOut[] = 'Have at most ' . $aRules['max'] . ' characters'; } if (!empty($aRules['requirements'])) { foreach ($aRules['requirements'] as $sKey => $bValue) { switch ($sKey) { case 'symbol': $aOut[] = 'Contain a symbol'; break; case 'lower_alpha': $aOut[] = 'Contain a lowercase letter'; break; case 'upper_alpha': $aOut[] = 'Contain an upper case letter'; break; case 'number': $aOut[] = 'Contain a number'; break; } } } return $aOut; }
[ "public", "function", "getRulesAsArray", "(", "$", "iGroupId", ")", "{", "$", "aRules", "=", "$", "this", "->", "getRules", "(", "$", "iGroupId", ")", ";", "$", "aOut", "=", "[", "]", ";", "if", "(", "!", "empty", "(", "$", "aRules", "[", "'min'", ...
Returns the app's password rules as an array of human friendly strings @param integer $iGroupId The group who's rules to fetch @return array
[ "Returns", "the", "app", "s", "password", "rules", "as", "an", "array", "of", "human", "friendly", "strings" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User/Password.php#L482-L518
train
nails/module-auth
src/Model/User/Password.php
Password.setToken
public function setToken($sIdentifier) { if (empty($sIdentifier)) { return false; } // -------------------------------------------------------------------------- // Generate code $sKey = sha1(sha1($this->salt()) . $this->salt() . APP_PRIVATE_KEY); $iTtl = time() + 86400; // 24 hours. // -------------------------------------------------------------------------- // Update the user $oUserModel = Factory::model('User', 'nails/module-auth'); $oUser = $oUserModel->getByIdentifier($sIdentifier); if ($oUser) { $aData = [ 'forgotten_password_code' => $iTtl . ':' . $sKey, ]; return $oUserModel->update($oUser->id, $aData); } else { return false; } }
php
public function setToken($sIdentifier) { if (empty($sIdentifier)) { return false; } // -------------------------------------------------------------------------- // Generate code $sKey = sha1(sha1($this->salt()) . $this->salt() . APP_PRIVATE_KEY); $iTtl = time() + 86400; // 24 hours. // -------------------------------------------------------------------------- // Update the user $oUserModel = Factory::model('User', 'nails/module-auth'); $oUser = $oUserModel->getByIdentifier($sIdentifier); if ($oUser) { $aData = [ 'forgotten_password_code' => $iTtl . ':' . $sKey, ]; return $oUserModel->update($oUser->id, $aData); } else { return false; } }
[ "public", "function", "setToken", "(", "$", "sIdentifier", ")", "{", "if", "(", "empty", "(", "$", "sIdentifier", ")", ")", "{", "return", "false", ";", "}", "// --------------------------------------------------------------------------", "// Generate code", "$", "sK...
Sets a forgotten password token for a user @param string $sIdentifier The identifier to use for setting the token (set by APP_NATIVE_LOGIN_USING) @return boolean
[ "Sets", "a", "forgotten", "password", "token", "for", "a", "user" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User/Password.php#L543-L574
train
nails/module-auth
src/Model/User/Password.php
Password.validateToken
public function validateToken($sCode, $bGenerateNewPw) { if (empty($sCode)) { return false; } // -------------------------------------------------------------------------- $oDb = Factory::service('Database'); $oDb->select('id, group_id, forgotten_password_code'); $oDb->like('forgotten_password_code', ':' . $sCode, 'before'); $oResult = $oDb->get(NAILS_DB_PREFIX . 'user'); // -------------------------------------------------------------------------- if ($oResult->num_rows() != 1) { return false; } // -------------------------------------------------------------------------- $oUser = $oResult->row(); $aCode = explode(':', $oUser->forgotten_password_code); // -------------------------------------------------------------------------- // Check that the link is still valid if (time() > $aCode[0]) { return 'EXPIRED'; } else { // Valid hash and hasn't expired. $aOut = []; $aOut['user_id'] = $oUser->id; // Generate a new password? if ($bGenerateNewPw) { $aOut['password'] = $this->generate($oUser->group_id); if (empty($aOut['password'])) { // This should never happen, but just in case. return false; } $oHash = $this->generateHash($oUser->group_id, $aOut['password']); if (!$oHash) { // Again, this should never happen, but just in case. return false; } // -------------------------------------------------------------------------- $aData['password'] = $oHash->password; $aData['password_md5'] = $oHash->password_md5; $aData['password_engine'] = $oHash->engine; $aData['salt'] = $oHash->salt; $aData['temp_pw'] = true; $aData['forgotten_password_code'] = null; $oDb->where('forgotten_password_code', $oUser->forgotten_password_code); $oDb->set($aData); $oDb->update(NAILS_DB_PREFIX . 'user'); } } return $aOut; }
php
public function validateToken($sCode, $bGenerateNewPw) { if (empty($sCode)) { return false; } // -------------------------------------------------------------------------- $oDb = Factory::service('Database'); $oDb->select('id, group_id, forgotten_password_code'); $oDb->like('forgotten_password_code', ':' . $sCode, 'before'); $oResult = $oDb->get(NAILS_DB_PREFIX . 'user'); // -------------------------------------------------------------------------- if ($oResult->num_rows() != 1) { return false; } // -------------------------------------------------------------------------- $oUser = $oResult->row(); $aCode = explode(':', $oUser->forgotten_password_code); // -------------------------------------------------------------------------- // Check that the link is still valid if (time() > $aCode[0]) { return 'EXPIRED'; } else { // Valid hash and hasn't expired. $aOut = []; $aOut['user_id'] = $oUser->id; // Generate a new password? if ($bGenerateNewPw) { $aOut['password'] = $this->generate($oUser->group_id); if (empty($aOut['password'])) { // This should never happen, but just in case. return false; } $oHash = $this->generateHash($oUser->group_id, $aOut['password']); if (!$oHash) { // Again, this should never happen, but just in case. return false; } // -------------------------------------------------------------------------- $aData['password'] = $oHash->password; $aData['password_md5'] = $oHash->password_md5; $aData['password_engine'] = $oHash->engine; $aData['salt'] = $oHash->salt; $aData['temp_pw'] = true; $aData['forgotten_password_code'] = null; $oDb->where('forgotten_password_code', $oUser->forgotten_password_code); $oDb->set($aData); $oDb->update(NAILS_DB_PREFIX . 'user'); } } return $aOut; }
[ "public", "function", "validateToken", "(", "$", "sCode", ",", "$", "bGenerateNewPw", ")", "{", "if", "(", "empty", "(", "$", "sCode", ")", ")", "{", "return", "false", ";", "}", "// --------------------------------------------------------------------------", "$", ...
Validate a forgotten password code. @param string $sCode The token to validate @param string $bGenerateNewPw Whether or not to generate a new password (only if token is valid) @return boolean|array
[ "Validate", "a", "forgotten", "password", "code", "." ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User/Password.php#L586-L656
train
PitonCMS/Engine
app/Models/PageSettingMapper.php
PageSettingMapper.findPageSettings
public function findPageSettings($pageId) { $this->makeSelect(); $this->sql .= ' and page_id = ?'; $this->bindValues[] = $pageId; return $this->find(); }
php
public function findPageSettings($pageId) { $this->makeSelect(); $this->sql .= ' and page_id = ?'; $this->bindValues[] = $pageId; return $this->find(); }
[ "public", "function", "findPageSettings", "(", "$", "pageId", ")", "{", "$", "this", "->", "makeSelect", "(", ")", ";", "$", "this", "->", "sql", ".=", "' and page_id = ?'", ";", "$", "this", "->", "bindValues", "[", "]", "=", "$", "pageId", ";", "retu...
Find Page Settings Get page level settings @param int $pageId Page ID @return mixed Array | null
[ "Find", "Page", "Settings" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Models/PageSettingMapper.php#L32-L39
train
mirko-pagliai/me-cms
src/View/Helper/WidgetHelper.php
WidgetHelper.getAll
protected function getAll() { $widgets = getConfig('Widgets.general', []); if ($this->getView()->getRequest()->isUrl(['_name' => 'homepage']) && getConfig('Widgets.homepage')) { $widgets = getConfig('Widgets.homepage'); } return $widgets ? collection($widgets)->map(function ($args, $name) { if (is_string($name) && is_array($args)) { return [$name => $args]; } elseif (is_string($args)) { return [$args => []]; } list($name, $args) = [array_key_first($args), array_value_first($args)]; return is_int($name) && is_string($args) ? [$args => []] : [$name => $args]; })->toList() : []; }
php
protected function getAll() { $widgets = getConfig('Widgets.general', []); if ($this->getView()->getRequest()->isUrl(['_name' => 'homepage']) && getConfig('Widgets.homepage')) { $widgets = getConfig('Widgets.homepage'); } return $widgets ? collection($widgets)->map(function ($args, $name) { if (is_string($name) && is_array($args)) { return [$name => $args]; } elseif (is_string($args)) { return [$args => []]; } list($name, $args) = [array_key_first($args), array_value_first($args)]; return is_int($name) && is_string($args) ? [$args => []] : [$name => $args]; })->toList() : []; }
[ "protected", "function", "getAll", "(", ")", "{", "$", "widgets", "=", "getConfig", "(", "'Widgets.general'", ",", "[", "]", ")", ";", "if", "(", "$", "this", "->", "getView", "(", ")", "->", "getRequest", "(", ")", "->", "isUrl", "(", "[", "'_name'"...
Internal method to get all widgets @return array
[ "Internal", "method", "to", "get", "all", "widgets" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/View/Helper/WidgetHelper.php#L28-L47
train
mirko-pagliai/me-cms
src/View/Helper/WidgetHelper.php
WidgetHelper.all
public function all() { foreach ($this->getAll() as $widget) { foreach ($widget as $name => $args) { $widgets[] = $this->widget($name, $args); } } return empty($widgets) ? null : trim(implode(PHP_EOL, $widgets)); }
php
public function all() { foreach ($this->getAll() as $widget) { foreach ($widget as $name => $args) { $widgets[] = $this->widget($name, $args); } } return empty($widgets) ? null : trim(implode(PHP_EOL, $widgets)); }
[ "public", "function", "all", "(", ")", "{", "foreach", "(", "$", "this", "->", "getAll", "(", ")", "as", "$", "widget", ")", "{", "foreach", "(", "$", "widget", "as", "$", "name", "=>", "$", "args", ")", "{", "$", "widgets", "[", "]", "=", "$",...
Renders all widgets @return string|void Html code @uses getAll() @uses widget()
[ "Renders", "all", "widgets" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/View/Helper/WidgetHelper.php#L55-L64
train
mirko-pagliai/me-cms
src/View/Helper/WidgetHelper.php
WidgetHelper.widget
public function widget($name, array $data = [], array $options = []) { $parts = explode('::', $name); $name = $parts[0] . 'Widgets'; $name = empty($parts[1]) ? $name : sprintf('%s::%s', $name, $parts[1]); return $this->getView()->cell($name, $data, $options); }
php
public function widget($name, array $data = [], array $options = []) { $parts = explode('::', $name); $name = $parts[0] . 'Widgets'; $name = empty($parts[1]) ? $name : sprintf('%s::%s', $name, $parts[1]); return $this->getView()->cell($name, $data, $options); }
[ "public", "function", "widget", "(", "$", "name", ",", "array", "$", "data", "=", "[", "]", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "parts", "=", "explode", "(", "'::'", ",", "$", "name", ")", ";", "$", "name", "=", "$", "...
Returns a widget @param string $name Cell name @param array $data Additional arguments for cell method @param array $options Options for Cell's constructor @return Cake\View\Cell The cell instance
[ "Returns", "a", "widget" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/View/Helper/WidgetHelper.php#L73-L80
train
mirko-pagliai/me-cms
src/Controller/Admin/BackupsController.php
BackupsController.index
public function index() { $backups = collection($this->BackupManager->index()) ->map(function (Entity $backup) { return $backup->set('slug', urlencode($backup->filename)); }); $this->set(compact('backups')); }
php
public function index() { $backups = collection($this->BackupManager->index()) ->map(function (Entity $backup) { return $backup->set('slug', urlencode($backup->filename)); }); $this->set(compact('backups')); }
[ "public", "function", "index", "(", ")", "{", "$", "backups", "=", "collection", "(", "$", "this", "->", "BackupManager", "->", "index", "(", ")", ")", "->", "map", "(", "function", "(", "Entity", "$", "backup", ")", "{", "return", "$", "backup", "->...
Lists backup files @return void @uses DatabaseBackup\Utility\BackupManager::index()
[ "Lists", "backup", "files" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/Admin/BackupsController.php#L74-L82
train
mirko-pagliai/me-cms
src/Controller/Admin/BackupsController.php
BackupsController.add
public function add() { $backup = new BackupForm; if ($this->request->is('post')) { //Creates the backup if ($backup->execute($this->request->getData())) { $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); } $this->Flash->error(I18N_OPERATION_NOT_OK); } $this->set(compact('backup')); }
php
public function add() { $backup = new BackupForm; if ($this->request->is('post')) { //Creates the backup if ($backup->execute($this->request->getData())) { $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); } $this->Flash->error(I18N_OPERATION_NOT_OK); } $this->set(compact('backup')); }
[ "public", "function", "add", "(", ")", "{", "$", "backup", "=", "new", "BackupForm", ";", "if", "(", "$", "this", "->", "request", "->", "is", "(", "'post'", ")", ")", "{", "//Creates the backup", "if", "(", "$", "backup", "->", "execute", "(", "$", ...
Adds a backup file @return \Cake\Network\Response|null|void @see MeCms\Form\BackupForm @see MeCms\Form\BackupForm::execute()
[ "Adds", "a", "backup", "file" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/Admin/BackupsController.php#L90-L106
train
mirko-pagliai/me-cms
src/Controller/Admin/BackupsController.php
BackupsController.delete
public function delete($filename) { $this->request->allowMethod(['post', 'delete']); $this->BackupManager->delete($this->getFilename($filename)); $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); }
php
public function delete($filename) { $this->request->allowMethod(['post', 'delete']); $this->BackupManager->delete($this->getFilename($filename)); $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); }
[ "public", "function", "delete", "(", "$", "filename", ")", "{", "$", "this", "->", "request", "->", "allowMethod", "(", "[", "'post'", ",", "'delete'", "]", ")", ";", "$", "this", "->", "BackupManager", "->", "delete", "(", "$", "this", "->", "getFilen...
Deletes a backup file @param string $filename Backup filename @return \Cake\Network\Response|null @uses DatabaseBackup\Utility\BackupManager::delete() @uses getFilename()
[ "Deletes", "a", "backup", "file" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/Admin/BackupsController.php#L115-L122
train
mirko-pagliai/me-cms
src/Controller/Admin/BackupsController.php
BackupsController.deleteAll
public function deleteAll() { $this->request->allowMethod(['post', 'delete']); $this->BackupManager->deleteAll(); $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); }
php
public function deleteAll() { $this->request->allowMethod(['post', 'delete']); $this->BackupManager->deleteAll(); $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); }
[ "public", "function", "deleteAll", "(", ")", "{", "$", "this", "->", "request", "->", "allowMethod", "(", "[", "'post'", ",", "'delete'", "]", ")", ";", "$", "this", "->", "BackupManager", "->", "deleteAll", "(", ")", ";", "$", "this", "->", "Flash", ...
Deletes all backup files @return \Cake\Network\Response|null @uses DatabaseBackup\Utility\BackupManager::deleteAll()
[ "Deletes", "all", "backup", "files" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/Admin/BackupsController.php#L129-L136
train
mirko-pagliai/me-cms
src/Controller/Admin/BackupsController.php
BackupsController.restore
public function restore($filename) { //Imports and clears the cache (new BackupImport)->filename($this->getFilename($filename))->import(); Cache::clearAll(); $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); }
php
public function restore($filename) { //Imports and clears the cache (new BackupImport)->filename($this->getFilename($filename))->import(); Cache::clearAll(); $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); }
[ "public", "function", "restore", "(", "$", "filename", ")", "{", "//Imports and clears the cache", "(", "new", "BackupImport", ")", "->", "filename", "(", "$", "this", "->", "getFilename", "(", "$", "filename", ")", ")", "->", "import", "(", ")", ";", "Cac...
Restores a backup file @param string $filename Backup filename @return \Cake\Network\Response|null @uses DatabaseBackup\Utility\BackupImport::filename() @uses DatabaseBackup\Utility\BackupImport::import() @uses getFilename()
[ "Restores", "a", "backup", "file" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/Admin/BackupsController.php#L157-L166
train
mirko-pagliai/me-cms
src/Controller/Admin/BackupsController.php
BackupsController.send
public function send($filename) { $this->BackupManager->send($this->getFilename($filename), getConfigOrFail('email.webmaster')); $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); }
php
public function send($filename) { $this->BackupManager->send($this->getFilename($filename), getConfigOrFail('email.webmaster')); $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); }
[ "public", "function", "send", "(", "$", "filename", ")", "{", "$", "this", "->", "BackupManager", "->", "send", "(", "$", "this", "->", "getFilename", "(", "$", "filename", ")", ",", "getConfigOrFail", "(", "'email.webmaster'", ")", ")", ";", "$", "this"...
Sends a backup file via mail @param string $filename Backup filename @return \Cake\Network\Response|null @since 2.18.3 @uses DatabaseBackup\Utility\BackupManager::send() @uses getFilename()
[ "Sends", "a", "backup", "file", "via", "mail" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/Admin/BackupsController.php#L176-L182
train
excelwebzone/Omlex
lib/Omlex/OEmbed.php
OEmbed.setURL
public function setURL($url) { if (!$this->validateURL($url)) { throw new \InvalidArgumentException(sprintf('The URL "%s" is invalid.', $url)); } $this->url = $url; $this->endpoint = null; }
php
public function setURL($url) { if (!$this->validateURL($url)) { throw new \InvalidArgumentException(sprintf('The URL "%s" is invalid.', $url)); } $this->url = $url; $this->endpoint = null; }
[ "public", "function", "setURL", "(", "$", "url", ")", "{", "if", "(", "!", "$", "this", "->", "validateURL", "(", "$", "url", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'The URL \"%s\" is invalid.'", ",", "$", ...
Set a URL to fetch from @param string $url The URL to fetch from @throws \InvalidArgumentException If the URL is invalid
[ "Set", "a", "URL", "to", "fetch", "from" ]
88fa11bf02d1ab364fbc1cba208e82156d5ef784
https://github.com/excelwebzone/Omlex/blob/88fa11bf02d1ab364fbc1cba208e82156d5ef784/lib/Omlex/OEmbed.php#L187-L195
train
excelwebzone/Omlex
lib/Omlex/OEmbed.php
OEmbed.removeProvider
public function removeProvider(Provider $provider) { $index = array_search($provider, $this->providers); if ($index !== false) { unset($this->providers[$index]); } return $this; }
php
public function removeProvider(Provider $provider) { $index = array_search($provider, $this->providers); if ($index !== false) { unset($this->providers[$index]); } return $this; }
[ "public", "function", "removeProvider", "(", "Provider", "$", "provider", ")", "{", "$", "index", "=", "array_search", "(", "$", "provider", ",", "$", "this", "->", "providers", ")", ";", "if", "(", "$", "index", "!==", "false", ")", "{", "unset", "(",...
Removes the given provider from the registered providers array. @param Provider $provider the provider to remove. @return OEmbed
[ "Removes", "the", "given", "provider", "from", "the", "registered", "providers", "array", "." ]
88fa11bf02d1ab364fbc1cba208e82156d5ef784
https://github.com/excelwebzone/Omlex/blob/88fa11bf02d1ab364fbc1cba208e82156d5ef784/lib/Omlex/OEmbed.php#L225-L234
train
excelwebzone/Omlex
lib/Omlex/OEmbed.php
OEmbed.getObject
public function getObject(array $parameters = array()) { if ($this->url === null) { throw new \InvalidArgumentException('Missing URL.'); } if ($this->endpoint === null) { $this->endpoint = $this->discover($this->url); } $sign = '?'; if ($query = parse_url($this->endpoint, PHP_URL_QUERY)) { $sign = '&'; parse_str($query, $parameters); } if (!isset($parameters['url'])) { $parameters['url'] = $this->url; } if (!isset($parameters['format'])) { $parameters['format'] = 'json'; } $client = new Client( sprintf('%s%s%s', $this->endpoint, $sign, http_build_query($parameters)) ); $data = $client->send(); switch ($parameters['format']) { case 'json': $data = json_decode($data); if (!is_object($data)) { throw new \InvalidArgumentException('Could not parse JSON response.'); } break; case 'xml': libxml_use_internal_errors(true); $data = simplexml_load_string($data); if (!$data instanceof \SimpleXMLElement) { $errors = libxml_get_errors(); $error = array_shift($errors); libxml_clear_errors(); libxml_use_internal_errors(false); throw new \InvalidArgumentException($error->message, $error->code); } break; } return Object::factory($data); }
php
public function getObject(array $parameters = array()) { if ($this->url === null) { throw new \InvalidArgumentException('Missing URL.'); } if ($this->endpoint === null) { $this->endpoint = $this->discover($this->url); } $sign = '?'; if ($query = parse_url($this->endpoint, PHP_URL_QUERY)) { $sign = '&'; parse_str($query, $parameters); } if (!isset($parameters['url'])) { $parameters['url'] = $this->url; } if (!isset($parameters['format'])) { $parameters['format'] = 'json'; } $client = new Client( sprintf('%s%s%s', $this->endpoint, $sign, http_build_query($parameters)) ); $data = $client->send(); switch ($parameters['format']) { case 'json': $data = json_decode($data); if (!is_object($data)) { throw new \InvalidArgumentException('Could not parse JSON response.'); } break; case 'xml': libxml_use_internal_errors(true); $data = simplexml_load_string($data); if (!$data instanceof \SimpleXMLElement) { $errors = libxml_get_errors(); $error = array_shift($errors); libxml_clear_errors(); libxml_use_internal_errors(false); throw new \InvalidArgumentException($error->message, $error->code); } break; } return Object::factory($data); }
[ "public", "function", "getObject", "(", "array", "$", "parameters", "=", "array", "(", ")", ")", "{", "if", "(", "$", "this", "->", "url", "===", "null", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Missing URL.'", ")", ";", "}", ...
Get the oEmbed response @param array $params Optional parameters for @return object The oEmbed response as an object @throws \RuntimeException On HTTP errors @throws \InvalidArgumentException when result is not parsable
[ "Get", "the", "oEmbed", "response" ]
88fa11bf02d1ab364fbc1cba208e82156d5ef784
https://github.com/excelwebzone/Omlex/blob/88fa11bf02d1ab364fbc1cba208e82156d5ef784/lib/Omlex/OEmbed.php#L287-L341
train
excelwebzone/Omlex
lib/Omlex/OEmbed.php
OEmbed.discover
protected function discover($url) { $endpoint = $this->findEndpointFromProviders($url); // if no provider was found, try to discover the endpoint URL if ($this->discovery && !$endpoint) { $discover = new Discoverer(); $endpoint = $discover->getEndpointForUrl($url); } if (!$endpoint) { throw new \InvalidArgumentException('No oEmbed links found.'); } return $endpoint; }
php
protected function discover($url) { $endpoint = $this->findEndpointFromProviders($url); // if no provider was found, try to discover the endpoint URL if ($this->discovery && !$endpoint) { $discover = new Discoverer(); $endpoint = $discover->getEndpointForUrl($url); } if (!$endpoint) { throw new \InvalidArgumentException('No oEmbed links found.'); } return $endpoint; }
[ "protected", "function", "discover", "(", "$", "url", ")", "{", "$", "endpoint", "=", "$", "this", "->", "findEndpointFromProviders", "(", "$", "url", ")", ";", "// if no provider was found, try to discover the endpoint URL", "if", "(", "$", "this", "->", "discove...
Discover an oEmbed API endpoint @param string $url The URL to attempt to discover Omlex for @return string The oEmbed API endpoint discovered @throws \InvalidArgumentException If not $endpoint was found
[ "Discover", "an", "oEmbed", "API", "endpoint" ]
88fa11bf02d1ab364fbc1cba208e82156d5ef784
https://github.com/excelwebzone/Omlex/blob/88fa11bf02d1ab364fbc1cba208e82156d5ef784/lib/Omlex/OEmbed.php#L352-L367
train
excelwebzone/Omlex
lib/Omlex/OEmbed.php
OEmbed.findEndpointFromProviders
protected function findEndpointFromProviders($url) { // try to find a provider matching the supplied URL if no one has been supplied foreach ($this->providers as $provider) { /** @var $provider Provider */ if ($provider->match($url)) { return $provider->getEndpoint(); } } return null; }
php
protected function findEndpointFromProviders($url) { // try to find a provider matching the supplied URL if no one has been supplied foreach ($this->providers as $provider) { /** @var $provider Provider */ if ($provider->match($url)) { return $provider->getEndpoint(); } } return null; }
[ "protected", "function", "findEndpointFromProviders", "(", "$", "url", ")", "{", "// try to find a provider matching the supplied URL if no one has been supplied", "foreach", "(", "$", "this", "->", "providers", "as", "$", "provider", ")", "{", "/** @var $provider Provider */...
Finds an endpoint by looping trough the providers array and matching the url against the allowed schemes for each provider. @param string $url the url to find an endpoint for. @return string|null the endpoint if a match was found, null if no suitable provider was found.
[ "Finds", "an", "endpoint", "by", "looping", "trough", "the", "providers", "array", "and", "matching", "the", "url", "against", "the", "allowed", "schemes", "for", "each", "provider", "." ]
88fa11bf02d1ab364fbc1cba208e82156d5ef784
https://github.com/excelwebzone/Omlex/blob/88fa11bf02d1ab364fbc1cba208e82156d5ef784/lib/Omlex/OEmbed.php#L377-L388
train
mirko-pagliai/me-cms
src/Controller/PostsController.php
PostsController.indexByDate
public function indexByDate($date) { //Data can be passed as query string, from a widget if ($this->request->getQuery('q')) { return $this->redirect([$this->request->getQuery('q')]); } list($start, $end) = $this->getStartAndEndDate($date); $page = $this->request->getQuery('page', 1); //Sets the cache name $cache = sprintf('index_date_%s_limit_%s_page_%s', md5(serialize([$start, $end])), $this->paginate['limit'], $page); //Tries to get data from the cache list($posts, $paging) = array_values(Cache::readMany( [$cache, sprintf('%s_paging', $cache)], $this->Posts->getCacheName() )); //If the data are not available from the cache if (empty($posts) || empty($paging)) { $query = $this->Posts->find('active') ->find('forIndex') ->where([ sprintf('%s.created >=', $this->Posts->getAlias()) => $start, sprintf('%s.created <', $this->Posts->getAlias()) => $end, ]); $posts = $this->paginate($query); //Writes on cache Cache::writeMany([ $cache => $posts, sprintf('%s_paging', $cache) => $this->request->getParam('paging'), ], $this->Posts->getCacheName()); //Else, sets the paging parameter } else { $this->request = $this->request->withParam('paging', $paging); } $this->set(compact('date', 'posts', 'start')); }
php
public function indexByDate($date) { //Data can be passed as query string, from a widget if ($this->request->getQuery('q')) { return $this->redirect([$this->request->getQuery('q')]); } list($start, $end) = $this->getStartAndEndDate($date); $page = $this->request->getQuery('page', 1); //Sets the cache name $cache = sprintf('index_date_%s_limit_%s_page_%s', md5(serialize([$start, $end])), $this->paginate['limit'], $page); //Tries to get data from the cache list($posts, $paging) = array_values(Cache::readMany( [$cache, sprintf('%s_paging', $cache)], $this->Posts->getCacheName() )); //If the data are not available from the cache if (empty($posts) || empty($paging)) { $query = $this->Posts->find('active') ->find('forIndex') ->where([ sprintf('%s.created >=', $this->Posts->getAlias()) => $start, sprintf('%s.created <', $this->Posts->getAlias()) => $end, ]); $posts = $this->paginate($query); //Writes on cache Cache::writeMany([ $cache => $posts, sprintf('%s_paging', $cache) => $this->request->getParam('paging'), ], $this->Posts->getCacheName()); //Else, sets the paging parameter } else { $this->request = $this->request->withParam('paging', $paging); } $this->set(compact('date', 'posts', 'start')); }
[ "public", "function", "indexByDate", "(", "$", "date", ")", "{", "//Data can be passed as query string, from a widget", "if", "(", "$", "this", "->", "request", "->", "getQuery", "(", "'q'", ")", ")", "{", "return", "$", "this", "->", "redirect", "(", "[", "...
Lists posts for a specific date. Month and day are optional and you can also use special keywords `today` or `yesterday`. Examples: <pre>/posts/2016/06/11</pre> <pre>/posts/2016/06</pre> <pre>/posts/2016</pre> <pre>/posts/today</pre> <pre>/posts/yesterday</pre> @param string $date Date as `today`, `yesterday`, `YYYY/MM/dd`, `YYYY/MM` or `YYYY` @return \Cake\Network\Response|null|void @use \MeCms\Controller\Traits\GetStartAndEndDateTrait\getStartAndEndDate()
[ "Lists", "posts", "for", "a", "specific", "date", "." ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/PostsController.php#L97-L138
train
mirko-pagliai/me-cms
src/Controller/PostsController.php
PostsController.rss
public function rss() { //This method works only for RSS is_true_or_fail($this->RequestHandler->prefers('rss'), ForbiddenException::class); $posts = $this->Posts->find('active') ->select(['title', 'preview', 'slug', 'text', 'created']) ->limit(getConfigOrFail('default.records_for_rss')) ->order([sprintf('%s.created', $this->Posts->getAlias()) => 'DESC']) ->cache('rss', $this->Posts->getCacheName()); $this->set(compact('posts')); }
php
public function rss() { //This method works only for RSS is_true_or_fail($this->RequestHandler->prefers('rss'), ForbiddenException::class); $posts = $this->Posts->find('active') ->select(['title', 'preview', 'slug', 'text', 'created']) ->limit(getConfigOrFail('default.records_for_rss')) ->order([sprintf('%s.created', $this->Posts->getAlias()) => 'DESC']) ->cache('rss', $this->Posts->getCacheName()); $this->set(compact('posts')); }
[ "public", "function", "rss", "(", ")", "{", "//This method works only for RSS", "is_true_or_fail", "(", "$", "this", "->", "RequestHandler", "->", "prefers", "(", "'rss'", ")", ",", "ForbiddenException", "::", "class", ")", ";", "$", "posts", "=", "$", "this",...
Lists posts as RSS @return void @throws ForbiddenException
[ "Lists", "posts", "as", "RSS" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/PostsController.php#L145-L157
train
mirko-pagliai/me-cms
src/Controller/PostsController.php
PostsController.preview
public function preview($slug = null) { $post = $this->Posts->findPendingBySlug($slug) ->find('forIndex') ->firstOrFail(); $this->set(compact('post')); //Gets related posts if (getConfig('post.related')) { $related = $this->Posts->getRelated($post, getConfigOrFail('post.related.limit'), getConfig('post.related.images')); $this->set(compact('related')); } $this->render('view'); }
php
public function preview($slug = null) { $post = $this->Posts->findPendingBySlug($slug) ->find('forIndex') ->firstOrFail(); $this->set(compact('post')); //Gets related posts if (getConfig('post.related')) { $related = $this->Posts->getRelated($post, getConfigOrFail('post.related.limit'), getConfig('post.related.images')); $this->set(compact('related')); } $this->render('view'); }
[ "public", "function", "preview", "(", "$", "slug", "=", "null", ")", "{", "$", "post", "=", "$", "this", "->", "Posts", "->", "findPendingBySlug", "(", "$", "slug", ")", "->", "find", "(", "'forIndex'", ")", "->", "firstOrFail", "(", ")", ";", "$", ...
Preview for posts. It uses the `view` template. @param string $slug Post slug @return void @uses MeCms\Model\Table\PostsTable::getRelated()
[ "Preview", "for", "posts", ".", "It", "uses", "the", "view", "template", "." ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/PostsController.php#L258-L273
train
mirko-pagliai/me-cms
src/Model/Table/Traits/GetPreviewsFromTextTrait.php
GetPreviewsFromTextTrait.extractImages
protected function extractImages($html) { if (empty($html)) { return []; } $libxmlPreviousState = libxml_use_internal_errors(true); $dom = new DOMDocument; $dom->loadHTML($html); libxml_clear_errors(); libxml_use_internal_errors($libxmlPreviousState); $images = []; //Gets all image tags foreach ($dom->getElementsByTagName('img') as $item) { $src = $item->getAttribute('src'); if (in_array(strtolower(pathinfo($src, PATHINFO_EXTENSION)), ['gif', 'jpg', 'jpeg', 'png'])) { $images[] = $src; } } //Gets all Youtube videos if (preg_match_all('/\[youtube](.+?)\[\/youtube]/', $html, $items)) { foreach ($items[1] as $item) { $images[] = Youtube::getPreview($item); } } return $images; }
php
protected function extractImages($html) { if (empty($html)) { return []; } $libxmlPreviousState = libxml_use_internal_errors(true); $dom = new DOMDocument; $dom->loadHTML($html); libxml_clear_errors(); libxml_use_internal_errors($libxmlPreviousState); $images = []; //Gets all image tags foreach ($dom->getElementsByTagName('img') as $item) { $src = $item->getAttribute('src'); if (in_array(strtolower(pathinfo($src, PATHINFO_EXTENSION)), ['gif', 'jpg', 'jpeg', 'png'])) { $images[] = $src; } } //Gets all Youtube videos if (preg_match_all('/\[youtube](.+?)\[\/youtube]/', $html, $items)) { foreach ($items[1] as $item) { $images[] = Youtube::getPreview($item); } } return $images; }
[ "protected", "function", "extractImages", "(", "$", "html", ")", "{", "if", "(", "empty", "(", "$", "html", ")", ")", "{", "return", "[", "]", ";", "}", "$", "libxmlPreviousState", "=", "libxml_use_internal_errors", "(", "true", ")", ";", "$", "dom", "...
Internal method to extract all images from an html string, including the previews of Youtube videos @param string $html Html string @return array @since 2.23.0
[ "Internal", "method", "to", "extract", "all", "images", "from", "an", "html", "string", "including", "the", "previews", "of", "Youtube", "videos" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Model/Table/Traits/GetPreviewsFromTextTrait.php#L35-L68
train
mirko-pagliai/me-cms
src/Model/Table/Traits/GetPreviewsFromTextTrait.php
GetPreviewsFromTextTrait.getPreviews
public function getPreviews($html) { $images = array_map(function ($url) { if ($url && !is_url($url)) { //If is relative path $url = Folder::isAbsolute($url) ? $url : WWW_ROOT . 'img' . DS . $url; if (!file_exists($url)) { return false; } $thumber = new ThumbCreator($url); $thumber->resize(1200, 1200)->save(['format' => 'jpg']); $url = $thumber->getUrl(); } list($width, $height) = $this->getPreviewSize($url); return new Entity(compact('url', 'width', 'height')); }, $this->extractImages($html)); return array_filter($images); }
php
public function getPreviews($html) { $images = array_map(function ($url) { if ($url && !is_url($url)) { //If is relative path $url = Folder::isAbsolute($url) ? $url : WWW_ROOT . 'img' . DS . $url; if (!file_exists($url)) { return false; } $thumber = new ThumbCreator($url); $thumber->resize(1200, 1200)->save(['format' => 'jpg']); $url = $thumber->getUrl(); } list($width, $height) = $this->getPreviewSize($url); return new Entity(compact('url', 'width', 'height')); }, $this->extractImages($html)); return array_filter($images); }
[ "public", "function", "getPreviews", "(", "$", "html", ")", "{", "$", "images", "=", "array_map", "(", "function", "(", "$", "url", ")", "{", "if", "(", "$", "url", "&&", "!", "is_url", "(", "$", "url", ")", ")", "{", "//If is relative path", "$", ...
Gets all the available images from an html string, including the previews of Youtube videos, and returns an array of `Entity` @param string $html Html string @return array Array of entities. Each `Entity` has `url`, `width` and `height` properties @since 2.23.0 @uses extractImages() @uses getPreviewSize()
[ "Gets", "all", "the", "available", "images", "from", "an", "html", "string", "including", "the", "previews", "of", "Youtube", "videos", "and", "returns", "an", "array", "of", "Entity" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Model/Table/Traits/GetPreviewsFromTextTrait.php#L90-L112
train
GigaSavvy/liteview-api
src/Liteview/Connection.php
Connection.get
public function get($resource, $body = null, $params = []) { return $this->send($this->prepare('GET', $resource, $body, $params)); }
php
public function get($resource, $body = null, $params = []) { return $this->send($this->prepare('GET', $resource, $body, $params)); }
[ "public", "function", "get", "(", "$", "resource", ",", "$", "body", "=", "null", ",", "$", "params", "=", "[", "]", ")", "{", "return", "$", "this", "->", "send", "(", "$", "this", "->", "prepare", "(", "'GET'", ",", "$", "resource", ",", "$", ...
Perform a GET request for the specified resource. @param string $resource @param string $body @return \GuzzleHttp\Psr7\Response
[ "Perform", "a", "GET", "request", "for", "the", "specified", "resource", "." ]
98ed73599f9c879f85291eda8bef0d151738d463
https://github.com/GigaSavvy/liteview-api/blob/98ed73599f9c879f85291eda8bef0d151738d463/src/Liteview/Connection.php#L89-L92
train
GigaSavvy/liteview-api
src/Liteview/Connection.php
Connection.post
public function post($resource, $body = null, $params = []) { return $this->send($this->prepare('POST', $resource, $body, $params)); }
php
public function post($resource, $body = null, $params = []) { return $this->send($this->prepare('POST', $resource, $body, $params)); }
[ "public", "function", "post", "(", "$", "resource", ",", "$", "body", "=", "null", ",", "$", "params", "=", "[", "]", ")", "{", "return", "$", "this", "->", "send", "(", "$", "this", "->", "prepare", "(", "'POST'", ",", "$", "resource", ",", "$",...
Perform a POST request on the specified resource. @param string $resource @param string $body @return \GuzzleHttp\Psr7\Response
[ "Perform", "a", "POST", "request", "on", "the", "specified", "resource", "." ]
98ed73599f9c879f85291eda8bef0d151738d463
https://github.com/GigaSavvy/liteview-api/blob/98ed73599f9c879f85291eda8bef0d151738d463/src/Liteview/Connection.php#L101-L104
train
GigaSavvy/liteview-api
src/Liteview/Connection.php
Connection.send
protected function send(Request $request) { try { $response = $this->client->send($request); } catch (ClientException $e) { $response = $e->getResponse(); } catch (ServerException $e) { $response = $e->getResponse(); } return $response; }
php
protected function send(Request $request) { try { $response = $this->client->send($request); } catch (ClientException $e) { $response = $e->getResponse(); } catch (ServerException $e) { $response = $e->getResponse(); } return $response; }
[ "protected", "function", "send", "(", "Request", "$", "request", ")", "{", "try", "{", "$", "response", "=", "$", "this", "->", "client", "->", "send", "(", "$", "request", ")", ";", "}", "catch", "(", "ClientException", "$", "e", ")", "{", "$", "r...
Perform the given request and return the response. @param \GuzzleHttp\Psr7\Request $request @return \GuzzleHttp\Psr7\Response
[ "Perform", "the", "given", "request", "and", "return", "the", "response", "." ]
98ed73599f9c879f85291eda8bef0d151738d463
https://github.com/GigaSavvy/liteview-api/blob/98ed73599f9c879f85291eda8bef0d151738d463/src/Liteview/Connection.php#L112-L123
train
GigaSavvy/liteview-api
src/Liteview/Connection.php
Connection.prepare
protected function prepare($method, $resource, $body, $params) { // Append the username parameter to the end of every resource URI. $resource = trim($resource, '/').'/'.$this->username; foreach ($params as $param) { $resource .= '/'.$param; } return new Request($method, $resource, [], $body); }
php
protected function prepare($method, $resource, $body, $params) { // Append the username parameter to the end of every resource URI. $resource = trim($resource, '/').'/'.$this->username; foreach ($params as $param) { $resource .= '/'.$param; } return new Request($method, $resource, [], $body); }
[ "protected", "function", "prepare", "(", "$", "method", ",", "$", "resource", ",", "$", "body", ",", "$", "params", ")", "{", "// Append the username parameter to the end of every resource URI.", "$", "resource", "=", "trim", "(", "$", "resource", ",", "'/'", ")...
Prepare a request for sending. @param string $method @param string $resource @param string $body @return \GuzzleHttp\Psr7\Request
[ "Prepare", "a", "request", "for", "sending", "." ]
98ed73599f9c879f85291eda8bef0d151738d463
https://github.com/GigaSavvy/liteview-api/blob/98ed73599f9c879f85291eda8bef0d151738d463/src/Liteview/Connection.php#L133-L143
train
s9e/RegexpBuilder
src/Output/PrintableAscii.php
PrintableAscii.escapeControlCode
protected function escapeControlCode($cp) { $table = [9 => '\\t', 10 => '\\n', 13 => '\\r']; return (isset($table[$cp])) ? $table[$cp] : $this->escapeAscii($cp); }
php
protected function escapeControlCode($cp) { $table = [9 => '\\t', 10 => '\\n', 13 => '\\r']; return (isset($table[$cp])) ? $table[$cp] : $this->escapeAscii($cp); }
[ "protected", "function", "escapeControlCode", "(", "$", "cp", ")", "{", "$", "table", "=", "[", "9", "=>", "'\\\\t'", ",", "10", "=>", "'\\\\n'", ",", "13", "=>", "'\\\\r'", "]", ";", "return", "(", "isset", "(", "$", "table", "[", "$", "cp", "]", ...
Escape given control code @param integer $cp @return string
[ "Escape", "given", "control", "code" ]
59d0167a909659d718f53964f7653d2c83a5f8fe
https://github.com/s9e/RegexpBuilder/blob/59d0167a909659d718f53964f7653d2c83a5f8fe/src/Output/PrintableAscii.php#L42-L47
train
drdplusinfo/health
DrdPlus/Health/Afflictions/Effects/BleedingEffect.php
BleedingEffect.bleed
public function bleed(Bleeding $bleeding, WoundsTable $woundsTable, WoundBoundary $woundBoundary): Wound { // see PPH page 78 right column, Bleeding $effectSize = $bleeding->getAfflictionSize()->getValue() - 6; $woundsFromTable = $woundsTable->toWounds(new WoundsBonus($effectSize, $woundsTable)); $woundSize = new WoundSize($woundsFromTable->getValue()); $woundCausedBleeding = $bleeding->getSeriousWound(); return $woundCausedBleeding->getHealth()->addWound( $woundSize, $woundCausedBleeding->getWoundOriginCode(), $woundBoundary ); }
php
public function bleed(Bleeding $bleeding, WoundsTable $woundsTable, WoundBoundary $woundBoundary): Wound { // see PPH page 78 right column, Bleeding $effectSize = $bleeding->getAfflictionSize()->getValue() - 6; $woundsFromTable = $woundsTable->toWounds(new WoundsBonus($effectSize, $woundsTable)); $woundSize = new WoundSize($woundsFromTable->getValue()); $woundCausedBleeding = $bleeding->getSeriousWound(); return $woundCausedBleeding->getHealth()->addWound( $woundSize, $woundCausedBleeding->getWoundOriginCode(), $woundBoundary ); }
[ "public", "function", "bleed", "(", "Bleeding", "$", "bleeding", ",", "WoundsTable", "$", "woundsTable", ",", "WoundBoundary", "$", "woundBoundary", ")", ":", "Wound", "{", "// see PPH page 78 right column, Bleeding", "$", "effectSize", "=", "$", "bleeding", "->", ...
Creates new wound right in the health of origin wound @param Bleeding $bleeding @param WoundsTable $woundsTable @param WoundBoundary $woundBoundary @return SeriousWound|OrdinaryWound|Wound @throws \DrdPlus\Health\Exceptions\NeedsToRollAgainstMalusFromWoundsFirst
[ "Creates", "new", "wound", "right", "in", "the", "health", "of", "origin", "wound" ]
f8dee76ddf651367afbbaab6f30376fc80f97001
https://github.com/drdplusinfo/health/blob/f8dee76ddf651367afbbaab6f30376fc80f97001/DrdPlus/Health/Afflictions/Effects/BleedingEffect.php#L42-L55
train
au-research/ANDS-DOI-Service
src/Repository/ClientRepository.php
ClientRepository.create
public function create($params) { $client = new Client; $client->fill($params); $client->save(); // update datacite_symbol $this->generateDataciteSymbol($client); return $client; }
php
public function create($params) { $client = new Client; $client->fill($params); $client->save(); // update datacite_symbol $this->generateDataciteSymbol($client); return $client; }
[ "public", "function", "create", "(", "$", "params", ")", "{", "$", "client", "=", "new", "Client", ";", "$", "client", "->", "fill", "(", "$", "params", ")", ";", "$", "client", "->", "save", "(", ")", ";", "// update datacite_symbol", "$", "this", "...
Create a client @param $params @return Client
[ "Create", "a", "client" ]
c8e2cc98eca23a0c550af9a45b5c5dee230da1c9
https://github.com/au-research/ANDS-DOI-Service/blob/c8e2cc98eca23a0c550af9a45b5c5dee230da1c9/src/Repository/ClientRepository.php#L22-L32
train
au-research/ANDS-DOI-Service
src/Repository/ClientRepository.php
ClientRepository.generateDataciteSymbol
public function generateDataciteSymbol(Client $client) { $prefix = "ANDS."; $id = $client->client_id; // prefix before the if ($id < 100) { $prefix .= "CENTRE"; } if ($id < 10) { $prefix .= "-"; } elseif ($id >= 100) { // prefix before the ID (new form) $prefix .= "C"; } $client->datacite_symbol = $prefix . $id; $client->save(); return $client; }
php
public function generateDataciteSymbol(Client $client) { $prefix = "ANDS."; $id = $client->client_id; // prefix before the if ($id < 100) { $prefix .= "CENTRE"; } if ($id < 10) { $prefix .= "-"; } elseif ($id >= 100) { // prefix before the ID (new form) $prefix .= "C"; } $client->datacite_symbol = $prefix . $id; $client->save(); return $client; }
[ "public", "function", "generateDataciteSymbol", "(", "Client", "$", "client", ")", "{", "$", "prefix", "=", "\"ANDS.\"", ";", "$", "id", "=", "$", "client", "->", "client_id", ";", "// prefix before the", "if", "(", "$", "id", "<", "100", ")", "{", "$", ...
Generate a datacite symbol for the given client ANDS.CENTRE-1 ANDS.CENTRE-9 ANDS.CENTRE10 ANDS.CENTRE99 ANDS.C100 ANDS.C102 @param Client $client @return Client
[ "Generate", "a", "datacite", "symbol", "for", "the", "given", "client", "ANDS", ".", "CENTRE", "-", "1", "ANDS", ".", "CENTRE", "-", "9", "ANDS", ".", "CENTRE10", "ANDS", ".", "CENTRE99", "ANDS", ".", "C100", "ANDS", ".", "C102" ]
c8e2cc98eca23a0c550af9a45b5c5dee230da1c9
https://github.com/au-research/ANDS-DOI-Service/blob/c8e2cc98eca23a0c550af9a45b5c5dee230da1c9/src/Repository/ClientRepository.php#L71-L92
train
froq/froq-http
src/Request.php
Request.postParam
public function postParam(string $name, $valueDefault = null) { return $this->params->post($name, $valueDefault); }
php
public function postParam(string $name, $valueDefault = null) { return $this->params->post($name, $valueDefault); }
[ "public", "function", "postParam", "(", "string", "$", "name", ",", "$", "valueDefault", "=", "null", ")", "{", "return", "$", "this", "->", "params", "->", "post", "(", "$", "name", ",", "$", "valueDefault", ")", ";", "}" ]
Post param. @param string $name @param any $valueDefault @return any
[ "Post", "param", "." ]
067207669b5054b867b7df2b5557acf1d43f572a
https://github.com/froq/froq-http/blob/067207669b5054b867b7df2b5557acf1d43f572a/src/Request.php#L253-L256
train
froq/froq-http
src/Request.php
Request.cookieParam
public function cookieParam(string $name, $valueDefault = null) { return $this->params->cookie($name, $valueDefault); }
php
public function cookieParam(string $name, $valueDefault = null) { return $this->params->cookie($name, $valueDefault); }
[ "public", "function", "cookieParam", "(", "string", "$", "name", ",", "$", "valueDefault", "=", "null", ")", "{", "return", "$", "this", "->", "params", "->", "cookie", "(", "$", "name", ",", "$", "valueDefault", ")", ";", "}" ]
Cookie param. @param string $name @param any $valueDefault @return any
[ "Cookie", "param", "." ]
067207669b5054b867b7df2b5557acf1d43f572a
https://github.com/froq/froq-http/blob/067207669b5054b867b7df2b5557acf1d43f572a/src/Request.php#L273-L276
train
froq/froq-http
src/Request.php
Request.loadHttpHeaders
private function loadHttpHeaders(): array { if (function_exists('getallheaders')) { $headers = getallheaders(); // apache } else { $headers = []; foreach ($_SERVER as $key => $value) { if (stripos(strval($key), 'HTTP_') === 0) { $headers[ // normalize key implode('-', array_map('ucwords', explode('_', strtolower(substr($key, 5))))) ] = $value; } } } // content issues if (isset($_SERVER['CONTENT_TYPE'])) { $headers['Content-Type'] = $_SERVER['CONTENT_TYPE']; } if (isset($_SERVER['CONTENT_LENGTH'])) { $headers['Content-Length'] = $_SERVER['CONTENT_LENGTH']; } if (isset($_SERVER['CONTENT_MD5'])) { $headers['Content-MD5'] = $_SERVER['CONTENT_MD5']; } // authorization issues if (!isset($headers['Authorization'])) { if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) { $headers['Authorization'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION']; } elseif (isset($_SERVER['PHP_AUTH_DIGEST'])) { $headers['Authorization'] = $_SERVER['PHP_AUTH_DIGEST']; } elseif (isset($_SERVER['PHP_AUTH_USER'])) { $headers['Authorization'] = 'Basic ' . base64_encode($_SERVER['PHP_AUTH_USER'] .':'. ($_SERVER['PHP_AUTH_PW'] ?? '')); } } return $headers; }
php
private function loadHttpHeaders(): array { if (function_exists('getallheaders')) { $headers = getallheaders(); // apache } else { $headers = []; foreach ($_SERVER as $key => $value) { if (stripos(strval($key), 'HTTP_') === 0) { $headers[ // normalize key implode('-', array_map('ucwords', explode('_', strtolower(substr($key, 5))))) ] = $value; } } } // content issues if (isset($_SERVER['CONTENT_TYPE'])) { $headers['Content-Type'] = $_SERVER['CONTENT_TYPE']; } if (isset($_SERVER['CONTENT_LENGTH'])) { $headers['Content-Length'] = $_SERVER['CONTENT_LENGTH']; } if (isset($_SERVER['CONTENT_MD5'])) { $headers['Content-MD5'] = $_SERVER['CONTENT_MD5']; } // authorization issues if (!isset($headers['Authorization'])) { if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) { $headers['Authorization'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION']; } elseif (isset($_SERVER['PHP_AUTH_DIGEST'])) { $headers['Authorization'] = $_SERVER['PHP_AUTH_DIGEST']; } elseif (isset($_SERVER['PHP_AUTH_USER'])) { $headers['Authorization'] = 'Basic ' . base64_encode($_SERVER['PHP_AUTH_USER'] .':'. ($_SERVER['PHP_AUTH_PW'] ?? '')); } } return $headers; }
[ "private", "function", "loadHttpHeaders", "(", ")", ":", "array", "{", "if", "(", "function_exists", "(", "'getallheaders'", ")", ")", "{", "$", "headers", "=", "getallheaders", "(", ")", ";", "// apache", "}", "else", "{", "$", "headers", "=", "[", "]",...
Load http headers. @return array
[ "Load", "http", "headers", "." ]
067207669b5054b867b7df2b5557acf1d43f572a
https://github.com/froq/froq-http/blob/067207669b5054b867b7df2b5557acf1d43f572a/src/Request.php#L291-L331
train
au-research/ANDS-DOI-Service
src/Validator/IPValidator.php
IPValidator.validate
public static function validate($ip, $ip_range) { // first lets get the lists of ip address or ranges separated by commas $ip_ranges = explode(',', $ip_range); foreach ($ip_ranges as $ip_range) { $ip_range = explode('-', $ip_range); if (sizeof($ip_range) > 1) { $target_ip = ip2long($ip); // If exactly 2, then treat the values as the upper and lower bounds of a range for checking // AND the target_ip is valid if (count($ip_range) == 2 && $target_ip) { // convert dotted quad notation to long for numeric comparison $lower_bound = ip2long($ip_range[0]); $upper_bound = ip2long($ip_range[1]); // If the target_ip is valid if ($target_ip >= $lower_bound && $target_ip <= $upper_bound) { return true; } } } else { if (self::ip_match($ip, $ip_range[0])) { return true; } } } return false; }
php
public static function validate($ip, $ip_range) { // first lets get the lists of ip address or ranges separated by commas $ip_ranges = explode(',', $ip_range); foreach ($ip_ranges as $ip_range) { $ip_range = explode('-', $ip_range); if (sizeof($ip_range) > 1) { $target_ip = ip2long($ip); // If exactly 2, then treat the values as the upper and lower bounds of a range for checking // AND the target_ip is valid if (count($ip_range) == 2 && $target_ip) { // convert dotted quad notation to long for numeric comparison $lower_bound = ip2long($ip_range[0]); $upper_bound = ip2long($ip_range[1]); // If the target_ip is valid if ($target_ip >= $lower_bound && $target_ip <= $upper_bound) { return true; } } } else { if (self::ip_match($ip, $ip_range[0])) { return true; } } } return false; }
[ "public", "static", "function", "validate", "(", "$", "ip", ",", "$", "ip_range", ")", "{", "// first lets get the lists of ip address or ranges separated by commas", "$", "ip_ranges", "=", "explode", "(", "','", ",", "$", "ip_range", ")", ";", "foreach", "(", "$"...
Test a string free form IP against a range @param string $ip the ip address to test on @param string $ip_range the ip address to match on / or a comma separated list of ips to match on @return bool returns true if the ip is found in some manner that match the ip range
[ "Test", "a", "string", "free", "form", "IP", "against", "a", "range" ]
c8e2cc98eca23a0c550af9a45b5c5dee230da1c9
https://github.com/au-research/ANDS-DOI-Service/blob/c8e2cc98eca23a0c550af9a45b5c5dee230da1c9/src/Validator/IPValidator.php#L13-L41
train
au-research/ANDS-DOI-Service
src/Validator/IPValidator.php
IPValidator.ip_match
public static function ip_match($ip, $match) { if (ip2long($match)) {//is an actual IP if ($ip == $match) { return true; } } else {//is something weird if (strpos($match, '/')) {//if it's a cidr notation if (self::cidr_match($ip, $match)) { return true; } } else {//is a random string (let's say a host name) $match = gethostbyname($match); if ($ip == $match) { return true; } else { return false; } } } return false; }
php
public static function ip_match($ip, $match) { if (ip2long($match)) {//is an actual IP if ($ip == $match) { return true; } } else {//is something weird if (strpos($match, '/')) {//if it's a cidr notation if (self::cidr_match($ip, $match)) { return true; } } else {//is a random string (let's say a host name) $match = gethostbyname($match); if ($ip == $match) { return true; } else { return false; } } } return false; }
[ "public", "static", "function", "ip_match", "(", "$", "ip", ",", "$", "match", ")", "{", "if", "(", "ip2long", "(", "$", "match", ")", ")", "{", "//is an actual IP", "if", "(", "$", "ip", "==", "$", "match", ")", "{", "return", "true", ";", "}", ...
a helper function for test_ip @param string $ip the ip address of most any form to test @param string $match the ip to perform a matching truth test @return bool return true/false depends on if the first ip match the second ip
[ "a", "helper", "function", "for", "test_ip" ]
c8e2cc98eca23a0c550af9a45b5c5dee230da1c9
https://github.com/au-research/ANDS-DOI-Service/blob/c8e2cc98eca23a0c550af9a45b5c5dee230da1c9/src/Validator/IPValidator.php#L49-L70
train
drdplusinfo/tables
DrdPlus/Tables/Measurements/Weight/WeightTable.php
WeightTable.getMalusFromLoad
public function getMalusFromLoad(Strength $strength, Weight $cargoWeight): int { $requiredStrength = $cargoWeight->getBonus()->getValue(); $missingStrength = $requiredStrength - $strength->getValue(); $malus = -SumAndRound::half($missingStrength); // see PPH page 113, right column if ($malus > 0) { return 0; } return $malus; }
php
public function getMalusFromLoad(Strength $strength, Weight $cargoWeight): int { $requiredStrength = $cargoWeight->getBonus()->getValue(); $missingStrength = $requiredStrength - $strength->getValue(); $malus = -SumAndRound::half($missingStrength); // see PPH page 113, right column if ($malus > 0) { return 0; } return $malus; }
[ "public", "function", "getMalusFromLoad", "(", "Strength", "$", "strength", ",", "Weight", "$", "cargoWeight", ")", ":", "int", "{", "$", "requiredStrength", "=", "$", "cargoWeight", "->", "getBonus", "(", ")", "->", "getValue", "(", ")", ";", "$", "missin...
Affects activities using strength, agility or knack, see PPH page 113, right column, bottom. @param Strength $strength @param Weight $cargoWeight @return int negative number or zero @throws \DrdPlus\Tables\Measurements\Partials\Exceptions\BonusRequiresInteger
[ "Affects", "activities", "using", "strength", "agility", "or", "knack", "see", "PPH", "page", "113", "right", "column", "bottom", "." ]
7a577ddbd1748369eec4e84effcc92ffcb54d1f3
https://github.com/drdplusinfo/tables/blob/7a577ddbd1748369eec4e84effcc92ffcb54d1f3/DrdPlus/Tables/Measurements/Weight/WeightTable.php#L100-L110
train
ommu/mod-core
models/OmmuThemes.php
OmmuThemes.getThemes
public static function getThemes($array=true) { $criteria=new CDbCriteria; $model = self::model()->findAll($criteria); if($array == true) { $items = array(); if($model != null) { foreach($model as $key => $val) { $items[$val->theme_id] = $val->name; } return $items; } else return false; } else return $model; }
php
public static function getThemes($array=true) { $criteria=new CDbCriteria; $model = self::model()->findAll($criteria); if($array == true) { $items = array(); if($model != null) { foreach($model as $key => $val) { $items[$val->theme_id] = $val->name; } return $items; } else return false; } else return $model; }
[ "public", "static", "function", "getThemes", "(", "$", "array", "=", "true", ")", "{", "$", "criteria", "=", "new", "CDbCriteria", ";", "$", "model", "=", "self", "::", "model", "(", ")", "->", "findAll", "(", "$", "criteria", ")", ";", "if", "(", ...
getThemes 0 = unpublish 1 = publish
[ "getThemes", "0", "=", "unpublish", "1", "=", "publish" ]
68c90e76440e74ee93bcf82905a54d86c941b771
https://github.com/ommu/mod-core/blob/68c90e76440e74ee93bcf82905a54d86c941b771/models/OmmuThemes.php#L291-L307
train
nails/module-auth
auth/controllers/Override.php
Override.login_as
public function login_as() { // Perform lookup of user $oUserModel = Factory::model('User', 'nails/module-auth'); $oUri = Factory::service('Uri'); $sHashId = $oUri->segment(4); $sHashPw = $oUri->segment(5); $oUser = $oUserModel->getByHashes($sHashId, $sHashPw); if (!$oUser) { show404(); } // -------------------------------------------------------------------------- /** * Check sign-in permissions; ignore if recovering. * Users cannot: * - Sign in as themselves * - Sign in as superusers (unless they are a superuser) */ $oSession = Factory::service('Session', 'nails/module-auth'); if (!wasAdmin()) { $bHasPermission = userHasPermission('admin:auth:accounts:loginAs'); $bIsCloning = activeUser('id') == $oUser->id; $bIsSuperuser = !isSuperuser() && isSuperuser($oUser) ? true : false; if (!$bHasPermission || $bIsCloning || $bIsSuperuser) { if (!$bHasPermission) { $oSession->setFlashData('error', lang('auth_override_fail_nopermission')); redirect('admin/dashboard'); } elseif ($bIsCloning) { show404(); } elseif ($bIsSuperuser) { show404(); } } } // -------------------------------------------------------------------------- $oInput = Factory::service('Input'); if (!$oInput->get('returningAdmin') && isAdmin()) { /** * The current user is an admin, we should set our Admin Recovery Data so * that they can come back. */ $oUserModel->setAdminRecoveryData($oUser->id, $oInput->get('return_to')); $sRedirectUrl = $oUser->group_homepage; // A bit of feedback $sStatus = 'success'; $sMessage = lang('auth_override_ok', $oUser->first_name . ' ' . $oUser->last_name); } elseif (wasAdmin()) { /** * This user is a recovering adminaholic. Work out where we're sending * them back to then remove the adminRecovery data. */ $oRecoveryData = getAdminRecoveryData(); $sRedirectUrl = !empty($oRecoveryData->returnTo) ? $oRecoveryData->returnTo : $oUser->group_homepage; unsetAdminRecoveryData(); // Some feedback $sStatus = 'success'; $sMessage = lang('auth_override_return', $oUser->first_name . ' ' . $oUser->last_name); } else { /** * This user is simply logging in as someone else and has passed the hash * verification. */ $sRedirectUrl = $oUser->group_homepage; // Some feedback $sStatus = 'success'; $sMessage = lang('auth_override_ok', $oUser->first_name . ' ' . $oUser->last_name); } // -------------------------------------------------------------------------- // Replace current user's session data $oUserModel->setLoginData($oUser->id); // -------------------------------------------------------------------------- // Any feedback? if (!empty($sMessage)) { $oSession->setFlashData($sStatus, $sMessage); } // -------------------------------------------------------------------------- redirect($sRedirectUrl); }
php
public function login_as() { // Perform lookup of user $oUserModel = Factory::model('User', 'nails/module-auth'); $oUri = Factory::service('Uri'); $sHashId = $oUri->segment(4); $sHashPw = $oUri->segment(5); $oUser = $oUserModel->getByHashes($sHashId, $sHashPw); if (!$oUser) { show404(); } // -------------------------------------------------------------------------- /** * Check sign-in permissions; ignore if recovering. * Users cannot: * - Sign in as themselves * - Sign in as superusers (unless they are a superuser) */ $oSession = Factory::service('Session', 'nails/module-auth'); if (!wasAdmin()) { $bHasPermission = userHasPermission('admin:auth:accounts:loginAs'); $bIsCloning = activeUser('id') == $oUser->id; $bIsSuperuser = !isSuperuser() && isSuperuser($oUser) ? true : false; if (!$bHasPermission || $bIsCloning || $bIsSuperuser) { if (!$bHasPermission) { $oSession->setFlashData('error', lang('auth_override_fail_nopermission')); redirect('admin/dashboard'); } elseif ($bIsCloning) { show404(); } elseif ($bIsSuperuser) { show404(); } } } // -------------------------------------------------------------------------- $oInput = Factory::service('Input'); if (!$oInput->get('returningAdmin') && isAdmin()) { /** * The current user is an admin, we should set our Admin Recovery Data so * that they can come back. */ $oUserModel->setAdminRecoveryData($oUser->id, $oInput->get('return_to')); $sRedirectUrl = $oUser->group_homepage; // A bit of feedback $sStatus = 'success'; $sMessage = lang('auth_override_ok', $oUser->first_name . ' ' . $oUser->last_name); } elseif (wasAdmin()) { /** * This user is a recovering adminaholic. Work out where we're sending * them back to then remove the adminRecovery data. */ $oRecoveryData = getAdminRecoveryData(); $sRedirectUrl = !empty($oRecoveryData->returnTo) ? $oRecoveryData->returnTo : $oUser->group_homepage; unsetAdminRecoveryData(); // Some feedback $sStatus = 'success'; $sMessage = lang('auth_override_return', $oUser->first_name . ' ' . $oUser->last_name); } else { /** * This user is simply logging in as someone else and has passed the hash * verification. */ $sRedirectUrl = $oUser->group_homepage; // Some feedback $sStatus = 'success'; $sMessage = lang('auth_override_ok', $oUser->first_name . ' ' . $oUser->last_name); } // -------------------------------------------------------------------------- // Replace current user's session data $oUserModel->setLoginData($oUser->id); // -------------------------------------------------------------------------- // Any feedback? if (!empty($sMessage)) { $oSession->setFlashData($sStatus, $sMessage); } // -------------------------------------------------------------------------- redirect($sRedirectUrl); }
[ "public", "function", "login_as", "(", ")", "{", "// Perform lookup of user", "$", "oUserModel", "=", "Factory", "::", "model", "(", "'User'", ",", "'nails/module-auth'", ")", ";", "$", "oUri", "=", "Factory", "::", "service", "(", "'Uri'", ")", ";", "$", ...
Log in as another user @return void
[ "Log", "in", "as", "another", "user" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/auth/controllers/Override.php#L40-L145
train