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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
GrupaZero/cms | src/Gzero/Cms/Handlers/Block/CacheBlockTrait.php | CacheBlockTrait.putInCache | protected function putInCache(Block $block, Language $language, $html)
{
if ($block->is_cacheable) {
cache()->tags(['blocks'])->forever('blocks:cache:' . $block->id . ':' . $language->code, $html);
}
} | php | protected function putInCache(Block $block, Language $language, $html)
{
if ($block->is_cacheable) {
cache()->tags(['blocks'])->forever('blocks:cache:' . $block->id . ':' . $language->code, $html);
}
} | [
"protected",
"function",
"putInCache",
"(",
"Block",
"$",
"block",
",",
"Language",
"$",
"language",
",",
"$",
"html",
")",
"{",
"if",
"(",
"$",
"block",
"->",
"is_cacheable",
")",
"{",
"cache",
"(",
")",
"->",
"tags",
"(",
"[",
"'blocks'",
"]",
")",... | Put rendered html in to block cache
@param Block $block Block
@param Language $language Language
@param string $html Rendered html
@return void | [
"Put",
"rendered",
"html",
"in",
"to",
"block",
"cache"
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/Handlers/Block/CacheBlockTrait.php#L33-L38 | train |
MetaModels/filter_range | src/EventListener/DcGeneral/Table/FilterSetting/AbstractAbstainingListener.php | AbstractAbstainingListener.isAllowedContext | protected function isAllowedContext($dataDefinition, $propertyName, $model)
{
// Check the name of the data def.
if ('tl_metamodel_filtersetting' !== $dataDefinition->getName()) {
return false;
}
// Check the name of the property.
if ('attr_id2' !== $propertyName) {
return false;
}
// Check the type.
$property = $model->getProperty('type');
return !('range' !== $property && 'rangedate' !== $property);
} | php | protected function isAllowedContext($dataDefinition, $propertyName, $model)
{
// Check the name of the data def.
if ('tl_metamodel_filtersetting' !== $dataDefinition->getName()) {
return false;
}
// Check the name of the property.
if ('attr_id2' !== $propertyName) {
return false;
}
// Check the type.
$property = $model->getProperty('type');
return !('range' !== $property && 'rangedate' !== $property);
} | [
"protected",
"function",
"isAllowedContext",
"(",
"$",
"dataDefinition",
",",
"$",
"propertyName",
",",
"$",
"model",
")",
"{",
"// Check the name of the data def.",
"if",
"(",
"'tl_metamodel_filtersetting'",
"!==",
"$",
"dataDefinition",
"->",
"getName",
"(",
")",
... | Check if the context of the event is a allowed one.
@param ContainerInterface $dataDefinition The data definition from the environment.
@param string $propertyName The current property name.
@param ModelInterface $model The current model.
@return bool True => It is a allowed one | False => nope | [
"Check",
"if",
"the",
"context",
"of",
"the",
"event",
"is",
"a",
"allowed",
"one",
"."
] | 1875e4a2206df2c5c98f5b0a7f18feb17b34f393 | https://github.com/MetaModels/filter_range/blob/1875e4a2206df2c5c98f5b0a7f18feb17b34f393/src/EventListener/DcGeneral/Table/FilterSetting/AbstractAbstainingListener.php#L63-L78 | train |
MetaModels/filter_range | src/EventListener/DcGeneral/Table/FilterSetting/AbstractAbstainingListener.php | AbstractAbstainingListener.getMetaModel | protected function getMetaModel(ModelInterface $model)
{
$filterSetting = $this->filterSettingFactory->createCollection($model->getProperty('fid'));
return $filterSetting->getMetaModel();
} | php | protected function getMetaModel(ModelInterface $model)
{
$filterSetting = $this->filterSettingFactory->createCollection($model->getProperty('fid'));
return $filterSetting->getMetaModel();
} | [
"protected",
"function",
"getMetaModel",
"(",
"ModelInterface",
"$",
"model",
")",
"{",
"$",
"filterSetting",
"=",
"$",
"this",
"->",
"filterSettingFactory",
"->",
"createCollection",
"(",
"$",
"model",
"->",
"getProperty",
"(",
"'fid'",
")",
")",
";",
"return... | Retrieve the MetaModel attached to the model filter setting.
@param ModelInterface $model The model for which to retrieve the MetaModel.
@return IMetaModel
@throws \RuntimeException When the MetaModel can not be determined. | [
"Retrieve",
"the",
"MetaModel",
"attached",
"to",
"the",
"model",
"filter",
"setting",
"."
] | 1875e4a2206df2c5c98f5b0a7f18feb17b34f393 | https://github.com/MetaModels/filter_range/blob/1875e4a2206df2c5c98f5b0a7f18feb17b34f393/src/EventListener/DcGeneral/Table/FilterSetting/AbstractAbstainingListener.php#L89-L94 | train |
alexislefebvre/AsyncTweetsBundle | src/Controller/DefaultController.php | DefaultController.getTweetsVars | private function getTweetsVars($tweets, $vars)
{
/** @var string $firstTweetId */
$firstTweetId = $tweets[0]->getId();
$vars['previous'] = $this->tweetRepository
->getPreviousTweetId($firstTweetId);
$vars['next'] = $this->tweetRepository
->getNextTweetId($firstTweetId);
// Only update the cookie if the last Tweet Id is bigger than
// the one in the cookie
if ($firstTweetId > $vars['cookieId']) {
$vars['cookie'] = $this->createCookie($firstTweetId);
$vars['cookieId'] = $firstTweetId;
}
$vars['number'] = $this->tweetRepository
->countPendingTweets($vars['cookieId']);
$vars['first'] = $firstTweetId;
return $vars;
} | php | private function getTweetsVars($tweets, $vars)
{
/** @var string $firstTweetId */
$firstTweetId = $tweets[0]->getId();
$vars['previous'] = $this->tweetRepository
->getPreviousTweetId($firstTweetId);
$vars['next'] = $this->tweetRepository
->getNextTweetId($firstTweetId);
// Only update the cookie if the last Tweet Id is bigger than
// the one in the cookie
if ($firstTweetId > $vars['cookieId']) {
$vars['cookie'] = $this->createCookie($firstTweetId);
$vars['cookieId'] = $firstTweetId;
}
$vars['number'] = $this->tweetRepository
->countPendingTweets($vars['cookieId']);
$vars['first'] = $firstTweetId;
return $vars;
} | [
"private",
"function",
"getTweetsVars",
"(",
"$",
"tweets",
",",
"$",
"vars",
")",
"{",
"/** @var string $firstTweetId */",
"$",
"firstTweetId",
"=",
"$",
"tweets",
"[",
"0",
"]",
"->",
"getId",
"(",
")",
";",
"$",
"vars",
"[",
"'previous'",
"]",
"=",
"$... | If a Tweet is displayed, fetch data from repository.
@param Tweet[] $tweets
@param array $vars
@return array $vars | [
"If",
"a",
"Tweet",
"is",
"displayed",
"fetch",
"data",
"from",
"repository",
"."
] | 76266fae7de978963e05dadb14c81f8398bb00a6 | https://github.com/alexislefebvre/AsyncTweetsBundle/blob/76266fae7de978963e05dadb14c81f8398bb00a6/src/Controller/DefaultController.php#L86-L109 | train |
datalaere/php-http | src/Input.php | Input.toSlug | public static function toSlug($string, $replace = array(), $delimiter = '-')
{
if (!empty($replace)) {
$string = str_replace((array) $replace, ' ', $string);
}
return preg_replace('/[^A-Za-z0-9-]+/', $delimiter, $string);
} | php | public static function toSlug($string, $replace = array(), $delimiter = '-')
{
if (!empty($replace)) {
$string = str_replace((array) $replace, ' ', $string);
}
return preg_replace('/[^A-Za-z0-9-]+/', $delimiter, $string);
} | [
"public",
"static",
"function",
"toSlug",
"(",
"$",
"string",
",",
"$",
"replace",
"=",
"array",
"(",
")",
",",
"$",
"delimiter",
"=",
"'-'",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"replace",
")",
")",
"{",
"$",
"string",
"=",
"str_replace",
... | This function expects the input to be UTF-8 encoded. | [
"This",
"function",
"expects",
"the",
"input",
"to",
"be",
"UTF",
"-",
"8",
"encoded",
"."
] | 575e12aa853465b1430b3f2c5b074937e8819e8b | https://github.com/datalaere/php-http/blob/575e12aa853465b1430b3f2c5b074937e8819e8b/src/Input.php#L38-L45 | train |
GrupaZero/cms | src/Gzero/Cms/Menu/Register.php | Register.addChild | public function addChild($parentUrl, Link $link)
{
$this->links->each(
function ($value) use ($parentUrl, $link) {
if ($value->url === $parentUrl) {
$value->children->push($link);
return false;
}
}
);
} | php | public function addChild($parentUrl, Link $link)
{
$this->links->each(
function ($value) use ($parentUrl, $link) {
if ($value->url === $parentUrl) {
$value->children->push($link);
return false;
}
}
);
} | [
"public",
"function",
"addChild",
"(",
"$",
"parentUrl",
",",
"Link",
"$",
"link",
")",
"{",
"$",
"this",
"->",
"links",
"->",
"each",
"(",
"function",
"(",
"$",
"value",
")",
"use",
"(",
"$",
"parentUrl",
",",
"$",
"link",
")",
"{",
"if",
"(",
"... | It adds child link to parent specified by url parameter
@param string $parentUrl Parent url
@param Link $link Menu link
@return void | [
"It",
"adds",
"child",
"link",
"to",
"parent",
"specified",
"by",
"url",
"parameter"
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/Menu/Register.php#L43-L53 | train |
GrupaZero/cms | src/Gzero/Cms/Menu/Register.php | Register.getMenu | public function getMenu()
{
$this->links->each(
function ($link) {
if (!$link->children->isEmpty()) {
$link->children = $link->children->sortBy('weight')->values();
}
}
);
return $this->links->sortBy('weight')->values();
} | php | public function getMenu()
{
$this->links->each(
function ($link) {
if (!$link->children->isEmpty()) {
$link->children = $link->children->sortBy('weight')->values();
}
}
);
return $this->links->sortBy('weight')->values();
} | [
"public",
"function",
"getMenu",
"(",
")",
"{",
"$",
"this",
"->",
"links",
"->",
"each",
"(",
"function",
"(",
"$",
"link",
")",
"{",
"if",
"(",
"!",
"$",
"link",
"->",
"children",
"->",
"isEmpty",
"(",
")",
")",
"{",
"$",
"link",
"->",
"childre... | It returns whole menu as tree
@return Collection | [
"It",
"returns",
"whole",
"menu",
"as",
"tree"
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/Menu/Register.php#L60-L70 | train |
jon48/webtrees-lib | src/Webtrees/Module/Sosa/SosaConfigController.php | SosaConfigController.canUpdate | protected function canUpdate() {
$user_id = Filter::postInteger('userid', -1) ?: Filter::getInteger('userid', -1);
return Auth::check() &&
(
$user_id == Auth::user()->getUserId() || // Allow update for yourself
($user_id == -1 && Auth::isManager(Globals::getTree())) // Allow a manager to update the default user
);
} | php | protected function canUpdate() {
$user_id = Filter::postInteger('userid', -1) ?: Filter::getInteger('userid', -1);
return Auth::check() &&
(
$user_id == Auth::user()->getUserId() || // Allow update for yourself
($user_id == -1 && Auth::isManager(Globals::getTree())) // Allow a manager to update the default user
);
} | [
"protected",
"function",
"canUpdate",
"(",
")",
"{",
"$",
"user_id",
"=",
"Filter",
"::",
"postInteger",
"(",
"'userid'",
",",
"-",
"1",
")",
"?",
":",
"Filter",
"::",
"getInteger",
"(",
"'userid'",
",",
"-",
"1",
")",
";",
"return",
"Auth",
"::",
"c... | Check if the user can update the sosa ancestors list
@return bool | [
"Check",
"if",
"the",
"user",
"can",
"update",
"the",
"sosa",
"ancestors",
"list"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/Sosa/SosaConfigController.php#L38-L45 | train |
CESNET/perun-simplesamlphp-module | lib/AdapterRpc.php | AdapterRpc.getMemberByUser | public function getMemberByUser($user, $vo)
{
$member = $this->connector->get('membersManager', 'getMemberByUser', array(
'user' => $user->getId(),
'vo' => $vo->getId(),
));
if (is_null($member)) {
throw new Exception(
"Member for User with name " . $user->getName() . " and Vo with shortName " .
$vo->getShortName() . "does not exist in Perun!"
);
}
return new Member($member['id'], $member['voId'], $member['status']);
} | php | public function getMemberByUser($user, $vo)
{
$member = $this->connector->get('membersManager', 'getMemberByUser', array(
'user' => $user->getId(),
'vo' => $vo->getId(),
));
if (is_null($member)) {
throw new Exception(
"Member for User with name " . $user->getName() . " and Vo with shortName " .
$vo->getShortName() . "does not exist in Perun!"
);
}
return new Member($member['id'], $member['voId'], $member['status']);
} | [
"public",
"function",
"getMemberByUser",
"(",
"$",
"user",
",",
"$",
"vo",
")",
"{",
"$",
"member",
"=",
"$",
"this",
"->",
"connector",
"->",
"get",
"(",
"'membersManager'",
",",
"'getMemberByUser'",
",",
"array",
"(",
"'user'",
"=>",
"$",
"user",
"->",... | Returns member by User and Vo
@param User $user
@param Vo $vo
@return Member | [
"Returns",
"member",
"by",
"User",
"and",
"Vo"
] | f1d686f06472053a7cdb31f2b2776f9714779ee1 | https://github.com/CESNET/perun-simplesamlphp-module/blob/f1d686f06472053a7cdb31f2b2776f9714779ee1/lib/AdapterRpc.php#L360-L373 | train |
CESNET/perun-simplesamlphp-module | lib/AdapterRpc.php | AdapterRpc.hasRegistrationForm | public function hasRegistrationForm($group)
{
try {
$this->connector->get('registrarManager', 'getApplicationForm', array(
'group' => $group->getId(),
));
return true;
} catch (\Exception $exception) {
return false;
}
} | php | public function hasRegistrationForm($group)
{
try {
$this->connector->get('registrarManager', 'getApplicationForm', array(
'group' => $group->getId(),
));
return true;
} catch (\Exception $exception) {
return false;
}
} | [
"public",
"function",
"hasRegistrationForm",
"(",
"$",
"group",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"connector",
"->",
"get",
"(",
"'registrarManager'",
",",
"'getApplicationForm'",
",",
"array",
"(",
"'group'",
"=>",
"$",
"group",
"->",
"getId",
"(",
... | Returns true if group has registration form, false otherwise
@param Group $group
@return bool | [
"Returns",
"true",
"if",
"group",
"has",
"registration",
"form",
"false",
"otherwise"
] | f1d686f06472053a7cdb31f2b2776f9714779ee1 | https://github.com/CESNET/perun-simplesamlphp-module/blob/f1d686f06472053a7cdb31f2b2776f9714779ee1/lib/AdapterRpc.php#L380-L390 | train |
voslartomas/WebCMS2 | libs/Settings.php | Settings.get | public function get($key, $section = 'basic', $type = null, $options = array(), $language = true)
{
// system settings
if (array_key_exists($section, $this->settings)) {
if (array_key_exists($key, $this->settings[$section])) {
$settings = $this->settings[$section][$key];
if ($settings->getType() === null && $type !== null) {
$settings->setType($type);
$this->em->flush();
}
return $settings;
}
}
return $this->save($key, $section, $type, $options, $language);
} | php | public function get($key, $section = 'basic', $type = null, $options = array(), $language = true)
{
// system settings
if (array_key_exists($section, $this->settings)) {
if (array_key_exists($key, $this->settings[$section])) {
$settings = $this->settings[$section][$key];
if ($settings->getType() === null && $type !== null) {
$settings->setType($type);
$this->em->flush();
}
return $settings;
}
}
return $this->save($key, $section, $type, $options, $language);
} | [
"public",
"function",
"get",
"(",
"$",
"key",
",",
"$",
"section",
"=",
"'basic'",
",",
"$",
"type",
"=",
"null",
",",
"$",
"options",
"=",
"array",
"(",
")",
",",
"$",
"language",
"=",
"true",
")",
"{",
"// system settings",
"if",
"(",
"array_key_ex... | Gets settings by key and section.
@param String $key
@param String $section
@param string $type
@return String
@throws Exception | [
"Gets",
"settings",
"by",
"key",
"and",
"section",
"."
] | b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf | https://github.com/voslartomas/WebCMS2/blob/b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf/libs/Settings.php#L39-L56 | train |
c4studio/chronos | src/Chronos/Scaffolding/app/Traits/ChronosUser.php | ChronosUser.hasOneOfPermissions | public function hasOneOfPermissions($permissions)
{
if ($this->hasRole('root'))
return true;
$has = false;
foreach ($permissions as $permission) {
$has = $has || $this->hasPermission($permission);
}
return $has;
} | php | public function hasOneOfPermissions($permissions)
{
if ($this->hasRole('root'))
return true;
$has = false;
foreach ($permissions as $permission) {
$has = $has || $this->hasPermission($permission);
}
return $has;
} | [
"public",
"function",
"hasOneOfPermissions",
"(",
"$",
"permissions",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"hasRole",
"(",
"'root'",
")",
")",
"return",
"true",
";",
"$",
"has",
"=",
"false",
";",
"foreach",
"(",
"$",
"permissions",
"as",
"$",
"perm... | Determine if the user has one of the given permissions.
@param $permissions
@return bool | [
"Determine",
"if",
"the",
"user",
"has",
"one",
"of",
"the",
"given",
"permissions",
"."
] | df7f3a9794afaade3bee8f6be1223c98e4936cb2 | https://github.com/c4studio/chronos/blob/df7f3a9794afaade3bee8f6be1223c98e4936cb2/src/Chronos/Scaffolding/app/Traits/ChronosUser.php#L62-L74 | train |
CESNET/perun-simplesamlphp-module | lib/IdpListsService.php | IdpListsService.getInstance | public static function getInstance()
{
$configuration = Configuration::getConfig(self::CONFIG_FILE_NAME);
$idpListServiceType = $configuration->getString(self::PROPNAME_IDP_LIST_SERVICE_TYPE, self::CSV);
if ($idpListServiceType === self::CSV) {
return new IdpListsServiceCsv();
} elseif ($idpListServiceType === self::DB) {
return new IdpListsServiceDB();
} else {
throw new Exception(
'Unknown idpListService type. Hint: try ' . self::CSV . ' or ' . self::DB
);
}
} | php | public static function getInstance()
{
$configuration = Configuration::getConfig(self::CONFIG_FILE_NAME);
$idpListServiceType = $configuration->getString(self::PROPNAME_IDP_LIST_SERVICE_TYPE, self::CSV);
if ($idpListServiceType === self::CSV) {
return new IdpListsServiceCsv();
} elseif ($idpListServiceType === self::DB) {
return new IdpListsServiceDB();
} else {
throw new Exception(
'Unknown idpListService type. Hint: try ' . self::CSV . ' or ' . self::DB
);
}
} | [
"public",
"static",
"function",
"getInstance",
"(",
")",
"{",
"$",
"configuration",
"=",
"Configuration",
"::",
"getConfig",
"(",
"self",
"::",
"CONFIG_FILE_NAME",
")",
";",
"$",
"idpListServiceType",
"=",
"$",
"configuration",
"->",
"getString",
"(",
"self",
... | Function returns the instance of sspmod_perun_IdPListsService by configuration
Default is CSV
@return IdpListsServiceCsv|IdpListsServiceDB | [
"Function",
"returns",
"the",
"instance",
"of",
"sspmod_perun_IdPListsService",
"by",
"configuration",
"Default",
"is",
"CSV"
] | f1d686f06472053a7cdb31f2b2776f9714779ee1 | https://github.com/CESNET/perun-simplesamlphp-module/blob/f1d686f06472053a7cdb31f2b2776f9714779ee1/lib/IdpListsService.php#L35-L48 | train |
GrupaZero/cms | database/migrations/2014_11_16_114113_create_content.php | CreateContent.seedContentTypes | private function seedContentTypes()
{
ContentType::firstOrCreate(['name' => 'content', 'handler' => Gzero\Cms\Handlers\Content\ContentHandler::class]);
ContentType::firstOrCreate(['name' => 'category', 'handler' => Gzero\Cms\Handlers\Content\CategoryHandler::class]);
} | php | private function seedContentTypes()
{
ContentType::firstOrCreate(['name' => 'content', 'handler' => Gzero\Cms\Handlers\Content\ContentHandler::class]);
ContentType::firstOrCreate(['name' => 'category', 'handler' => Gzero\Cms\Handlers\Content\CategoryHandler::class]);
} | [
"private",
"function",
"seedContentTypes",
"(",
")",
"{",
"ContentType",
"::",
"firstOrCreate",
"(",
"[",
"'name'",
"=>",
"'content'",
",",
"'handler'",
"=>",
"Gzero",
"\\",
"Cms",
"\\",
"Handlers",
"\\",
"Content",
"\\",
"ContentHandler",
"::",
"class",
"]",
... | Seed content types
@return void | [
"Seed",
"content",
"types"
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/database/migrations/2014_11_16_114113_create_content.php#L93-L97 | train |
locomotivemtl/charcoal-user | src/Charcoal/User/AbstractUser.php | AbstractUser.logout | public function logout()
{
// Irrelevant call...
if (!$this->id()) {
return false;
}
$key = static::sessionKey();
$_SESSION[$key] = null;
unset($_SESSION[$key], static::$authenticatedUser[$key]);
return true;
} | php | public function logout()
{
// Irrelevant call...
if (!$this->id()) {
return false;
}
$key = static::sessionKey();
$_SESSION[$key] = null;
unset($_SESSION[$key], static::$authenticatedUser[$key]);
return true;
} | [
"public",
"function",
"logout",
"(",
")",
"{",
"// Irrelevant call...",
"if",
"(",
"!",
"$",
"this",
"->",
"id",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"key",
"=",
"static",
"::",
"sessionKey",
"(",
")",
";",
"$",
"_SESSION",
"[",
"$... | Empties the session var associated to the session key.
@return boolean Logged out or not. | [
"Empties",
"the",
"session",
"var",
"associated",
"to",
"the",
"session",
"key",
"."
] | 86405a592379ebc2b77a7a9a7f68a85f2afe85f0 | https://github.com/locomotivemtl/charcoal-user/blob/86405a592379ebc2b77a7a9a7f68a85f2afe85f0/src/Charcoal/User/AbstractUser.php#L478-L491 | train |
locomotivemtl/charcoal-user | src/Charcoal/User/AbstractUser.php | AbstractUser.validate | public function validate(ValidatorInterface &$v = null)
{
$result = parent::validate($v);
$objType = self::objType();
$previousModel = $this->modelFactory()->create($objType)->load($this->id());
$email = $this->email();
if (empty($email)) {
$this->validator()->error(
'Email is required.',
'email'
);
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->validator()->error(
'Email format is incorrect.',
'email'
);
/** Check if updating/changing email. */
} elseif ($previousModel->email() !== $email) {
$existingModel = $this->modelFactory()->create($objType)->loadFrom('email', $email);
/** Check for existing user with given email. */
if (!empty($existingModel->id())) {
$this->validator()->error(
'This email is not available.',
'email'
);
}
}
return count($this->validator()->errorResults()) === 0 && $result;
} | php | public function validate(ValidatorInterface &$v = null)
{
$result = parent::validate($v);
$objType = self::objType();
$previousModel = $this->modelFactory()->create($objType)->load($this->id());
$email = $this->email();
if (empty($email)) {
$this->validator()->error(
'Email is required.',
'email'
);
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->validator()->error(
'Email format is incorrect.',
'email'
);
/** Check if updating/changing email. */
} elseif ($previousModel->email() !== $email) {
$existingModel = $this->modelFactory()->create($objType)->loadFrom('email', $email);
/** Check for existing user with given email. */
if (!empty($existingModel->id())) {
$this->validator()->error(
'This email is not available.',
'email'
);
}
}
return count($this->validator()->errorResults()) === 0 && $result;
} | [
"public",
"function",
"validate",
"(",
"ValidatorInterface",
"&",
"$",
"v",
"=",
"null",
")",
"{",
"$",
"result",
"=",
"parent",
"::",
"validate",
"(",
"$",
"v",
")",
";",
"$",
"objType",
"=",
"self",
"::",
"objType",
"(",
")",
";",
"$",
"previousMod... | Validate the model.
@see \Charcoal\Validator\ValidatorInterface
@param ValidatorInterface $v Optional. A custom validator object to use for validation. If null, use object's.
@return boolean | [
"Validate",
"the",
"model",
"."
] | 86405a592379ebc2b77a7a9a7f68a85f2afe85f0 | https://github.com/locomotivemtl/charcoal-user/blob/86405a592379ebc2b77a7a9a7f68a85f2afe85f0/src/Charcoal/User/AbstractUser.php#L579-L609 | train |
jon48/webtrees-lib | src/Webtrees/Module/PatronymicLineage/Views/LineageView.php | LineageView.printRootLineage | private function printRootLineage(LineageRootNode $node) {
print '<div class="patrolin_tree">';
if($node->getIndividual() === null) {
$fam_nodes = $node->getFamiliesNodes();
foreach($fam_nodes as $fam){
foreach($fam_nodes[$fam] as $child_node) {
if($child_node) {
$this->printLineage($child_node);
}
}
}
}
else {
$this->printLineage($node);
}
echo '</div>';
$places = $node->getPlaces();
if($places && count($places)>0){
echo '<div class="patrolin_places">';
echo \MyArtJaub\Webtrees\Functions\FunctionsPrint::htmlPlacesCloud($places, false, $this->data->get('tree'));
echo '</div>';
}
} | php | private function printRootLineage(LineageRootNode $node) {
print '<div class="patrolin_tree">';
if($node->getIndividual() === null) {
$fam_nodes = $node->getFamiliesNodes();
foreach($fam_nodes as $fam){
foreach($fam_nodes[$fam] as $child_node) {
if($child_node) {
$this->printLineage($child_node);
}
}
}
}
else {
$this->printLineage($node);
}
echo '</div>';
$places = $node->getPlaces();
if($places && count($places)>0){
echo '<div class="patrolin_places">';
echo \MyArtJaub\Webtrees\Functions\FunctionsPrint::htmlPlacesCloud($places, false, $this->data->get('tree'));
echo '</div>';
}
} | [
"private",
"function",
"printRootLineage",
"(",
"LineageRootNode",
"$",
"node",
")",
"{",
"print",
"'<div class=\"patrolin_tree\">'",
";",
"if",
"(",
"$",
"node",
"->",
"getIndividual",
"(",
")",
"===",
"null",
")",
"{",
"$",
"fam_nodes",
"=",
"$",
"node",
"... | Print a root lineage node
@param LineageRootNode $node | [
"Print",
"a",
"root",
"lineage",
"node"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/PatronymicLineage/Views/LineageView.php#L148-L171 | train |
jon48/webtrees-lib | src/Webtrees/Module/PatronymicLineage/Views/LineageView.php | LineageView.printLineage | private function printLineage(LineageNode $node) {
echo '<ul>';
$fam_nodes = $node->getFamiliesNodes();
if(count($fam_nodes) > 0) {
$is_first_family = true;
foreach($fam_nodes as $fam) {
$node_indi = $node->getIndividual();
echo '<li>';
if($is_first_family){
echo FunctionsPrint::htmlIndividualForList($node_indi);
}
else{
echo FunctionsPrint::htmlIndividualForList($node_indi, false);
}
//Get individual's spouse
$dfam = new Family($fam);
$spouse=$dfam->getSpouseById($node_indi);
//Print the spouse if relevant
if($spouse){
$marrdate = I18N::translate('yes');
$marryear = '';
echo ' <a href="'.$fam->getHtmlUrl().'">';
if ($fam->getMarriageYear()){
$marrdate = strip_tags($fam->getMarriageDate()->Display());
$marryear = $fam->getMarriageYear();
}
echo '<span class="details1" title="'.$marrdate.'"><i class="icon-rings"></i>'.$marryear.'</span></a> ';
echo FunctionsPrint::htmlIndividualForList($spouse);
}
foreach($fam_nodes[$fam] as $child_node) {
if($child_node) {
$this->printLineage($child_node);
}
else {
echo '<ul><li><strong>…</strong></li></ul>';
}
}
$is_first_family = false;
}
}
else {
echo '<li>';
echo \MyArtJaub\Webtrees\Functions\FunctionsPrint::htmlIndividualForList($node->getIndividual());
if($node->hasFollowUpSurname()) {
$url_base = WT_SCRIPT_NAME . '?mod=' . \MyArtJaub\Webtrees\Constants::MODULE_MAJ_PATROLIN_NAME . '&mod_action=Lineage';
echo ' '.
'<a href="' . $url_base . '&surname=' . rawurlencode($node->getFollowUpSurname()) . '&ged=' . $this->data->get('tree')->getNameUrl() . '">'.
'('.I18N::translate('Go to %s lineages', $node->getFollowUpSurname()).')'.
'</a>';
}
echo '</li>';
}
echo '</ul>';
} | php | private function printLineage(LineageNode $node) {
echo '<ul>';
$fam_nodes = $node->getFamiliesNodes();
if(count($fam_nodes) > 0) {
$is_first_family = true;
foreach($fam_nodes as $fam) {
$node_indi = $node->getIndividual();
echo '<li>';
if($is_first_family){
echo FunctionsPrint::htmlIndividualForList($node_indi);
}
else{
echo FunctionsPrint::htmlIndividualForList($node_indi, false);
}
//Get individual's spouse
$dfam = new Family($fam);
$spouse=$dfam->getSpouseById($node_indi);
//Print the spouse if relevant
if($spouse){
$marrdate = I18N::translate('yes');
$marryear = '';
echo ' <a href="'.$fam->getHtmlUrl().'">';
if ($fam->getMarriageYear()){
$marrdate = strip_tags($fam->getMarriageDate()->Display());
$marryear = $fam->getMarriageYear();
}
echo '<span class="details1" title="'.$marrdate.'"><i class="icon-rings"></i>'.$marryear.'</span></a> ';
echo FunctionsPrint::htmlIndividualForList($spouse);
}
foreach($fam_nodes[$fam] as $child_node) {
if($child_node) {
$this->printLineage($child_node);
}
else {
echo '<ul><li><strong>…</strong></li></ul>';
}
}
$is_first_family = false;
}
}
else {
echo '<li>';
echo \MyArtJaub\Webtrees\Functions\FunctionsPrint::htmlIndividualForList($node->getIndividual());
if($node->hasFollowUpSurname()) {
$url_base = WT_SCRIPT_NAME . '?mod=' . \MyArtJaub\Webtrees\Constants::MODULE_MAJ_PATROLIN_NAME . '&mod_action=Lineage';
echo ' '.
'<a href="' . $url_base . '&surname=' . rawurlencode($node->getFollowUpSurname()) . '&ged=' . $this->data->get('tree')->getNameUrl() . '">'.
'('.I18N::translate('Go to %s lineages', $node->getFollowUpSurname()).')'.
'</a>';
}
echo '</li>';
}
echo '</ul>';
} | [
"private",
"function",
"printLineage",
"(",
"LineageNode",
"$",
"node",
")",
"{",
"echo",
"'<ul>'",
";",
"$",
"fam_nodes",
"=",
"$",
"node",
"->",
"getFamiliesNodes",
"(",
")",
";",
"if",
"(",
"count",
"(",
"$",
"fam_nodes",
")",
">",
"0",
")",
"{",
... | Print a lineage node, recursively.
@param LineageNode $node | [
"Print",
"a",
"lineage",
"node",
"recursively",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/PatronymicLineage/Views/LineageView.php#L177-L232 | train |
jon48/webtrees-lib | src/Webtrees/Module/PatronymicLineage/LineageController.php | LineageController.getSurnamesList | protected function getSurnamesList() {
return QueryName::surnames(Globals::getTree(), $this->surname, $this->alpha, false, false);
} | php | protected function getSurnamesList() {
return QueryName::surnames(Globals::getTree(), $this->surname, $this->alpha, false, false);
} | [
"protected",
"function",
"getSurnamesList",
"(",
")",
"{",
"return",
"QueryName",
"::",
"surnames",
"(",
"Globals",
"::",
"getTree",
"(",
")",
",",
"$",
"this",
"->",
"surname",
",",
"$",
"this",
"->",
"alpha",
",",
"false",
",",
"false",
")",
";",
"}"... | Get list of surnames, starting with the specified initial
@return array | [
"Get",
"list",
"of",
"surnames",
"starting",
"with",
"the",
"specified",
"initial"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/PatronymicLineage/LineageController.php#L132-L134 | train |
jon48/webtrees-lib | src/Webtrees/Module/PatronymicLineage/LineageController.php | LineageController.getLineages | protected function getLineages() {
$builder = new LineageBuilder($this->surname, Globals::getTree());
$lineages = $builder->buildLineages();
return $lineages;
} | php | protected function getLineages() {
$builder = new LineageBuilder($this->surname, Globals::getTree());
$lineages = $builder->buildLineages();
return $lineages;
} | [
"protected",
"function",
"getLineages",
"(",
")",
"{",
"$",
"builder",
"=",
"new",
"LineageBuilder",
"(",
"$",
"this",
"->",
"surname",
",",
"Globals",
"::",
"getTree",
"(",
")",
")",
";",
"$",
"lineages",
"=",
"$",
"builder",
"->",
"buildLineages",
"(",... | Get the lineages for the controller's specified surname | [
"Get",
"the",
"lineages",
"for",
"the",
"controller",
"s",
"specified",
"surname"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/PatronymicLineage/LineageController.php#L139-L144 | train |
g4code/log | src/Writer.php | Writer.preVarDump | public static function preVarDump($var, $die = false, $color = '#000000', $parsable = false, $output = true, $indirect = false)
{
// last line of defense ;)
if(!defined('DEBUG') || DEBUG !== true) {
return false;
}
$formated = '';
// if ajax or cli, skip preformating
$skipFormating =
(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')
|| php_sapi_name() == 'cli'
|| (defined('DEBUG_SKIP_FORMATTING') && DEBUG_SKIP_FORMATTING)
|| !$output;
$skipFormating || $formated .= "<pre style='padding: 5px; background:#ffffff; font: normal 12px \"Lucida Console\", \"Courier\",
monospace; position:relative; clear:both; color:{$color}; border:1px solid {$color}; text-align: left !important;'>";
$formated .= self::_preFormat($var, $parsable, intval($indirect) + 1, $skipFormating);
$skipFormating || $formated .= "</pre>";
if(!$output) {
return $formated;
}
echo $formated . "\n";
if($die) {
die("\n\nDebug terminated\n");
}
} | php | public static function preVarDump($var, $die = false, $color = '#000000', $parsable = false, $output = true, $indirect = false)
{
// last line of defense ;)
if(!defined('DEBUG') || DEBUG !== true) {
return false;
}
$formated = '';
// if ajax or cli, skip preformating
$skipFormating =
(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')
|| php_sapi_name() == 'cli'
|| (defined('DEBUG_SKIP_FORMATTING') && DEBUG_SKIP_FORMATTING)
|| !$output;
$skipFormating || $formated .= "<pre style='padding: 5px; background:#ffffff; font: normal 12px \"Lucida Console\", \"Courier\",
monospace; position:relative; clear:both; color:{$color}; border:1px solid {$color}; text-align: left !important;'>";
$formated .= self::_preFormat($var, $parsable, intval($indirect) + 1, $skipFormating);
$skipFormating || $formated .= "</pre>";
if(!$output) {
return $formated;
}
echo $formated . "\n";
if($die) {
die("\n\nDebug terminated\n");
}
} | [
"public",
"static",
"function",
"preVarDump",
"(",
"$",
"var",
",",
"$",
"die",
"=",
"false",
",",
"$",
"color",
"=",
"'#000000'",
",",
"$",
"parsable",
"=",
"false",
",",
"$",
"output",
"=",
"true",
",",
"$",
"indirect",
"=",
"false",
")",
"{",
"/... | Dump debug variable
@author Dejan Samardzija <samardzija.dejan@gmail.com>
@param mixed $var - variable
@param bool $die - terminate script after dump
@param string $color - text color
@param bool $parsable - if true it uses var_export that dumps php usable value
@param bool $output - if true it will echo formated string, for false it will return and override die part
@param bool $indirect - if call is direct or from wrapper function
@return void | [
"Dump",
"debug",
"variable"
] | 909d06503abbb21ac6c79a61d1b2b1bd89eb26d7 | https://github.com/g4code/log/blob/909d06503abbb21ac6c79a61d1b2b1bd89eb26d7/src/Writer.php#L55-L87 | train |
g4code/log | src/Writer.php | Writer.writeLog | public static function writeLog ($filename, $string)
{
$logs_path = defined('PATH_LOGS')
? PATH_LOGS
: getcwd();
$logs_path_real = realpath($logs_path);
if(!$logs_path_real || !is_writable($logs_path_real)) {
throw new \Exception("Log path is not accessible or writable");
}
$file_name = $logs_path_real . DIRECTORY_SEPARATOR . strtolower(trim($filename));
$file_folder = dirname($file_name);
if (!is_dir($file_folder)) {
if (!mkdir($file_folder, 0766, true)) {
throw new \Exception("Couldn't create logs subfolder");
}
}
if (!is_file($file_name)) {
if (@touch($file_name)) {
@chmod($file_name, 0777);
}
}
return file_put_contents($file_name, $string . PHP_EOL, FILE_APPEND | LOCK_EX);
} | php | public static function writeLog ($filename, $string)
{
$logs_path = defined('PATH_LOGS')
? PATH_LOGS
: getcwd();
$logs_path_real = realpath($logs_path);
if(!$logs_path_real || !is_writable($logs_path_real)) {
throw new \Exception("Log path is not accessible or writable");
}
$file_name = $logs_path_real . DIRECTORY_SEPARATOR . strtolower(trim($filename));
$file_folder = dirname($file_name);
if (!is_dir($file_folder)) {
if (!mkdir($file_folder, 0766, true)) {
throw new \Exception("Couldn't create logs subfolder");
}
}
if (!is_file($file_name)) {
if (@touch($file_name)) {
@chmod($file_name, 0777);
}
}
return file_put_contents($file_name, $string . PHP_EOL, FILE_APPEND | LOCK_EX);
} | [
"public",
"static",
"function",
"writeLog",
"(",
"$",
"filename",
",",
"$",
"string",
")",
"{",
"$",
"logs_path",
"=",
"defined",
"(",
"'PATH_LOGS'",
")",
"?",
"PATH_LOGS",
":",
"getcwd",
"(",
")",
";",
"$",
"logs_path_real",
"=",
"realpath",
"(",
"$",
... | Write to a log file
@param string $filename - log file name
@param string $string - text to write in log file
@return bool | [
"Write",
"to",
"a",
"log",
"file"
] | 909d06503abbb21ac6c79a61d1b2b1bd89eb26d7 | https://github.com/g4code/log/blob/909d06503abbb21ac6c79a61d1b2b1bd89eb26d7/src/Writer.php#L120-L149 | train |
g4code/log | src/Writer.php | Writer._formatFilePath | private static function _formatFilePath($filename, $format, $extras = array(), $addHostname = false)
{
// we can parse scalars also
if(is_scalar($extras)) {
$extras = array($extras);
}
if(!is_array($extras)) {
throw new \Exception('Extras parameter must be array');
}
$dot_pos = strrpos($filename, '.');
if(!$dot_pos) {
$filename .= '.log';
$dot_pos = strrpos($filename, '.');
}
$tmp = strlen($filename) - $dot_pos;
switch ($format) {
case self::LOGPATH_FORMAT_COMPLEX:
// add short date and 24 hour format as last parama
$extras[] = $addHostname
? substr($filename, 0, $dot_pos) . '_' . gethostname()
: substr($filename, 0, $dot_pos);
$extras = array_merge($extras, explode('-', date("H-d-m-Y", Tools::ts())));
// reverse order or extras array so that year is first, month etc...
$extras = array_reverse($extras);
$glue = DIRECTORY_SEPARATOR;
break;
default:
case self::LOGPATH_FORMAT_SIMPLE:
// add machine hostname to extra array
$extras[] = substr($filename, 0, $dot_pos);
if($addHostname) {
$extras[] = gethostname();
}
$extras[] = date("Y-m-d", Tools::ts());
$glue = '_';
break;
}
return implode($glue, $extras) . substr($filename, "-{$tmp}", $tmp);
} | php | private static function _formatFilePath($filename, $format, $extras = array(), $addHostname = false)
{
// we can parse scalars also
if(is_scalar($extras)) {
$extras = array($extras);
}
if(!is_array($extras)) {
throw new \Exception('Extras parameter must be array');
}
$dot_pos = strrpos($filename, '.');
if(!$dot_pos) {
$filename .= '.log';
$dot_pos = strrpos($filename, '.');
}
$tmp = strlen($filename) - $dot_pos;
switch ($format) {
case self::LOGPATH_FORMAT_COMPLEX:
// add short date and 24 hour format as last parama
$extras[] = $addHostname
? substr($filename, 0, $dot_pos) . '_' . gethostname()
: substr($filename, 0, $dot_pos);
$extras = array_merge($extras, explode('-', date("H-d-m-Y", Tools::ts())));
// reverse order or extras array so that year is first, month etc...
$extras = array_reverse($extras);
$glue = DIRECTORY_SEPARATOR;
break;
default:
case self::LOGPATH_FORMAT_SIMPLE:
// add machine hostname to extra array
$extras[] = substr($filename, 0, $dot_pos);
if($addHostname) {
$extras[] = gethostname();
}
$extras[] = date("Y-m-d", Tools::ts());
$glue = '_';
break;
}
return implode($glue, $extras) . substr($filename, "-{$tmp}", $tmp);
} | [
"private",
"static",
"function",
"_formatFilePath",
"(",
"$",
"filename",
",",
"$",
"format",
",",
"$",
"extras",
"=",
"array",
"(",
")",
",",
"$",
"addHostname",
"=",
"false",
")",
"{",
"// we can parse scalars also",
"if",
"(",
"is_scalar",
"(",
"$",
"ex... | Format file path
@param string $filename
@param int $format
@param array $extras
@param bool $addHostname
@throws \Exception
@return string | [
"Format",
"file",
"path"
] | 909d06503abbb21ac6c79a61d1b2b1bd89eb26d7 | https://github.com/g4code/log/blob/909d06503abbb21ac6c79a61d1b2b1bd89eb26d7/src/Writer.php#L176-L220 | train |
g4code/log | src/Writer.php | Writer.writeLogPre | public static function writeLogPre($var, $filename = '__preformated.log', $addRequestData = false, $traceIndex = 1)
{
$msg = self::_preFormat($var, false, $traceIndex, true);
if($addRequestData) {
$msg = Debug::formatHeaderWithTime() . $msg . Debug::formatRequestData();
}
return self::writeLogVerbose($filename, $msg);
} | php | public static function writeLogPre($var, $filename = '__preformated.log', $addRequestData = false, $traceIndex = 1)
{
$msg = self::_preFormat($var, false, $traceIndex, true);
if($addRequestData) {
$msg = Debug::formatHeaderWithTime() . $msg . Debug::formatRequestData();
}
return self::writeLogVerbose($filename, $msg);
} | [
"public",
"static",
"function",
"writeLogPre",
"(",
"$",
"var",
",",
"$",
"filename",
"=",
"'__preformated.log'",
",",
"$",
"addRequestData",
"=",
"false",
",",
"$",
"traceIndex",
"=",
"1",
")",
"{",
"$",
"msg",
"=",
"self",
"::",
"_preFormat",
"(",
"$",... | It will use preVarDump to format variable and WriteLogVerbose to log it to file
@param mixed $var variable to parse and log
@param string $filename log file name
@param bool $addRequestData if we want to log more data, request, time...
@param int $traceIndex debug trace index so we have where method was called
@return bool | [
"It",
"will",
"use",
"preVarDump",
"to",
"format",
"variable",
"and",
"WriteLogVerbose",
"to",
"log",
"it",
"to",
"file"
] | 909d06503abbb21ac6c79a61d1b2b1bd89eb26d7 | https://github.com/g4code/log/blob/909d06503abbb21ac6c79a61d1b2b1bd89eb26d7/src/Writer.php#L231-L240 | train |
nails/module-cdn | admin/controllers/Utilities.php | Utilities.index | public function index()
{
if (!userHasPermission('admin:cdn:utilities:findOrphan')) {
unauthorised();
}
// --------------------------------------------------------------------------
$oInput = Factory::service('Input');
if ($oInput::isCli()) {
$this->indexCli();
} else {
if ($oInput->post()) {
// A little form validation
$type = $oInput->post('type');
$parser = $oInput->post('parser');
$error = '';
if ($type == 'db' && $parser == 'create') {
$error = 'Cannot use "Add to database" results parser when finding orphaned database objects.';
}
if (empty($error)) {
switch ($type) {
case 'db':
$oCdn = Factory::service('Cdn', 'nails/module-cdn');
$this->data['orphans'] = $oCdn->findOrphanedObjects();
break;
// @TODO
case 'file':
$this->data['message'] = '<strong>TODO:</strong> find orphaned files.';
break;
// Invalid request
default:
$this->data['error'] = 'Invalid search type.';
break;
}
if (isset($this->data['orphans'])) {
switch ($parser) {
case 'list':
$this->data['success'] = '<strong>Search complete!</strong> your results are show below.';
break;
// @todo: keep the unset(), it prevents the table from rendering
case 'purge':
$this->data['message'] = '<strong>TODO:</strong> purge results.';
unset($this->data['orphans']);
break;
case 'create':
$this->data['message'] = '<strong>TODO:</strong> create objects using results.';
unset($this->data['orphans']);
break;
// Invalid request
default:
$this->data['error'] = 'Invalid result parse selected.';
unset($this->data['orphans']);
break;
}
}
} else {
$this->data['error'] = 'An error occurred. ' . $error;
}
}
// --------------------------------------------------------------------------
$this->data['page']->title = 'CDN: Find Orphaned Objects';
// --------------------------------------------------------------------------
Helper::loadView('index');
}
} | php | public function index()
{
if (!userHasPermission('admin:cdn:utilities:findOrphan')) {
unauthorised();
}
// --------------------------------------------------------------------------
$oInput = Factory::service('Input');
if ($oInput::isCli()) {
$this->indexCli();
} else {
if ($oInput->post()) {
// A little form validation
$type = $oInput->post('type');
$parser = $oInput->post('parser');
$error = '';
if ($type == 'db' && $parser == 'create') {
$error = 'Cannot use "Add to database" results parser when finding orphaned database objects.';
}
if (empty($error)) {
switch ($type) {
case 'db':
$oCdn = Factory::service('Cdn', 'nails/module-cdn');
$this->data['orphans'] = $oCdn->findOrphanedObjects();
break;
// @TODO
case 'file':
$this->data['message'] = '<strong>TODO:</strong> find orphaned files.';
break;
// Invalid request
default:
$this->data['error'] = 'Invalid search type.';
break;
}
if (isset($this->data['orphans'])) {
switch ($parser) {
case 'list':
$this->data['success'] = '<strong>Search complete!</strong> your results are show below.';
break;
// @todo: keep the unset(), it prevents the table from rendering
case 'purge':
$this->data['message'] = '<strong>TODO:</strong> purge results.';
unset($this->data['orphans']);
break;
case 'create':
$this->data['message'] = '<strong>TODO:</strong> create objects using results.';
unset($this->data['orphans']);
break;
// Invalid request
default:
$this->data['error'] = 'Invalid result parse selected.';
unset($this->data['orphans']);
break;
}
}
} else {
$this->data['error'] = 'An error occurred. ' . $error;
}
}
// --------------------------------------------------------------------------
$this->data['page']->title = 'CDN: Find Orphaned Objects';
// --------------------------------------------------------------------------
Helper::loadView('index');
}
} | [
"public",
"function",
"index",
"(",
")",
"{",
"if",
"(",
"!",
"userHasPermission",
"(",
"'admin:cdn:utilities:findOrphan'",
")",
")",
"{",
"unauthorised",
"(",
")",
";",
"}",
"// --------------------------------------------------------------------------",
"$",
"oInput",
... | Find orphaned CDN objects
@return void | [
"Find",
"orphaned",
"CDN",
"objects"
] | 1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef | https://github.com/nails/module-cdn/blob/1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef/admin/controllers/Utilities.php#L57-L149 | train |
Rareloop/primer-core | src/Primer/Templating/View.php | View.render | public static function render($name, $params = array())
{
if (is_array($params)) {
$params = new ViewData($params);
}
$templateClass = Primer::$TEMPLATE_CLASS;
$template = new $templateClass(Primer::$VIEW_PATH, $name);
Event::fire('view.' . $name, $params);
return $template->render($params);
} | php | public static function render($name, $params = array())
{
if (is_array($params)) {
$params = new ViewData($params);
}
$templateClass = Primer::$TEMPLATE_CLASS;
$template = new $templateClass(Primer::$VIEW_PATH, $name);
Event::fire('view.' . $name, $params);
return $template->render($params);
} | [
"public",
"static",
"function",
"render",
"(",
"$",
"name",
",",
"$",
"params",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"params",
")",
")",
"{",
"$",
"params",
"=",
"new",
"ViewData",
"(",
"$",
"params",
")",
";",
"}",
... | Load a template and optionally pass in params
@param string $name The name of the template to load (without .handlebars extension)
@param Array|ViewData $params An associative array of variables to export into the view
@return string HTML text
@author Joe Lambert | [
"Load",
"a",
"template",
"and",
"optionally",
"pass",
"in",
"params"
] | fe098d6794a4add368f97672397dc93d223a1786 | https://github.com/Rareloop/primer-core/blob/fe098d6794a4add368f97672397dc93d223a1786/src/Primer/Templating/View.php#L21-L33 | train |
jon48/webtrees-lib | src/Webtrees/Module/PatronymicLineage/Model/LineageRootNode.php | LineageRootNode.addPlace | public function addPlace(Place $place) {
if(!is_null($place) && !$place->isEmpty()){
$place_name = $place->getFullName();
if(isset($this->places[$place_name])){
$this->places[$place_name]+=1;
}
else{
$this->places[$place_name] = 1;
}
}
} | php | public function addPlace(Place $place) {
if(!is_null($place) && !$place->isEmpty()){
$place_name = $place->getFullName();
if(isset($this->places[$place_name])){
$this->places[$place_name]+=1;
}
else{
$this->places[$place_name] = 1;
}
}
} | [
"public",
"function",
"addPlace",
"(",
"Place",
"$",
"place",
")",
"{",
"if",
"(",
"!",
"is_null",
"(",
"$",
"place",
")",
"&&",
"!",
"$",
"place",
"->",
"isEmpty",
"(",
")",
")",
"{",
"$",
"place_name",
"=",
"$",
"place",
"->",
"getFullName",
"(",... | Adds a place to the list of lineage's place
@param Place $place | [
"Adds",
"a",
"place",
"to",
"the",
"list",
"of",
"lineage",
"s",
"place"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/PatronymicLineage/Model/LineageRootNode.php#L39-L49 | train |
voslartomas/WebCMS2 | AdminModule/presenters/BasePresenter.php | BasePresenter.createGrid | public function createGrid(Nette\Application\UI\Presenter $presenter, $name, $entity, $order = null, $where = null)
{
$grid = new \Grido\Grid($presenter, $name);
$qb = $this->em->createQueryBuilder();
if ($order) {
foreach ($order as $o) {
$qb->addOrderBy('l.'.$o['by'], $o['dir']);
}
}
if ($where) {
foreach ($where as $w) {
$qb->andWhere('l.'.$w);
}
}
if (strpos($entity, 'WebCMS') === false) {
$grid->setModel($qb->select('l')->from("WebCMS\Entity\\$entity", 'l'));
} else {
$grid->setModel($qb->select('l')->from($entity, 'l'));
}
$grid->setRememberState(true);
$grid->setDefaultPerPage(10);
$grid->setTranslator($this->translator);
$grid->setFilterRenderType(\Grido\Components\Filters\Filter::RENDER_INNER);
return $grid;
} | php | public function createGrid(Nette\Application\UI\Presenter $presenter, $name, $entity, $order = null, $where = null)
{
$grid = new \Grido\Grid($presenter, $name);
$qb = $this->em->createQueryBuilder();
if ($order) {
foreach ($order as $o) {
$qb->addOrderBy('l.'.$o['by'], $o['dir']);
}
}
if ($where) {
foreach ($where as $w) {
$qb->andWhere('l.'.$w);
}
}
if (strpos($entity, 'WebCMS') === false) {
$grid->setModel($qb->select('l')->from("WebCMS\Entity\\$entity", 'l'));
} else {
$grid->setModel($qb->select('l')->from($entity, 'l'));
}
$grid->setRememberState(true);
$grid->setDefaultPerPage(10);
$grid->setTranslator($this->translator);
$grid->setFilterRenderType(\Grido\Components\Filters\Filter::RENDER_INNER);
return $grid;
} | [
"public",
"function",
"createGrid",
"(",
"Nette",
"\\",
"Application",
"\\",
"UI",
"\\",
"Presenter",
"$",
"presenter",
",",
"$",
"name",
",",
"$",
"entity",
",",
"$",
"order",
"=",
"null",
",",
"$",
"where",
"=",
"null",
")",
"{",
"$",
"grid",
"=",
... | Creates default basic grid.
@param Nette\Application\UI\Presenter $presenter
@param String $name
@param String $entity
@param string[] $where
@return \Grido\Grid | [
"Creates",
"default",
"basic",
"grid",
"."
] | b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf | https://github.com/voslartomas/WebCMS2/blob/b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf/AdminModule/presenters/BasePresenter.php#L291-L321 | train |
voslartomas/WebCMS2 | AdminModule/presenters/BasePresenter.php | BasePresenter.createForm | public function createForm()
{
$form = new Nette\Application\UI\Form();
$form->getElementPrototype()->addAttributes(array('class' => 'ajax'));
$form->setTranslator($this->translator);
$form->setRenderer(new BootstrapRenderer());
return $form;
} | php | public function createForm()
{
$form = new Nette\Application\UI\Form();
$form->getElementPrototype()->addAttributes(array('class' => 'ajax'));
$form->setTranslator($this->translator);
$form->setRenderer(new BootstrapRenderer());
return $form;
} | [
"public",
"function",
"createForm",
"(",
")",
"{",
"$",
"form",
"=",
"new",
"Nette",
"\\",
"Application",
"\\",
"UI",
"\\",
"Form",
"(",
")",
";",
"$",
"form",
"->",
"getElementPrototype",
"(",
")",
"->",
"addAttributes",
"(",
"array",
"(",
"'class'",
... | Creates form and rewrite renderer for bootstrap.
@return UI\Form | [
"Creates",
"form",
"and",
"rewrite",
"renderer",
"for",
"bootstrap",
"."
] | b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf | https://github.com/voslartomas/WebCMS2/blob/b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf/AdminModule/presenters/BasePresenter.php#L327-L336 | train |
voslartomas/WebCMS2 | AdminModule/presenters/BasePresenter.php | BasePresenter.injectEntityManager | public function injectEntityManager(\Doctrine\ORM\EntityManager $em)
{
if ($this->em) {
throw new \Nette\InvalidStateException('Entity manager has been already set.');
}
$this->em = $em;
return $this;
} | php | public function injectEntityManager(\Doctrine\ORM\EntityManager $em)
{
if ($this->em) {
throw new \Nette\InvalidStateException('Entity manager has been already set.');
}
$this->em = $em;
return $this;
} | [
"public",
"function",
"injectEntityManager",
"(",
"\\",
"Doctrine",
"\\",
"ORM",
"\\",
"EntityManager",
"$",
"em",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"em",
")",
"{",
"throw",
"new",
"\\",
"Nette",
"\\",
"InvalidStateException",
"(",
"'Entity manager has... | Injects entity manager.
@param \Doctrine\ORM\EntityManager $em
@return BasePresenter
@throws \Nette\InvalidStateException | [
"Injects",
"entity",
"manager",
"."
] | b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf | https://github.com/voslartomas/WebCMS2/blob/b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf/AdminModule/presenters/BasePresenter.php#L344-L353 | train |
voslartomas/WebCMS2 | AdminModule/presenters/BasePresenter.php | BasePresenter.checkPermission | private function checkPermission()
{
// creates system acl
$acl = $this->initAcl();
$identity = $this->getUser()->getIdentity();
$permissions = $this->initPermissions($identity);
foreach ($permissions as $key => $p) {
if ($p && $acl->hasResource($key)) {
$acl->allow($identity->roles[0], $key, Nette\Security\Permission::ALL);
}
}
// homepage and login page can access everyone
$acl->allow(Nette\Security\Permission::ALL, 'admin:Homepage', Nette\Security\Permission::ALL);
$acl->allow(Nette\Security\Permission::ALL, 'admin:Login', Nette\Security\Permission::ALL);
// superadmin has access to everywhere
$acl->allow('superadmin', Nette\Security\Permission::ALL, Nette\Security\Permission::ALL);
$roles = $this->getUser()->getRoles();
if (!$this->checkRights($acl, $roles)) {
$this->presenter->flashMessage($this->translation['You do not have a permission to do this operation!'], 'danger');
$this->redirect(":Admin:Homepage:");
}
} | php | private function checkPermission()
{
// creates system acl
$acl = $this->initAcl();
$identity = $this->getUser()->getIdentity();
$permissions = $this->initPermissions($identity);
foreach ($permissions as $key => $p) {
if ($p && $acl->hasResource($key)) {
$acl->allow($identity->roles[0], $key, Nette\Security\Permission::ALL);
}
}
// homepage and login page can access everyone
$acl->allow(Nette\Security\Permission::ALL, 'admin:Homepage', Nette\Security\Permission::ALL);
$acl->allow(Nette\Security\Permission::ALL, 'admin:Login', Nette\Security\Permission::ALL);
// superadmin has access to everywhere
$acl->allow('superadmin', Nette\Security\Permission::ALL, Nette\Security\Permission::ALL);
$roles = $this->getUser()->getRoles();
if (!$this->checkRights($acl, $roles)) {
$this->presenter->flashMessage($this->translation['You do not have a permission to do this operation!'], 'danger');
$this->redirect(":Admin:Homepage:");
}
} | [
"private",
"function",
"checkPermission",
"(",
")",
"{",
"// creates system acl",
"$",
"acl",
"=",
"$",
"this",
"->",
"initAcl",
"(",
")",
";",
"$",
"identity",
"=",
"$",
"this",
"->",
"getUser",
"(",
")",
"->",
"getIdentity",
"(",
")",
";",
"$",
"perm... | Checks user permission.
@return void | [
"Checks",
"user",
"permission",
"."
] | b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf | https://github.com/voslartomas/WebCMS2/blob/b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf/AdminModule/presenters/BasePresenter.php#L451-L477 | train |
voslartomas/WebCMS2 | AdminModule/presenters/BasePresenter.php | BasePresenter.formatLayoutTemplateFiles | public function formatLayoutTemplateFiles()
{
$name = $this->getName();
$presenter = substr($name, strrpos(':'.$name, ':'));
$layout = $this->layout ? $this->layout : 'layout';
$dir = dirname($this->getReflection()->getFileName());
$dir = is_dir("$dir/templates") ? $dir : dirname($dir);
$list = array(
APP_DIR."/../libs/webcms2/webcms2/AdminModule/templates/@$layout.latte",
);
do {
$list[] = "$dir/templates/@$layout.latte";
$list[] = "$dir/templates/@$layout.phtml";
$dir = dirname($dir);
} while ($dir && ($name = substr($name, 0, strrpos($name, ':'))));
return $list;
} | php | public function formatLayoutTemplateFiles()
{
$name = $this->getName();
$presenter = substr($name, strrpos(':'.$name, ':'));
$layout = $this->layout ? $this->layout : 'layout';
$dir = dirname($this->getReflection()->getFileName());
$dir = is_dir("$dir/templates") ? $dir : dirname($dir);
$list = array(
APP_DIR."/../libs/webcms2/webcms2/AdminModule/templates/@$layout.latte",
);
do {
$list[] = "$dir/templates/@$layout.latte";
$list[] = "$dir/templates/@$layout.phtml";
$dir = dirname($dir);
} while ($dir && ($name = substr($name, 0, strrpos($name, ':'))));
return $list;
} | [
"public",
"function",
"formatLayoutTemplateFiles",
"(",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"getName",
"(",
")",
";",
"$",
"presenter",
"=",
"substr",
"(",
"$",
"name",
",",
"strrpos",
"(",
"':'",
".",
"$",
"name",
",",
"':'",
")",
")",
... | Formats layout template file names.
@return array | [
"Formats",
"layout",
"template",
"file",
"names",
"."
] | b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf | https://github.com/voslartomas/WebCMS2/blob/b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf/AdminModule/presenters/BasePresenter.php#L700-L719 | train |
voslartomas/WebCMS2 | AdminModule/presenters/BasePresenter.php | BasePresenter.collectionToArray | public function collectionToArray($collection, $title = 'title')
{
$array = array();
foreach ($collection as $item) {
$getter = 'get'.ucfirst($title);
$array[$item->getId()] = $item->$getter();
}
return $array;
} | php | public function collectionToArray($collection, $title = 'title')
{
$array = array();
foreach ($collection as $item) {
$getter = 'get'.ucfirst($title);
$array[$item->getId()] = $item->$getter();
}
return $array;
} | [
"public",
"function",
"collectionToArray",
"(",
"$",
"collection",
",",
"$",
"title",
"=",
"'title'",
")",
"{",
"$",
"array",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"collection",
"as",
"$",
"item",
")",
"{",
"$",
"getter",
"=",
"'get'",
".... | Transfer collection into array.
@param [type] $collection [description]
@param string $title [description]
@return array [description] | [
"Transfer",
"collection",
"into",
"array",
"."
] | b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf | https://github.com/voslartomas/WebCMS2/blob/b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf/AdminModule/presenters/BasePresenter.php#L729-L738 | train |
jon48/webtrees-lib | src/Webtrees/Module/Sosa/Views/SosaListView.php | SosaListView.renderSosaHeader | protected function renderSosaHeader() {
$selectedgen = $this->data->get('generation');
$max_gen = $this->data->get('max_gen');
?>
<form method="get" name="setgen" action="module.php">
<input type="hidden" name="mod" value="<?php echo $this->data->get('url_module');?>">
<input type="hidden" name="mod_action" value="<?php echo $this->data->get('url_action');?>">
<input type="hidden" name="ged" value="<?php echo $this->data->get('url_ged');?>">
<div class="maj-table">
<div class="maj-row">
<div class="label"><?php echo I18N::translate('Choose generation') ?></div>
</div>
<div class="maj-row">
<div class="value">
<select name="gen">
<?php for($i=$this->data->get('min_gen'); $i <= $max_gen;$i++) {?>
<option value="<?php echo $i; ?>"
<?php if($selectedgen && $selectedgen==$i) { ?> selected="true" <?php } ?>
><?php echo I18N::translate('Generation %d', $i); ?>
</option>
<?php } ?>
</select>
</div>
</div>
</div>
<input type="submit" value="<?php echo I18N::translate('Show');?>" />
<br />
</form>
<?php if($selectedgen > 0) { ?>
<h4>
<?php if($selectedgen > $this->data->get('min_gen')) { ?>
<a href="module.php?mod=<?php echo $this->data->get('url_module');?>&mod_action=<?php echo $this->data->get('url_action');?>&ged=<?php echo $this->data->get('url_ged');?>&gen=<?php echo $selectedgen-1; ?>">
<i class="icon-ldarrow" title="<?php echo I18N::translate('Previous generation'); ?>" ></i>
</a>
<?php } ?>
<?php echo I18N::translate('Generation %d', $selectedgen); ?>
<?php if($selectedgen < $max_gen) { ?>
<a href="module.php?mod=<?php echo $this->data->get('url_module');?>&mod_action=<?php echo $this->data->get('url_action');?>&ged=<?php echo $this->data->get('url_ged');?>&gen=<?php echo $selectedgen+1; ?>">
<i class="icon-rdarrow" title="<?php echo I18N::translate('Next generation'); ?>" ></i>
</a>
<?php } ?>
</h4>
<?php
}
} | php | protected function renderSosaHeader() {
$selectedgen = $this->data->get('generation');
$max_gen = $this->data->get('max_gen');
?>
<form method="get" name="setgen" action="module.php">
<input type="hidden" name="mod" value="<?php echo $this->data->get('url_module');?>">
<input type="hidden" name="mod_action" value="<?php echo $this->data->get('url_action');?>">
<input type="hidden" name="ged" value="<?php echo $this->data->get('url_ged');?>">
<div class="maj-table">
<div class="maj-row">
<div class="label"><?php echo I18N::translate('Choose generation') ?></div>
</div>
<div class="maj-row">
<div class="value">
<select name="gen">
<?php for($i=$this->data->get('min_gen'); $i <= $max_gen;$i++) {?>
<option value="<?php echo $i; ?>"
<?php if($selectedgen && $selectedgen==$i) { ?> selected="true" <?php } ?>
><?php echo I18N::translate('Generation %d', $i); ?>
</option>
<?php } ?>
</select>
</div>
</div>
</div>
<input type="submit" value="<?php echo I18N::translate('Show');?>" />
<br />
</form>
<?php if($selectedgen > 0) { ?>
<h4>
<?php if($selectedgen > $this->data->get('min_gen')) { ?>
<a href="module.php?mod=<?php echo $this->data->get('url_module');?>&mod_action=<?php echo $this->data->get('url_action');?>&ged=<?php echo $this->data->get('url_ged');?>&gen=<?php echo $selectedgen-1; ?>">
<i class="icon-ldarrow" title="<?php echo I18N::translate('Previous generation'); ?>" ></i>
</a>
<?php } ?>
<?php echo I18N::translate('Generation %d', $selectedgen); ?>
<?php if($selectedgen < $max_gen) { ?>
<a href="module.php?mod=<?php echo $this->data->get('url_module');?>&mod_action=<?php echo $this->data->get('url_action');?>&ged=<?php echo $this->data->get('url_ged');?>&gen=<?php echo $selectedgen+1; ?>">
<i class="icon-rdarrow" title="<?php echo I18N::translate('Next generation'); ?>" ></i>
</a>
<?php } ?>
</h4>
<?php
}
} | [
"protected",
"function",
"renderSosaHeader",
"(",
")",
"{",
"$",
"selectedgen",
"=",
"$",
"this",
"->",
"data",
"->",
"get",
"(",
"'generation'",
")",
";",
"$",
"max_gen",
"=",
"$",
"this",
"->",
"data",
"->",
"get",
"(",
"'max_gen'",
")",
";",
"?>\n ... | Render the common header to Sosa Lists, made of the generation selector, and the generation navigator | [
"Render",
"the",
"common",
"header",
"to",
"Sosa",
"Lists",
"made",
"of",
"the",
"generation",
"selector",
"and",
"the",
"generation",
"navigator"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/Sosa/Views/SosaListView.php#L71-L119 | train |
nails/module-cdn | admin/controllers/Manager.php | Manager.index | public function index()
{
if (!userHasPermission('admin:cdn:manager:object:browse')) {
unauthorised();
}
$oInput = Factory::service('Input');
$this->data['sBucketSlug'] = $oInput->get('bucket');
$oAsset = Factory::service('Asset');
$oAsset->library('KNOCKOUT');
// @todo (Pablo - 2018-12-01) - Update/Remove/Use minified once JS is refactored to be a module
$oAsset->load('admin.mediamanager.js', 'nails/module-cdn');
$sBucketSlug = $oInput->get('bucket');
$sCallbackHandler = $oInput->get('CKEditor') ? 'ckeditor' : 'picker';
if ($sCallbackHandler === 'ckeditor') {
$aCallback = [$oInput->get('CKEditorFuncNum')];
} else {
$aCallback = array_filter((array) $oInput->get('callback'));
}
$oAsset->inline(
'ko.applyBindings(
new MediaManager(
"' . $sBucketSlug . '",
"' . $sCallbackHandler . '",
' . json_encode($aCallback) . ',
' . json_encode((bool) $oInput->get('isModal')) . '
)
);',
'JS'
);
Helper::loadView('index');
} | php | public function index()
{
if (!userHasPermission('admin:cdn:manager:object:browse')) {
unauthorised();
}
$oInput = Factory::service('Input');
$this->data['sBucketSlug'] = $oInput->get('bucket');
$oAsset = Factory::service('Asset');
$oAsset->library('KNOCKOUT');
// @todo (Pablo - 2018-12-01) - Update/Remove/Use minified once JS is refactored to be a module
$oAsset->load('admin.mediamanager.js', 'nails/module-cdn');
$sBucketSlug = $oInput->get('bucket');
$sCallbackHandler = $oInput->get('CKEditor') ? 'ckeditor' : 'picker';
if ($sCallbackHandler === 'ckeditor') {
$aCallback = [$oInput->get('CKEditorFuncNum')];
} else {
$aCallback = array_filter((array) $oInput->get('callback'));
}
$oAsset->inline(
'ko.applyBindings(
new MediaManager(
"' . $sBucketSlug . '",
"' . $sCallbackHandler . '",
' . json_encode($aCallback) . ',
' . json_encode((bool) $oInput->get('isModal')) . '
)
);',
'JS'
);
Helper::loadView('index');
} | [
"public",
"function",
"index",
"(",
")",
"{",
"if",
"(",
"!",
"userHasPermission",
"(",
"'admin:cdn:manager:object:browse'",
")",
")",
"{",
"unauthorised",
"(",
")",
";",
"}",
"$",
"oInput",
"=",
"Factory",
"::",
"service",
"(",
"'Input'",
")",
";",
"$",
... | Browse CDN Objects
@return void | [
"Browse",
"CDN",
"Objects"
] | 1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef | https://github.com/nails/module-cdn/blob/1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef/admin/controllers/Manager.php#L62-L98 | train |
RobinDev/PHPToJS | src/PHPToJS.php | PHPToJS.render | public static function render($mixed)
{
if (!is_array($mixed) && !is_object($mixed)) {
return strpos(str_replace(' ', '', $mixed), 'function(') === 0 ? $mixed : json_encode($mixed);
}
$isNumArr = array_keys((array) $mixed) === range(0, count((array) $mixed) - 1);
$isObject = is_object($mixed) || (!$isNumArr && !empty($mixed));
$r = array();
$i = 0;
foreach ($mixed as $k => $m) {
$r[$i] = ($isObject ? self::renderObjectKey($k).':' : '').self::render($m);
++$i;
}
return ($isObject ? '{' : '[').implode(',', $r).($isObject ? '}' : ']');
} | php | public static function render($mixed)
{
if (!is_array($mixed) && !is_object($mixed)) {
return strpos(str_replace(' ', '', $mixed), 'function(') === 0 ? $mixed : json_encode($mixed);
}
$isNumArr = array_keys((array) $mixed) === range(0, count((array) $mixed) - 1);
$isObject = is_object($mixed) || (!$isNumArr && !empty($mixed));
$r = array();
$i = 0;
foreach ($mixed as $k => $m) {
$r[$i] = ($isObject ? self::renderObjectKey($k).':' : '').self::render($m);
++$i;
}
return ($isObject ? '{' : '[').implode(',', $r).($isObject ? '}' : ']');
} | [
"public",
"static",
"function",
"render",
"(",
"$",
"mixed",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"mixed",
")",
"&&",
"!",
"is_object",
"(",
"$",
"mixed",
")",
")",
"{",
"return",
"strpos",
"(",
"str_replace",
"(",
"' '",
",",
"''",
",",... | Render the variable's content from PHP to Javascript
@param mixed $mixed
@return string Javascript code | [
"Render",
"the",
"variable",
"s",
"content",
"from",
"PHP",
"to",
"Javascript"
] | e2ea20b2d75478fb40352be06e69704488a248a1 | https://github.com/RobinDev/PHPToJS/blob/e2ea20b2d75478fb40352be06e69704488a248a1/src/PHPToJS.php#L22-L39 | train |
jon48/webtrees-lib | src/Webtrees/Module/WelcomeBlock/PiwikController.php | PiwikController.getNumberOfVisitsPiwik | private function getNumberOfVisitsPiwik($block_id, $period='year'){
$piwik_url = $this->module->getBlockSetting($block_id, 'piwik_url');
$piwik_siteid = $this->module->getBlockSetting($block_id, 'piwik_siteid');
$piwik_token = $this->module->getBlockSetting($block_id, 'piwik_token');
if($piwik_url && strlen($piwik_url) > 0 &&
$piwik_siteid && strlen($piwik_siteid) > 0 &&
$piwik_token && strlen($piwik_token)
)
{
// calling Piwik REST API
$url = $piwik_url;
$url .= '?module=API&method=VisitsSummary.getVisits';
$url .= '&idSite='.$piwik_siteid.'&period='.$period.'&date=today';
$url .= '&format=PHP';
$url .= '&token_auth='.$piwik_token;
if($fetched = File::fetchUrl($url)) {
$content = @unserialize($fetched);
if(is_numeric($content)) return $content;
}
}
return null;
} | php | private function getNumberOfVisitsPiwik($block_id, $period='year'){
$piwik_url = $this->module->getBlockSetting($block_id, 'piwik_url');
$piwik_siteid = $this->module->getBlockSetting($block_id, 'piwik_siteid');
$piwik_token = $this->module->getBlockSetting($block_id, 'piwik_token');
if($piwik_url && strlen($piwik_url) > 0 &&
$piwik_siteid && strlen($piwik_siteid) > 0 &&
$piwik_token && strlen($piwik_token)
)
{
// calling Piwik REST API
$url = $piwik_url;
$url .= '?module=API&method=VisitsSummary.getVisits';
$url .= '&idSite='.$piwik_siteid.'&period='.$period.'&date=today';
$url .= '&format=PHP';
$url .= '&token_auth='.$piwik_token;
if($fetched = File::fetchUrl($url)) {
$content = @unserialize($fetched);
if(is_numeric($content)) return $content;
}
}
return null;
} | [
"private",
"function",
"getNumberOfVisitsPiwik",
"(",
"$",
"block_id",
",",
"$",
"period",
"=",
"'year'",
")",
"{",
"$",
"piwik_url",
"=",
"$",
"this",
"->",
"module",
"->",
"getBlockSetting",
"(",
"$",
"block_id",
",",
"'piwik_url'",
")",
";",
"$",
"piwik... | Retrieve the number of visitors from Piwik, for a given period.
@param string $block_id
@param string $period
@param (null|int) Number of visits | [
"Retrieve",
"the",
"number",
"of",
"visitors",
"from",
"Piwik",
"for",
"a",
"given",
"period",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/WelcomeBlock/PiwikController.php#L33-L58 | train |
jon48/webtrees-lib | src/Webtrees/Module/PatronymicLineage/Model/LineageBuilder.php | LineageBuilder.buildLineages | public function buildLineages() {
$indis = \Fisharebest\Webtrees\Query\QueryName::individuals($this->tree, $this->surname, null, null, false, false);
if(count($indis) == 0) return null;
$root_lineages = array();
foreach($indis as $indi) {
$pid = $indi->getXref();
if(!isset($this->used_indis[$pid])){
//Find the root of the lineage
/** @var Fisharebest\Webtrees\Individual $indiFirst */
$indiFirst= $this->getLineageRootIndividual($indi);
if($indiFirst){
$this->used_indis[$indiFirst->getXref()] = true;
if($indiFirst->canShow()){
//Check if the root individual has brothers and sisters, without parents
$indiChildFamily = $indiFirst->getPrimaryChildFamily();
if($indiChildFamily !== null){
$root_node = new LineageRootNode(null);
$root_node->addFamily($indiChildFamily);
}
else{
$root_node = new LineageRootNode($indiFirst);
}
$root_node = $this->buildLineage($root_node);
if($root_node) $root_lineages[] = $root_node;
}
}
}
}
return $root_lineages;
} | php | public function buildLineages() {
$indis = \Fisharebest\Webtrees\Query\QueryName::individuals($this->tree, $this->surname, null, null, false, false);
if(count($indis) == 0) return null;
$root_lineages = array();
foreach($indis as $indi) {
$pid = $indi->getXref();
if(!isset($this->used_indis[$pid])){
//Find the root of the lineage
/** @var Fisharebest\Webtrees\Individual $indiFirst */
$indiFirst= $this->getLineageRootIndividual($indi);
if($indiFirst){
$this->used_indis[$indiFirst->getXref()] = true;
if($indiFirst->canShow()){
//Check if the root individual has brothers and sisters, without parents
$indiChildFamily = $indiFirst->getPrimaryChildFamily();
if($indiChildFamily !== null){
$root_node = new LineageRootNode(null);
$root_node->addFamily($indiChildFamily);
}
else{
$root_node = new LineageRootNode($indiFirst);
}
$root_node = $this->buildLineage($root_node);
if($root_node) $root_lineages[] = $root_node;
}
}
}
}
return $root_lineages;
} | [
"public",
"function",
"buildLineages",
"(",
")",
"{",
"$",
"indis",
"=",
"\\",
"Fisharebest",
"\\",
"Webtrees",
"\\",
"Query",
"\\",
"QueryName",
"::",
"individuals",
"(",
"$",
"this",
"->",
"tree",
",",
"$",
"this",
"->",
"surname",
",",
"null",
",",
... | Build all patronymic lineages for the reference surname.
@return array List of root patronymic lineages | [
"Build",
"all",
"patronymic",
"lineages",
"for",
"the",
"reference",
"surname",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/PatronymicLineage/Model/LineageBuilder.php#L54-L87 | train |
jon48/webtrees-lib | src/Webtrees/Module/PatronymicLineage/Model/LineageBuilder.php | LineageBuilder.getLineageRootIndividual | protected function getLineageRootIndividual(Individual $indi) {
$is_first=false;
$dindi = new \MyArtJaub\Webtrees\Individual($indi);
$indi_surname=$dindi->getUnprotectedPrimarySurname();
$resIndi = $indi;
while(!$is_first){
//Get the individual parents family
$fam=$resIndi->getPrimaryChildFamily();
if($fam){
$husb=$fam->getHusband();
$wife=$fam->getWife();
//If the father exists, take him
if($husb){
$dhusb = new \MyArtJaub\Webtrees\Individual($husb);
$dhusb->isNewAddition() ? $is_first = true : $resIndi=$husb;
}
//If only a mother exists
else if($wife){
$dwife = new \MyArtJaub\Webtrees\Individual($wife);
$wife_surname=$dwife->getUnprotectedPrimarySurname();
//Check if the child is a natural child of the mother (based on the surname - Warning : surname must be identical)
if(!$dwife->isNewAddition() && I18N::strcasecmp($wife_surname, $indi_surname) == 0){
$resIndi=$wife;
}
else{
$is_first=true;
}
}
else{
$is_first=true;
}
}
else{
$is_first=true;
}
}
if(isset($this->used_indis[$resIndi->getXref()])){
return null;
}
else{
return $resIndi;
}
} | php | protected function getLineageRootIndividual(Individual $indi) {
$is_first=false;
$dindi = new \MyArtJaub\Webtrees\Individual($indi);
$indi_surname=$dindi->getUnprotectedPrimarySurname();
$resIndi = $indi;
while(!$is_first){
//Get the individual parents family
$fam=$resIndi->getPrimaryChildFamily();
if($fam){
$husb=$fam->getHusband();
$wife=$fam->getWife();
//If the father exists, take him
if($husb){
$dhusb = new \MyArtJaub\Webtrees\Individual($husb);
$dhusb->isNewAddition() ? $is_first = true : $resIndi=$husb;
}
//If only a mother exists
else if($wife){
$dwife = new \MyArtJaub\Webtrees\Individual($wife);
$wife_surname=$dwife->getUnprotectedPrimarySurname();
//Check if the child is a natural child of the mother (based on the surname - Warning : surname must be identical)
if(!$dwife->isNewAddition() && I18N::strcasecmp($wife_surname, $indi_surname) == 0){
$resIndi=$wife;
}
else{
$is_first=true;
}
}
else{
$is_first=true;
}
}
else{
$is_first=true;
}
}
if(isset($this->used_indis[$resIndi->getXref()])){
return null;
}
else{
return $resIndi;
}
} | [
"protected",
"function",
"getLineageRootIndividual",
"(",
"Individual",
"$",
"indi",
")",
"{",
"$",
"is_first",
"=",
"false",
";",
"$",
"dindi",
"=",
"new",
"\\",
"MyArtJaub",
"\\",
"Webtrees",
"\\",
"Individual",
"(",
"$",
"indi",
")",
";",
"$",
"indi_sur... | Retrieve the root individual, from any individual.
The Root individual is the individual without a father, or without a mother holding the same name.
@param Individual $indi
@return (Individual|null) Root individual | [
"Retrieve",
"the",
"root",
"individual",
"from",
"any",
"individual",
".",
"The",
"Root",
"individual",
"is",
"the",
"individual",
"without",
"a",
"father",
"or",
"without",
"a",
"mother",
"holding",
"the",
"same",
"name",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/PatronymicLineage/Model/LineageBuilder.php#L96-L138 | train |
CESNET/perun-simplesamlphp-module | lib/Auth/Process/PerunIdentity.php | PerunIdentity.register | public function register($request, $vosForRegistration, $registerUrL = null, $dynamicRegistration = null)
{
if (is_null($registerUrL)) {
$registerUrL = $this->registerUrl;
}
if (is_null($dynamicRegistration)) {
$dynamicRegistration = $this->dynamicRegistration;
}
$request['config'] = array(
self::UIDS_ATTR => $this->uidsAttr,
self::REGISTER_URL => $registerUrL,
self::REGISTER_URL_BASE => $this->registerUrlBase,
self::INTERFACE_PROPNAME => $this->interface,
self::SOURCE_IDP_ENTITY_ID_ATTR => $this->sourceIdPEntityIDAttr,
self::VO_SHORTNAME => $this->voShortName,
self::PERUN_FACILITY_ALLOW_REGISTRATION_TO_GROUPS => $this->facilityAllowRegistrationToGroupsAttr,
self::PERUN_FACILITY_CHECK_GROUP_MEMBERSHIP_ATTR => $this->facilityCheckGroupMembershipAttr,
self::PERUN_FACILITY_DYNAMIC_REGISTRATION_ATTR => $this->facilityDynamicRegistrationAttr,
self::PERUN_FACILITY_REGISTER_URL_ATTR => $this->facilityRegisterUrlAttr,
self::PERUN_FACILITY_VO_SHORT_NAMES_ATTR => $this->facilityVoShortNamesAttr,
);
$stateId = State::saveState($request, 'perun:PerunIdentity');
$callback = Module::getModuleURL('perun/perun_identity_callback.php', array('stateId' => $stateId));
if ($dynamicRegistration) {
$this->registerChooseVoAndGroup($callback, $vosForRegistration, $request);
} else {
$this->registerDirectly($request, $callback, $registerUrL);
}
} | php | public function register($request, $vosForRegistration, $registerUrL = null, $dynamicRegistration = null)
{
if (is_null($registerUrL)) {
$registerUrL = $this->registerUrl;
}
if (is_null($dynamicRegistration)) {
$dynamicRegistration = $this->dynamicRegistration;
}
$request['config'] = array(
self::UIDS_ATTR => $this->uidsAttr,
self::REGISTER_URL => $registerUrL,
self::REGISTER_URL_BASE => $this->registerUrlBase,
self::INTERFACE_PROPNAME => $this->interface,
self::SOURCE_IDP_ENTITY_ID_ATTR => $this->sourceIdPEntityIDAttr,
self::VO_SHORTNAME => $this->voShortName,
self::PERUN_FACILITY_ALLOW_REGISTRATION_TO_GROUPS => $this->facilityAllowRegistrationToGroupsAttr,
self::PERUN_FACILITY_CHECK_GROUP_MEMBERSHIP_ATTR => $this->facilityCheckGroupMembershipAttr,
self::PERUN_FACILITY_DYNAMIC_REGISTRATION_ATTR => $this->facilityDynamicRegistrationAttr,
self::PERUN_FACILITY_REGISTER_URL_ATTR => $this->facilityRegisterUrlAttr,
self::PERUN_FACILITY_VO_SHORT_NAMES_ATTR => $this->facilityVoShortNamesAttr,
);
$stateId = State::saveState($request, 'perun:PerunIdentity');
$callback = Module::getModuleURL('perun/perun_identity_callback.php', array('stateId' => $stateId));
if ($dynamicRegistration) {
$this->registerChooseVoAndGroup($callback, $vosForRegistration, $request);
} else {
$this->registerDirectly($request, $callback, $registerUrL);
}
} | [
"public",
"function",
"register",
"(",
"$",
"request",
",",
"$",
"vosForRegistration",
",",
"$",
"registerUrL",
"=",
"null",
",",
"$",
"dynamicRegistration",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"registerUrL",
")",
")",
"{",
"$",
"regis... | Method for register user to Perun
@param $request
@param $vosForRegistration
@param string $registerUrL
@param bool $dynamicRegistration | [
"Method",
"for",
"register",
"user",
"to",
"Perun"
] | f1d686f06472053a7cdb31f2b2776f9714779ee1 | https://github.com/CESNET/perun-simplesamlphp-module/blob/f1d686f06472053a7cdb31f2b2776f9714779ee1/lib/Auth/Process/PerunIdentity.php#L262-L294 | train |
CESNET/perun-simplesamlphp-module | lib/Auth/Process/PerunIdentity.php | PerunIdentity.registerDirectly | protected function registerDirectly($request, $callback, $registerUrL, $vo = null, $group = null)
{
$params = array();
if (!is_null($vo)) {
$params['vo'] = $vo->getShortName();
if (!is_null($group)) {
$params['group'] = $group->getName();
}
}
$params[self::TARGET_NEW] = $callback;
$params[self::TARGET_EXISTING] = $callback;
$params[self::TARGET_EXTENDED] = $callback;
$id = State::saveState($request, 'perun:PerunIdentity');
if (in_array($this->spEntityId, $this->listOfSpsWithoutInfoAboutRedirection)) {
HTTP::redirectTrustedURL($registerUrL, $params);
}
$url = Module::getModuleURL('perun/unauthorized_access_go_to_registration.php');
HTTP::redirectTrustedURL(
$url,
array(
'StateId' => $id,
'SPMetadata' => $request['SPMetadata'],
'registerUrL' => $registerUrL,
'params' => $params
)
);
} | php | protected function registerDirectly($request, $callback, $registerUrL, $vo = null, $group = null)
{
$params = array();
if (!is_null($vo)) {
$params['vo'] = $vo->getShortName();
if (!is_null($group)) {
$params['group'] = $group->getName();
}
}
$params[self::TARGET_NEW] = $callback;
$params[self::TARGET_EXISTING] = $callback;
$params[self::TARGET_EXTENDED] = $callback;
$id = State::saveState($request, 'perun:PerunIdentity');
if (in_array($this->spEntityId, $this->listOfSpsWithoutInfoAboutRedirection)) {
HTTP::redirectTrustedURL($registerUrL, $params);
}
$url = Module::getModuleURL('perun/unauthorized_access_go_to_registration.php');
HTTP::redirectTrustedURL(
$url,
array(
'StateId' => $id,
'SPMetadata' => $request['SPMetadata'],
'registerUrL' => $registerUrL,
'params' => $params
)
);
} | [
"protected",
"function",
"registerDirectly",
"(",
"$",
"request",
",",
"$",
"callback",
",",
"$",
"registerUrL",
",",
"$",
"vo",
"=",
"null",
",",
"$",
"group",
"=",
"null",
")",
"{",
"$",
"params",
"=",
"array",
"(",
")",
";",
"if",
"(",
"!",
"is_... | Redirect user to registerUrL
@param $request
@param string $callback
@param string $registerUrL
@param Vo|null $vo
@param Group|null $group | [
"Redirect",
"user",
"to",
"registerUrL"
] | f1d686f06472053a7cdb31f2b2776f9714779ee1 | https://github.com/CESNET/perun-simplesamlphp-module/blob/f1d686f06472053a7cdb31f2b2776f9714779ee1/lib/Auth/Process/PerunIdentity.php#L304-L333 | train |
CESNET/perun-simplesamlphp-module | lib/Auth/Process/PerunIdentity.php | PerunIdentity.registerChooseVoAndGroup | protected function registerChooseVoAndGroup($callback, $vosForRegistration, $request)
{
$vosId = array();
$chooseGroupUrl = Module::getModuleURL('perun/perun_identity_choose_vo_and_group.php');
$stateId = State::saveState($request, 'perun:PerunIdentity');
foreach ($vosForRegistration as $vo) {
array_push($vosId, $vo->getId());
}
HTTP::redirectTrustedURL(
$chooseGroupUrl,
array(
self::REGISTER_URL_BASE => $this->registerUrlBase,
'spEntityId' => $this->spEntityId,
'vosIdForRegistration' => $vosId,
self::INTERFACE_PROPNAME => $this->interface,
'callbackUrl' => $callback,
'SPMetadata' => $request['SPMetadata'],
'stateId' => $stateId
)
);
} | php | protected function registerChooseVoAndGroup($callback, $vosForRegistration, $request)
{
$vosId = array();
$chooseGroupUrl = Module::getModuleURL('perun/perun_identity_choose_vo_and_group.php');
$stateId = State::saveState($request, 'perun:PerunIdentity');
foreach ($vosForRegistration as $vo) {
array_push($vosId, $vo->getId());
}
HTTP::redirectTrustedURL(
$chooseGroupUrl,
array(
self::REGISTER_URL_BASE => $this->registerUrlBase,
'spEntityId' => $this->spEntityId,
'vosIdForRegistration' => $vosId,
self::INTERFACE_PROPNAME => $this->interface,
'callbackUrl' => $callback,
'SPMetadata' => $request['SPMetadata'],
'stateId' => $stateId
)
);
} | [
"protected",
"function",
"registerChooseVoAndGroup",
"(",
"$",
"callback",
",",
"$",
"vosForRegistration",
",",
"$",
"request",
")",
"{",
"$",
"vosId",
"=",
"array",
"(",
")",
";",
"$",
"chooseGroupUrl",
"=",
"Module",
"::",
"getModuleURL",
"(",
"'perun/perun_... | Redirect user to page with selection Vo and Group for registration
@param string $callback
@param $vosForRegistration
@param $request | [
"Redirect",
"user",
"to",
"page",
"with",
"selection",
"Vo",
"and",
"Group",
"for",
"registration"
] | f1d686f06472053a7cdb31f2b2776f9714779ee1 | https://github.com/CESNET/perun-simplesamlphp-module/blob/f1d686f06472053a7cdb31f2b2776f9714779ee1/lib/Auth/Process/PerunIdentity.php#L341-L365 | train |
CESNET/perun-simplesamlphp-module | lib/Auth/Process/PerunIdentity.php | PerunIdentity.containsMembersGroup | private function containsMembersGroup($entities)
{
if (empty($entities)) {
return false;
}
foreach ($entities as $entity) {
if (preg_match('/[^:]*:members$/', $entity->getName())) {
return true;
}
}
return false;
} | php | private function containsMembersGroup($entities)
{
if (empty($entities)) {
return false;
}
foreach ($entities as $entity) {
if (preg_match('/[^:]*:members$/', $entity->getName())) {
return true;
}
}
return false;
} | [
"private",
"function",
"containsMembersGroup",
"(",
"$",
"entities",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"entities",
")",
")",
"{",
"return",
"false",
";",
"}",
"foreach",
"(",
"$",
"entities",
"as",
"$",
"entity",
")",
"{",
"if",
"(",
"preg_match"... | Returns true, if entities contains VO members group
@param Group[] $entities
@return bool | [
"Returns",
"true",
"if",
"entities",
"contains",
"VO",
"members",
"group"
] | f1d686f06472053a7cdb31f2b2776f9714779ee1 | https://github.com/CESNET/perun-simplesamlphp-module/blob/f1d686f06472053a7cdb31f2b2776f9714779ee1/lib/Auth/Process/PerunIdentity.php#L373-L384 | train |
CESNET/perun-simplesamlphp-module | lib/Auth/Process/PerunIdentity.php | PerunIdentity.getSPAttributes | protected function getSPAttributes($spEntityID)
{
try {
$facilities = $this->rpcAdapter->getFacilitiesByEntityId($spEntityID);
if (empty($facilities)) {
Logger::warning(
"perun:PerunIdentity: No facility with entityID '" . $spEntityID . "' found."
);
return;
}
$checkGroupMembership = $this->rpcAdapter->getFacilityAttribute(
$facilities[0],
$this->facilityCheckGroupMembershipAttr
);
if (!is_null($checkGroupMembership)) {
$this->checkGroupMembership = $checkGroupMembership;
}
$facilityVoShortNames = $this->rpcAdapter->getFacilityAttribute(
$facilities[0],
$this->facilityVoShortNamesAttr
);
if (!empty($facilityVoShortNames)) {
$this->facilityVoShortNames = $facilityVoShortNames;
}
$dynamicRegistration = $this->rpcAdapter->getFacilityAttribute(
$facilities[0],
$this->facilityDynamicRegistrationAttr
);
if (!is_null($dynamicRegistration)) {
$this->dynamicRegistration = $dynamicRegistration;
}
$this->registerUrl = $this->rpcAdapter->getFacilityAttribute(
$facilities[0],
$this->facilityRegisterUrlAttr
);
if (is_null($this->registerUrl)) {
$this->registerUrl = $this->defaultRegisterUrl;
}
$allowRegistartionToGroups = $this->rpcAdapter->getFacilityAttribute(
$facilities[0],
$this->facilityAllowRegistrationToGroupsAttr
);
if (!is_null($allowRegistartionToGroups)) {
$this->allowRegistrationToGroups = $allowRegistartionToGroups;
}
} catch (\Exception $ex) {
Logger::warning("perun:PerunIdentity: " . $ex);
}
} | php | protected function getSPAttributes($spEntityID)
{
try {
$facilities = $this->rpcAdapter->getFacilitiesByEntityId($spEntityID);
if (empty($facilities)) {
Logger::warning(
"perun:PerunIdentity: No facility with entityID '" . $spEntityID . "' found."
);
return;
}
$checkGroupMembership = $this->rpcAdapter->getFacilityAttribute(
$facilities[0],
$this->facilityCheckGroupMembershipAttr
);
if (!is_null($checkGroupMembership)) {
$this->checkGroupMembership = $checkGroupMembership;
}
$facilityVoShortNames = $this->rpcAdapter->getFacilityAttribute(
$facilities[0],
$this->facilityVoShortNamesAttr
);
if (!empty($facilityVoShortNames)) {
$this->facilityVoShortNames = $facilityVoShortNames;
}
$dynamicRegistration = $this->rpcAdapter->getFacilityAttribute(
$facilities[0],
$this->facilityDynamicRegistrationAttr
);
if (!is_null($dynamicRegistration)) {
$this->dynamicRegistration = $dynamicRegistration;
}
$this->registerUrl = $this->rpcAdapter->getFacilityAttribute(
$facilities[0],
$this->facilityRegisterUrlAttr
);
if (is_null($this->registerUrl)) {
$this->registerUrl = $this->defaultRegisterUrl;
}
$allowRegistartionToGroups = $this->rpcAdapter->getFacilityAttribute(
$facilities[0],
$this->facilityAllowRegistrationToGroupsAttr
);
if (!is_null($allowRegistartionToGroups)) {
$this->allowRegistrationToGroups = $allowRegistartionToGroups;
}
} catch (\Exception $ex) {
Logger::warning("perun:PerunIdentity: " . $ex);
}
} | [
"protected",
"function",
"getSPAttributes",
"(",
"$",
"spEntityID",
")",
"{",
"try",
"{",
"$",
"facilities",
"=",
"$",
"this",
"->",
"rpcAdapter",
"->",
"getFacilitiesByEntityId",
"(",
"$",
"spEntityID",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"facilities",
... | This functions get attributes for facility
@param string $spEntityID | [
"This",
"functions",
"get",
"attributes",
"for",
"facility"
] | f1d686f06472053a7cdb31f2b2776f9714779ee1 | https://github.com/CESNET/perun-simplesamlphp-module/blob/f1d686f06472053a7cdb31f2b2776f9714779ee1/lib/Auth/Process/PerunIdentity.php#L428-L481 | train |
CESNET/perun-simplesamlphp-module | lib/Auth/Process/PerunIdentity.php | PerunIdentity.getVosForRegistration | protected function getVosForRegistration($user)
{
$vos = array();
$members = array();
$vosIdForRegistration = array();
$vosForRegistration = array();
$vos = $this->getVosByFacilityVoShortNames();
foreach ($vos as $vo) {
Logger::debug("Vo:" . print_r($vo, true));
try {
$member = $this->rpcAdapter->getMemberByUser($user, $vo);
Logger::debug("Member:" . print_r($member, true));
array_push($members, $member);
} catch (\Exception $exception) {
array_push($vosForRegistration, $vo);
Logger::warning("perun:PerunIdentity: " . $exception);
}
}
foreach ($members as $member) {
if ($member->getStatus() === Member::VALID ||
$member->getStatus() === Member::EXPIRED) {
array_push($vosIdForRegistration, $member->getVoId());
}
}
foreach ($vos as $vo) {
if (in_array($vo->getId(), $vosIdForRegistration)) {
array_push($vosForRegistration, $vo);
}
}
Logger::debug("VOs for registration: " . print_r($vosForRegistration, true));
return $vosForRegistration;
} | php | protected function getVosForRegistration($user)
{
$vos = array();
$members = array();
$vosIdForRegistration = array();
$vosForRegistration = array();
$vos = $this->getVosByFacilityVoShortNames();
foreach ($vos as $vo) {
Logger::debug("Vo:" . print_r($vo, true));
try {
$member = $this->rpcAdapter->getMemberByUser($user, $vo);
Logger::debug("Member:" . print_r($member, true));
array_push($members, $member);
} catch (\Exception $exception) {
array_push($vosForRegistration, $vo);
Logger::warning("perun:PerunIdentity: " . $exception);
}
}
foreach ($members as $member) {
if ($member->getStatus() === Member::VALID ||
$member->getStatus() === Member::EXPIRED) {
array_push($vosIdForRegistration, $member->getVoId());
}
}
foreach ($vos as $vo) {
if (in_array($vo->getId(), $vosIdForRegistration)) {
array_push($vosForRegistration, $vo);
}
}
Logger::debug("VOs for registration: " . print_r($vosForRegistration, true));
return $vosForRegistration;
} | [
"protected",
"function",
"getVosForRegistration",
"(",
"$",
"user",
")",
"{",
"$",
"vos",
"=",
"array",
"(",
")",
";",
"$",
"members",
"=",
"array",
"(",
")",
";",
"$",
"vosIdForRegistration",
"=",
"array",
"(",
")",
";",
"$",
"vosForRegistration",
"=",
... | Returns list of sspmod_perun_model_Vo to which the user may register
@param User $user
@return array of Vo | [
"Returns",
"list",
"of",
"sspmod_perun_model_Vo",
"to",
"which",
"the",
"user",
"may",
"register"
] | f1d686f06472053a7cdb31f2b2776f9714779ee1 | https://github.com/CESNET/perun-simplesamlphp-module/blob/f1d686f06472053a7cdb31f2b2776f9714779ee1/lib/Auth/Process/PerunIdentity.php#L551-L585 | train |
jon48/webtrees-lib | src/Webtrees/Module/GeoDispersion/Model/OutlineMap.php | OutlineMap.load | protected function load() {
if(file_exists(WT_ROOT.WT_MODULES_DIR.Constants::MODULE_MAJ_GEODISP_NAME.'/maps/'.$this->filename)){
$xml = simplexml_load_file(WT_ROOT.WT_MODULES_DIR.Constants::MODULE_MAJ_GEODISP_NAME.'/maps/'.$this->filename);
if($xml){
$this->description = trim($xml->displayName);
$this->top_level_name = trim($xml->topLevel);
$this->canvas = new OutlineMapCanvas(
trim($xml->canvas->width),
trim($xml->canvas->height),
trim($xml->canvas->maxcolor),
trim($xml->canvas->hovercolor),
trim($xml->canvas->bgcolor),
trim($xml->canvas->bgstroke),
trim($xml->canvas->defaultcolor),
trim($xml->canvas->defaultstroke)
);
foreach($xml->subdivisions->children() as $subdivision){
$attributes = $subdivision->attributes();
$key = I18N::strtolower(trim($attributes['name']));
if(isset($attributes['parent'])) $key .= '@'. I18N::strtolower(trim($attributes['parent']));
$this->subdivisions[$key] = array(
'id' => trim($attributes['id']),
'displayname' => trim($attributes['name']),
'coord' => trim($subdivision[0])
);
}
if(isset($xml->mappings)) {
foreach($xml->mappings->children() as $mappings){
$attributes = $mappings->attributes();
$this->mappings[I18N::strtolower(trim($attributes['name']))] = I18N::strtolower(trim($attributes['mapto']));
}
}
$this->is_loaded = true;
return;
}
}
throw new \Exception('The Outline Map could not be loaded from XML.');
} | php | protected function load() {
if(file_exists(WT_ROOT.WT_MODULES_DIR.Constants::MODULE_MAJ_GEODISP_NAME.'/maps/'.$this->filename)){
$xml = simplexml_load_file(WT_ROOT.WT_MODULES_DIR.Constants::MODULE_MAJ_GEODISP_NAME.'/maps/'.$this->filename);
if($xml){
$this->description = trim($xml->displayName);
$this->top_level_name = trim($xml->topLevel);
$this->canvas = new OutlineMapCanvas(
trim($xml->canvas->width),
trim($xml->canvas->height),
trim($xml->canvas->maxcolor),
trim($xml->canvas->hovercolor),
trim($xml->canvas->bgcolor),
trim($xml->canvas->bgstroke),
trim($xml->canvas->defaultcolor),
trim($xml->canvas->defaultstroke)
);
foreach($xml->subdivisions->children() as $subdivision){
$attributes = $subdivision->attributes();
$key = I18N::strtolower(trim($attributes['name']));
if(isset($attributes['parent'])) $key .= '@'. I18N::strtolower(trim($attributes['parent']));
$this->subdivisions[$key] = array(
'id' => trim($attributes['id']),
'displayname' => trim($attributes['name']),
'coord' => trim($subdivision[0])
);
}
if(isset($xml->mappings)) {
foreach($xml->mappings->children() as $mappings){
$attributes = $mappings->attributes();
$this->mappings[I18N::strtolower(trim($attributes['name']))] = I18N::strtolower(trim($attributes['mapto']));
}
}
$this->is_loaded = true;
return;
}
}
throw new \Exception('The Outline Map could not be loaded from XML.');
} | [
"protected",
"function",
"load",
"(",
")",
"{",
"if",
"(",
"file_exists",
"(",
"WT_ROOT",
".",
"WT_MODULES_DIR",
".",
"Constants",
"::",
"MODULE_MAJ_GEODISP_NAME",
".",
"'/maps/'",
".",
"$",
"this",
"->",
"filename",
")",
")",
"{",
"$",
"xml",
"=",
"simple... | Load the map settings contained within its XML representation
XML structure :
- displayName : Display name of the map
- topLevel : Values of the top level subdivisions (separated by commas, if multiple)
- canvas : all settings related to the map canvas.
- width : canvas width, in px
- height : canvas height, in px
- maxcolor : color to identify places with ancestors, RGB hexadecimal
- hovercolor : same as previous, color when mouse is hovering the place, RGB hexadecimal
- bgcolor : map background color, RGB hexadecimal
- bgstroke : map stroke color, RGB hexadecimal
- defaultcolor : default color of places, RGB hexadecimal
- defaultstroke : default stroke color, RGB hexadecimal
- subdvisions : for each subdivision :
- id : Subdivision id, must be compatible with PHP variable constraints, and unique
- name: Display name for the place
- parent: if any, describe to which parent level the place if belonging to
- <em>Element value<em> : SVG description of the subdvision shape
- mapping : for each subdivision :
- name : Name of the place to map
- mapto: Name of the place to map to | [
"Load",
"the",
"map",
"settings",
"contained",
"within",
"its",
"XML",
"representation"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/GeoDispersion/Model/OutlineMap.php#L102-L139 | train |
GrupaZero/cms | src/Gzero/Cms/Repositories/BlockReadRepository.php | BlockReadRepository.getVisibleBlocks | public function getVisibleBlocks(array $ids, Language $language, $onlyActive = true)
{
$query = Block::query()->with(self::$loadRelations);
if (!empty($ids)) {
$query->where(function ($query) use ($ids) {
$query->whereIn('id', $ids)
->orWhere('filter', null);
});
} else { // blocks on all pages only
$query->where('filter', null);
}
if ($onlyActive) {
$query->whereHas('translations', function ($query) use ($language) {
$query->where('block_translations.is_active', true)
->where('language_code', $language->code);
})->where('is_active', '=', true);
}
$blocks = $query->orderBy('weight', 'ASC')->get();
return $blocks;
} | php | public function getVisibleBlocks(array $ids, Language $language, $onlyActive = true)
{
$query = Block::query()->with(self::$loadRelations);
if (!empty($ids)) {
$query->where(function ($query) use ($ids) {
$query->whereIn('id', $ids)
->orWhere('filter', null);
});
} else { // blocks on all pages only
$query->where('filter', null);
}
if ($onlyActive) {
$query->whereHas('translations', function ($query) use ($language) {
$query->where('block_translations.is_active', true)
->where('language_code', $language->code);
})->where('is_active', '=', true);
}
$blocks = $query->orderBy('weight', 'ASC')->get();
return $blocks;
} | [
"public",
"function",
"getVisibleBlocks",
"(",
"array",
"$",
"ids",
",",
"Language",
"$",
"language",
",",
"$",
"onlyActive",
"=",
"true",
")",
"{",
"$",
"query",
"=",
"Block",
"::",
"query",
"(",
")",
"->",
"with",
"(",
"self",
"::",
"$",
"loadRelatio... | Returns all visible blocks
@param array $ids Array with blocks ids returned from block finder
@param Language $language Language
@param bool $onlyActive Return only active blocks
@return Collection | [
"Returns",
"all",
"visible",
"blocks"
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/Repositories/BlockReadRepository.php#L99-L123 | train |
GrupaZero/cms | src/Gzero/Cms/Repositories/BlockReadRepository.php | BlockReadRepository.getBlocksWithFilter | public function getBlocksWithFilter($onlyActive = true)
{
$query = Block::query()->with(self::$loadRelations)
->where('filter', '!=', null);
if ($onlyActive) {
$query->where('is_active', '=', true);
}
$blocks = $query->orderBy('weight', 'ASC')->get();
return $blocks;
} | php | public function getBlocksWithFilter($onlyActive = true)
{
$query = Block::query()->with(self::$loadRelations)
->where('filter', '!=', null);
if ($onlyActive) {
$query->where('is_active', '=', true);
}
$blocks = $query->orderBy('weight', 'ASC')->get();
return $blocks;
} | [
"public",
"function",
"getBlocksWithFilter",
"(",
"$",
"onlyActive",
"=",
"true",
")",
"{",
"$",
"query",
"=",
"Block",
"::",
"query",
"(",
")",
"->",
"with",
"(",
"self",
"::",
"$",
"loadRelations",
")",
"->",
"where",
"(",
"'filter'",
",",
"'!='",
",... | Returns all blocks with filter
@param bool $onlyActive Return only active blocks
@return Collection | [
"Returns",
"all",
"blocks",
"with",
"filter"
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/Repositories/BlockReadRepository.php#L132-L144 | train |
GrupaZero/cms | src/Gzero/Cms/Repositories/BlockReadRepository.php | BlockReadRepository.getManyTranslations | public function getManyTranslations(Block $block, QueryBuilder $builder): LengthAwarePaginator
{
$query = $block->translations(false)->newQuery()->getQuery();
$builder->applyFilters($query, 'block_translations');
$builder->applySorts($query, 'block_translations');
$count = clone $query->getQuery();
$results = $query->limit($builder->getPageSize())
->offset($builder->getPageSize() * ($builder->getPage() - 1))
->get(['block_translations.*']);
return new LengthAwarePaginator(
$results,
$count->select('block_translations.id')->get()->count(),
$builder->getPageSize(),
$builder->getPage()
);
} | php | public function getManyTranslations(Block $block, QueryBuilder $builder): LengthAwarePaginator
{
$query = $block->translations(false)->newQuery()->getQuery();
$builder->applyFilters($query, 'block_translations');
$builder->applySorts($query, 'block_translations');
$count = clone $query->getQuery();
$results = $query->limit($builder->getPageSize())
->offset($builder->getPageSize() * ($builder->getPage() - 1))
->get(['block_translations.*']);
return new LengthAwarePaginator(
$results,
$count->select('block_translations.id')->get()->count(),
$builder->getPageSize(),
$builder->getPage()
);
} | [
"public",
"function",
"getManyTranslations",
"(",
"Block",
"$",
"block",
",",
"QueryBuilder",
"$",
"builder",
")",
":",
"LengthAwarePaginator",
"{",
"$",
"query",
"=",
"$",
"block",
"->",
"translations",
"(",
"false",
")",
"->",
"newQuery",
"(",
")",
"->",
... | Get all block translations for specified content.
@param Block $block Content model
@param QueryBuilder $builder Query builder
@return Collection|LengthAwarePaginator | [
"Get",
"all",
"block",
"translations",
"for",
"specified",
"content",
"."
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/Repositories/BlockReadRepository.php#L197-L216 | train |
GrupaZero/cms | src/Gzero/Cms/Repositories/BlockReadRepository.php | BlockReadRepository.getManyFiles | public function getManyFiles(Block $block, QueryBuilder $builder): LengthAwarePaginator
{
$query = $block->files(false)->with(['type','translations']);
$count = clone $query->getQuery();
$results = $query->limit($builder->getPageSize())
->offset($builder->getPageSize() * ($builder->getPage() - 1))
->get(['files.*']);
return new LengthAwarePaginator(
$results,
$count->select('files.id')->get()->count(),
$builder->getPageSize(),
$builder->getPage()
);
} | php | public function getManyFiles(Block $block, QueryBuilder $builder): LengthAwarePaginator
{
$query = $block->files(false)->with(['type','translations']);
$count = clone $query->getQuery();
$results = $query->limit($builder->getPageSize())
->offset($builder->getPageSize() * ($builder->getPage() - 1))
->get(['files.*']);
return new LengthAwarePaginator(
$results,
$count->select('files.id')->get()->count(),
$builder->getPageSize(),
$builder->getPage()
);
} | [
"public",
"function",
"getManyFiles",
"(",
"Block",
"$",
"block",
",",
"QueryBuilder",
"$",
"builder",
")",
":",
"LengthAwarePaginator",
"{",
"$",
"query",
"=",
"$",
"block",
"->",
"files",
"(",
"false",
")",
"->",
"with",
"(",
"[",
"'type'",
",",
"'tran... | Get all files with translations for specified block.
@param Block $block Block model
@param QueryBuilder $builder Query builder
@return Collection|LengthAwarePaginator | [
"Get",
"all",
"files",
"with",
"translations",
"for",
"specified",
"block",
"."
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/Repositories/BlockReadRepository.php#L226-L242 | train |
CESNET/perun-simplesamlphp-module | lib/Auth/Process/StringifyTargetedID.php | StringifyTargetedID.stringify | private function stringify($attributeValue)
{
if (is_object($attributeValue) && get_class($attributeValue) == "SAML2\XML\saml\NameID") {
return $attributeValue->NameQualifier . '!' . $attributeValue->SPNameQualifier . '!'
. $attributeValue->value;
} else {
return $attributeValue;
}
} | php | private function stringify($attributeValue)
{
if (is_object($attributeValue) && get_class($attributeValue) == "SAML2\XML\saml\NameID") {
return $attributeValue->NameQualifier . '!' . $attributeValue->SPNameQualifier . '!'
. $attributeValue->value;
} else {
return $attributeValue;
}
} | [
"private",
"function",
"stringify",
"(",
"$",
"attributeValue",
")",
"{",
"if",
"(",
"is_object",
"(",
"$",
"attributeValue",
")",
"&&",
"get_class",
"(",
"$",
"attributeValue",
")",
"==",
"\"SAML2\\XML\\saml\\NameID\"",
")",
"{",
"return",
"$",
"attributeValue"... | Convert NameID value into the text representation. | [
"Convert",
"NameID",
"value",
"into",
"the",
"text",
"representation",
"."
] | f1d686f06472053a7cdb31f2b2776f9714779ee1 | https://github.com/CESNET/perun-simplesamlphp-module/blob/f1d686f06472053a7cdb31f2b2776f9714779ee1/lib/Auth/Process/StringifyTargetedID.php#L56-L64 | train |
jon48/webtrees-lib | src/Webtrees/Mvc/MvcException.php | MvcException.setHttpCode | public function setHttpCode($http_code) {
if(!in_array($http_code, self::$VALID_HTTP))
throw new \InvalidArgumentException('Invalid HTTP code');
$this->http_code= $http_code;
} | php | public function setHttpCode($http_code) {
if(!in_array($http_code, self::$VALID_HTTP))
throw new \InvalidArgumentException('Invalid HTTP code');
$this->http_code= $http_code;
} | [
"public",
"function",
"setHttpCode",
"(",
"$",
"http_code",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"http_code",
",",
"self",
"::",
"$",
"VALID_HTTP",
")",
")",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Invalid HTTP code'",
")",
";",
... | Set the HTTP code
@param int $http_code
@throws InvalidArgumentException Thrown if not valid Http code | [
"Set",
"the",
"HTTP",
"code"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Mvc/MvcException.php#L60-L64 | train |
alexislefebvre/AsyncTweetsBundle | src/Utils/PersistTweet.php | PersistTweet.createTweet | protected function createTweet(\stdClass $tweetTmp, $user, $inTimeline)
{
$tweet = new Tweet();
$tweet
->setId($tweetTmp->id)
->setValues($tweetTmp)
->setUser($user)
->setInTimeline($inTimeline);
$this->addMedias($tweetTmp, $tweet);
return $tweet;
} | php | protected function createTweet(\stdClass $tweetTmp, $user, $inTimeline)
{
$tweet = new Tweet();
$tweet
->setId($tweetTmp->id)
->setValues($tweetTmp)
->setUser($user)
->setInTimeline($inTimeline);
$this->addMedias($tweetTmp, $tweet);
return $tweet;
} | [
"protected",
"function",
"createTweet",
"(",
"\\",
"stdClass",
"$",
"tweetTmp",
",",
"$",
"user",
",",
"$",
"inTimeline",
")",
"{",
"$",
"tweet",
"=",
"new",
"Tweet",
"(",
")",
";",
"$",
"tweet",
"->",
"setId",
"(",
"$",
"tweetTmp",
"->",
"id",
")",
... | Create a Tweet object and return it.
@param \stdClass $tweetTmp
@param User $user
@param bool $inTimeline
@return Tweet | [
"Create",
"a",
"Tweet",
"object",
"and",
"return",
"it",
"."
] | 76266fae7de978963e05dadb14c81f8398bb00a6 | https://github.com/alexislefebvre/AsyncTweetsBundle/blob/76266fae7de978963e05dadb14c81f8398bb00a6/src/Utils/PersistTweet.php#L80-L93 | train |
GrupaZero/cms | src/Gzero/Cms/Http/Controllers/Api/PublicContentController.php | PublicContentController.index | public function index()
{
$results = $this->repository->getManyPublished(new QueryBuilder());
$results->setPath(apiUrl('public-contents'));
return new ContentCollection($results);
} | php | public function index()
{
$results = $this->repository->getManyPublished(new QueryBuilder());
$results->setPath(apiUrl('public-contents'));
return new ContentCollection($results);
} | [
"public",
"function",
"index",
"(",
")",
"{",
"$",
"results",
"=",
"$",
"this",
"->",
"repository",
"->",
"getManyPublished",
"(",
"new",
"QueryBuilder",
"(",
")",
")",
";",
"$",
"results",
"->",
"setPath",
"(",
"apiUrl",
"(",
"'public-contents'",
")",
"... | Display list of public contents
@SWG\Get(
path="/public-contents",
tags={"content","public"},
summary="List of public contents",
description="List of all publicly accessible contents",
produces={"application/json"},
@SWG\Response(
response=200,
description="Successful operation",
@SWG\Schema(type="array", @SWG\Items(ref="#/definitions/Content")),
),
)
@return ContentCollection | [
"Display",
"list",
"of",
"public",
"contents"
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/Http/Controllers/Api/PublicContentController.php#L50-L56 | train |
jon48/webtrees-lib | src/Webtrees/Module/GeoDispersion/Views/GeoAnalysisTabGenerationsView.php | GeoAnalysisTabGenerationsView.htmlGenerationAllPlacesRow | protected function htmlGenerationAllPlacesRow($data, $analysis_level) {
$html =
'<table class="geodispersion_bigrow">
<tr>';
$sum_gen = $data['sum'];
$unknownother = $data['unknown'] + $data['other'];
foreach($data['places'] as $placename=> $dataplace){
$levels = array_map('trim',explode(',', $placename));
$content = '';
if(isset($dataplace['flag'])){
$content .= '<td class="geodispersion_flag">'. FunctionsPrint::htmlPlaceIcon($dataplace['place'], $dataplace['flag']) .'</td><td>';
}
else{
$content .= '<td><span title="'.implode(I18N::$list_separator, array_reverse($levels)).'">'.$levels[$analysis_level-1].'</span><br/>';
}
$count = $dataplace['count'];
$content .= I18N::number($count);
$perc = Functions::safeDivision($count, $sum_gen + $unknownother);
$perc2= Functions::safeDivision($count, $sum_gen);
if($perc2>=0.1)
$content.= '<br/><span class="small">('.I18N::percentage($perc2, 1).')</span>';
$content .= '</td>';
$html .= '
<td class="geodispersion_rowitem" width="'.max(round(100*$perc, 0),1).'%">
<table>
<tr>
<td>
<table>
<tr>'.$content.'</tr>
</table>
</td>
</tr>
</table>
</td>';
}
if($unknownother>0){
$perc= Functions::safeDivision($unknownother, $sum_gen + $unknownother);
$html .='<td class="geodispersion_unknownitem left" >'.I18N::number($unknownother);
if($perc>=0.1) $html.= '<br/><span class="small">('.I18N::percentage($perc, 1).')</span>';
$html .='</td>';
}
$html .=
'</tr>
</table>';
return $html;
} | php | protected function htmlGenerationAllPlacesRow($data, $analysis_level) {
$html =
'<table class="geodispersion_bigrow">
<tr>';
$sum_gen = $data['sum'];
$unknownother = $data['unknown'] + $data['other'];
foreach($data['places'] as $placename=> $dataplace){
$levels = array_map('trim',explode(',', $placename));
$content = '';
if(isset($dataplace['flag'])){
$content .= '<td class="geodispersion_flag">'. FunctionsPrint::htmlPlaceIcon($dataplace['place'], $dataplace['flag']) .'</td><td>';
}
else{
$content .= '<td><span title="'.implode(I18N::$list_separator, array_reverse($levels)).'">'.$levels[$analysis_level-1].'</span><br/>';
}
$count = $dataplace['count'];
$content .= I18N::number($count);
$perc = Functions::safeDivision($count, $sum_gen + $unknownother);
$perc2= Functions::safeDivision($count, $sum_gen);
if($perc2>=0.1)
$content.= '<br/><span class="small">('.I18N::percentage($perc2, 1).')</span>';
$content .= '</td>';
$html .= '
<td class="geodispersion_rowitem" width="'.max(round(100*$perc, 0),1).'%">
<table>
<tr>
<td>
<table>
<tr>'.$content.'</tr>
</table>
</td>
</tr>
</table>
</td>';
}
if($unknownother>0){
$perc= Functions::safeDivision($unknownother, $sum_gen + $unknownother);
$html .='<td class="geodispersion_unknownitem left" >'.I18N::number($unknownother);
if($perc>=0.1) $html.= '<br/><span class="small">('.I18N::percentage($perc, 1).')</span>';
$html .='</td>';
}
$html .=
'</tr>
</table>';
return $html;
} | [
"protected",
"function",
"htmlGenerationAllPlacesRow",
"(",
"$",
"data",
",",
"$",
"analysis_level",
")",
"{",
"$",
"html",
"=",
"'<table class=\"geodispersion_bigrow\">\n <tr>'",
";",
"$",
"sum_gen",
"=",
"$",
"data",
"[",
"'sum'",
"]",
";",
"$",
"unkn... | Return the HTML code to display a row with all places found in a generation.
@param array $data Data array
@param int $analysis_level Level of subdivision of analysis
@return string HTML code for all places row | [
"Return",
"the",
"HTML",
"code",
"to",
"display",
"a",
"row",
"with",
"all",
"places",
"found",
"in",
"a",
"generation",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/GeoDispersion/Views/GeoAnalysisTabGenerationsView.php#L85-L134 | train |
jon48/webtrees-lib | src/Webtrees/Module/GeoDispersion/Views/GeoAnalysisTabGenerationsView.php | GeoAnalysisTabGenerationsView.htmlGenerationTopPlacesRow | protected function htmlGenerationTopPlacesRow($data, $analysis_level) {
$tmp_places = array();
$sum_gen = $data['sum'];
$other = $data['other'];
foreach($data['places'] as $placename => $count) {
if($placename != 'other'){
$levels = array_map('trim',explode(',', $placename));
$placename = '<span title="'.implode(I18N::$list_separator, array_reverse($levels)).'">'.$levels[$analysis_level-1].'</span>';
}
else{
$placename = I18N::translate('Other places');
}
$tmp_places[] = I18N::translate('<strong>%s</strong> [%d - %s]', $placename, $count, I18N::percentage(Functions::safeDivision($count, $sum_gen + $other), 1));
}
return implode(I18N::$list_separator, $tmp_places);
} | php | protected function htmlGenerationTopPlacesRow($data, $analysis_level) {
$tmp_places = array();
$sum_gen = $data['sum'];
$other = $data['other'];
foreach($data['places'] as $placename => $count) {
if($placename != 'other'){
$levels = array_map('trim',explode(',', $placename));
$placename = '<span title="'.implode(I18N::$list_separator, array_reverse($levels)).'">'.$levels[$analysis_level-1].'</span>';
}
else{
$placename = I18N::translate('Other places');
}
$tmp_places[] = I18N::translate('<strong>%s</strong> [%d - %s]', $placename, $count, I18N::percentage(Functions::safeDivision($count, $sum_gen + $other), 1));
}
return implode(I18N::$list_separator, $tmp_places);
} | [
"protected",
"function",
"htmlGenerationTopPlacesRow",
"(",
"$",
"data",
",",
"$",
"analysis_level",
")",
"{",
"$",
"tmp_places",
"=",
"array",
"(",
")",
";",
"$",
"sum_gen",
"=",
"$",
"data",
"[",
"'sum'",
"]",
";",
"$",
"other",
"=",
"$",
"data",
"["... | Returns the HTML code fo display a row of the Top Places found for a generation.
@param array $data Data array
@param int $analysis_level Level of subdivision of analysis
@return string HTML code for Top Places row | [
"Returns",
"the",
"HTML",
"code",
"fo",
"display",
"a",
"row",
"of",
"the",
"Top",
"Places",
"found",
"for",
"a",
"generation",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/GeoDispersion/Views/GeoAnalysisTabGenerationsView.php#L143-L160 | train |
GrupaZero/cms | src/Gzero/Cms/Http/Controllers/Api/ContentTreeController.php | ContentTreeController.index | public function index(UrlParamsProcessor $processor)
{
$this->authorize('readList', Content::class);
// @TODO Implement contents/{id}/tree
$processor
->addFilter(new BoolParser('only_categories'))
->process($this->request);
Resource::wrap('data');
return (new ContentCollection($this->repository->getTree($processor->buildQueryBuilder())));
} | php | public function index(UrlParamsProcessor $processor)
{
$this->authorize('readList', Content::class);
// @TODO Implement contents/{id}/tree
$processor
->addFilter(new BoolParser('only_categories'))
->process($this->request);
Resource::wrap('data');
return (new ContentCollection($this->repository->getTree($processor->buildQueryBuilder())));
} | [
"public",
"function",
"index",
"(",
"UrlParamsProcessor",
"$",
"processor",
")",
"{",
"$",
"this",
"->",
"authorize",
"(",
"'readList'",
",",
"Content",
"::",
"class",
")",
";",
"// @TODO Implement contents/{id}/tree",
"$",
"processor",
"->",
"addFilter",
"(",
"... | Fetches all content in a tree structure
@SWG\Get(
path="/contents-tree",
tags={"content"},
summary="Fetches all content in a tree structure",
produces={"application/json"},
security={{"AdminAccess": {}}},
@SWG\Parameter(
name="only_category",
in="query",
description="Should fetch only categories?",
required=false,
type="boolean",
default="false"
),
@SWG\Response(
response=200,
description="Successful operation",
@SWG\Schema(type="array", @SWG\Items(ref="#/definitions/Content"))
),
),
@param UrlParamsProcessor $processor params processor
@return string | [
"Fetches",
"all",
"content",
"in",
"a",
"tree",
"structure"
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/Http/Controllers/Api/ContentTreeController.php#L71-L82 | train |
MetaModels/filter_range | src/EventListener/DcGeneral/Table/FilterSetting/GetPropertyOptionsListener.php | GetPropertyOptionsListener.handle | public function handle(GetPropertyOptionsEvent $event)
{
$isAllowed = $this->isAllowedContext(
$event->getEnvironment()->getDataDefinition(),
$event->getPropertyName(),
$event->getModel()
);
if (!$isAllowed) {
return;
}
$result = [];
$model = $event->getModel();
$metaModel = $this->getMetaModel($model);
$typeFactory = $this->filterSettingFactory->getTypeFactory($model->getProperty('type'));
$typeFilter = null;
if ($typeFactory) {
$typeFilter = $typeFactory->getKnownAttributeTypes();
}
foreach ($metaModel->getAttributes() as $attribute) {
$typeName = $attribute->get('type');
if ($typeFilter && (!\in_array($typeName, $typeFilter, true))) {
continue;
}
$strSelectVal = $metaModel->getTableName().'_'.$attribute->getColName();
$result[$strSelectVal] = $attribute->getName().' ['.$typeName.']';
}
$event->setOptions($result);
} | php | public function handle(GetPropertyOptionsEvent $event)
{
$isAllowed = $this->isAllowedContext(
$event->getEnvironment()->getDataDefinition(),
$event->getPropertyName(),
$event->getModel()
);
if (!$isAllowed) {
return;
}
$result = [];
$model = $event->getModel();
$metaModel = $this->getMetaModel($model);
$typeFactory = $this->filterSettingFactory->getTypeFactory($model->getProperty('type'));
$typeFilter = null;
if ($typeFactory) {
$typeFilter = $typeFactory->getKnownAttributeTypes();
}
foreach ($metaModel->getAttributes() as $attribute) {
$typeName = $attribute->get('type');
if ($typeFilter && (!\in_array($typeName, $typeFilter, true))) {
continue;
}
$strSelectVal = $metaModel->getTableName().'_'.$attribute->getColName();
$result[$strSelectVal] = $attribute->getName().' ['.$typeName.']';
}
$event->setOptions($result);
} | [
"public",
"function",
"handle",
"(",
"GetPropertyOptionsEvent",
"$",
"event",
")",
"{",
"$",
"isAllowed",
"=",
"$",
"this",
"->",
"isAllowedContext",
"(",
"$",
"event",
"->",
"getEnvironment",
"(",
")",
"->",
"getDataDefinition",
"(",
")",
",",
"$",
"event",... | Prepares a option list with alias => name connection for all attributes.
This is used in the attr_id select box.
@param GetPropertyOptionsEvent $event The event.
@return void
@throws \RuntimeException When the MetaModel can not be determined. | [
"Prepares",
"a",
"option",
"list",
"with",
"alias",
"=",
">",
"name",
"connection",
"for",
"all",
"attributes",
"."
] | 1875e4a2206df2c5c98f5b0a7f18feb17b34f393 | https://github.com/MetaModels/filter_range/blob/1875e4a2206df2c5c98f5b0a7f18feb17b34f393/src/EventListener/DcGeneral/Table/FilterSetting/GetPropertyOptionsListener.php#L43-L78 | train |
nepttune/nepttune | src/Model/PushNotificationModel.php | PushNotificationModel.sendAll | public function sendAll($msg) : void
{
foreach ($this->subscriptionTable->findActive() as $row)
{
$this->sendNotification($row, $msg, false);
}
if ($flush)
{
$this->flush();
}
} | php | public function sendAll($msg) : void
{
foreach ($this->subscriptionTable->findActive() as $row)
{
$this->sendNotification($row, $msg, false);
}
if ($flush)
{
$this->flush();
}
} | [
"public",
"function",
"sendAll",
"(",
"$",
"msg",
")",
":",
"void",
"{",
"foreach",
"(",
"$",
"this",
"->",
"subscriptionTable",
"->",
"findActive",
"(",
")",
"as",
"$",
"row",
")",
"{",
"$",
"this",
"->",
"sendNotification",
"(",
"$",
"row",
",",
"$... | Send notification to all active subscriptions.
@param string $msg | [
"Send",
"notification",
"to",
"all",
"active",
"subscriptions",
"."
] | 63b41f62e0589a0ebac698abd1b8cf65abfcb1d5 | https://github.com/nepttune/nepttune/blob/63b41f62e0589a0ebac698abd1b8cf65abfcb1d5/src/Model/PushNotificationModel.php#L61-L72 | train |
nepttune/nepttune | src/Model/PushNotificationModel.php | PushNotificationModel.sendByUserId | public function sendByUserId(int $userId, string $msg, ?string $dest = null, bool $flush = false) : void
{
$msg = $this->composeMsg($msg, $dest);
foreach ($this->subscriptionTable->findActive()->where('user_id', $userId) as $row)
{
$this->sendNotification($row, $msg, false);
}
if ($flush)
{
$this->flush();
}
} | php | public function sendByUserId(int $userId, string $msg, ?string $dest = null, bool $flush = false) : void
{
$msg = $this->composeMsg($msg, $dest);
foreach ($this->subscriptionTable->findActive()->where('user_id', $userId) as $row)
{
$this->sendNotification($row, $msg, false);
}
if ($flush)
{
$this->flush();
}
} | [
"public",
"function",
"sendByUserId",
"(",
"int",
"$",
"userId",
",",
"string",
"$",
"msg",
",",
"?",
"string",
"$",
"dest",
"=",
"null",
",",
"bool",
"$",
"flush",
"=",
"false",
")",
":",
"void",
"{",
"$",
"msg",
"=",
"$",
"this",
"->",
"composeMs... | Send notification to all subscriptions paired with specific user.
@param int $userId
@param string $msg
@param string $dest
@param bool $flush | [
"Send",
"notification",
"to",
"all",
"subscriptions",
"paired",
"with",
"specific",
"user",
"."
] | 63b41f62e0589a0ebac698abd1b8cf65abfcb1d5 | https://github.com/nepttune/nepttune/blob/63b41f62e0589a0ebac698abd1b8cf65abfcb1d5/src/Model/PushNotificationModel.php#L81-L94 | train |
nepttune/nepttune | src/Model/PushNotificationModel.php | PushNotificationModel.sendByType | public function sendByType(int $typeId, string $msg, ?string $dest = null, bool $flush = false) : void
{
$msg = $this->composeMsg($msg, $dest);
$subscriptions = $this->subscriptionTable->findAll()
->where('subscription.active', 1)
->where('user.active', 1)
->where('user:user_subscription_type.subscription_type_id', $typeId);
foreach ($subscriptions as $row)
{
$this->sendNotification($row, $msg, false);
}
if ($flush)
{
$this->flush();
}
} | php | public function sendByType(int $typeId, string $msg, ?string $dest = null, bool $flush = false) : void
{
$msg = $this->composeMsg($msg, $dest);
$subscriptions = $this->subscriptionTable->findAll()
->where('subscription.active', 1)
->where('user.active', 1)
->where('user:user_subscription_type.subscription_type_id', $typeId);
foreach ($subscriptions as $row)
{
$this->sendNotification($row, $msg, false);
}
if ($flush)
{
$this->flush();
}
} | [
"public",
"function",
"sendByType",
"(",
"int",
"$",
"typeId",
",",
"string",
"$",
"msg",
",",
"?",
"string",
"$",
"dest",
"=",
"null",
",",
"bool",
"$",
"flush",
"=",
"false",
")",
":",
"void",
"{",
"$",
"msg",
"=",
"$",
"this",
"->",
"composeMsg"... | Send notification to all users subscribed to specific type.
@param int $typeId
@param string $msg
@param string $dest
@param bool $flush | [
"Send",
"notification",
"to",
"all",
"users",
"subscribed",
"to",
"specific",
"type",
"."
] | 63b41f62e0589a0ebac698abd1b8cf65abfcb1d5 | https://github.com/nepttune/nepttune/blob/63b41f62e0589a0ebac698abd1b8cf65abfcb1d5/src/Model/PushNotificationModel.php#L103-L121 | train |
nepttune/nepttune | src/Model/PushNotificationModel.php | PushNotificationModel.saveSubscription | public function saveSubscription(int $userId = null) : void
{
$json = \file_get_contents('php://input');
if (!$json)
{
return;
}
$data = \json_decode($json, true);
if (!$data || empty($data['endpoint']) || empty($data['publicKey']) || empty($data['authToken']))
{
return;
}
$row = $this->subscriptionTable->findActive()->where('endpoint', $data['endpoint'])->fetch();
switch ($this->request->getMethod()) {
case 'POST':
case 'PUT':
{
if ($row)
{
$row->update([
'user_id' => $userId ?: $row->user_id ?: null,
'key' => $data['publicKey'],
'token' => $data['authToken'],
'encoding' => $data['contentEncoding']
]);
return;
}
$row = $this->subscriptionTable->insert([
'user_id' => $userId,
'endpoint' => $data['endpoint'],
'key' => $data['publicKey'],
'token' => $data['authToken'],
'encoding' => $data['contentEncoding']
]);
$this->sendNotification($row, 'Notifications enabled!', true);
return;
}
case 'DELETE':
{
if ($row)
{
$row->update([
'active' => 0
]);
}
return;
}
default:
throw new \Nette\Application\BadRequestException();
}
} | php | public function saveSubscription(int $userId = null) : void
{
$json = \file_get_contents('php://input');
if (!$json)
{
return;
}
$data = \json_decode($json, true);
if (!$data || empty($data['endpoint']) || empty($data['publicKey']) || empty($data['authToken']))
{
return;
}
$row = $this->subscriptionTable->findActive()->where('endpoint', $data['endpoint'])->fetch();
switch ($this->request->getMethod()) {
case 'POST':
case 'PUT':
{
if ($row)
{
$row->update([
'user_id' => $userId ?: $row->user_id ?: null,
'key' => $data['publicKey'],
'token' => $data['authToken'],
'encoding' => $data['contentEncoding']
]);
return;
}
$row = $this->subscriptionTable->insert([
'user_id' => $userId,
'endpoint' => $data['endpoint'],
'key' => $data['publicKey'],
'token' => $data['authToken'],
'encoding' => $data['contentEncoding']
]);
$this->sendNotification($row, 'Notifications enabled!', true);
return;
}
case 'DELETE':
{
if ($row)
{
$row->update([
'active' => 0
]);
}
return;
}
default:
throw new \Nette\Application\BadRequestException();
}
} | [
"public",
"function",
"saveSubscription",
"(",
"int",
"$",
"userId",
"=",
"null",
")",
":",
"void",
"{",
"$",
"json",
"=",
"\\",
"file_get_contents",
"(",
"'php://input'",
")",
";",
"if",
"(",
"!",
"$",
"json",
")",
"{",
"return",
";",
"}",
"$",
"dat... | Save or update subscriber information.
@throws \Nette\Application\BadRequestException
@param int $userId | [
"Save",
"or",
"update",
"subscriber",
"information",
"."
] | 63b41f62e0589a0ebac698abd1b8cf65abfcb1d5 | https://github.com/nepttune/nepttune/blob/63b41f62e0589a0ebac698abd1b8cf65abfcb1d5/src/Model/PushNotificationModel.php#L128-L188 | train |
voslartomas/WebCMS2 | AdminModule/presenters/LanguagesPresenter.php | LanguagesPresenter.actionExportLanguage | public function actionExportLanguage($id)
{
$language = $this->em->find("WebCMS\Entity\Language", $id);
$export = array(
'name' => $language->getName(),
'abbr' => $language->getAbbr(),
'translations' => array(),
);
foreach ($language->getTranslations() as $translation) {
if ($translation->getBackend()) {
$export['translations'][] = array(
'key' => $translation->getKey(),
'translation' => $translation->getTranslation(),
'backend' => $translation->getBackend(),
);
}
}
$export = json_encode($export);
$filename = $language->getAbbr().'.json';
$response = $this->getHttpResponse();
$response->setHeader('Content-Description', 'File Transfer');
$response->setContentType('text/plain', 'UTF-8');
$response->setHeader('Content-Disposition', 'attachment; filename='.$filename);
$response->setHeader('Content-Transfer-Encoding', 'binary');
$response->setHeader('Expires', 0);
$response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
$response->setHeader('Pragma', 'public');
$response->setHeader('Content-Length', strlen($export));
ob_clean();
flush();
echo $export;
$this->terminate();
} | php | public function actionExportLanguage($id)
{
$language = $this->em->find("WebCMS\Entity\Language", $id);
$export = array(
'name' => $language->getName(),
'abbr' => $language->getAbbr(),
'translations' => array(),
);
foreach ($language->getTranslations() as $translation) {
if ($translation->getBackend()) {
$export['translations'][] = array(
'key' => $translation->getKey(),
'translation' => $translation->getTranslation(),
'backend' => $translation->getBackend(),
);
}
}
$export = json_encode($export);
$filename = $language->getAbbr().'.json';
$response = $this->getHttpResponse();
$response->setHeader('Content-Description', 'File Transfer');
$response->setContentType('text/plain', 'UTF-8');
$response->setHeader('Content-Disposition', 'attachment; filename='.$filename);
$response->setHeader('Content-Transfer-Encoding', 'binary');
$response->setHeader('Expires', 0);
$response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
$response->setHeader('Pragma', 'public');
$response->setHeader('Content-Length', strlen($export));
ob_clean();
flush();
echo $export;
$this->terminate();
} | [
"public",
"function",
"actionExportLanguage",
"(",
"$",
"id",
")",
"{",
"$",
"language",
"=",
"$",
"this",
"->",
"em",
"->",
"find",
"(",
"\"WebCMS\\Entity\\Language\"",
",",
"$",
"id",
")",
";",
"$",
"export",
"=",
"array",
"(",
"'name'",
"=>",
"$",
"... | Export language into JSON file and terminate response for download it.
@param Int $id | [
"Export",
"language",
"into",
"JSON",
"file",
"and",
"terminate",
"response",
"for",
"download",
"it",
"."
] | b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf | https://github.com/voslartomas/WebCMS2/blob/b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf/AdminModule/presenters/LanguagesPresenter.php#L142-L180 | train |
CESNET/perun-simplesamlphp-module | lib/DatabaseConnector.php | DatabaseConnector.getConnection | public function getConnection()
{
$conn = mysqli_init();
if ($this->encryption === true) {
Logger::debug("Getting connection with encryption.");
mysqli_ssl_set($conn, $this->sslKey, $this->sslCert, $this->sslCA, $this->sslCAPath, null);
if ($this->port === null) {
mysqli_real_connect($conn, $this->serverName, $this->username, $this->password, $this->databaseName);
} else {
mysqli_real_connect(
$conn,
$this->serverName,
$this->username,
$this->password,
$this->databaseName,
$this->port
);
}
} elseif ($this->port === null) {
mysqli_real_connect($conn, $this->serverName, $this->username, $this->password, $this->databaseName);
} else {
mysqli_real_connect(
$conn,
$this->serverName,
$this->username,
$this->password,
$this->databaseName,
$this->port
);
}
return $conn;
} | php | public function getConnection()
{
$conn = mysqli_init();
if ($this->encryption === true) {
Logger::debug("Getting connection with encryption.");
mysqli_ssl_set($conn, $this->sslKey, $this->sslCert, $this->sslCA, $this->sslCAPath, null);
if ($this->port === null) {
mysqli_real_connect($conn, $this->serverName, $this->username, $this->password, $this->databaseName);
} else {
mysqli_real_connect(
$conn,
$this->serverName,
$this->username,
$this->password,
$this->databaseName,
$this->port
);
}
} elseif ($this->port === null) {
mysqli_real_connect($conn, $this->serverName, $this->username, $this->password, $this->databaseName);
} else {
mysqli_real_connect(
$conn,
$this->serverName,
$this->username,
$this->password,
$this->databaseName,
$this->port
);
}
return $conn;
} | [
"public",
"function",
"getConnection",
"(",
")",
"{",
"$",
"conn",
"=",
"mysqli_init",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"encryption",
"===",
"true",
")",
"{",
"Logger",
"::",
"debug",
"(",
"\"Getting connection with encryption.\"",
")",
";",
"m... | Function returns the connection to db
@return mysqli connection | [
"Function",
"returns",
"the",
"connection",
"to",
"db"
] | f1d686f06472053a7cdb31f2b2776f9714779ee1 | https://github.com/CESNET/perun-simplesamlphp-module/blob/f1d686f06472053a7cdb31f2b2776f9714779ee1/lib/DatabaseConnector.php#L63-L94 | train |
MetaModels/filter_range | src/FilterSetting/AbstractRange.php | AbstractRange.getReferencedAttributes | public function getReferencedAttributes()
{
$objMetaModel = $this->getMetaModel();
$objAttribute = $objMetaModel->getAttributeById($this->get('attr_id'));
$objAttribute2 = $objMetaModel->getAttributeById($this->get('attr_id2'));
$arrResult = [];
if ($objAttribute) {
$arrResult[] = $objAttribute->getColName();
}
if ($objAttribute2) {
$arrResult[] = $objAttribute2->getColName();
}
return $arrResult;
} | php | public function getReferencedAttributes()
{
$objMetaModel = $this->getMetaModel();
$objAttribute = $objMetaModel->getAttributeById($this->get('attr_id'));
$objAttribute2 = $objMetaModel->getAttributeById($this->get('attr_id2'));
$arrResult = [];
if ($objAttribute) {
$arrResult[] = $objAttribute->getColName();
}
if ($objAttribute2) {
$arrResult[] = $objAttribute2->getColName();
}
return $arrResult;
} | [
"public",
"function",
"getReferencedAttributes",
"(",
")",
"{",
"$",
"objMetaModel",
"=",
"$",
"this",
"->",
"getMetaModel",
"(",
")",
";",
"$",
"objAttribute",
"=",
"$",
"objMetaModel",
"->",
"getAttributeById",
"(",
"$",
"this",
"->",
"get",
"(",
"'attr_id... | Retrieve the attributes that are referenced in this filter setting.
@return array | [
"Retrieve",
"the",
"attributes",
"that",
"are",
"referenced",
"in",
"this",
"filter",
"setting",
"."
] | 1875e4a2206df2c5c98f5b0a7f18feb17b34f393 | https://github.com/MetaModels/filter_range/blob/1875e4a2206df2c5c98f5b0a7f18feb17b34f393/src/FilterSetting/AbstractRange.php#L102-L118 | train |
MetaModels/filter_range | src/FilterSetting/AbstractRange.php | AbstractRange.getFilterWidgetParameters | protected function getFilterWidgetParameters(IAttribute $attribute, $currentValue, $ids)
{
return [
'label' => $this->prepareWidgetLabel($attribute),
'inputType' => 'multitext',
'options' => $this->prepareWidgetOptions($ids, $attribute),
'timetype' => $this->get('timetype'),
'dateformat' => $this->get('dateformat'),
'eval' => [
'multiple' => true,
'size' => $this->get('fromfield') && $this->get('tofield') ? 2 : 1,
'urlparam' => $this->getParamName(),
'template' => $this->get('template'),
'colname' => $attribute->getColName(),
],
// We need to implode to have it transported correctly in the frontend filter.
'urlvalue' => !empty($currentValue) ? implode(',', $currentValue) : ''
];
} | php | protected function getFilterWidgetParameters(IAttribute $attribute, $currentValue, $ids)
{
return [
'label' => $this->prepareWidgetLabel($attribute),
'inputType' => 'multitext',
'options' => $this->prepareWidgetOptions($ids, $attribute),
'timetype' => $this->get('timetype'),
'dateformat' => $this->get('dateformat'),
'eval' => [
'multiple' => true,
'size' => $this->get('fromfield') && $this->get('tofield') ? 2 : 1,
'urlparam' => $this->getParamName(),
'template' => $this->get('template'),
'colname' => $attribute->getColName(),
],
// We need to implode to have it transported correctly in the frontend filter.
'urlvalue' => !empty($currentValue) ? implode(',', $currentValue) : ''
];
} | [
"protected",
"function",
"getFilterWidgetParameters",
"(",
"IAttribute",
"$",
"attribute",
",",
"$",
"currentValue",
",",
"$",
"ids",
")",
"{",
"return",
"[",
"'label'",
"=>",
"$",
"this",
"->",
"prepareWidgetLabel",
"(",
"$",
"attribute",
")",
",",
"'inputTyp... | Get the parameter array for configuring the widget.
@param IAttribute $attribute The attribute.
@param array $currentValue The current value.
@param string[] $ids The list of ids.
@return array | [
"Get",
"the",
"parameter",
"array",
"for",
"configuring",
"the",
"widget",
"."
] | 1875e4a2206df2c5c98f5b0a7f18feb17b34f393 | https://github.com/MetaModels/filter_range/blob/1875e4a2206df2c5c98f5b0a7f18feb17b34f393/src/FilterSetting/AbstractRange.php#L263-L281 | train |
Rareloop/primer-core | src/Primer/Renderable/Group.php | Group.loadPatternsInPath | public static function loadPatternsInPath($path)
{
$groups = array();
if ($handle = opendir($path)) {
while (false !== ($entry = readdir($handle))) {
$fullPath = $path . '/' . $entry;
if (substr($entry, 0, 1) !== '.') {
$id = trim(str_replace(Primer::$PATTERN_PATH, '', $fullPath), '/');
// Load the pattern
$groups[] = new Group($id);
}
}
closedir($handle);
}
return $groups;
} | php | public static function loadPatternsInPath($path)
{
$groups = array();
if ($handle = opendir($path)) {
while (false !== ($entry = readdir($handle))) {
$fullPath = $path . '/' . $entry;
if (substr($entry, 0, 1) !== '.') {
$id = trim(str_replace(Primer::$PATTERN_PATH, '', $fullPath), '/');
// Load the pattern
$groups[] = new Group($id);
}
}
closedir($handle);
}
return $groups;
} | [
"public",
"static",
"function",
"loadPatternsInPath",
"(",
"$",
"path",
")",
"{",
"$",
"groups",
"=",
"array",
"(",
")",
";",
"if",
"(",
"$",
"handle",
"=",
"opendir",
"(",
"$",
"path",
")",
")",
"{",
"while",
"(",
"false",
"!==",
"(",
"$",
"entry"... | Helper function to load all groups in a folder
@param String $path The path of the directory to load from
@return Array Array of all groups loaded | [
"Helper",
"function",
"to",
"load",
"all",
"groups",
"in",
"a",
"folder"
] | fe098d6794a4add368f97672397dc93d223a1786 | https://github.com/Rareloop/primer-core/blob/fe098d6794a4add368f97672397dc93d223a1786/src/Primer/Renderable/Group.php#L93-L116 | train |
c4studio/chronos | src/Chronos/Scaffolding/ScaffoldingServiceProvider.php | ScaffoldingServiceProvider.registerGates | protected function registerGates($gate)
{
if (class_exists('Chronos\Scaffolding\Models\Permission') && Schema::hasTable('roles')) {
$permissions = \Chronos\Scaffolding\Models\Permission::all();
foreach ($permissions as $permission) {
$gate->define($permission->name, function ($user) use ($permission) {
return $user->hasPermission($permission->name);
});
}
}
} | php | protected function registerGates($gate)
{
if (class_exists('Chronos\Scaffolding\Models\Permission') && Schema::hasTable('roles')) {
$permissions = \Chronos\Scaffolding\Models\Permission::all();
foreach ($permissions as $permission) {
$gate->define($permission->name, function ($user) use ($permission) {
return $user->hasPermission($permission->name);
});
}
}
} | [
"protected",
"function",
"registerGates",
"(",
"$",
"gate",
")",
"{",
"if",
"(",
"class_exists",
"(",
"'Chronos\\Scaffolding\\Models\\Permission'",
")",
"&&",
"Schema",
"::",
"hasTable",
"(",
"'roles'",
")",
")",
"{",
"$",
"permissions",
"=",
"\\",
"Chronos",
... | Register gates. | [
"Register",
"gates",
"."
] | df7f3a9794afaade3bee8f6be1223c98e4936cb2 | https://github.com/c4studio/chronos/blob/df7f3a9794afaade3bee8f6be1223c98e4936cb2/src/Chronos/Scaffolding/ScaffoldingServiceProvider.php#L93-L103 | train |
c4studio/chronos | src/Chronos/Scaffolding/ScaffoldingServiceProvider.php | ScaffoldingServiceProvider.registerMenu | protected function registerMenu()
{
\Menu::make('ChronosMenu', function($menu) {
// $menu->add(trans('chronos.scaffolding::menu.Dashboard'), ['route' => 'chronos.dashboard'])
// ->prepend('<span class="icon c4icon-dashboard"></span>')
// ->data('order', 1)->data('permissions', ['view_dashboard']);
// Users tab
$users_menu = $menu->add(trans('chronos.scaffolding::menu.Users'), null)
->prepend('<span class="icon c4icon-user-3"></span>')
->data('order', 800)->data('permissions', ['view_roles', 'edit_permissions']);
$users_menu->add(trans('chronos.scaffolding::menu.Roles'), ['route' => 'chronos.users.roles'])
->data('order', 810)->data('permissions', ['view_roles']);
$users_menu->add(trans('chronos.scaffolding::menu.Permissions'), ['route' => 'chronos.users.permissions'])
->data('order', 820)->data('permissions', ['edit_permissions']);
// Settings tab
$settings_menu = $menu->add(trans('chronos.scaffolding::menu.Settings'), null)
->prepend('<span class="icon c4icon-sliders-1"></span>')
->data('order', 900)->data('permissions', ['edit_settings', 'edit_access_tokens', 'edit_image_styles']);
$settings_menu->add(trans('chronos.scaffolding::menu.Access tokens'), ['route' => 'chronos.settings.access_tokens'])
->data('order', 910)->data('permissions', ['edit_access_tokens']);
$settings_menu->add(trans('chronos.scaffolding::menu.Image styles'), ['route' => 'chronos.settings.image_styles'])
->data('order', 910)->data('permissions', ['view_image_styles']);
});
\View::composer('*', function($view) {
$view->with('chronos_menu', \Menu::get('ChronosMenu')->sortBy('order'));
});
} | php | protected function registerMenu()
{
\Menu::make('ChronosMenu', function($menu) {
// $menu->add(trans('chronos.scaffolding::menu.Dashboard'), ['route' => 'chronos.dashboard'])
// ->prepend('<span class="icon c4icon-dashboard"></span>')
// ->data('order', 1)->data('permissions', ['view_dashboard']);
// Users tab
$users_menu = $menu->add(trans('chronos.scaffolding::menu.Users'), null)
->prepend('<span class="icon c4icon-user-3"></span>')
->data('order', 800)->data('permissions', ['view_roles', 'edit_permissions']);
$users_menu->add(trans('chronos.scaffolding::menu.Roles'), ['route' => 'chronos.users.roles'])
->data('order', 810)->data('permissions', ['view_roles']);
$users_menu->add(trans('chronos.scaffolding::menu.Permissions'), ['route' => 'chronos.users.permissions'])
->data('order', 820)->data('permissions', ['edit_permissions']);
// Settings tab
$settings_menu = $menu->add(trans('chronos.scaffolding::menu.Settings'), null)
->prepend('<span class="icon c4icon-sliders-1"></span>')
->data('order', 900)->data('permissions', ['edit_settings', 'edit_access_tokens', 'edit_image_styles']);
$settings_menu->add(trans('chronos.scaffolding::menu.Access tokens'), ['route' => 'chronos.settings.access_tokens'])
->data('order', 910)->data('permissions', ['edit_access_tokens']);
$settings_menu->add(trans('chronos.scaffolding::menu.Image styles'), ['route' => 'chronos.settings.image_styles'])
->data('order', 910)->data('permissions', ['view_image_styles']);
});
\View::composer('*', function($view) {
$view->with('chronos_menu', \Menu::get('ChronosMenu')->sortBy('order'));
});
} | [
"protected",
"function",
"registerMenu",
"(",
")",
"{",
"\\",
"Menu",
"::",
"make",
"(",
"'ChronosMenu'",
",",
"function",
"(",
"$",
"menu",
")",
"{",
"// $menu->add(trans('chronos.scaffolding::menu.Dashboard'), ['route' => 'chronos.dashboard'])",
"// ... | Register menu and share it with all views. | [
"Register",
"menu",
"and",
"share",
"it",
"with",
"all",
"views",
"."
] | df7f3a9794afaade3bee8f6be1223c98e4936cb2 | https://github.com/c4studio/chronos/blob/df7f3a9794afaade3bee8f6be1223c98e4936cb2/src/Chronos/Scaffolding/ScaffoldingServiceProvider.php#L108-L138 | train |
voslartomas/WebCMS2 | libs/translation/Translator.php | Translator.translate | public function translate($message, $parameters = array())
{
if (count($parameters) === 0) {
return $this->translations[$message];
} else {
return vsprintf($this->translations[$message], $parameters);
}
} | php | public function translate($message, $parameters = array())
{
if (count($parameters) === 0) {
return $this->translations[$message];
} else {
return vsprintf($this->translations[$message], $parameters);
}
} | [
"public",
"function",
"translate",
"(",
"$",
"message",
",",
"$",
"parameters",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"parameters",
")",
"===",
"0",
")",
"{",
"return",
"$",
"this",
"->",
"translations",
"[",
"$",
"message",... | Translates given message.
@param type $message
@param type $parameters | [
"Translates",
"given",
"message",
"."
] | b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf | https://github.com/voslartomas/WebCMS2/blob/b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf/libs/translation/Translator.php#L26-L33 | train |
c4studio/chronos | src/Chronos/Scaffolding/app/Services/RouteMapService.php | RouteMapService.add | public static function add($action, $type, $id = null)
{
if (!is_null($id))
self::$modelMap[$type][$id] = $action;
else
self::$typeMap[$type] = $action;
} | php | public static function add($action, $type, $id = null)
{
if (!is_null($id))
self::$modelMap[$type][$id] = $action;
else
self::$typeMap[$type] = $action;
} | [
"public",
"static",
"function",
"add",
"(",
"$",
"action",
",",
"$",
"type",
",",
"$",
"id",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"is_null",
"(",
"$",
"id",
")",
")",
"self",
"::",
"$",
"modelMap",
"[",
"$",
"type",
"]",
"[",
"$",
"id",
"]"... | Register new mapping
@param $action
@param $type
@param null $id | [
"Register",
"new",
"mapping"
] | df7f3a9794afaade3bee8f6be1223c98e4936cb2 | https://github.com/c4studio/chronos/blob/df7f3a9794afaade3bee8f6be1223c98e4936cb2/src/Chronos/Scaffolding/app/Services/RouteMapService.php#L17-L23 | train |
voslartomas/WebCMS2 | libs/helpers/SystemHelper.php | SystemHelper.checkFileContainsStr | public static function checkFileContainsStr($filename, $needle)
{
if (file_exists($filename)) {
$content = file_get_contents($filename);
if (strstr($content, $needle)) {
return true;
}
}
return false;
} | php | public static function checkFileContainsStr($filename, $needle)
{
if (file_exists($filename)) {
$content = file_get_contents($filename);
if (strstr($content, $needle)) {
return true;
}
}
return false;
} | [
"public",
"static",
"function",
"checkFileContainsStr",
"(",
"$",
"filename",
",",
"$",
"needle",
")",
"{",
"if",
"(",
"file_exists",
"(",
"$",
"filename",
")",
")",
"{",
"$",
"content",
"=",
"file_get_contents",
"(",
"$",
"filename",
")",
";",
"if",
"("... | Check if given file contains given string
@param String $filename
@param String $needle
@return Boolean | [
"Check",
"if",
"given",
"file",
"contains",
"given",
"string"
] | b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf | https://github.com/voslartomas/WebCMS2/blob/b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf/libs/helpers/SystemHelper.php#L107-L118 | train |
voslartomas/WebCMS2 | libs/helpers/SystemHelper.php | SystemHelper.isSuperAdmin | public static function isSuperAdmin(\Nette\Security\User $user)
{
$roles = $user->getIdentity()->getRoles();
return in_array('superadmin', $roles);
} | php | public static function isSuperAdmin(\Nette\Security\User $user)
{
$roles = $user->getIdentity()->getRoles();
return in_array('superadmin', $roles);
} | [
"public",
"static",
"function",
"isSuperAdmin",
"(",
"\\",
"Nette",
"\\",
"Security",
"\\",
"User",
"$",
"user",
")",
"{",
"$",
"roles",
"=",
"$",
"user",
"->",
"getIdentity",
"(",
")",
"->",
"getRoles",
"(",
")",
";",
"return",
"in_array",
"(",
"'supe... | Checks whether user has role superadmin or not.
@param \Nette\Security\User $user
@return Boolean | [
"Checks",
"whether",
"user",
"has",
"role",
"superadmin",
"or",
"not",
"."
] | b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf | https://github.com/voslartomas/WebCMS2/blob/b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf/libs/helpers/SystemHelper.php#L149-L154 | train |
voslartomas/WebCMS2 | libs/helpers/SystemHelper.php | SystemHelper.strFindAndReplaceAll | public static function strFindAndReplaceAll($vars = array(), $str)
{
if (array_count_values($vars) > 0){
foreach ($vars as $key => $val) {
for ($i = substr_count($str, $key); $i > 0; $i--) {
$str = \WebCMS\Helpers\SystemHelper::strlReplace($key, $val, $str);
}
}
}
return $str;
} | php | public static function strFindAndReplaceAll($vars = array(), $str)
{
if (array_count_values($vars) > 0){
foreach ($vars as $key => $val) {
for ($i = substr_count($str, $key); $i > 0; $i--) {
$str = \WebCMS\Helpers\SystemHelper::strlReplace($key, $val, $str);
}
}
}
return $str;
} | [
"public",
"static",
"function",
"strFindAndReplaceAll",
"(",
"$",
"vars",
"=",
"array",
"(",
")",
",",
"$",
"str",
")",
"{",
"if",
"(",
"array_count_values",
"(",
"$",
"vars",
")",
">",
"0",
")",
"{",
"foreach",
"(",
"$",
"vars",
"as",
"$",
"key",
... | Replace all needles found in str with rewrites
@param Array[needle, rewrite]
@param string $str
@return string $str | [
"Replace",
"all",
"needles",
"found",
"in",
"str",
"with",
"rewrites"
] | b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf | https://github.com/voslartomas/WebCMS2/blob/b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf/libs/helpers/SystemHelper.php#L197-L207 | train |
voslartomas/WebCMS2 | libs/helpers/SystemHelper.php | SystemHelper.relative | public static function relative($path)
{
// windows fix :/
$path = str_replace('\\', '/', $path);
// standard working directory
if (strpos($path, WWW_DIR) !== false) {
return str_replace(WWW_DIR, '', $path);
}
// symlink
$pos = strpos($path, 'upload/');
return substr($path, $pos - 1);
} | php | public static function relative($path)
{
// windows fix :/
$path = str_replace('\\', '/', $path);
// standard working directory
if (strpos($path, WWW_DIR) !== false) {
return str_replace(WWW_DIR, '', $path);
}
// symlink
$pos = strpos($path, 'upload/');
return substr($path, $pos - 1);
} | [
"public",
"static",
"function",
"relative",
"(",
"$",
"path",
")",
"{",
"// windows fix :/",
"$",
"path",
"=",
"str_replace",
"(",
"'\\\\'",
",",
"'/'",
",",
"$",
"path",
")",
";",
"// standard working directory",
"if",
"(",
"strpos",
"(",
"$",
"path",
","... | Create relative path from an absolute path.
@param string $path absolute path | [
"Create",
"relative",
"path",
"from",
"an",
"absolute",
"path",
"."
] | b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf | https://github.com/voslartomas/WebCMS2/blob/b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf/libs/helpers/SystemHelper.php#L239-L253 | train |
nails/module-cdn | src/Api/Controller/CdnObject.php | CdnObject.postCreate | public function postCreate()
{
// @todo (Pablo - 2017-12-18) - this should be protected using admin permissions or the token uploader
$oHttpCodes = Factory::service('HttpCodes');
$oInput = Factory::service('Input');
$oCdn = Factory::service('Cdn', 'nails/module-cdn');
$aOut = [];
// --------------------------------------------------------------------------
$sBucket = $oInput->post('bucket') ?: $oInput->header('X-Cdn-Bucket');
if (!$sBucket) {
throw new ApiException(
'Bucket not defined',
$oHttpCodes::STATUS_BAD_REQUEST
);
}
// --------------------------------------------------------------------------
// Attempt upload
$oObject = $oCdn->objectCreate('upload', $sBucket);
if (!$oObject) {
throw new ApiException(
$oCdn->lastError(),
$oHttpCodes::STATUS_BAD_REQUEST
);
}
// @todo (Pablo - 2018-06-25) - Reduce the namespace here (i.e remove `object`)
return Factory::factory('ApiResponse', 'nails/module-api')
->setData([
'object' => $this->formatObject(
$oObject,
$this->getRequestedUrls()
),
]);
} | php | public function postCreate()
{
// @todo (Pablo - 2017-12-18) - this should be protected using admin permissions or the token uploader
$oHttpCodes = Factory::service('HttpCodes');
$oInput = Factory::service('Input');
$oCdn = Factory::service('Cdn', 'nails/module-cdn');
$aOut = [];
// --------------------------------------------------------------------------
$sBucket = $oInput->post('bucket') ?: $oInput->header('X-Cdn-Bucket');
if (!$sBucket) {
throw new ApiException(
'Bucket not defined',
$oHttpCodes::STATUS_BAD_REQUEST
);
}
// --------------------------------------------------------------------------
// Attempt upload
$oObject = $oCdn->objectCreate('upload', $sBucket);
if (!$oObject) {
throw new ApiException(
$oCdn->lastError(),
$oHttpCodes::STATUS_BAD_REQUEST
);
}
// @todo (Pablo - 2018-06-25) - Reduce the namespace here (i.e remove `object`)
return Factory::factory('ApiResponse', 'nails/module-api')
->setData([
'object' => $this->formatObject(
$oObject,
$this->getRequestedUrls()
),
]);
} | [
"public",
"function",
"postCreate",
"(",
")",
"{",
"// @todo (Pablo - 2017-12-18) - this should be protected using admin permissions or the token uploader",
"$",
"oHttpCodes",
"=",
"Factory",
"::",
"service",
"(",
"'HttpCodes'",
")",
";",
"$",
"oInput",
"=",
"Factory",
"::... | Upload a new object to the CDN
@return array | [
"Upload",
"a",
"new",
"object",
"to",
"the",
"CDN"
] | 1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef | https://github.com/nails/module-cdn/blob/1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef/src/Api/Controller/CdnObject.php#L99-L138 | train |
nails/module-cdn | src/Api/Controller/CdnObject.php | CdnObject.postDelete | public function postDelete()
{
$oHttpCodes = Factory::service('HttpCodes');
if (!userHasPermission('admin:cdn:manager:object:delete')) {
throw new ApiException(
'You do not have permission to access this resource',
$oHttpCodes::STATUS_UNAUTHORIZED
);
}
$oInput = Factory::service('Input');
$oCdn = Factory::service('Cdn', 'nails/module-cdn');
$iObjectId = $oInput->post('object_id');
if (empty($iObjectId)) {
throw new ApiException(
'`object_id` is a required field',
$oHttpCodes::STATUS_BAD_REQUEST
);
}
$oObject = $oCdn->getObject($iObjectId);
$bIsTrash = false;
if (empty($oObject)) {
$oObject = $oCdn->getObjectFromTrash($iObjectId);
$bIsTrash = true;
}
if (empty($oObject)) {
throw new ApiException(
'Invalid object ID',
$oHttpCodes::STATUS_NOT_FOUND
);
}
if ($bIsTrash) {
$bDelete = $oCdn->purgeTrash([$iObjectId]);
} else {
$bDelete = $oCdn->objectDelete($iObjectId);
}
if (!$bDelete) {
throw new ApiException(
$oCdn->lastError(),
$oHttpCodes::STATUS_BAD_REQUEST
);
}
return Factory::factory('ApiResponse', 'nails/module-api');
} | php | public function postDelete()
{
$oHttpCodes = Factory::service('HttpCodes');
if (!userHasPermission('admin:cdn:manager:object:delete')) {
throw new ApiException(
'You do not have permission to access this resource',
$oHttpCodes::STATUS_UNAUTHORIZED
);
}
$oInput = Factory::service('Input');
$oCdn = Factory::service('Cdn', 'nails/module-cdn');
$iObjectId = $oInput->post('object_id');
if (empty($iObjectId)) {
throw new ApiException(
'`object_id` is a required field',
$oHttpCodes::STATUS_BAD_REQUEST
);
}
$oObject = $oCdn->getObject($iObjectId);
$bIsTrash = false;
if (empty($oObject)) {
$oObject = $oCdn->getObjectFromTrash($iObjectId);
$bIsTrash = true;
}
if (empty($oObject)) {
throw new ApiException(
'Invalid object ID',
$oHttpCodes::STATUS_NOT_FOUND
);
}
if ($bIsTrash) {
$bDelete = $oCdn->purgeTrash([$iObjectId]);
} else {
$bDelete = $oCdn->objectDelete($iObjectId);
}
if (!$bDelete) {
throw new ApiException(
$oCdn->lastError(),
$oHttpCodes::STATUS_BAD_REQUEST
);
}
return Factory::factory('ApiResponse', 'nails/module-api');
} | [
"public",
"function",
"postDelete",
"(",
")",
"{",
"$",
"oHttpCodes",
"=",
"Factory",
"::",
"service",
"(",
"'HttpCodes'",
")",
";",
"if",
"(",
"!",
"userHasPermission",
"(",
"'admin:cdn:manager:object:delete'",
")",
")",
"{",
"throw",
"new",
"ApiException",
"... | Delete an object from the CDN
@return array | [
"Delete",
"an",
"object",
"from",
"the",
"CDN"
] | 1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef | https://github.com/nails/module-cdn/blob/1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef/src/Api/Controller/CdnObject.php#L147-L197 | train |
nails/module-cdn | src/Api/Controller/CdnObject.php | CdnObject.postRestore | public function postRestore()
{
$oHttpCodes = Factory::service('HttpCodes');
if (!userHasPermission('admin:cdn:manager:object:restore')) {
throw new ApiException(
'You do not have permission to access this resource',
$oHttpCodes::STATUS_UNAUTHORIZED
);
}
$oInput = Factory::service('Input');
$oCdn = Factory::service('Cdn', 'nails/module-cdn');
$iObjectId = $oInput->post('object_id');
if (!$oCdn->objectRestore($iObjectId)) {
throw new ApiException(
$oCdn->lastError(),
$oHttpCodes::STATUS_INTERNAL_SERVER_ERROR
);
}
return Factory::factory('ApiResponse', 'nails/module-api');
} | php | public function postRestore()
{
$oHttpCodes = Factory::service('HttpCodes');
if (!userHasPermission('admin:cdn:manager:object:restore')) {
throw new ApiException(
'You do not have permission to access this resource',
$oHttpCodes::STATUS_UNAUTHORIZED
);
}
$oInput = Factory::service('Input');
$oCdn = Factory::service('Cdn', 'nails/module-cdn');
$iObjectId = $oInput->post('object_id');
if (!$oCdn->objectRestore($iObjectId)) {
throw new ApiException(
$oCdn->lastError(),
$oHttpCodes::STATUS_INTERNAL_SERVER_ERROR
);
}
return Factory::factory('ApiResponse', 'nails/module-api');
} | [
"public",
"function",
"postRestore",
"(",
")",
"{",
"$",
"oHttpCodes",
"=",
"Factory",
"::",
"service",
"(",
"'HttpCodes'",
")",
";",
"if",
"(",
"!",
"userHasPermission",
"(",
"'admin:cdn:manager:object:restore'",
")",
")",
"{",
"throw",
"new",
"ApiException",
... | Restore an item form the trash
@return array | [
"Restore",
"an",
"item",
"form",
"the",
"trash"
] | 1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef | https://github.com/nails/module-cdn/blob/1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef/src/Api/Controller/CdnObject.php#L206-L229 | train |
nails/module-cdn | src/Api/Controller/CdnObject.php | CdnObject.getSearch | public function getSearch()
{
$oHttpCodes = Factory::service('HttpCodes');
if (!userHasPermission('admin:cdn:manager:object:browse')) {
throw new ApiException(
'You do not have permission to access this resource',
$oHttpCodes::STATUS_UNAUTHORIZED
);
}
$oInput = Factory::service('Input');
$oModel = Factory::model('Object', 'nails/module-cdn');
$sKeywords = $oInput->get('keywords');
$iPage = (int) $oInput->get('page') ?: 1;
$oResult = $oModel->search(
$sKeywords,
$iPage,
static::MAX_OBJECTS_PER_REQUEST
);
$oResponse = Factory::factory('ApiResponse', 'nails/module-api');
$oResponse->setData(array_map(
function ($oObj) {
$oObj->is_img = isset($oObj->img);
$oObj->url = (object) [
'src' => cdnServe($oObj->id),
'preview' => isset($oObj->img) ? cdnCrop($oObj->id, 400, 400) : null,
];
return $oObj;
},
$oResult->data
));
return $oResponse;
} | php | public function getSearch()
{
$oHttpCodes = Factory::service('HttpCodes');
if (!userHasPermission('admin:cdn:manager:object:browse')) {
throw new ApiException(
'You do not have permission to access this resource',
$oHttpCodes::STATUS_UNAUTHORIZED
);
}
$oInput = Factory::service('Input');
$oModel = Factory::model('Object', 'nails/module-cdn');
$sKeywords = $oInput->get('keywords');
$iPage = (int) $oInput->get('page') ?: 1;
$oResult = $oModel->search(
$sKeywords,
$iPage,
static::MAX_OBJECTS_PER_REQUEST
);
$oResponse = Factory::factory('ApiResponse', 'nails/module-api');
$oResponse->setData(array_map(
function ($oObj) {
$oObj->is_img = isset($oObj->img);
$oObj->url = (object) [
'src' => cdnServe($oObj->id),
'preview' => isset($oObj->img) ? cdnCrop($oObj->id, 400, 400) : null,
];
return $oObj;
},
$oResult->data
));
return $oResponse;
} | [
"public",
"function",
"getSearch",
"(",
")",
"{",
"$",
"oHttpCodes",
"=",
"Factory",
"::",
"service",
"(",
"'HttpCodes'",
")",
";",
"if",
"(",
"!",
"userHasPermission",
"(",
"'admin:cdn:manager:object:browse'",
")",
")",
"{",
"throw",
"new",
"ApiException",
"(... | Search across all objects
@return array | [
"Search",
"across",
"all",
"objects"
] | 1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef | https://github.com/nails/module-cdn/blob/1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef/src/Api/Controller/CdnObject.php#L238-L272 | train |
nails/module-cdn | src/Api/Controller/CdnObject.php | CdnObject.getTrash | public function getTrash()
{
$oHttpCodes = Factory::service('HttpCodes');
if (!userHasPermission('admin:cdn:manager:object:browse')) {
throw new ApiException(
'You do not have permission to access this resource',
$oHttpCodes::STATUS_UNAUTHORIZED
);
}
$oInput = Factory::service('Input');
$oModel = Factory::model('ObjectTrash', 'nails/module-cdn');
$iPage = (int) $oInput->get('page') ?: 1;
$aResults = $oModel->getAll(
$iPage,
static::MAX_OBJECTS_PER_REQUEST,
['sort' => [['trashed', 'desc']]]
);
$oResponse = Factory::factory('ApiResponse', 'nails/module-api');
$oResponse->setData(array_map(
function ($oObj) {
$oObj->is_img = isset($oObj->img);
$oObj->url = (object) [
'src' => cdnServe($oObj->id),
'preview' => isset($oObj->img) ? cdnCrop($oObj->id, 400, 400) : null,
];
return $oObj;
},
$aResults
));
return $oResponse;
} | php | public function getTrash()
{
$oHttpCodes = Factory::service('HttpCodes');
if (!userHasPermission('admin:cdn:manager:object:browse')) {
throw new ApiException(
'You do not have permission to access this resource',
$oHttpCodes::STATUS_UNAUTHORIZED
);
}
$oInput = Factory::service('Input');
$oModel = Factory::model('ObjectTrash', 'nails/module-cdn');
$iPage = (int) $oInput->get('page') ?: 1;
$aResults = $oModel->getAll(
$iPage,
static::MAX_OBJECTS_PER_REQUEST,
['sort' => [['trashed', 'desc']]]
);
$oResponse = Factory::factory('ApiResponse', 'nails/module-api');
$oResponse->setData(array_map(
function ($oObj) {
$oObj->is_img = isset($oObj->img);
$oObj->url = (object) [
'src' => cdnServe($oObj->id),
'preview' => isset($oObj->img) ? cdnCrop($oObj->id, 400, 400) : null,
];
return $oObj;
},
$aResults
));
return $oResponse;
} | [
"public",
"function",
"getTrash",
"(",
")",
"{",
"$",
"oHttpCodes",
"=",
"Factory",
"::",
"service",
"(",
"'HttpCodes'",
")",
";",
"if",
"(",
"!",
"userHasPermission",
"(",
"'admin:cdn:manager:object:browse'",
")",
")",
"{",
"throw",
"new",
"ApiException",
"("... | List items in the trash
@return array | [
"List",
"items",
"in",
"the",
"trash"
] | 1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef | https://github.com/nails/module-cdn/blob/1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef/src/Api/Controller/CdnObject.php#L281-L314 | train |
nails/module-cdn | src/Api/Controller/CdnObject.php | CdnObject.getRequestedUrls | protected function getRequestedUrls()
{
$oInput = Factory::service('Input');
$sUrls = $oInput->get('urls') ?: $oInput->header('X-Cdn-Urls');
$aUrls = !is_array($sUrls) ? explode(',', $sUrls) : $sUrls;
$aUrls = array_map('strtolower', $aUrls);
// Filter out any which don't follow the format {digit}x{digit}-{scale|crop} || raw
foreach ($aUrls as &$sDimension) {
if (!is_string($sDimension)) {
$sDimension = null;
continue;
}
preg_match_all('/^(\d+?)x(\d+?)-(scale|crop)$/i', $sDimension, $aMatches);
if (empty($aMatches[0])) {
$sDimension = null;
} else {
$sDimension = [
'width' => !empty($aMatches[1][0]) ? $aMatches[1][0] : null,
'height' => !empty($aMatches[2][0]) ? $aMatches[2][0] : null,
'type' => !empty($aMatches[3][0]) ? $aMatches[3][0] : 'crop',
];
}
}
return array_filter($aUrls);
} | php | protected function getRequestedUrls()
{
$oInput = Factory::service('Input');
$sUrls = $oInput->get('urls') ?: $oInput->header('X-Cdn-Urls');
$aUrls = !is_array($sUrls) ? explode(',', $sUrls) : $sUrls;
$aUrls = array_map('strtolower', $aUrls);
// Filter out any which don't follow the format {digit}x{digit}-{scale|crop} || raw
foreach ($aUrls as &$sDimension) {
if (!is_string($sDimension)) {
$sDimension = null;
continue;
}
preg_match_all('/^(\d+?)x(\d+?)-(scale|crop)$/i', $sDimension, $aMatches);
if (empty($aMatches[0])) {
$sDimension = null;
} else {
$sDimension = [
'width' => !empty($aMatches[1][0]) ? $aMatches[1][0] : null,
'height' => !empty($aMatches[2][0]) ? $aMatches[2][0] : null,
'type' => !empty($aMatches[3][0]) ? $aMatches[3][0] : 'crop',
];
}
}
return array_filter($aUrls);
} | [
"protected",
"function",
"getRequestedUrls",
"(",
")",
"{",
"$",
"oInput",
"=",
"Factory",
"::",
"service",
"(",
"'Input'",
")",
";",
"$",
"sUrls",
"=",
"$",
"oInput",
"->",
"get",
"(",
"'urls'",
")",
"?",
":",
"$",
"oInput",
"->",
"header",
"(",
"'X... | Return an array of the requested URLs form the request
@return array | [
"Return",
"an",
"array",
"of",
"the",
"requested",
"URLs",
"form",
"the",
"request"
] | 1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef | https://github.com/nails/module-cdn/blob/1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef/src/Api/Controller/CdnObject.php#L323-L352 | train |
nails/module-cdn | src/Api/Controller/CdnObject.php | CdnObject.formatObject | protected function formatObject($oObject, $aUrls = [])
{
return (object) [
'id' => $oObject->id,
'object' => (object) [
'name' => $oObject->file->name->human,
'mime' => $oObject->file->mime,
'size' => $oObject->file->size,
],
'bucket' => $oObject->bucket,
'is_img' => $oObject->is_img,
'img' => (object) [
'width' => $oObject->img_width,
'height' => $oObject->img_height,
'orientation' => $oObject->img_orientation,
'is_animated' => $oObject->is_animated,
],
'created' => $oObject->created,
'modified' => $oObject->modified,
'url' => (object) $this->generateUrls($oObject, $aUrls),
];
} | php | protected function formatObject($oObject, $aUrls = [])
{
return (object) [
'id' => $oObject->id,
'object' => (object) [
'name' => $oObject->file->name->human,
'mime' => $oObject->file->mime,
'size' => $oObject->file->size,
],
'bucket' => $oObject->bucket,
'is_img' => $oObject->is_img,
'img' => (object) [
'width' => $oObject->img_width,
'height' => $oObject->img_height,
'orientation' => $oObject->img_orientation,
'is_animated' => $oObject->is_animated,
],
'created' => $oObject->created,
'modified' => $oObject->modified,
'url' => (object) $this->generateUrls($oObject, $aUrls),
];
} | [
"protected",
"function",
"formatObject",
"(",
"$",
"oObject",
",",
"$",
"aUrls",
"=",
"[",
"]",
")",
"{",
"return",
"(",
"object",
")",
"[",
"'id'",
"=>",
"$",
"oObject",
"->",
"id",
",",
"'object'",
"=>",
"(",
"object",
")",
"[",
"'name'",
"=>",
"... | Format an object object
@param \stdClass $oObject the object to format
@param array $aUrls The requested URLs
@return object | [
"Format",
"an",
"object",
"object"
] | 1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef | https://github.com/nails/module-cdn/blob/1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef/src/Api/Controller/CdnObject.php#L364-L385 | train |
nails/module-cdn | src/Api/Controller/CdnObject.php | CdnObject.generateUrls | protected function generateUrls($oObject, $aUrls)
{
$oCdn = Factory::service('Cdn', 'nails/module-cdn');
$aOut = ['src' => $oCdn->urlServe($oObject)];
if (!empty($aUrls) && $oObject->is_img) {
foreach ($aUrls as $aDimension) {
$sProperty = $aDimension['width'] . 'x' . $aDimension['height'] . '-' . $aDimension['type'];
switch ($aDimension['type']) {
case 'crop':
$aOut[$sProperty] = $oCdn->urlCrop(
$oObject,
$aDimension['width'],
$aDimension['height']
);
break;
case 'scale':
$aOut[$sProperty] = $oCdn->urlScale(
$oObject,
$aDimension['width'],
$aDimension['height']
);
break;
}
}
}
return $aOut;
} | php | protected function generateUrls($oObject, $aUrls)
{
$oCdn = Factory::service('Cdn', 'nails/module-cdn');
$aOut = ['src' => $oCdn->urlServe($oObject)];
if (!empty($aUrls) && $oObject->is_img) {
foreach ($aUrls as $aDimension) {
$sProperty = $aDimension['width'] . 'x' . $aDimension['height'] . '-' . $aDimension['type'];
switch ($aDimension['type']) {
case 'crop':
$aOut[$sProperty] = $oCdn->urlCrop(
$oObject,
$aDimension['width'],
$aDimension['height']
);
break;
case 'scale':
$aOut[$sProperty] = $oCdn->urlScale(
$oObject,
$aDimension['width'],
$aDimension['height']
);
break;
}
}
}
return $aOut;
} | [
"protected",
"function",
"generateUrls",
"(",
"$",
"oObject",
",",
"$",
"aUrls",
")",
"{",
"$",
"oCdn",
"=",
"Factory",
"::",
"service",
"(",
"'Cdn'",
",",
"'nails/module-cdn'",
")",
";",
"$",
"aOut",
"=",
"[",
"'src'",
"=>",
"$",
"oCdn",
"->",
"urlSer... | Generate the requested URLs
@param \stdClass $oObject The object object
@param array $aUrls The URLs to generate
@return array | [
"Generate",
"the",
"requested",
"URLs"
] | 1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef | https://github.com/nails/module-cdn/blob/1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef/src/Api/Controller/CdnObject.php#L397-L428 | train |
CanalTP/NmmPortalBundle | Controller/CustomerController.php | CustomerController.findCustomerById | private function findCustomerById ($id) {
$customer = $this->getDoctrine()
->getManager()
->getRepository('CanalTPNmmPortalBundle:Customer')
->find($id);
return $customer;
} | php | private function findCustomerById ($id) {
$customer = $this->getDoctrine()
->getManager()
->getRepository('CanalTPNmmPortalBundle:Customer')
->find($id);
return $customer;
} | [
"private",
"function",
"findCustomerById",
"(",
"$",
"id",
")",
"{",
"$",
"customer",
"=",
"$",
"this",
"->",
"getDoctrine",
"(",
")",
"->",
"getManager",
"(",
")",
"->",
"getRepository",
"(",
"'CanalTPNmmPortalBundle:Customer'",
")",
"->",
"find",
"(",
"$",... | Find a Customer by id.
@param mixed $id The customer id
@return CanalTP\NmmPortalBundle\Entity\Customer | [
"Find",
"a",
"Customer",
"by",
"id",
"."
] | b1ad026a33897984206ea1691ad9e25db5854efb | https://github.com/CanalTP/NmmPortalBundle/blob/b1ad026a33897984206ea1691ad9e25db5854efb/Controller/CustomerController.php#L120-L127 | train |
kadet1090/KeyLighter | Parser/Rules.php | Rules.addMany | public function addMany(array $rules, $prefix = null)
{
foreach ($rules as $type => $rule) {
$type = $this->_getName($type, $prefix);
if ($rule instanceof Rule) {
$this->add($type, $rule);
} elseif (is_array($rule)) {
$this->addMany($rule, $type);
} else {
throw new \LogicException('Array values has to be either arrays of rules or rules.');
}
}
} | php | public function addMany(array $rules, $prefix = null)
{
foreach ($rules as $type => $rule) {
$type = $this->_getName($type, $prefix);
if ($rule instanceof Rule) {
$this->add($type, $rule);
} elseif (is_array($rule)) {
$this->addMany($rule, $type);
} else {
throw new \LogicException('Array values has to be either arrays of rules or rules.');
}
}
} | [
"public",
"function",
"addMany",
"(",
"array",
"$",
"rules",
",",
"$",
"prefix",
"=",
"null",
")",
"{",
"foreach",
"(",
"$",
"rules",
"as",
"$",
"type",
"=>",
"$",
"rule",
")",
"{",
"$",
"type",
"=",
"$",
"this",
"->",
"_getName",
"(",
"$",
"type... | Adds array of rules
@param array $rules
@param string|null $prefix
@throws \LogicException | [
"Adds",
"array",
"of",
"rules"
] | 6aac402b7fe0170edf3c5afbae652009951068af | https://github.com/kadet1090/KeyLighter/blob/6aac402b7fe0170edf3c5afbae652009951068af/Parser/Rules.php#L61-L74 | train |
kadet1090/KeyLighter | Parser/Rules.php | Rules.add | public function add($type, Rule $rule)
{
if (!isset($this[$type])) {
$this[$type] = [];
}
if ($rule->language === false) {
$rule->language = $this->_language;
}
if ($rule->validator === false) {
$rule->validator = $this->validator;
}
$rule->factory->setBase($type);
if ($rule->name !== null) {
if (isset($this[$type][$rule->name])) {
throw new NameConflictException("Rule with '{$rule->name}' is already defined, name has to be unique!");
}
$this[$type][$rule->name] = $rule;
return;
}
$this[$type][] = $rule;
} | php | public function add($type, Rule $rule)
{
if (!isset($this[$type])) {
$this[$type] = [];
}
if ($rule->language === false) {
$rule->language = $this->_language;
}
if ($rule->validator === false) {
$rule->validator = $this->validator;
}
$rule->factory->setBase($type);
if ($rule->name !== null) {
if (isset($this[$type][$rule->name])) {
throw new NameConflictException("Rule with '{$rule->name}' is already defined, name has to be unique!");
}
$this[$type][$rule->name] = $rule;
return;
}
$this[$type][] = $rule;
} | [
"public",
"function",
"add",
"(",
"$",
"type",
",",
"Rule",
"$",
"rule",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"[",
"$",
"type",
"]",
")",
")",
"{",
"$",
"this",
"[",
"$",
"type",
"]",
"=",
"[",
"]",
";",
"}",
"if",
"(",
"$... | Adds one rule
@param string $type
@param Rule $rule
@throws NameConflictException When there is already defined rule with given name. | [
"Adds",
"one",
"rule"
] | 6aac402b7fe0170edf3c5afbae652009951068af | https://github.com/kadet1090/KeyLighter/blob/6aac402b7fe0170edf3c5afbae652009951068af/Parser/Rules.php#L84-L110 | train |
kadet1090/KeyLighter | Parser/Rules.php | Rules.replace | public function replace(Rule $replacement, $type, $index = 0)
{
$current = $this->rule($type, $index);
if ($current->name !== null) {
$replacement->name = $current->name;
}
$this[$type][$index] = $replacement;
} | php | public function replace(Rule $replacement, $type, $index = 0)
{
$current = $this->rule($type, $index);
if ($current->name !== null) {
$replacement->name = $current->name;
}
$this[$type][$index] = $replacement;
} | [
"public",
"function",
"replace",
"(",
"Rule",
"$",
"replacement",
",",
"$",
"type",
",",
"$",
"index",
"=",
"0",
")",
"{",
"$",
"current",
"=",
"$",
"this",
"->",
"rule",
"(",
"$",
"type",
",",
"$",
"index",
")",
";",
"if",
"(",
"$",
"current",
... | Replaces rule of given type and index with provided one.
@param Rule $replacement
@param $type
@param int $index | [
"Replaces",
"rule",
"of",
"given",
"type",
"and",
"index",
"with",
"provided",
"one",
"."
] | 6aac402b7fe0170edf3c5afbae652009951068af | https://github.com/kadet1090/KeyLighter/blob/6aac402b7fe0170edf3c5afbae652009951068af/Parser/Rules.php#L149-L157 | train |
kadet1090/KeyLighter | Parser/Rules.php | Rules.remove | public function remove($type, $index = null)
{
if ($index === null) {
unset($this[$type]);
return;
}
if(!isset($this[$type][$index])) {
throw new NoSuchElementException("There is no rule '$type' type indexed by '$index'.");
}
unset($this[$type][$index]);
} | php | public function remove($type, $index = null)
{
if ($index === null) {
unset($this[$type]);
return;
}
if(!isset($this[$type][$index])) {
throw new NoSuchElementException("There is no rule '$type' type indexed by '$index'.");
}
unset($this[$type][$index]);
} | [
"public",
"function",
"remove",
"(",
"$",
"type",
",",
"$",
"index",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"index",
"===",
"null",
")",
"{",
"unset",
"(",
"$",
"this",
"[",
"$",
"type",
"]",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"iss... | Removes rule of given type and index.
@param string $type
@param mixed $index
@throws NoSuchElementException | [
"Removes",
"rule",
"of",
"given",
"type",
"and",
"index",
"."
] | 6aac402b7fe0170edf3c5afbae652009951068af | https://github.com/kadet1090/KeyLighter/blob/6aac402b7fe0170edf3c5afbae652009951068af/Parser/Rules.php#L167-L179 | train |
Rareloop/primer-core | src/Primer/FileSystem.php | FileSystem.getDataForPattern | public static function getDataForPattern($id, $resolveAlias = false)
{
$data = array();
$id = Primer::cleanId($id);
// Load the Patterns default data
$defaultData = @file_get_contents(Primer::$PATTERN_PATH . '/' . $id . '/data.json');
if ($defaultData) {
$json = json_decode($defaultData);
if ($json) {
// Merge in the data
$data += (array)$json;
}
}
if ($resolveAlias) {
// Parent data - e.g. elements/button is the parent of elements/button~primary
$parentData = array();
// Load parent data if this is inherit
if (preg_match('/(.*?)~.*?/', $id, $matches)) {
$parentData = FileSystem::getDataForPattern($matches[1]);
}
// Merge the parent and pattern data together, giving preference to the pattern data
$data = array_replace_recursive((array)$parentData, (array)$data);
}
// Create the data structure
$viewData = new ViewData($data);
// Give the system a chance to mutate the data
ViewData::fire($id, $viewData);
// Return the data structure
return $viewData;
} | php | public static function getDataForPattern($id, $resolveAlias = false)
{
$data = array();
$id = Primer::cleanId($id);
// Load the Patterns default data
$defaultData = @file_get_contents(Primer::$PATTERN_PATH . '/' . $id . '/data.json');
if ($defaultData) {
$json = json_decode($defaultData);
if ($json) {
// Merge in the data
$data += (array)$json;
}
}
if ($resolveAlias) {
// Parent data - e.g. elements/button is the parent of elements/button~primary
$parentData = array();
// Load parent data if this is inherit
if (preg_match('/(.*?)~.*?/', $id, $matches)) {
$parentData = FileSystem::getDataForPattern($matches[1]);
}
// Merge the parent and pattern data together, giving preference to the pattern data
$data = array_replace_recursive((array)$parentData, (array)$data);
}
// Create the data structure
$viewData = new ViewData($data);
// Give the system a chance to mutate the data
ViewData::fire($id, $viewData);
// Return the data structure
return $viewData;
} | [
"public",
"static",
"function",
"getDataForPattern",
"(",
"$",
"id",
",",
"$",
"resolveAlias",
"=",
"false",
")",
"{",
"$",
"data",
"=",
"array",
"(",
")",
";",
"$",
"id",
"=",
"Primer",
"::",
"cleanId",
"(",
"$",
"id",
")",
";",
"// Load the Patterns ... | Retrieve data for a patter
@param String $id The id of the pattern
@param Boolean $resolveAlias Whether or not to resolve data from aliased patterns (e.g. button~outline -> button)
@return ViewData The decoded JSON data | [
"Retrieve",
"data",
"for",
"a",
"patter"
] | fe098d6794a4add368f97672397dc93d223a1786 | https://github.com/Rareloop/primer-core/blob/fe098d6794a4add368f97672397dc93d223a1786/src/Primer/FileSystem.php#L20-L59 | train |
jon48/webtrees-lib | src/Webtrees/Module/GeoDispersion/Model/GeoAnalysisProvider.php | GeoAnalysisProvider.getGeoAnalysis | public function getGeoAnalysis($id, $only_enabled = true) {
$args = array (
'gedcom_id' => $this->tree->getTreeId(),
'ga_id' => $id
);
$sql = 'SELECT majgd_id, majgd_descr, majgd_sublevel, majgd_map, majgd_toplevel, majgd_useflagsgen, majgd_detailsgen, majgd_status' .
' FROM `##maj_geodispersion`' .
' WHERE majgd_file = :gedcom_id AND majgd_id=:ga_id';
if($only_enabled) {
$sql .= ' AND majgd_status = :status';
$args['status'] = 'enabled';
}
$sql .= ' ORDER BY majgd_descr';
$ga_array = Database::prepare($sql)->execute($args)->fetchOneRow(\PDO::FETCH_ASSOC);
if($ga_array) {
return $this->loadGeoAnalysisFromRow($ga_array);
}
return null;
} | php | public function getGeoAnalysis($id, $only_enabled = true) {
$args = array (
'gedcom_id' => $this->tree->getTreeId(),
'ga_id' => $id
);
$sql = 'SELECT majgd_id, majgd_descr, majgd_sublevel, majgd_map, majgd_toplevel, majgd_useflagsgen, majgd_detailsgen, majgd_status' .
' FROM `##maj_geodispersion`' .
' WHERE majgd_file = :gedcom_id AND majgd_id=:ga_id';
if($only_enabled) {
$sql .= ' AND majgd_status = :status';
$args['status'] = 'enabled';
}
$sql .= ' ORDER BY majgd_descr';
$ga_array = Database::prepare($sql)->execute($args)->fetchOneRow(\PDO::FETCH_ASSOC);
if($ga_array) {
return $this->loadGeoAnalysisFromRow($ga_array);
}
return null;
} | [
"public",
"function",
"getGeoAnalysis",
"(",
"$",
"id",
",",
"$",
"only_enabled",
"=",
"true",
")",
"{",
"$",
"args",
"=",
"array",
"(",
"'gedcom_id'",
"=>",
"$",
"this",
"->",
"tree",
"->",
"getTreeId",
"(",
")",
",",
"'ga_id'",
"=>",
"$",
"id",
")"... | Get a geographical analysis by its ID.
The function can only search for only enabled analysis, or all.
@param int $id geodispersion analysis ID
@param bool $only_enabled Search for only enabled geodispersion analysis
@return \MyArtJaub\Webtrees\Module\GeoDispersion\Model\GeoAnalysis|NULL | [
"Get",
"a",
"geographical",
"analysis",
"by",
"its",
"ID",
".",
"The",
"function",
"can",
"only",
"search",
"for",
"only",
"enabled",
"analysis",
"or",
"all",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/GeoDispersion/Model/GeoAnalysisProvider.php#L112-L134 | train |
jon48/webtrees-lib | src/Webtrees/Module/GeoDispersion/Model/GeoAnalysisProvider.php | GeoAnalysisProvider.createGeoAnalysis | public function createGeoAnalysis($description, $analysis_level, $map_file, $map_top_level, $use_flags, $gen_details) {
try{
Database::beginTransaction();
Database::prepare(
'INSERT INTO `##maj_geodispersion`'.
' (majgd_file, majgd_descr, majgd_sublevel, majgd_map, majgd_toplevel, majgd_useflagsgen, majgd_detailsgen)'.
' VALUES (:gedcom_id, :description, :analysis_level, :map, :map_top_level, :use_flags, :gen_details)'
)->execute(array(
'gedcom_id' => $this->tree->getTreeId(),
'description' => $description,
'analysis_level' => $analysis_level,
'use_flags' => $use_flags ? 'yes' : 'no',
'gen_details' => $gen_details,
'map' => $map_file,
'map_top_level' => $map_top_level
));
$id = Database::lastInsertId();
$ga = $this->getGeoAnalysis($id, false);
Database::commit();
}
catch(\Exception $ex) {
Database::rollback();
$ga = null;
Log::addErrorLog('A new Geo Analysis failed to be created. Transaction rollbacked. Parameters ['.$description.', '.$analysis_level.','.$map_file.','.$map_top_level.','.$use_flags.', '.$gen_details.']. Exception: '.$ex->getMessage());
}
return $ga;
} | php | public function createGeoAnalysis($description, $analysis_level, $map_file, $map_top_level, $use_flags, $gen_details) {
try{
Database::beginTransaction();
Database::prepare(
'INSERT INTO `##maj_geodispersion`'.
' (majgd_file, majgd_descr, majgd_sublevel, majgd_map, majgd_toplevel, majgd_useflagsgen, majgd_detailsgen)'.
' VALUES (:gedcom_id, :description, :analysis_level, :map, :map_top_level, :use_flags, :gen_details)'
)->execute(array(
'gedcom_id' => $this->tree->getTreeId(),
'description' => $description,
'analysis_level' => $analysis_level,
'use_flags' => $use_flags ? 'yes' : 'no',
'gen_details' => $gen_details,
'map' => $map_file,
'map_top_level' => $map_top_level
));
$id = Database::lastInsertId();
$ga = $this->getGeoAnalysis($id, false);
Database::commit();
}
catch(\Exception $ex) {
Database::rollback();
$ga = null;
Log::addErrorLog('A new Geo Analysis failed to be created. Transaction rollbacked. Parameters ['.$description.', '.$analysis_level.','.$map_file.','.$map_top_level.','.$use_flags.', '.$gen_details.']. Exception: '.$ex->getMessage());
}
return $ga;
} | [
"public",
"function",
"createGeoAnalysis",
"(",
"$",
"description",
",",
"$",
"analysis_level",
",",
"$",
"map_file",
",",
"$",
"map_top_level",
",",
"$",
"use_flags",
",",
"$",
"gen_details",
")",
"{",
"try",
"{",
"Database",
"::",
"beginTransaction",
"(",
... | Add a new geodispersion analysis in the database, in a transactional manner.
When successful, eturns the newly created GeoAnalysis object.
@param string $description geodispersion analysis title
@param int $analysis_level Analysis level
@param string $map_file Filename of the map
@param int $map_top_level Parent level of the map
@param bool $use_flags Use flag in the place display
@param int $gen_details Number of top places to display
@return GeoAnalysis | [
"Add",
"a",
"new",
"geodispersion",
"analysis",
"in",
"the",
"database",
"in",
"a",
"transactional",
"manner",
".",
"When",
"successful",
"eturns",
"the",
"newly",
"created",
"GeoAnalysis",
"object",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/GeoDispersion/Model/GeoAnalysisProvider.php#L148-L177 | train |
jon48/webtrees-lib | src/Webtrees/Module/GeoDispersion/Model/GeoAnalysisProvider.php | GeoAnalysisProvider.deleteGeoAnalysis | public function deleteGeoAnalysis(GeoAnalysis $ga) {
Database::prepare(
'DELETE FROM `##maj_geodispersion`'.
' WHERE majgd_file = :gedcom_id AND majgd_id=:ga_id'
)->execute(array(
'gedcom_id' => $this->tree->getTreeId(),
'ga_id' => $ga->getId()
));
} | php | public function deleteGeoAnalysis(GeoAnalysis $ga) {
Database::prepare(
'DELETE FROM `##maj_geodispersion`'.
' WHERE majgd_file = :gedcom_id AND majgd_id=:ga_id'
)->execute(array(
'gedcom_id' => $this->tree->getTreeId(),
'ga_id' => $ga->getId()
));
} | [
"public",
"function",
"deleteGeoAnalysis",
"(",
"GeoAnalysis",
"$",
"ga",
")",
"{",
"Database",
"::",
"prepare",
"(",
"'DELETE FROM `##maj_geodispersion`'",
".",
"' WHERE majgd_file = :gedcom_id AND majgd_id=:ga_id'",
")",
"->",
"execute",
"(",
"array",
"(",
"'gedcom_id'"... | Delete a geodispersion analysis from the database.
@param GeoAnalysis $ga | [
"Delete",
"a",
"geodispersion",
"analysis",
"from",
"the",
"database",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/GeoDispersion/Model/GeoAnalysisProvider.php#L246-L254 | train |
jon48/webtrees-lib | src/Webtrees/Module/GeoDispersion/Model/GeoAnalysisProvider.php | GeoAnalysisProvider.getGeoAnalysisList | public function getGeoAnalysisList(){
$res = array();
$list = Database::prepare(
'SELECT majgd_id, majgd_descr, majgd_sublevel, majgd_map, majgd_toplevel, majgd_useflagsgen, majgd_detailsgen' .
' FROM `##maj_geodispersion`' .
' WHERE majgd_file = :gedcom_id AND majgd_status = :status'.
' ORDER BY majgd_descr'
)->execute(array(
'gedcom_id' => $this->tree->getTreeId(),
'status' => 'enabled'
))->fetchAll(\PDO::FETCH_ASSOC);
foreach($list as $ga) {
$res[] = $this->loadGeoAnalysisFromRow($ga);
}
return $res;
} | php | public function getGeoAnalysisList(){
$res = array();
$list = Database::prepare(
'SELECT majgd_id, majgd_descr, majgd_sublevel, majgd_map, majgd_toplevel, majgd_useflagsgen, majgd_detailsgen' .
' FROM `##maj_geodispersion`' .
' WHERE majgd_file = :gedcom_id AND majgd_status = :status'.
' ORDER BY majgd_descr'
)->execute(array(
'gedcom_id' => $this->tree->getTreeId(),
'status' => 'enabled'
))->fetchAll(\PDO::FETCH_ASSOC);
foreach($list as $ga) {
$res[] = $this->loadGeoAnalysisFromRow($ga);
}
return $res;
} | [
"public",
"function",
"getGeoAnalysisList",
"(",
")",
"{",
"$",
"res",
"=",
"array",
"(",
")",
";",
"$",
"list",
"=",
"Database",
"::",
"prepare",
"(",
"'SELECT majgd_id, majgd_descr, majgd_sublevel, majgd_map, majgd_toplevel, majgd_useflagsgen, majgd_detailsgen'",
".",
"... | Return the list of geodispersion analysis recorded and enabled for a specific GEDCOM
@return array List of enabled maps | [
"Return",
"the",
"list",
"of",
"geodispersion",
"analysis",
"recorded",
"and",
"enabled",
"for",
"a",
"specific",
"GEDCOM"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/GeoDispersion/Model/GeoAnalysisProvider.php#L261-L279 | train |
jon48/webtrees-lib | src/Webtrees/Module/GeoDispersion/Model/GeoAnalysisProvider.php | GeoAnalysisProvider.getFilteredGeoAnalysisList | public function getFilteredGeoAnalysisList($search = null, $order_by = null, $start = 0, $limit = null){
$res = array();
$sql =
'SELECT majgd_id, majgd_descr, majgd_sublevel, majgd_map, majgd_toplevel, majgd_useflagsgen, majgd_detailsgen, majgd_status' .
' FROM `##maj_geodispersion`' .
' WHERE majgd_file = :gedcom_id';
$args = array('gedcom_id'=> $this->tree->getTreeId());
if($search) {
$sql .= ' AND majgd_descr LIKE CONCAT(\'%\', :search, \'%\')';
$args['search'] = $search;
}
if ($order_by) {
$sql .= ' ORDER BY ';
foreach ($order_by as $key => $value) {
if ($key > 0) {
$sql .= ',';
}
switch ($value['dir']) {
case 'asc':
$sql .= $value['column'] . ' ASC ';
break;
case 'desc':
$sql .= $value['column'] . ' DESC ';
break;
}
}
} else {
$sql .= ' ORDER BY majgd_descr ASC';
}
if ($limit) {
$sql .= " LIMIT :limit OFFSET :offset";
$args['limit'] = $limit;
$args['offset'] = $start;
}
$data = Database::prepare($sql)->execute($args)->fetchAll(\PDO::FETCH_ASSOC);
foreach($data as $ga) {
$res[] = $this->loadGeoAnalysisFromRow($ga);
}
return $res;
} | php | public function getFilteredGeoAnalysisList($search = null, $order_by = null, $start = 0, $limit = null){
$res = array();
$sql =
'SELECT majgd_id, majgd_descr, majgd_sublevel, majgd_map, majgd_toplevel, majgd_useflagsgen, majgd_detailsgen, majgd_status' .
' FROM `##maj_geodispersion`' .
' WHERE majgd_file = :gedcom_id';
$args = array('gedcom_id'=> $this->tree->getTreeId());
if($search) {
$sql .= ' AND majgd_descr LIKE CONCAT(\'%\', :search, \'%\')';
$args['search'] = $search;
}
if ($order_by) {
$sql .= ' ORDER BY ';
foreach ($order_by as $key => $value) {
if ($key > 0) {
$sql .= ',';
}
switch ($value['dir']) {
case 'asc':
$sql .= $value['column'] . ' ASC ';
break;
case 'desc':
$sql .= $value['column'] . ' DESC ';
break;
}
}
} else {
$sql .= ' ORDER BY majgd_descr ASC';
}
if ($limit) {
$sql .= " LIMIT :limit OFFSET :offset";
$args['limit'] = $limit;
$args['offset'] = $start;
}
$data = Database::prepare($sql)->execute($args)->fetchAll(\PDO::FETCH_ASSOC);
foreach($data as $ga) {
$res[] = $this->loadGeoAnalysisFromRow($ga);
}
return $res;
} | [
"public",
"function",
"getFilteredGeoAnalysisList",
"(",
"$",
"search",
"=",
"null",
",",
"$",
"order_by",
"=",
"null",
",",
"$",
"start",
"=",
"0",
",",
"$",
"limit",
"=",
"null",
")",
"{",
"$",
"res",
"=",
"array",
"(",
")",
";",
"$",
"sql",
"=",... | Return the list of geodispersion analysis matching specified criterias.
@param string $search Search criteria in analysis description
@param array $order_by Columns to order by
@param int $start Offset to start with (for pagination)
@param int|null $limit Max number of items to return (for pagination)
@return \MyArtJaub\Webtrees\Module\GeoDispersion\Model\GeoAnalysis[] | [
"Return",
"the",
"list",
"of",
"geodispersion",
"analysis",
"matching",
"specified",
"criterias",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/GeoDispersion/Model/GeoAnalysisProvider.php#L290-L338 | train |
jon48/webtrees-lib | src/Webtrees/Module/GeoDispersion/Model/GeoAnalysisProvider.php | GeoAnalysisProvider.getPlacesHierarchyFromHeader | protected function getPlacesHierarchyFromHeader() {
$head = GedcomRecord::getInstance('HEAD', $this->tree);
$head_place = $head->getFirstFact('PLAC');
if($head_place && $head_place_value = $head_place->getAttribute('FORM')){
return array_reverse(array_map('trim',explode(',', $head_place_value)));
}
return null;
} | php | protected function getPlacesHierarchyFromHeader() {
$head = GedcomRecord::getInstance('HEAD', $this->tree);
$head_place = $head->getFirstFact('PLAC');
if($head_place && $head_place_value = $head_place->getAttribute('FORM')){
return array_reverse(array_map('trim',explode(',', $head_place_value)));
}
return null;
} | [
"protected",
"function",
"getPlacesHierarchyFromHeader",
"(",
")",
"{",
"$",
"head",
"=",
"GedcomRecord",
"::",
"getInstance",
"(",
"'HEAD'",
",",
"$",
"this",
"->",
"tree",
")",
";",
"$",
"head_place",
"=",
"$",
"head",
"->",
"getFirstFact",
"(",
"'PLAC'",
... | Returns an array of the place hierarchy, as defined in the GEDCOM header.
The places are reversed compared to normal GEDCOM structure.
@return array|null | [
"Returns",
"an",
"array",
"of",
"the",
"place",
"hierarchy",
"as",
"defined",
"in",
"the",
"GEDCOM",
"header",
".",
"The",
"places",
"are",
"reversed",
"compared",
"to",
"normal",
"GEDCOM",
"structure",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/GeoDispersion/Model/GeoAnalysisProvider.php#L367-L374 | train |
jon48/webtrees-lib | src/Webtrees/Module/GeoDispersion/Model/GeoAnalysisProvider.php | GeoAnalysisProvider.getPlacesHierarchyFromData | protected function getPlacesHierarchyFromData() {
$nb_levels = 0;
//Select all '2 PLAC ' tags in the file and create array
$places_list=array();
$ged_data = Database::prepare(
'SELECT i_gedcom AS gedcom'.
' FROM `##individuals`'.
' WHERE i_gedcom LIKE :gedcom AND i_file = :gedcom_id'.
' UNION ALL'.
'SELECT f_gedcom AS gedcom'.
' FROM `##families`'.
' WHERE f_gedcom LIKE :gedcom AND f_file = :gedcom_id'
)->execute(array(
'gedcom' => '%\n2 PLAC %',
'gedcom_id' => $this->tree->getTreeId()
))->fetchOneColumn();
foreach ($ged_data as $ged_datum) {
$matches = null;
preg_match_all('/\n2 PLAC (.+)/', $ged_datum, $matches);
foreach ($matches[1] as $match) {
$places_list[$match]=true;
}
}
// Unique list of places
$places_list=array_keys($places_list);
//sort the array, limit to unique values, and count them
usort($places_list, array('I18N', 'strcasecmp'));
//calculate maximum no. of levels to display
$has_found_good_example = false;
foreach($places_list as $place){
$levels = explode(",", $place);
$parts = count($levels);
if ($parts >= $nb_levels){
$nb_levels = $parts;
if(!$has_found_good_example){
$random_place = $place;
if(min(array_map('strlen', $levels)) > 0){
$has_found_good_example = true;
}
}
}
}
return array_reverse(array_map('trim',explode(',', $random_place)));
} | php | protected function getPlacesHierarchyFromData() {
$nb_levels = 0;
//Select all '2 PLAC ' tags in the file and create array
$places_list=array();
$ged_data = Database::prepare(
'SELECT i_gedcom AS gedcom'.
' FROM `##individuals`'.
' WHERE i_gedcom LIKE :gedcom AND i_file = :gedcom_id'.
' UNION ALL'.
'SELECT f_gedcom AS gedcom'.
' FROM `##families`'.
' WHERE f_gedcom LIKE :gedcom AND f_file = :gedcom_id'
)->execute(array(
'gedcom' => '%\n2 PLAC %',
'gedcom_id' => $this->tree->getTreeId()
))->fetchOneColumn();
foreach ($ged_data as $ged_datum) {
$matches = null;
preg_match_all('/\n2 PLAC (.+)/', $ged_datum, $matches);
foreach ($matches[1] as $match) {
$places_list[$match]=true;
}
}
// Unique list of places
$places_list=array_keys($places_list);
//sort the array, limit to unique values, and count them
usort($places_list, array('I18N', 'strcasecmp'));
//calculate maximum no. of levels to display
$has_found_good_example = false;
foreach($places_list as $place){
$levels = explode(",", $place);
$parts = count($levels);
if ($parts >= $nb_levels){
$nb_levels = $parts;
if(!$has_found_good_example){
$random_place = $place;
if(min(array_map('strlen', $levels)) > 0){
$has_found_good_example = true;
}
}
}
}
return array_reverse(array_map('trim',explode(',', $random_place)));
} | [
"protected",
"function",
"getPlacesHierarchyFromData",
"(",
")",
"{",
"$",
"nb_levels",
"=",
"0",
";",
"//Select all '2 PLAC ' tags in the file and create array",
"$",
"places_list",
"=",
"array",
"(",
")",
";",
"$",
"ged_data",
"=",
"Database",
"::",
"prepare",
"("... | Returns an array of the place hierarchy, based on a random example of place within the GEDCOM.
It will look for the longest hierarchy in the tree.
The places are reversed compared to normal GEDCOM structure.
@return array | [
"Returns",
"an",
"array",
"of",
"the",
"place",
"hierarchy",
"based",
"on",
"a",
"random",
"example",
"of",
"place",
"within",
"the",
"GEDCOM",
".",
"It",
"will",
"look",
"for",
"the",
"longest",
"hierarchy",
"in",
"the",
"tree",
".",
"The",
"places",
"a... | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/GeoDispersion/Model/GeoAnalysisProvider.php#L383-L431 | train |
jon48/webtrees-lib | src/Webtrees/Module/GeoDispersion/Model/GeoAnalysisProvider.php | GeoAnalysisProvider.getOutlineMapsList | public function getOutlineMapsList() {
$res = array();
$root_path = WT_ROOT.WT_MODULES_DIR.Constants::MODULE_MAJ_GEODISP_NAME.'/maps/';
if(is_dir($root_path)){
$dir = opendir($root_path);
while (($file=readdir($dir))!== false) {
if (preg_match('/^[a-zA-Z0-9_]+.xml$/', $file)) {
$res[base64_encode($file)] = new OutlineMap($file, true);
}
}
}
return $res;
} | php | public function getOutlineMapsList() {
$res = array();
$root_path = WT_ROOT.WT_MODULES_DIR.Constants::MODULE_MAJ_GEODISP_NAME.'/maps/';
if(is_dir($root_path)){
$dir = opendir($root_path);
while (($file=readdir($dir))!== false) {
if (preg_match('/^[a-zA-Z0-9_]+.xml$/', $file)) {
$res[base64_encode($file)] = new OutlineMap($file, true);
}
}
}
return $res;
} | [
"public",
"function",
"getOutlineMapsList",
"(",
")",
"{",
"$",
"res",
"=",
"array",
"(",
")",
";",
"$",
"root_path",
"=",
"WT_ROOT",
".",
"WT_MODULES_DIR",
".",
"Constants",
"::",
"MODULE_MAJ_GEODISP_NAME",
".",
"'/maps/'",
";",
"if",
"(",
"is_dir",
"(",
... | Returns the list of geodispersion maps available within the maps folder.
@return \MyArtJaub\Webtrees\Module\GeoDispersion\Model\OutlineMap[] | [
"Returns",
"the",
"list",
"of",
"geodispersion",
"maps",
"available",
"within",
"the",
"maps",
"folder",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/GeoDispersion/Model/GeoAnalysisProvider.php#L438-L450 | train |
jon48/webtrees-lib | src/Webtrees/Module/Sosa/SosaStatsController.php | SosaStatsController.htmlAncestorDispersionG2 | private function htmlAncestorDispersionG2()
{
$ancestorsDispGen2 = $this->sosa_provider->getAncestorDispersionForGen(2);
if(count($ancestorsDispGen2) == 0) return;
$size = '600x300';
$total = array_sum($ancestorsDispGen2);
$father_count = array_key_exists(1, $ancestorsDispGen2) ? $ancestorsDispGen2[1] : 0;
$father = array (
'color' => '84beff',
'count' => $father_count,
'perc' => Functions::safeDivision($father_count, $total),
'name' => \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('fat')
);
$mother_count = array_key_exists(2, $ancestorsDispGen2) ? $ancestorsDispGen2[2] : 0;
$mother = array (
'color' => 'ffd1dc',
'count' => $mother_count,
'perc' => Functions::safeDivision($mother_count, $total),
'name' => \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('mot')
);
$shared_count = array_key_exists(-1, $ancestorsDispGen2) ? $ancestorsDispGen2[-1] : 0;
$shared = array (
'color' => '777777',
'count' => $shared_count,
'perc' => Functions::safeDivision($shared_count, $total),
'name' => I18N::translate('Shared')
);
$chd = $this->arrayToExtendedEncoding(array(4095 * $father['perc'], 4095 * $shared['perc'], 4095 * $mother['perc']));
$chart_title = I18N::translate('Known Sosa ancestors\' dispersion');
$chl =
$father['name'] . ' - ' . I18N::percentage($father['perc'], 1) . '|' .
$shared['name'] . ' - ' . I18N::percentage($shared['perc'], 1) . '|' .
$mother['name'] . ' - ' . I18N::percentage($mother['perc'], 1);
return "<img src=\"https://chart.googleapis.com/chart?cht=p&chp=1.5708&chd=e:{$chd}&chs={$size}&chco={$father['color']},{$shared['color']},{$mother['color']}&chf=bg,s,ffffff00&chl={$chl}\" alt=\"" . $chart_title . "\" title=\"" . $chart_title . "\" />";
} | php | private function htmlAncestorDispersionG2()
{
$ancestorsDispGen2 = $this->sosa_provider->getAncestorDispersionForGen(2);
if(count($ancestorsDispGen2) == 0) return;
$size = '600x300';
$total = array_sum($ancestorsDispGen2);
$father_count = array_key_exists(1, $ancestorsDispGen2) ? $ancestorsDispGen2[1] : 0;
$father = array (
'color' => '84beff',
'count' => $father_count,
'perc' => Functions::safeDivision($father_count, $total),
'name' => \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('fat')
);
$mother_count = array_key_exists(2, $ancestorsDispGen2) ? $ancestorsDispGen2[2] : 0;
$mother = array (
'color' => 'ffd1dc',
'count' => $mother_count,
'perc' => Functions::safeDivision($mother_count, $total),
'name' => \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('mot')
);
$shared_count = array_key_exists(-1, $ancestorsDispGen2) ? $ancestorsDispGen2[-1] : 0;
$shared = array (
'color' => '777777',
'count' => $shared_count,
'perc' => Functions::safeDivision($shared_count, $total),
'name' => I18N::translate('Shared')
);
$chd = $this->arrayToExtendedEncoding(array(4095 * $father['perc'], 4095 * $shared['perc'], 4095 * $mother['perc']));
$chart_title = I18N::translate('Known Sosa ancestors\' dispersion');
$chl =
$father['name'] . ' - ' . I18N::percentage($father['perc'], 1) . '|' .
$shared['name'] . ' - ' . I18N::percentage($shared['perc'], 1) . '|' .
$mother['name'] . ' - ' . I18N::percentage($mother['perc'], 1);
return "<img src=\"https://chart.googleapis.com/chart?cht=p&chp=1.5708&chd=e:{$chd}&chs={$size}&chco={$father['color']},{$shared['color']},{$mother['color']}&chf=bg,s,ffffff00&chl={$chl}\" alt=\"" . $chart_title . "\" title=\"" . $chart_title . "\" />";
} | [
"private",
"function",
"htmlAncestorDispersionG2",
"(",
")",
"{",
"$",
"ancestorsDispGen2",
"=",
"$",
"this",
"->",
"sosa_provider",
"->",
"getAncestorDispersionForGen",
"(",
"2",
")",
";",
"if",
"(",
"count",
"(",
"$",
"ancestorsDispGen2",
")",
"==",
"0",
")"... | Returns HTML code for a graph showing the dispersion of ancestors across father & mother
@return string HTML code | [
"Returns",
"HTML",
"code",
"for",
"a",
"graph",
"showing",
"the",
"dispersion",
"of",
"ancestors",
"across",
"father",
"&",
"mother"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/Sosa/SosaStatsController.php#L154-L191 | train |
jon48/webtrees-lib | src/Webtrees/Module/Sosa/SosaStatsController.php | SosaStatsController.htmlAncestorDispersionG3 | private function htmlAncestorDispersionG3()
{
$ancestorsDispGen2 = $this->sosa_provider->getAncestorDispersionForGen(3);
$size = '700x300';
$color_motmot = 'ffd1dc';
$color_motfat = 'b998a0';
$color_fatfat = '577292';
$color_fatmot = '84beff';
$color_shared = '777777';
$total_fatfat = array_key_exists(1, $ancestorsDispGen2) ? $ancestorsDispGen2[1] : 0;
$total_fatmot = array_key_exists(2, $ancestorsDispGen2) ? $ancestorsDispGen2[2] : 0;
$total_motfat = array_key_exists(4, $ancestorsDispGen2) ? $ancestorsDispGen2[4] : 0;
$total_motmot = array_key_exists(8, $ancestorsDispGen2) ? $ancestorsDispGen2[8] : 0;
$total_sha = array_key_exists(-1, $ancestorsDispGen2) ? $ancestorsDispGen2[-1] : 0;
$total = $total_fatfat + $total_fatmot + $total_motfat+ $total_motmot + $total_sha;
$chd = $this->arrayToExtendedEncoding(array(
4095 * Functions::safeDivision($total_fatfat, $total),
4095 * Functions::safeDivision($total_fatmot, $total),
4095 * Functions::safeDivision($total_sha, $total),
4095 * Functions::safeDivision($total_motfat, $total),
4095 * Functions::safeDivision($total_motmot, $total)
));
$chart_title = I18N::translate('Known Sosa ancestors\' dispersion - G3');
$chl =
\Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('fatfat') . ' - ' . I18N::percentage(Functions::safeDivision($total_fatfat, $total), 1) . '|' .
\Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('fatmot') . ' - ' . I18N::percentage(Functions::safeDivision($total_fatmot, $total), 1) . '|' .
I18N::translate('Shared') . ' - ' . I18N::percentage(Functions::safeDivision($total_sha, $total), 1) . '|' .
\Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('motfat') . ' - ' . I18N::percentage(Functions::safeDivision($total_motfat, $total), 1) . '|' .
\Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('motmot') . ' - ' . I18N::percentage(Functions::safeDivision($total_motmot, $total), 1);
return "<img src=\"https://chart.googleapis.com/chart?cht=p&chp=1.5708&chd=e:{$chd}&chs={$size}&chco={$color_fatfat},{$color_fatmot},{$color_shared},{$color_motfat},{$color_motmot}&chf=bg,s,ffffff00&chl={$chl}\" alt=\"" . $chart_title . "\" title=\"" . $chart_title . "\" />";
} | php | private function htmlAncestorDispersionG3()
{
$ancestorsDispGen2 = $this->sosa_provider->getAncestorDispersionForGen(3);
$size = '700x300';
$color_motmot = 'ffd1dc';
$color_motfat = 'b998a0';
$color_fatfat = '577292';
$color_fatmot = '84beff';
$color_shared = '777777';
$total_fatfat = array_key_exists(1, $ancestorsDispGen2) ? $ancestorsDispGen2[1] : 0;
$total_fatmot = array_key_exists(2, $ancestorsDispGen2) ? $ancestorsDispGen2[2] : 0;
$total_motfat = array_key_exists(4, $ancestorsDispGen2) ? $ancestorsDispGen2[4] : 0;
$total_motmot = array_key_exists(8, $ancestorsDispGen2) ? $ancestorsDispGen2[8] : 0;
$total_sha = array_key_exists(-1, $ancestorsDispGen2) ? $ancestorsDispGen2[-1] : 0;
$total = $total_fatfat + $total_fatmot + $total_motfat+ $total_motmot + $total_sha;
$chd = $this->arrayToExtendedEncoding(array(
4095 * Functions::safeDivision($total_fatfat, $total),
4095 * Functions::safeDivision($total_fatmot, $total),
4095 * Functions::safeDivision($total_sha, $total),
4095 * Functions::safeDivision($total_motfat, $total),
4095 * Functions::safeDivision($total_motmot, $total)
));
$chart_title = I18N::translate('Known Sosa ancestors\' dispersion - G3');
$chl =
\Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('fatfat') . ' - ' . I18N::percentage(Functions::safeDivision($total_fatfat, $total), 1) . '|' .
\Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('fatmot') . ' - ' . I18N::percentage(Functions::safeDivision($total_fatmot, $total), 1) . '|' .
I18N::translate('Shared') . ' - ' . I18N::percentage(Functions::safeDivision($total_sha, $total), 1) . '|' .
\Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('motfat') . ' - ' . I18N::percentage(Functions::safeDivision($total_motfat, $total), 1) . '|' .
\Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('motmot') . ' - ' . I18N::percentage(Functions::safeDivision($total_motmot, $total), 1);
return "<img src=\"https://chart.googleapis.com/chart?cht=p&chp=1.5708&chd=e:{$chd}&chs={$size}&chco={$color_fatfat},{$color_fatmot},{$color_shared},{$color_motfat},{$color_motmot}&chf=bg,s,ffffff00&chl={$chl}\" alt=\"" . $chart_title . "\" title=\"" . $chart_title . "\" />";
} | [
"private",
"function",
"htmlAncestorDispersionG3",
"(",
")",
"{",
"$",
"ancestorsDispGen2",
"=",
"$",
"this",
"->",
"sosa_provider",
"->",
"getAncestorDispersionForGen",
"(",
"3",
")",
";",
"$",
"size",
"=",
"'700x300'",
";",
"$",
"color_motmot",
"=",
"'ffd1dc'"... | Returns HTML code for a graph showing the dispersion of ancestors across grand-parents
@return string HTML code | [
"Returns",
"HTML",
"code",
"for",
"a",
"graph",
"showing",
"the",
"dispersion",
"of",
"ancestors",
"across",
"grand",
"-",
"parents"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/Sosa/SosaStatsController.php#L197-L231 | train |
jon48/webtrees-lib | src/Webtrees/Module/Sosa/SosaStatsController.php | SosaStatsController.arrayToExtendedEncoding | private function arrayToExtendedEncoding($a) {
$xencoding = WT_GOOGLE_CHART_ENCODING;
$encoding = '';
foreach ($a as $value) {
if ($value < 0) {
$value = 0;
}
$first = (int) ($value / 64);
$second = $value % 64;
$encoding .= $xencoding[(int) $first] . $xencoding[(int) $second];
}
return $encoding;
} | php | private function arrayToExtendedEncoding($a) {
$xencoding = WT_GOOGLE_CHART_ENCODING;
$encoding = '';
foreach ($a as $value) {
if ($value < 0) {
$value = 0;
}
$first = (int) ($value / 64);
$second = $value % 64;
$encoding .= $xencoding[(int) $first] . $xencoding[(int) $second];
}
return $encoding;
} | [
"private",
"function",
"arrayToExtendedEncoding",
"(",
"$",
"a",
")",
"{",
"$",
"xencoding",
"=",
"WT_GOOGLE_CHART_ENCODING",
";",
"$",
"encoding",
"=",
"''",
";",
"foreach",
"(",
"$",
"a",
"as",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"value",
"<",
"0... | Convert an array to Google Chart encoding
@param arrat $a Array to encode
@return string | [
"Convert",
"an",
"array",
"to",
"Google",
"Chart",
"encoding"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/Sosa/SosaStatsController.php#L238-L252 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.