repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
makinacorpus/drupal-ucms | ucms_site/src/Controller/DashboardController.php | DashboardController.webmasterListAction | public function webmasterListAction(Request $request, Site $site)
{
return $this->renderPage('ucms_site.list_members', $request, [
'base_query' => [
'site_id' => $site->getId(),
],
]);
} | php | public function webmasterListAction(Request $request, Site $site)
{
return $this->renderPage('ucms_site.list_members', $request, [
'base_query' => [
'site_id' => $site->getId(),
],
]);
} | [
"public",
"function",
"webmasterListAction",
"(",
"Request",
"$",
"request",
",",
"Site",
"$",
"site",
")",
"{",
"return",
"$",
"this",
"->",
"renderPage",
"(",
"'ucms_site.list_members'",
",",
"$",
"request",
",",
"[",
"'base_query'",
"=>",
"[",
"'site_id'",
... | List current user site | [
"List",
"current",
"user",
"site"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/Controller/DashboardController.php#L80-L87 |
makinacorpus/drupal-ucms | ucms_site/src/Controller/DashboardController.php | DashboardController.viewAction | public function viewAction(Site $site)
{
$requester = user_load($site->uid);
if (!$requester) {
$requester = drupal_anonymous_user();
}
$template = null;
if ($site->template_id) {
try {
$template = $this->getSiteManager()->getStorage()->findOne($site->template_id);
$template = l($template->title, 'admin/dashboard/site/' . $template->id);
} catch (\Exception $e) {
$template = '<span class="text-muted>' . t("Template does not exist anymore") . '</span>';
}
} else {
$template = '';
}
$states = SiteState::getList();
$uri = 'http://' . $site->http_host;
$table = $this->createAdminTable('ucms_site_details', ['site' => $site])
->addHeader(t("Identification"))
->addRow(t("HTTP hostname"), l($uri, $uri))
->addRow(t("State"), t($states[$site->state]))
->addRow(t("Title"), check_plain($site->title))
->addRow(t("Created at"), format_date($site->ts_created->getTimestamp()))
->addRow(t("Lastest update"), format_date($site->ts_changed->getTimestamp()))
->addRow(t("Requester"), check_plain(format_username($requester)))
->addHeader(t("Description"))
->addRow(t("Description"), check_markup($site->title_admin))
->addRow(t("Replaces"), check_markup($site->replacement_of))
->addRow(t("HTTP redirections"), check_markup($site->http_redirects))
->addHeader(t("Display information"))
->addRow(t("Theme"), check_plain($site->theme))
->addRow(t("Is a template"), $site->is_template ? '<strong>' . t("yes") . '</strong>' : t("No"))
;
if ($template) {
$table->addRow(t("Site template"), $template);
}
$this->addArbitraryAttributesToTable($table, $site->getAttributes());
return $table->render();
} | php | public function viewAction(Site $site)
{
$requester = user_load($site->uid);
if (!$requester) {
$requester = drupal_anonymous_user();
}
$template = null;
if ($site->template_id) {
try {
$template = $this->getSiteManager()->getStorage()->findOne($site->template_id);
$template = l($template->title, 'admin/dashboard/site/' . $template->id);
} catch (\Exception $e) {
$template = '<span class="text-muted>' . t("Template does not exist anymore") . '</span>';
}
} else {
$template = '';
}
$states = SiteState::getList();
$uri = 'http://' . $site->http_host;
$table = $this->createAdminTable('ucms_site_details', ['site' => $site])
->addHeader(t("Identification"))
->addRow(t("HTTP hostname"), l($uri, $uri))
->addRow(t("State"), t($states[$site->state]))
->addRow(t("Title"), check_plain($site->title))
->addRow(t("Created at"), format_date($site->ts_created->getTimestamp()))
->addRow(t("Lastest update"), format_date($site->ts_changed->getTimestamp()))
->addRow(t("Requester"), check_plain(format_username($requester)))
->addHeader(t("Description"))
->addRow(t("Description"), check_markup($site->title_admin))
->addRow(t("Replaces"), check_markup($site->replacement_of))
->addRow(t("HTTP redirections"), check_markup($site->http_redirects))
->addHeader(t("Display information"))
->addRow(t("Theme"), check_plain($site->theme))
->addRow(t("Is a template"), $site->is_template ? '<strong>' . t("yes") . '</strong>' : t("No"))
;
if ($template) {
$table->addRow(t("Site template"), $template);
}
$this->addArbitraryAttributesToTable($table, $site->getAttributes());
return $table->render();
} | [
"public",
"function",
"viewAction",
"(",
"Site",
"$",
"site",
")",
"{",
"$",
"requester",
"=",
"user_load",
"(",
"$",
"site",
"->",
"uid",
")",
";",
"if",
"(",
"!",
"$",
"requester",
")",
"{",
"$",
"requester",
"=",
"drupal_anonymous_user",
"(",
")",
... | View site details action | [
"View",
"site",
"details",
"action"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/Controller/DashboardController.php#L92-L139 |
shopgate/cart-integration-sdk | src/models/catalog/Attribute.php | Shopgate_Model_Catalog_Attribute.asXml | public function asXml(Shopgate_Model_XmlResultObject $itemNode)
{
/**
* @var Shopgate_Model_XmlResultObject $attributeNode
*/
$attributeNode = $itemNode->addChildWithCDATA('attribute', $this->getLabel());
$attributeNode->addAttribute('uid', $this->getUid());
$attributeNode->addAttribute('group_uid', $this->getGroupUid());
return $itemNode;
} | php | public function asXml(Shopgate_Model_XmlResultObject $itemNode)
{
/**
* @var Shopgate_Model_XmlResultObject $attributeNode
*/
$attributeNode = $itemNode->addChildWithCDATA('attribute', $this->getLabel());
$attributeNode->addAttribute('uid', $this->getUid());
$attributeNode->addAttribute('group_uid', $this->getGroupUid());
return $itemNode;
} | [
"public",
"function",
"asXml",
"(",
"Shopgate_Model_XmlResultObject",
"$",
"itemNode",
")",
"{",
"/**\n * @var Shopgate_Model_XmlResultObject $attributeNode\n */",
"$",
"attributeNode",
"=",
"$",
"itemNode",
"->",
"addChildWithCDATA",
"(",
"'attribute'",
",",
... | @param Shopgate_Model_XmlResultObject $itemNode
@return Shopgate_Model_XmlResultObject | [
"@param",
"Shopgate_Model_XmlResultObject",
"$itemNode"
] | train | https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/models/catalog/Attribute.php#L55-L65 |
shopgate/cart-integration-sdk | src/helper/redirect/TagsGenerator.php | Shopgate_Helper_Redirect_TagsGenerator.createHtmlTag | protected function createHtmlTag(array $tag)
{
$tagModel = new Shopgate_Model_Redirect_HtmlTag();
$tagModel->setName($tag['name']);
if (empty($tag['attributes'])) {
return $tagModel;
}
$attributes = array();
foreach ($tag['attributes'] as $attribute) {
if (empty($attribute['name'])) {
continue;
}
$attributes[] = $this->createHtmlTagAttribute($attribute);
}
$tagModel->setAttributes($attributes);
return $tagModel;
} | php | protected function createHtmlTag(array $tag)
{
$tagModel = new Shopgate_Model_Redirect_HtmlTag();
$tagModel->setName($tag['name']);
if (empty($tag['attributes'])) {
return $tagModel;
}
$attributes = array();
foreach ($tag['attributes'] as $attribute) {
if (empty($attribute['name'])) {
continue;
}
$attributes[] = $this->createHtmlTagAttribute($attribute);
}
$tagModel->setAttributes($attributes);
return $tagModel;
} | [
"protected",
"function",
"createHtmlTag",
"(",
"array",
"$",
"tag",
")",
"{",
"$",
"tagModel",
"=",
"new",
"Shopgate_Model_Redirect_HtmlTag",
"(",
")",
";",
"$",
"tagModel",
"->",
"setName",
"(",
"$",
"tag",
"[",
"'name'",
"]",
")",
";",
"if",
"(",
"empt... | @param array $tag
@return Shopgate_Model_Redirect_HtmlTag | [
"@param",
"array",
"$tag"
] | train | https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/helper/redirect/TagsGenerator.php#L91-L112 |
shopgate/cart-integration-sdk | src/helper/redirect/TagsGenerator.php | Shopgate_Helper_Redirect_TagsGenerator.createHtmlTagAttribute | protected function createHtmlTagAttribute(array $attribute)
{
$attributeModel = new Shopgate_Model_Redirect_HtmlTagAttribute();
$attributeModel->setName($attribute['name']);
$attributeModel->setValue($attribute['value']);
$attributeModel->setVariables($this->templateParser->getVariables($attribute['value']));
if (!empty($attribute['deeplink_suffix'])) {
$attributeModel->setDeeplinkSuffix($this->createDeeplinkSuffixes($attribute['deeplink_suffix']));
}
return $attributeModel;
} | php | protected function createHtmlTagAttribute(array $attribute)
{
$attributeModel = new Shopgate_Model_Redirect_HtmlTagAttribute();
$attributeModel->setName($attribute['name']);
$attributeModel->setValue($attribute['value']);
$attributeModel->setVariables($this->templateParser->getVariables($attribute['value']));
if (!empty($attribute['deeplink_suffix'])) {
$attributeModel->setDeeplinkSuffix($this->createDeeplinkSuffixes($attribute['deeplink_suffix']));
}
return $attributeModel;
} | [
"protected",
"function",
"createHtmlTagAttribute",
"(",
"array",
"$",
"attribute",
")",
"{",
"$",
"attributeModel",
"=",
"new",
"Shopgate_Model_Redirect_HtmlTagAttribute",
"(",
")",
";",
"$",
"attributeModel",
"->",
"setName",
"(",
"$",
"attribute",
"[",
"'name'",
... | @param array $attribute
@return Shopgate_Model_Redirect_HtmlTagAttribute | [
"@param",
"array",
"$attribute"
] | train | https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/helper/redirect/TagsGenerator.php#L119-L131 |
shopgate/cart-integration-sdk | src/helper/redirect/TagsGenerator.php | Shopgate_Helper_Redirect_TagsGenerator.createDeeplinkSuffixes | protected function createDeeplinkSuffixes(array $deeplinkSuffix)
{
$suffixModel = new Shopgate_Model_Redirect_DeeplinkSuffix();
foreach ($deeplinkSuffix as $name => $template) {
$valueModel = new Shopgate_Model_Redirect_DeeplinkSuffixValue();
$valueModel->setName($name);
$valueModel->setValue($template);
if ($template === false) {
$valueModel->setDisabled(true);
} else {
$valueModel->setVariables($this->templateParser->getVariables($template));
}
$suffixModel->addValue($name, $valueModel);
}
return $suffixModel;
} | php | protected function createDeeplinkSuffixes(array $deeplinkSuffix)
{
$suffixModel = new Shopgate_Model_Redirect_DeeplinkSuffix();
foreach ($deeplinkSuffix as $name => $template) {
$valueModel = new Shopgate_Model_Redirect_DeeplinkSuffixValue();
$valueModel->setName($name);
$valueModel->setValue($template);
if ($template === false) {
$valueModel->setDisabled(true);
} else {
$valueModel->setVariables($this->templateParser->getVariables($template));
}
$suffixModel->addValue($name, $valueModel);
}
return $suffixModel;
} | [
"protected",
"function",
"createDeeplinkSuffixes",
"(",
"array",
"$",
"deeplinkSuffix",
")",
"{",
"$",
"suffixModel",
"=",
"new",
"Shopgate_Model_Redirect_DeeplinkSuffix",
"(",
")",
";",
"foreach",
"(",
"$",
"deeplinkSuffix",
"as",
"$",
"name",
"=>",
"$",
"templat... | @param array $deeplinkSuffix
@return Shopgate_Model_Redirect_DeeplinkSuffix | [
"@param",
"array",
"$deeplinkSuffix"
] | train | https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/helper/redirect/TagsGenerator.php#L138-L157 |
shopgate/cart-integration-sdk | src/helper/redirect/TagsGenerator.php | Shopgate_Helper_Redirect_TagsGenerator.getAttributes | protected function getAttributes($pageType, $attributes, array $parameters = array())
{
$attributesString = '';
foreach ($attributes as $attribute) {
if ($attribute->getDeeplinkSuffix()) {
$parameters['deeplink_suffix'] = $this->getDeeplinkSuffix(
$pageType,
$attribute->getDeeplinkSuffix(),
$parameters
);
}
$attributesString .= ' ' . $attribute->getName() . '="' .
$this->getVariables(
$attribute->getVariables(),
$attribute->getValue(),
$parameters
) . '"';
}
return $attributesString;
} | php | protected function getAttributes($pageType, $attributes, array $parameters = array())
{
$attributesString = '';
foreach ($attributes as $attribute) {
if ($attribute->getDeeplinkSuffix()) {
$parameters['deeplink_suffix'] = $this->getDeeplinkSuffix(
$pageType,
$attribute->getDeeplinkSuffix(),
$parameters
);
}
$attributesString .= ' ' . $attribute->getName() . '="' .
$this->getVariables(
$attribute->getVariables(),
$attribute->getValue(),
$parameters
) . '"';
}
return $attributesString;
} | [
"protected",
"function",
"getAttributes",
"(",
"$",
"pageType",
",",
"$",
"attributes",
",",
"array",
"$",
"parameters",
"=",
"array",
"(",
")",
")",
"{",
"$",
"attributesString",
"=",
"''",
";",
"foreach",
"(",
"$",
"attributes",
"as",
"$",
"attribute",
... | @param string $pageType
@param Shopgate_Model_Redirect_HtmlTagAttribute[] $attributes
@param array $parameters [string, string]
@return string
@throws ShopgateLibraryException in case a variable is in the template but not set in the parameters. | [
"@param",
"string",
"$pageType",
"@param",
"Shopgate_Model_Redirect_HtmlTagAttribute",
"[]",
"$attributes",
"@param",
"array",
"$parameters",
"[",
"string",
"string",
"]"
] | train | https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/helper/redirect/TagsGenerator.php#L167-L188 |
shopgate/cart-integration-sdk | src/helper/redirect/TagsGenerator.php | Shopgate_Helper_Redirect_TagsGenerator.getVariables | protected function getVariables($variables, $template, array $parameters = array())
{
foreach ($variables as $variable) {
if (!isset($parameters[$variable->getName()])) {
// don't log, this is caught internally
throw new ShopgateLibraryException(ShopgateLibraryException::CONFIG_INVALID_VALUE, '', false, false);
}
$parameter = !isset($parameters[$variable->getName()])
? ''
: $parameters[$variable->getName()];
$template = $this->templateParser->process(
$template,
$variable,
$parameter
);
}
return $template;
} | php | protected function getVariables($variables, $template, array $parameters = array())
{
foreach ($variables as $variable) {
if (!isset($parameters[$variable->getName()])) {
// don't log, this is caught internally
throw new ShopgateLibraryException(ShopgateLibraryException::CONFIG_INVALID_VALUE, '', false, false);
}
$parameter = !isset($parameters[$variable->getName()])
? ''
: $parameters[$variable->getName()];
$template = $this->templateParser->process(
$template,
$variable,
$parameter
);
}
return $template;
} | [
"protected",
"function",
"getVariables",
"(",
"$",
"variables",
",",
"$",
"template",
",",
"array",
"$",
"parameters",
"=",
"array",
"(",
")",
")",
"{",
"foreach",
"(",
"$",
"variables",
"as",
"$",
"variable",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
... | @param Shopgate_Model_Redirect_HtmlTagVariable[] $variables
@param string $template
@param array $parameters [string, string]
@return string
@throws ShopgateLibraryException in case a variable is in the template but not set in the parameters. | [
"@param",
"Shopgate_Model_Redirect_HtmlTagVariable",
"[]",
"$variables",
"@param",
"string",
"$template",
"@param",
"array",
"$parameters",
"[",
"string",
"string",
"]"
] | train | https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/helper/redirect/TagsGenerator.php#L198-L218 |
shopgate/cart-integration-sdk | src/helper/redirect/TagsGenerator.php | Shopgate_Helper_Redirect_TagsGenerator.getDeeplinkSuffix | protected function getDeeplinkSuffix(
$pageType,
Shopgate_Model_Redirect_DeeplinkSuffix $deeplinkSuffix,
array $parameters = array()
) {
$value = $deeplinkSuffix->getValue($pageType);
if ($value->getUnset()) {
$value = $deeplinkSuffix->getValue(Shopgate_Helper_Redirect_TagsGeneratorInterface::PAGE_TYPE_DEFAULT);
}
if ($value->getDisabled()) {
throw new ShopgateLibraryException(ShopgateLibraryException::CONFIG_INVALID_VALUE, '', false, false);
}
return $this->linkBuilder->getUrlFor($pageType, $value->getVariables(), $parameters, $value->getValue());
} | php | protected function getDeeplinkSuffix(
$pageType,
Shopgate_Model_Redirect_DeeplinkSuffix $deeplinkSuffix,
array $parameters = array()
) {
$value = $deeplinkSuffix->getValue($pageType);
if ($value->getUnset()) {
$value = $deeplinkSuffix->getValue(Shopgate_Helper_Redirect_TagsGeneratorInterface::PAGE_TYPE_DEFAULT);
}
if ($value->getDisabled()) {
throw new ShopgateLibraryException(ShopgateLibraryException::CONFIG_INVALID_VALUE, '', false, false);
}
return $this->linkBuilder->getUrlFor($pageType, $value->getVariables(), $parameters, $value->getValue());
} | [
"protected",
"function",
"getDeeplinkSuffix",
"(",
"$",
"pageType",
",",
"Shopgate_Model_Redirect_DeeplinkSuffix",
"$",
"deeplinkSuffix",
",",
"array",
"$",
"parameters",
"=",
"array",
"(",
")",
")",
"{",
"$",
"value",
"=",
"$",
"deeplinkSuffix",
"->",
"getValue",... | @param string $pageType
@param Shopgate_Model_Redirect_DeeplinkSuffix $deeplinkSuffix
@param array $parameters [string, string]
@return string
@throws ShopgateLibraryException | [
"@param",
"string",
"$pageType",
"@param",
"Shopgate_Model_Redirect_DeeplinkSuffix",
"$deeplinkSuffix",
"@param",
"array",
"$parameters",
"[",
"string",
"string",
"]"
] | train | https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/helper/redirect/TagsGenerator.php#L228-L244 |
hmlb/ddd | src/Persistence/PersistentMessageCapabilities.php | PersistentMessageCapabilities.getId | public function getId(): Identity
{
if (null === $this->id) {
throw new PersistentMessageWithoutIdentityException(get_class($this).'::$id has not been initialized');
}
return $this->id;
} | php | public function getId(): Identity
{
if (null === $this->id) {
throw new PersistentMessageWithoutIdentityException(get_class($this).'::$id has not been initialized');
}
return $this->id;
} | [
"public",
"function",
"getId",
"(",
")",
":",
"Identity",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"id",
")",
"{",
"throw",
"new",
"PersistentMessageWithoutIdentityException",
"(",
"get_class",
"(",
"$",
"this",
")",
".",
"'::$id has not been initiali... | Returns the message's identity.
@return Identity
@throws PersistentMessageWithoutIdentityException | [
"Returns",
"the",
"message",
"s",
"identity",
"."
] | train | https://github.com/hmlb/ddd/blob/f0796b909d189aac81df4ae42c0d5c80b6c86b0b/src/Persistence/PersistentMessageCapabilities.php#L26-L33 |
ramsey/vnderror | src/VndError.php | VndError.getData | public function getData()
{
$data = parent::getData();
if (!isset($data['message'])) {
$data['message'] = $this->message;
}
if ($this->logref !== null && !isset($data['@logref'])) {
$data['@logref'] = $this->logref;
}
return $data;
} | php | public function getData()
{
$data = parent::getData();
if (!isset($data['message'])) {
$data['message'] = $this->message;
}
if ($this->logref !== null && !isset($data['@logref'])) {
$data['@logref'] = $this->logref;
}
return $data;
} | [
"public",
"function",
"getData",
"(",
")",
"{",
"$",
"data",
"=",
"parent",
"::",
"getData",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"data",
"[",
"'message'",
"]",
")",
")",
"{",
"$",
"data",
"[",
"'message'",
"]",
"=",
"$",
"this",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/ramsey/vnderror/blob/b6924eee8a9f6f1c1e943e1419520aab7fc922ee/src/VndError.php#L53-L66 |
BugBuster1701/botdetection | src/classes/CheckBotAgentExtended.php | CheckBotAgentExtended.checkAgent | public static function checkAgent($UserAgent=false, $ouputBotName = false)
{
// Check if user agent present
if ($UserAgent === false)
{
return false; // No user agent, no search.
}
$UserAgent = trim( $UserAgent );
if (false === (bool) $UserAgent)
{
return false; // No user agent, no search.
}
//Search in browsecap
$objBrowscap = static::getBrowscapInfo($UserAgent);
// DEBUG fwrite(STDOUT, 'BrowscapInfo: '.print_r($objBrowscap,true) . "\n");
if ($objBrowscap->crawler == 'true')
{
if (false === $ouputBotName)
{
return true;
}
else
{
// DEBUG fwrite(STDOUT, "\n" . 'Agent: '.print_r($UserAgent,true) . "\n");
// DEBUG fwrite(STDOUT, 'Bot: '.print_r($objBrowscap->browser_type,true) . "\n");
return $objBrowscap->browser;
}
}
// Search in bot-agent-list
if (file_exists(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'config/bot-agent-list.php'))
{
include(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'config/bot-agent-list.php');
}
else
{
return false; // no definition, no search
}
// search for user bot filter definitions in localconfig.php
if ( isset($GLOBALS['BOTDETECTION']['BOT_AGENT']) )
{
foreach ($GLOBALS['BOTDETECTION']['BOT_AGENT'] as $search)
{
$botagents[$search[0]] = $search[1];
}
}
$num = count($botagents);
$arrBots = array_keys($botagents);
for ($c=0; $c < $num; $c++)
{
$CheckUserAgent = str_ireplace($arrBots[$c], '#', $UserAgent);
if ($UserAgent != $CheckUserAgent)
{ // found
// Debug fwrite(STDOUT, 'Bot: '.print_r($botagents[$arrBots[$c]],true) . "\n");
if (false === $ouputBotName)
{
return true;
}
else
{
return $botagents[$arrBots[$c]];
}
}
}
return false;
} | php | public static function checkAgent($UserAgent=false, $ouputBotName = false)
{
// Check if user agent present
if ($UserAgent === false)
{
return false; // No user agent, no search.
}
$UserAgent = trim( $UserAgent );
if (false === (bool) $UserAgent)
{
return false; // No user agent, no search.
}
//Search in browsecap
$objBrowscap = static::getBrowscapInfo($UserAgent);
// DEBUG fwrite(STDOUT, 'BrowscapInfo: '.print_r($objBrowscap,true) . "\n");
if ($objBrowscap->crawler == 'true')
{
if (false === $ouputBotName)
{
return true;
}
else
{
// DEBUG fwrite(STDOUT, "\n" . 'Agent: '.print_r($UserAgent,true) . "\n");
// DEBUG fwrite(STDOUT, 'Bot: '.print_r($objBrowscap->browser_type,true) . "\n");
return $objBrowscap->browser;
}
}
// Search in bot-agent-list
if (file_exists(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'config/bot-agent-list.php'))
{
include(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'config/bot-agent-list.php');
}
else
{
return false; // no definition, no search
}
// search for user bot filter definitions in localconfig.php
if ( isset($GLOBALS['BOTDETECTION']['BOT_AGENT']) )
{
foreach ($GLOBALS['BOTDETECTION']['BOT_AGENT'] as $search)
{
$botagents[$search[0]] = $search[1];
}
}
$num = count($botagents);
$arrBots = array_keys($botagents);
for ($c=0; $c < $num; $c++)
{
$CheckUserAgent = str_ireplace($arrBots[$c], '#', $UserAgent);
if ($UserAgent != $CheckUserAgent)
{ // found
// Debug fwrite(STDOUT, 'Bot: '.print_r($botagents[$arrBots[$c]],true) . "\n");
if (false === $ouputBotName)
{
return true;
}
else
{
return $botagents[$arrBots[$c]];
}
}
}
return false;
} | [
"public",
"static",
"function",
"checkAgent",
"(",
"$",
"UserAgent",
"=",
"false",
",",
"$",
"ouputBotName",
"=",
"false",
")",
"{",
"// Check if user agent present",
"if",
"(",
"$",
"UserAgent",
"===",
"false",
")",
"{",
"return",
"false",
";",
"// No user ag... | checkAgent
@param string $UserAgent
@param string $ouputBotName
@return boolean|string | [
"checkAgent"
] | train | https://github.com/BugBuster1701/botdetection/blob/b27cc1d80932af7d29b9f345da9132842d2adbce/src/classes/CheckBotAgentExtended.php#L34-L102 |
BugBuster1701/botdetection | src/classes/CheckBotAgentExtended.php | CheckBotAgentExtended.getBrowscapInfo | protected static function getBrowscapInfo($UserAgent=false)
{
// Check if user agent present
if ($UserAgent === false)
{
return false; // No user agent, no search.
}
// set an own cache directory (otherwise the system temp directory is used)
\Crossjoin\Browscap\Cache\File::setCacheDirectory(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'cache');
//Large sonst fehlt Browser_Type / Crawler um Bots zu erkennen
\Crossjoin\Browscap\Browscap::setDatasetType(\Crossjoin\Browscap\Browscap::DATASET_TYPE_LARGE);
// disable automatic updates
$updater = new \Crossjoin\Browscap\Updater\None();
\Crossjoin\Browscap\Browscap::setUpdater($updater);
$browscap = new \Crossjoin\Browscap\Browscap(false); //autoUpdate = false
$settings = $browscap->getBrowser($UserAgent)->getData();
return $settings;
/*
stdClass Object
(
[browser_name_regex] => /^Yandex\/1\.01\.001 \(compatible; Win16; .*\)$/
[browser_name_pattern] => Yandex/1.01.001 (compatible; Win16; *)
[parent] => Yandex
[comment] => Yandex
[browser] => Yandex
[browser_type] => Bot/Crawler
[browser_maker] => Yandex
[crawler] => true
.....
stdClass Object
(
[browser_name_regex] => /^Googlebot\-Image.*$/
[browser_name_pattern] => Googlebot-Image*
[parent] => Googlebot
[browser] => Googlebot-Image
[comment] => Googlebot
[browser_type] => Bot/Crawler
[browser_maker] => Google Inc
[crawler] => true
.....
*/
} | php | protected static function getBrowscapInfo($UserAgent=false)
{
// Check if user agent present
if ($UserAgent === false)
{
return false; // No user agent, no search.
}
// set an own cache directory (otherwise the system temp directory is used)
\Crossjoin\Browscap\Cache\File::setCacheDirectory(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'cache');
//Large sonst fehlt Browser_Type / Crawler um Bots zu erkennen
\Crossjoin\Browscap\Browscap::setDatasetType(\Crossjoin\Browscap\Browscap::DATASET_TYPE_LARGE);
// disable automatic updates
$updater = new \Crossjoin\Browscap\Updater\None();
\Crossjoin\Browscap\Browscap::setUpdater($updater);
$browscap = new \Crossjoin\Browscap\Browscap(false); //autoUpdate = false
$settings = $browscap->getBrowser($UserAgent)->getData();
return $settings;
/*
stdClass Object
(
[browser_name_regex] => /^Yandex\/1\.01\.001 \(compatible; Win16; .*\)$/
[browser_name_pattern] => Yandex/1.01.001 (compatible; Win16; *)
[parent] => Yandex
[comment] => Yandex
[browser] => Yandex
[browser_type] => Bot/Crawler
[browser_maker] => Yandex
[crawler] => true
.....
stdClass Object
(
[browser_name_regex] => /^Googlebot\-Image.*$/
[browser_name_pattern] => Googlebot-Image*
[parent] => Googlebot
[browser] => Googlebot-Image
[comment] => Googlebot
[browser_type] => Bot/Crawler
[browser_maker] => Google Inc
[crawler] => true
.....
*/
} | [
"protected",
"static",
"function",
"getBrowscapInfo",
"(",
"$",
"UserAgent",
"=",
"false",
")",
"{",
"// Check if user agent present",
"if",
"(",
"$",
"UserAgent",
"===",
"false",
")",
"{",
"return",
"false",
";",
"// No user agent, no search.",
"}",
"// set an own ... | Get Browscap info for the user agent string
@param string $UserAgent
@return stdClass Object | [
"Get",
"Browscap",
"info",
"for",
"the",
"user",
"agent",
"string"
] | train | https://github.com/BugBuster1701/botdetection/blob/b27cc1d80932af7d29b9f345da9132842d2adbce/src/classes/CheckBotAgentExtended.php#L125-L171 |
accompli/accompli | src/Deployment/Workspace.php | Workspace.getOtherDirectories | public function getOtherDirectories()
{
$directories = array();
foreach ($this->otherDirectories as $directory) {
$directories[] = sprintf('%s/%s', $this->getHost()->getPath(), $directory);
}
return $directories;
} | php | public function getOtherDirectories()
{
$directories = array();
foreach ($this->otherDirectories as $directory) {
$directories[] = sprintf('%s/%s', $this->getHost()->getPath(), $directory);
}
return $directories;
} | [
"public",
"function",
"getOtherDirectories",
"(",
")",
"{",
"$",
"directories",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"otherDirectories",
"as",
"$",
"directory",
")",
"{",
"$",
"directories",
"[",
"]",
"=",
"sprintf",
"(",
"'%s/... | Returns the array with absolute paths to other directories.
@return array | [
"Returns",
"the",
"array",
"with",
"absolute",
"paths",
"to",
"other",
"directories",
"."
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Deployment/Workspace.php#L109-L117 |
runcmf/runbb | src/RunBB/Controller/Admin/Users.php | Users.ipstats | public function ipstats($req, $res, $args)
{
Container::get('hooks')->fire('controller.admin.users.ipstats');
// Fetch ip count
$num_ips = $this->model->getNumIp($args['id']);
// Determine the ip offset (based on $_GET['p'])
$num_pages = ceil($num_ips / 50);
$p = (!Input::query('p') || Input::query('p') <= 1 || Input::query('p') > $num_pages) ?
1 : intval(Input::query('p'));
$start_from = 50 * ($p - 1);
return View::setPageInfo([
'title' => [Utils::escape(ForumSettings::get('o_board_title')), __('Admin'),
__('Users'), __('Results head')],
'active_page' => 'admin',
'admin_console' => true,
'page' => $p,
'paging_links' => '<span class="pages-label">' . __('Pages') . ' </span>' .
Url::paginateOld($num_pages, $p, '?ip_stats=' . $args['id']),
'start_from' => $start_from,
'ip_data' => $this->model->getIpStats($args['id'], $start_from),
])->display('@forum/admin/users/search_ip');
} | php | public function ipstats($req, $res, $args)
{
Container::get('hooks')->fire('controller.admin.users.ipstats');
// Fetch ip count
$num_ips = $this->model->getNumIp($args['id']);
// Determine the ip offset (based on $_GET['p'])
$num_pages = ceil($num_ips / 50);
$p = (!Input::query('p') || Input::query('p') <= 1 || Input::query('p') > $num_pages) ?
1 : intval(Input::query('p'));
$start_from = 50 * ($p - 1);
return View::setPageInfo([
'title' => [Utils::escape(ForumSettings::get('o_board_title')), __('Admin'),
__('Users'), __('Results head')],
'active_page' => 'admin',
'admin_console' => true,
'page' => $p,
'paging_links' => '<span class="pages-label">' . __('Pages') . ' </span>' .
Url::paginateOld($num_pages, $p, '?ip_stats=' . $args['id']),
'start_from' => $start_from,
'ip_data' => $this->model->getIpStats($args['id'], $start_from),
])->display('@forum/admin/users/search_ip');
} | [
"public",
"function",
"ipstats",
"(",
"$",
"req",
",",
"$",
"res",
",",
"$",
"args",
")",
"{",
"Container",
"::",
"get",
"(",
"'hooks'",
")",
"->",
"fire",
"(",
"'controller.admin.users.ipstats'",
")",
";",
"// Fetch ip count",
"$",
"num_ips",
"=",
"$",
... | Show IP statistics for a certain user ID | [
"Show",
"IP",
"statistics",
"for",
"a",
"certain",
"user",
"ID"
] | train | https://github.com/runcmf/runbb/blob/d4f4098bcece48b78ea2d1ae5eeead7ac9a8b463/src/RunBB/Controller/Admin/Users.php#L146-L171 |
runcmf/runbb | src/RunBB/Controller/Admin/Users.php | Users.showusers | public function showusers($req, $res, $args)
{
Container::get('hooks')->fire('controller.admin.users.showusers');
$search_ip = $args['ip'];
if (!@preg_match('%^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$%', $search_ip) &&
!@preg_match('%^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:'.
'[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|'.
'(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:'.
'([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:)'.
'{0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|'.
'(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(([0-9A-Fa-f]{1,4}:)'.
'{0,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|'.
'(2[0-4]\d)|(\d{1,2}))\b))|(::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|'.
'(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|([0-9A-Fa-f]{1,4}::'.
'([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|'.
'(([0-9A-Fa-f]{1,4}:){1,7}:))$%', $search_ip)) {
throw new RunBBException(__('Bad IP message'), 400);
}
// Fetch user count
$num_users = $this->model->getNumUsersIp($search_ip);
// Determine the user offset (based on $_GET['p'])
$num_pages = ceil($num_users / 50);
$p = (!Input::query('p') || Input::query('p') <= 1 || Input::query('p') > $num_pages) ?
1 : intval(Input::query('p'));
$start_from = 50 * ($p - 1);
return View::setPageInfo([
'title' => [Utils::escape(ForumSettings::get('o_board_title')), __('Admin'),
__('Users'), __('Results head')],
'active_page' => 'admin',
'admin_console' => true,
'paging_links' => '<span class="pages-label">' . __('Pages') . ' </span>' .
Url::paginateOld($num_pages, $p, '?ip_stats=' . $search_ip),
'page' => $p,
'start_from' => $start_from,
'info' => $this->model->getInfoPoster($search_ip, $start_from),
])->display('@forum/admin/users/show_users');
} | php | public function showusers($req, $res, $args)
{
Container::get('hooks')->fire('controller.admin.users.showusers');
$search_ip = $args['ip'];
if (!@preg_match('%^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$%', $search_ip) &&
!@preg_match('%^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:'.
'[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|'.
'(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:'.
'([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:)'.
'{0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|'.
'(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(([0-9A-Fa-f]{1,4}:)'.
'{0,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|'.
'(2[0-4]\d)|(\d{1,2}))\b))|(::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|'.
'(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|([0-9A-Fa-f]{1,4}::'.
'([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|'.
'(([0-9A-Fa-f]{1,4}:){1,7}:))$%', $search_ip)) {
throw new RunBBException(__('Bad IP message'), 400);
}
// Fetch user count
$num_users = $this->model->getNumUsersIp($search_ip);
// Determine the user offset (based on $_GET['p'])
$num_pages = ceil($num_users / 50);
$p = (!Input::query('p') || Input::query('p') <= 1 || Input::query('p') > $num_pages) ?
1 : intval(Input::query('p'));
$start_from = 50 * ($p - 1);
return View::setPageInfo([
'title' => [Utils::escape(ForumSettings::get('o_board_title')), __('Admin'),
__('Users'), __('Results head')],
'active_page' => 'admin',
'admin_console' => true,
'paging_links' => '<span class="pages-label">' . __('Pages') . ' </span>' .
Url::paginateOld($num_pages, $p, '?ip_stats=' . $search_ip),
'page' => $p,
'start_from' => $start_from,
'info' => $this->model->getInfoPoster($search_ip, $start_from),
])->display('@forum/admin/users/show_users');
} | [
"public",
"function",
"showusers",
"(",
"$",
"req",
",",
"$",
"res",
",",
"$",
"args",
")",
"{",
"Container",
"::",
"get",
"(",
"'hooks'",
")",
"->",
"fire",
"(",
"'controller.admin.users.showusers'",
")",
";",
"$",
"search_ip",
"=",
"$",
"args",
"[",
... | Show IP statistics for a certain user IP | [
"Show",
"IP",
"statistics",
"for",
"a",
"certain",
"user",
"IP"
] | train | https://github.com/runcmf/runbb/blob/d4f4098bcece48b78ea2d1ae5eeead7ac9a8b463/src/RunBB/Controller/Admin/Users.php#L174-L216 |
runcmf/runbb | src/RunBB/Core/Remote.php | Remote.getLangRepoList | public function getLangRepoList()
{
$data = json_decode(
$this->getRemoteContents($this->translationsInfoUrl)
);
$content = $data->encoding === 'base64' ? base64_decode($data->content) : [];
return json_decode($content);
} | php | public function getLangRepoList()
{
$data = json_decode(
$this->getRemoteContents($this->translationsInfoUrl)
);
$content = $data->encoding === 'base64' ? base64_decode($data->content) : [];
return json_decode($content);
} | [
"public",
"function",
"getLangRepoList",
"(",
")",
"{",
"$",
"data",
"=",
"json_decode",
"(",
"$",
"this",
"->",
"getRemoteContents",
"(",
"$",
"this",
"->",
"translationsInfoUrl",
")",
")",
";",
"$",
"content",
"=",
"$",
"data",
"->",
"encoding",
"===",
... | Get language list from repo
@return array | [
"Get",
"language",
"list",
"from",
"repo"
] | train | https://github.com/runcmf/runbb/blob/d4f4098bcece48b78ea2d1ae5eeead7ac9a8b463/src/RunBB/Core/Remote.php#L48-L56 |
runcmf/runbb | src/RunBB/Core/Remote.php | Remote.getExtensionsInfoList | public function getExtensionsInfoList()
{
$data = json_decode(
$this->getRemoteContents($this->extensionsInfofoUrl)
);
$content = $data->encoding === 'base64' ? base64_decode($data->content) : [];
return json_decode($content, true);// true to array
} | php | public function getExtensionsInfoList()
{
$data = json_decode(
$this->getRemoteContents($this->extensionsInfofoUrl)
);
$content = $data->encoding === 'base64' ? base64_decode($data->content) : [];
return json_decode($content, true);// true to array
} | [
"public",
"function",
"getExtensionsInfoList",
"(",
")",
"{",
"$",
"data",
"=",
"json_decode",
"(",
"$",
"this",
"->",
"getRemoteContents",
"(",
"$",
"this",
"->",
"extensionsInfofoUrl",
")",
")",
";",
"$",
"content",
"=",
"$",
"data",
"->",
"encoding",
"=... | Get Extensions list from repo
@return array | [
"Get",
"Extensions",
"list",
"from",
"repo"
] | train | https://github.com/runcmf/runbb/blob/d4f4098bcece48b78ea2d1ae5eeead7ac9a8b463/src/RunBB/Core/Remote.php#L76-L84 |
runcmf/runbb | src/RunBB/Core/Remote.php | Remote.getRemoteContents | public function getRemoteContents(&$url, $timeout = 30, $redirect_max = 5, $ua = 'Mozilla/5.0', $fp = null)
{
$method = (function_exists('curl_exec') &&
!ini_get('safe_mode') &&
!ini_get('open_basedir')) ?
'curlGetContents' : 'fsockGetContents';
return $this->$method( $url, $timeout, $redirect_max, $ua, $fp );
} | php | public function getRemoteContents(&$url, $timeout = 30, $redirect_max = 5, $ua = 'Mozilla/5.0', $fp = null)
{
$method = (function_exists('curl_exec') &&
!ini_get('safe_mode') &&
!ini_get('open_basedir')) ?
'curlGetContents' : 'fsockGetContents';
return $this->$method( $url, $timeout, $redirect_max, $ua, $fp );
} | [
"public",
"function",
"getRemoteContents",
"(",
"&",
"$",
"url",
",",
"$",
"timeout",
"=",
"30",
",",
"$",
"redirect_max",
"=",
"5",
",",
"$",
"ua",
"=",
"'Mozilla/5.0'",
",",
"$",
"fp",
"=",
"null",
")",
"{",
"$",
"method",
"=",
"(",
"function_exist... | Get remote contents
from elFinder Core class. v 2.1
@param string $url target url
@param int $timeout timeout (sec)
@param int $redirect_max redirect max count
@param string $ua
@param resource $fp
@return string or bool(false)
@retval string contents
@rettval false error
@author Naoki Sawada | [
"Get",
"remote",
"contents"
] | train | https://github.com/runcmf/runbb/blob/d4f4098bcece48b78ea2d1ae5eeead7ac9a8b463/src/RunBB/Core/Remote.php#L101-L108 |
runcmf/runbb | src/RunBB/Core/Remote.php | Remote.curlGetContents | protected function curlGetContents(&$url, $timeout, $redirect_max, $ua, $outfp)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
if ($outfp) {
curl_setopt($ch, CURLOPT_FILE, $outfp);
} else {
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
}
curl_setopt($ch, CURLOPT_LOW_SPEED_LIMIT, 1);
curl_setopt($ch, CURLOPT_LOW_SPEED_TIME, $timeout);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_MAXREDIRS, $redirect_max);
curl_setopt($ch, CURLOPT_USERAGENT, $ua);
$result = curl_exec($ch);
$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
curl_close($ch);
return $outfp? $outfp : $result;
} | php | protected function curlGetContents(&$url, $timeout, $redirect_max, $ua, $outfp)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
if ($outfp) {
curl_setopt($ch, CURLOPT_FILE, $outfp);
} else {
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
}
curl_setopt($ch, CURLOPT_LOW_SPEED_LIMIT, 1);
curl_setopt($ch, CURLOPT_LOW_SPEED_TIME, $timeout);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_MAXREDIRS, $redirect_max);
curl_setopt($ch, CURLOPT_USERAGENT, $ua);
$result = curl_exec($ch);
$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
curl_close($ch);
return $outfp? $outfp : $result;
} | [
"protected",
"function",
"curlGetContents",
"(",
"&",
"$",
"url",
",",
"$",
"timeout",
",",
"$",
"redirect_max",
",",
"$",
"ua",
",",
"$",
"outfp",
")",
"{",
"$",
"ch",
"=",
"curl_init",
"(",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_URL... | Get remote contents with cURL
from elFinder Core class. v 2.1
@param string $url target url
@param int $timeout timeout (sec)
@param int $redirect_max redirect max count
@param string $ua
@param resource $outfp
@return string or bool(false)
@retval string contents
@retval false error
@author Naoki Sawada | [
"Get",
"remote",
"contents",
"with",
"cURL"
] | train | https://github.com/runcmf/runbb/blob/d4f4098bcece48b78ea2d1ae5eeead7ac9a8b463/src/RunBB/Core/Remote.php#L125-L146 |
runcmf/runbb | src/RunBB/Core/Remote.php | Remote.fsockGetContents | protected function fsockGetContents(&$url, $timeout, $redirect_max, $ua, $outfp)
{
$connect_timeout = 3;
$connect_try = 3;
$method = 'GET';
$readsize = 4096;
$ssl = '';
$getSize = null;
$headers = '';
$arr = parse_url($url);
if (!$arr) {
// Bad request
return false;
}
if ($arr['scheme'] === 'https') {
$ssl = 'ssl://';
}
// query
$arr['query'] = isset($arr['query']) ? '?'.$arr['query'] : '';
// port
$arr['port'] = isset($arr['port']) ? $arr['port'] : ($ssl? 443 : 80);
$url_base = $arr['scheme'].'://'.$arr['host'].':'.$arr['port'];
$url_path = isset($arr['path']) ? $arr['path'] : '/';
$uri = $url_path.$arr['query'];
$query = $method.' '.$uri." HTTP/1.0\r\n";
$query .= "Host: ".$arr['host']."\r\n";
$query .= "Accept: */*\r\n";
$query .= "Connection: close\r\n";
if (!empty($ua)) {
$query .= "User-Agent: ".$ua."\r\n";
}
if (!is_null($getSize)) {
$query .= 'Range: bytes=0-' . ($getSize - 1) . "\r\n";
}
$query .= $headers;
$query .= "\r\n";
$fp = $connect_try_count = 0;
while (!$fp && $connect_try_count < $connect_try) {
$errno = 0;
$errstr = "";
$fp = fsockopen(
$ssl.$arr['host'],
$arr['port'],
$errno,
$errstr,
$connect_timeout
);
if ($fp) {
break;
}
$connect_try_count++;
if (connection_aborted()) {
exit();
}
sleep(1); // wait 1sec
}
$fwrite = 0;
for ($written = 0; $written < strlen($query); $written += $fwrite) {
$fwrite = fwrite($fp, substr($query, $written));
if (!$fwrite) {
break;
}
}
$response = '';
if ($timeout) {
socket_set_timeout($fp, $timeout);
}
$_response = '';
$header = '';
while ($_response !== "\r\n") {
$_response = fgets($fp, $readsize);
$header .= $_response;
};
$rccd = array_pad(explode(' ', $header, 2), 2, ''); // array('HTTP/1.1','200')
$rc = (int)$rccd[1];
$ret = false;
// Redirect
switch ($rc) {
case 307: // Temporary Redirect
case 303: // See Other
case 302: // Moved Temporarily
case 301: // Moved Permanently
$matches = [];
if (preg_match('/^Location: (.+?)(#.+)?$/im', $header, $matches) && --$redirect_max > 0) {
$_url = $url;
$url = trim($matches[1]);
$hash = isset($matches[2])? trim($matches[2]) : '';
if (!preg_match('/^https?:\//', $url)) { // no scheme
if ($url{0} != '/') { // Relative path
// to Absolute path
$url = substr($url_path, 0, strrpos($url_path, '/')).'/'.$url;
}
// add sheme,host
$url = $url_base.$url;
}
if ($_url !== $url) {
fclose($fp);
return $this->fsockGetContents($url, $timeout, $redirect_max, $ua, $outfp);
}
}
break;
case 200:
$ret = true;
}
if (! $ret) {
fclose($fp);
return false;
}
$body = '';
if (!$outfp) {
$outfp = fopen('php://temp', 'rwb');
$body = true;
}
while (fwrite($outfp, fread($fp, $readsize))) {
if ($timeout) {
$_status = socket_get_status($fp);
if ($_status['timed_out']) {
fclose($outfp);
fclose($fp);
return false; // Request Time-out
}
}
}
if ($body) {
rewind($outfp);
$body = stream_get_contents($outfp);
fclose($outfp);
$outfp = null;
}
fclose($fp);
return $outfp? $outfp : $body; // Data
} | php | protected function fsockGetContents(&$url, $timeout, $redirect_max, $ua, $outfp)
{
$connect_timeout = 3;
$connect_try = 3;
$method = 'GET';
$readsize = 4096;
$ssl = '';
$getSize = null;
$headers = '';
$arr = parse_url($url);
if (!$arr) {
// Bad request
return false;
}
if ($arr['scheme'] === 'https') {
$ssl = 'ssl://';
}
// query
$arr['query'] = isset($arr['query']) ? '?'.$arr['query'] : '';
// port
$arr['port'] = isset($arr['port']) ? $arr['port'] : ($ssl? 443 : 80);
$url_base = $arr['scheme'].'://'.$arr['host'].':'.$arr['port'];
$url_path = isset($arr['path']) ? $arr['path'] : '/';
$uri = $url_path.$arr['query'];
$query = $method.' '.$uri." HTTP/1.0\r\n";
$query .= "Host: ".$arr['host']."\r\n";
$query .= "Accept: */*\r\n";
$query .= "Connection: close\r\n";
if (!empty($ua)) {
$query .= "User-Agent: ".$ua."\r\n";
}
if (!is_null($getSize)) {
$query .= 'Range: bytes=0-' . ($getSize - 1) . "\r\n";
}
$query .= $headers;
$query .= "\r\n";
$fp = $connect_try_count = 0;
while (!$fp && $connect_try_count < $connect_try) {
$errno = 0;
$errstr = "";
$fp = fsockopen(
$ssl.$arr['host'],
$arr['port'],
$errno,
$errstr,
$connect_timeout
);
if ($fp) {
break;
}
$connect_try_count++;
if (connection_aborted()) {
exit();
}
sleep(1); // wait 1sec
}
$fwrite = 0;
for ($written = 0; $written < strlen($query); $written += $fwrite) {
$fwrite = fwrite($fp, substr($query, $written));
if (!$fwrite) {
break;
}
}
$response = '';
if ($timeout) {
socket_set_timeout($fp, $timeout);
}
$_response = '';
$header = '';
while ($_response !== "\r\n") {
$_response = fgets($fp, $readsize);
$header .= $_response;
};
$rccd = array_pad(explode(' ', $header, 2), 2, ''); // array('HTTP/1.1','200')
$rc = (int)$rccd[1];
$ret = false;
// Redirect
switch ($rc) {
case 307: // Temporary Redirect
case 303: // See Other
case 302: // Moved Temporarily
case 301: // Moved Permanently
$matches = [];
if (preg_match('/^Location: (.+?)(#.+)?$/im', $header, $matches) && --$redirect_max > 0) {
$_url = $url;
$url = trim($matches[1]);
$hash = isset($matches[2])? trim($matches[2]) : '';
if (!preg_match('/^https?:\//', $url)) { // no scheme
if ($url{0} != '/') { // Relative path
// to Absolute path
$url = substr($url_path, 0, strrpos($url_path, '/')).'/'.$url;
}
// add sheme,host
$url = $url_base.$url;
}
if ($_url !== $url) {
fclose($fp);
return $this->fsockGetContents($url, $timeout, $redirect_max, $ua, $outfp);
}
}
break;
case 200:
$ret = true;
}
if (! $ret) {
fclose($fp);
return false;
}
$body = '';
if (!$outfp) {
$outfp = fopen('php://temp', 'rwb');
$body = true;
}
while (fwrite($outfp, fread($fp, $readsize))) {
if ($timeout) {
$_status = socket_get_status($fp);
if ($_status['timed_out']) {
fclose($outfp);
fclose($fp);
return false; // Request Time-out
}
}
}
if ($body) {
rewind($outfp);
$body = stream_get_contents($outfp);
fclose($outfp);
$outfp = null;
}
fclose($fp);
return $outfp? $outfp : $body; // Data
} | [
"protected",
"function",
"fsockGetContents",
"(",
"&",
"$",
"url",
",",
"$",
"timeout",
",",
"$",
"redirect_max",
",",
"$",
"ua",
",",
"$",
"outfp",
")",
"{",
"$",
"connect_timeout",
"=",
"3",
";",
"$",
"connect_try",
"=",
"3",
";",
"$",
"method",
"=... | Get remote contents with fsockopen()
from elFinder Core class. v 2.1
@param string $url url
@param int $timeout timeout (sec)
@param int $redirect_max redirect max count
@param string $ua
@param resource $outfp
@return string or bool(false)
@retval string contents
@retval false error
@author Naoki Sawada | [
"Get",
"remote",
"contents",
"with",
"fsockopen",
"()"
] | train | https://github.com/runcmf/runbb/blob/d4f4098bcece48b78ea2d1ae5eeead7ac9a8b463/src/RunBB/Core/Remote.php#L163-L311 |
makinacorpus/drupal-ucms | ucms_extranet/src/Form/MemberAcceptanceForm.php | MemberAcceptanceForm.submitForm | public function submitForm(array &$form, FormStateInterface $formState)
{
/** @var $site Site */
$site = $formState->getTemporaryValue('site');
/** @var $account UserInterface */
$account = $formState->getTemporaryValue('account');
// Enables the new member
$account->status = 1;
$this->entityManager->getStorage('user')->save($account);
// Sends him the e-mail for the creation of his password
$params = ['site' => $site];
$this->tokenManager->sendTokenMail($account, 'ucms_extranet', 'new-member-accepted', $params);
drupal_set_message($this->t("Registration of !name has been accepted.", ['!name' => $account->getDisplayName()]));
$event = new ExtranetMemberEvent($account, $site);
$this->dispatcher->dispatch(ExtranetMemberEvent::EVENT_ACCEPT, $event);
} | php | public function submitForm(array &$form, FormStateInterface $formState)
{
/** @var $site Site */
$site = $formState->getTemporaryValue('site');
/** @var $account UserInterface */
$account = $formState->getTemporaryValue('account');
// Enables the new member
$account->status = 1;
$this->entityManager->getStorage('user')->save($account);
// Sends him the e-mail for the creation of his password
$params = ['site' => $site];
$this->tokenManager->sendTokenMail($account, 'ucms_extranet', 'new-member-accepted', $params);
drupal_set_message($this->t("Registration of !name has been accepted.", ['!name' => $account->getDisplayName()]));
$event = new ExtranetMemberEvent($account, $site);
$this->dispatcher->dispatch(ExtranetMemberEvent::EVENT_ACCEPT, $event);
} | [
"public",
"function",
"submitForm",
"(",
"array",
"&",
"$",
"form",
",",
"FormStateInterface",
"$",
"formState",
")",
"{",
"/** @var $site Site */",
"$",
"site",
"=",
"$",
"formState",
"->",
"getTemporaryValue",
"(",
"'site'",
")",
";",
"/** @var $account UserInte... | {@inheritdoc} | [
"{"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_extranet/src/Form/MemberAcceptanceForm.php#L97-L115 |
accompli/accompli | src/Console/Helper/TitleBlock.php | TitleBlock.render | public function render()
{
$this->output->writeln('');
$lineLength = $this->getTerminalWidth();
$lines = explode(PHP_EOL, wordwrap($this->message, $lineLength - (strlen($this->blockStyles[$this->style]['prefix']) + 3), PHP_EOL, true));
array_unshift($lines, ' ');
array_push($lines, ' ');
foreach ($lines as $i => $line) {
$prefix = str_repeat(' ', strlen($this->blockStyles[$this->style]['prefix']));
if ($i === 1) {
$prefix = $this->blockStyles[$this->style]['prefix'];
}
$line = sprintf(' %s %s', $prefix, $line);
$this->output->writeln(sprintf('<%s>%s%s</>', $this->blockStyles[$this->style]['style'], $line, str_repeat(' ', $lineLength - Helper::strlenWithoutDecoration($this->output->getFormatter(), $line))));
}
$this->output->writeln('');
} | php | public function render()
{
$this->output->writeln('');
$lineLength = $this->getTerminalWidth();
$lines = explode(PHP_EOL, wordwrap($this->message, $lineLength - (strlen($this->blockStyles[$this->style]['prefix']) + 3), PHP_EOL, true));
array_unshift($lines, ' ');
array_push($lines, ' ');
foreach ($lines as $i => $line) {
$prefix = str_repeat(' ', strlen($this->blockStyles[$this->style]['prefix']));
if ($i === 1) {
$prefix = $this->blockStyles[$this->style]['prefix'];
}
$line = sprintf(' %s %s', $prefix, $line);
$this->output->writeln(sprintf('<%s>%s%s</>', $this->blockStyles[$this->style]['style'], $line, str_repeat(' ', $lineLength - Helper::strlenWithoutDecoration($this->output->getFormatter(), $line))));
}
$this->output->writeln('');
} | [
"public",
"function",
"render",
"(",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"''",
")",
";",
"$",
"lineLength",
"=",
"$",
"this",
"->",
"getTerminalWidth",
"(",
")",
";",
"$",
"lines",
"=",
"explode",
"(",
"PHP_EOL",
",",
"wordwr... | Renders the title block to output. | [
"Renders",
"the",
"title",
"block",
"to",
"output",
"."
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Console/Helper/TitleBlock.php#L75-L96 |
runcmf/runbb | src/RunBB/Core/Url.php | Url.paginateOld | public static function paginateOld($num_pages, $cur_page, $link)
{
$pages = [];
$link_to_all = false;
// If $cur_page == -1, we link to all pages (used in Forum.php)
if ($cur_page == -1) {
$cur_page = 1;
$link_to_all = true;
}
if ($num_pages <= 1) {
$pages = ['<strong class="item1">1</strong>'];
} else {
// Add a previous page link
if ($num_pages > 1 && $cur_page > 1) {
$pages[] = '<a rel="prev"'.(empty($pages) ? ' class="item1"' : '')
.' href="'.$link.($cur_page == 2 ? '' : '&p='.($cur_page - 1)).'">'.__('Previous').'</a>';
}
if ($cur_page > 3) {
$pages[] = '<a'.(empty($pages) ? ' class="item1"' : '').' href="'.$link.'">1</a>';
if ($cur_page > 5) {
$pages[] = '<span class="spacer">'.__('Spacer').'</span>';
}
}
// Don't ask me how the following works. It just does, OK? :-)
for ($current = ($cur_page == 5) ? $cur_page - 3 : $cur_page - 2,
$stop = ($cur_page + 4 == $num_pages) ? $cur_page + 4 : $cur_page + 3; $current < $stop; ++$current) {
if ($current < 1 || $current > $num_pages) {
continue;
} elseif ($current != $cur_page || $link_to_all) {
$pages[] = '<a'.(empty($pages) ? ' class="item1"' : '').' href="'.$link.
($current == 1 ? '' : '&p='.$current).'">'.Utils::numberFormat($current).'</a>';
} else {
$pages[] = '<strong'.(empty($pages) ? ' class="item1"' : '').'>'.
Utils::numberFormat($current).'</strong>';
}
}
if ($cur_page <= ($num_pages-3)) {
if ($cur_page != ($num_pages-3) && $cur_page != ($num_pages-4)) {
$pages[] = '<span class="spacer">'.__('Spacer').'</span>';
}
$pages[] = '<a'.(empty($pages) ? ' class="item1"' : '').' href="'.$link.'&p='.$num_pages.'">'.
Utils::numberFormat($num_pages).'</a>';
}
// Add a next page link
if ($num_pages > 1 && !$link_to_all && $cur_page < $num_pages) {
$pages[] = '<a rel="next"'.(empty($pages) ? ' class="item1"' : '').' href="'.$link.'&p='.
($cur_page +1).'">'.__('Next').'</a>';
}
}
return implode(' ', $pages);
} | php | public static function paginateOld($num_pages, $cur_page, $link)
{
$pages = [];
$link_to_all = false;
// If $cur_page == -1, we link to all pages (used in Forum.php)
if ($cur_page == -1) {
$cur_page = 1;
$link_to_all = true;
}
if ($num_pages <= 1) {
$pages = ['<strong class="item1">1</strong>'];
} else {
// Add a previous page link
if ($num_pages > 1 && $cur_page > 1) {
$pages[] = '<a rel="prev"'.(empty($pages) ? ' class="item1"' : '')
.' href="'.$link.($cur_page == 2 ? '' : '&p='.($cur_page - 1)).'">'.__('Previous').'</a>';
}
if ($cur_page > 3) {
$pages[] = '<a'.(empty($pages) ? ' class="item1"' : '').' href="'.$link.'">1</a>';
if ($cur_page > 5) {
$pages[] = '<span class="spacer">'.__('Spacer').'</span>';
}
}
// Don't ask me how the following works. It just does, OK? :-)
for ($current = ($cur_page == 5) ? $cur_page - 3 : $cur_page - 2,
$stop = ($cur_page + 4 == $num_pages) ? $cur_page + 4 : $cur_page + 3; $current < $stop; ++$current) {
if ($current < 1 || $current > $num_pages) {
continue;
} elseif ($current != $cur_page || $link_to_all) {
$pages[] = '<a'.(empty($pages) ? ' class="item1"' : '').' href="'.$link.
($current == 1 ? '' : '&p='.$current).'">'.Utils::numberFormat($current).'</a>';
} else {
$pages[] = '<strong'.(empty($pages) ? ' class="item1"' : '').'>'.
Utils::numberFormat($current).'</strong>';
}
}
if ($cur_page <= ($num_pages-3)) {
if ($cur_page != ($num_pages-3) && $cur_page != ($num_pages-4)) {
$pages[] = '<span class="spacer">'.__('Spacer').'</span>';
}
$pages[] = '<a'.(empty($pages) ? ' class="item1"' : '').' href="'.$link.'&p='.$num_pages.'">'.
Utils::numberFormat($num_pages).'</a>';
}
// Add a next page link
if ($num_pages > 1 && !$link_to_all && $cur_page < $num_pages) {
$pages[] = '<a rel="next"'.(empty($pages) ? ' class="item1"' : '').' href="'.$link.'&p='.
($cur_page +1).'">'.__('Next').'</a>';
}
}
return implode(' ', $pages);
} | [
"public",
"static",
"function",
"paginateOld",
"(",
"$",
"num_pages",
",",
"$",
"cur_page",
",",
"$",
"link",
")",
"{",
"$",
"pages",
"=",
"[",
"]",
";",
"$",
"link_to_all",
"=",
"false",
";",
"// If $cur_page == -1, we link to all pages (used in Forum.php)",
"i... | Generate a string with numbered links (for multipage scripts)
Old FluxBB-style function for search page
@param $num_pages
@param $cur_page
@param $link
@return string | [
"Generate",
"a",
"string",
"with",
"numbered",
"links",
"(",
"for",
"multipage",
"scripts",
")",
"Old",
"FluxBB",
"-",
"style",
"function",
"for",
"search",
"page"
] | train | https://github.com/runcmf/runbb/blob/d4f4098bcece48b78ea2d1ae5eeead7ac9a8b463/src/RunBB/Core/Url.php#L670-L729 |
runcmf/runbb | src/RunBB/Core/Url.php | Url.slug | public static function slug($str)
{
$str = strtr($str, self::$url_replace);
$str = strtolower(utf8_decode($str));
$str = Utils::trim(preg_replace(['/[^a-z0-9\s]/', '/[\s]+/'], ['', '-'], $str), '-');
if (empty($str)) {
$str = 'view';
}
return $str;
} | php | public static function slug($str)
{
$str = strtr($str, self::$url_replace);
$str = strtolower(utf8_decode($str));
$str = Utils::trim(preg_replace(['/[^a-z0-9\s]/', '/[\s]+/'], ['', '-'], $str), '-');
if (empty($str)) {
$str = 'view';
}
return $str;
} | [
"public",
"static",
"function",
"slug",
"(",
"$",
"str",
")",
"{",
"$",
"str",
"=",
"strtr",
"(",
"$",
"str",
",",
"self",
"::",
"$",
"url_replace",
")",
";",
"$",
"str",
"=",
"strtolower",
"(",
"utf8_decode",
"(",
"$",
"str",
")",
")",
";",
"$",... | Make a string safe to use in a URL
Inspired by (c) Panther <http://www.pantherforum.org/>
@param $str
@return string | [
"Make",
"a",
"string",
"safe",
"to",
"use",
"in",
"a",
"URL",
"Inspired",
"by",
"(",
"c",
")",
"Panther",
"<http",
":",
"//",
"www",
".",
"pantherforum",
".",
"org",
"/",
">"
] | train | https://github.com/runcmf/runbb/blob/d4f4098bcece48b78ea2d1ae5eeead7ac9a8b463/src/RunBB/Core/Url.php#L738-L749 |
runcmf/runbb | src/RunBB/Core/Url.php | Url.get | public static function get($link, $args = null)
{
$base_url = self::base();
$gen_link = $link;
if ($args == null) {
$gen_link = $base_url.$link;
} elseif (!is_array($args)) {
$gen_link = $base_url.'/'.str_replace('$1', $args, $link);
} else {
for ($i = 0; isset($args[$i]); ++$i) {
$gen_link = str_replace('$'.($i + 1), $args[$i], $gen_link);
}
$gen_link = $base_url.$gen_link;
}
return $gen_link;
} | php | public static function get($link, $args = null)
{
$base_url = self::base();
$gen_link = $link;
if ($args == null) {
$gen_link = $base_url.$link;
} elseif (!is_array($args)) {
$gen_link = $base_url.'/'.str_replace('$1', $args, $link);
} else {
for ($i = 0; isset($args[$i]); ++$i) {
$gen_link = str_replace('$'.($i + 1), $args[$i], $gen_link);
}
$gen_link = $base_url.$gen_link;
}
return $gen_link;
} | [
"public",
"static",
"function",
"get",
"(",
"$",
"link",
",",
"$",
"args",
"=",
"null",
")",
"{",
"$",
"base_url",
"=",
"self",
"::",
"base",
"(",
")",
";",
"$",
"gen_link",
"=",
"$",
"link",
";",
"if",
"(",
"$",
"args",
"==",
"null",
")",
"{",... | Generate link to another page on the forum
Inspired by (c) Panther <http://www.pantherforum.org/>
@param $link
@param null $args
@return mixed|string | [
"Generate",
"link",
"to",
"another",
"page",
"on",
"the",
"forum",
"Inspired",
"by",
"(",
"c",
")",
"Panther",
"<http",
":",
"//",
"www",
".",
"pantherforum",
".",
"org",
"/",
">"
] | train | https://github.com/runcmf/runbb/blob/d4f4098bcece48b78ea2d1ae5eeead7ac9a8b463/src/RunBB/Core/Url.php#L759-L776 |
runcmf/runbb | src/RunBB/Core/Url.php | Url.getSublink | private static function getSublink($link, $sublink, $subarg, $args = null)
{
$base_url = self::base();
if ($sublink == 'p$1' && $subarg == 1) {
return self::get($link, $args);
}
$gen_link = $link;
if (!is_array($args) && $args != null) {
$gen_link = str_replace('$1', $args, $link);
} else {
for ($i = 0; isset($args[$i]); ++$i) {
$gen_link = str_replace('$'.($i + 1), $args[$i], $gen_link);
}
}
// $gen_link = $base_url.'/'.str_replace(
$gen_link = $base_url.str_replace(
'#',
str_replace('$1', str_replace('$1', $subarg, $sublink), '$1/'),
$gen_link
);
return $gen_link;
} | php | private static function getSublink($link, $sublink, $subarg, $args = null)
{
$base_url = self::base();
if ($sublink == 'p$1' && $subarg == 1) {
return self::get($link, $args);
}
$gen_link = $link;
if (!is_array($args) && $args != null) {
$gen_link = str_replace('$1', $args, $link);
} else {
for ($i = 0; isset($args[$i]); ++$i) {
$gen_link = str_replace('$'.($i + 1), $args[$i], $gen_link);
}
}
// $gen_link = $base_url.'/'.str_replace(
$gen_link = $base_url.str_replace(
'#',
str_replace('$1', str_replace('$1', $subarg, $sublink), '$1/'),
$gen_link
);
return $gen_link;
} | [
"private",
"static",
"function",
"getSublink",
"(",
"$",
"link",
",",
"$",
"sublink",
",",
"$",
"subarg",
",",
"$",
"args",
"=",
"null",
")",
"{",
"$",
"base_url",
"=",
"self",
"::",
"base",
"(",
")",
";",
"if",
"(",
"$",
"sublink",
"==",
"'p$1'",
... | Generate a hyperlink with parameters and anchor and a subsection such as a subpage
Inspired by (c) Panther <http://www.pantherforum.org/>
@param $link
@param $sublink
@param $subarg
@param null $args
@return mixed|string | [
"Generate",
"a",
"hyperlink",
"with",
"parameters",
"and",
"anchor",
"and",
"a",
"subsection",
"such",
"as",
"a",
"subpage",
"Inspired",
"by",
"(",
"c",
")",
"Panther",
"<http",
":",
"//",
"www",
".",
"pantherforum",
".",
"org",
"/",
">"
] | train | https://github.com/runcmf/runbb/blob/d4f4098bcece48b78ea2d1ae5eeead7ac9a8b463/src/RunBB/Core/Url.php#L788-L813 |
runcmf/runbb | src/RunBB/Core/Url.php | Url.base | public static function base()
{
return Request::getUri()->getScheme().'://'.Request::getUri()->getHost().
Request::getUri()->getBasePath();
} | php | public static function base()
{
return Request::getUri()->getScheme().'://'.Request::getUri()->getHost().
Request::getUri()->getBasePath();
} | [
"public",
"static",
"function",
"base",
"(",
")",
"{",
"return",
"Request",
"::",
"getUri",
"(",
")",
"->",
"getScheme",
"(",
")",
".",
"'://'",
".",
"Request",
"::",
"getUri",
"(",
")",
"->",
"getHost",
"(",
")",
".",
"Request",
"::",
"getUri",
"(",... | Fetch the base_url, optionally support HTTPS and HTTP
@return string | [
"Fetch",
"the",
"base_url",
"optionally",
"support",
"HTTPS",
"and",
"HTTP"
] | train | https://github.com/runcmf/runbb/blob/d4f4098bcece48b78ea2d1ae5eeead7ac9a8b463/src/RunBB/Core/Url.php#L819-L823 |
runcmf/runbb | src/RunBB/Core/Url.php | Url.isValidUrl | public static function isValidUrl($url)
{
if (strpos($url, 'www.') === 0) {
$url = 'http://'. $url;
}
if (strpos($url, 'ftp.') === 0) {
$url = 'ftp://'. $url;
}
if (!preg_match('/# Valid absolute URI having a non-empty, valid DNS host.
^
(?P<scheme>[A-Za-z][A-Za-z0-9+\-.]*):\/\/
(?P<authority>
(?:(?P<userinfo>(?:[A-Za-z0-9\-._~!$&\'()*+,;=:]|%[0-9A-Fa-f]{2})*)@)?
(?P<host>
(?P<IP_literal>
\[
(?:
(?P<IPV6address>
(?: (?:[0-9A-Fa-f]{1,4}:){6}
| ::(?:[0-9A-Fa-f]{1,4}:){5}
| (?: [0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){4}
| (?:(?:[0-9A-Fa-f]{1,4}:){0,1}[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){3}
| (?:(?:[0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){2}
| (?:(?:[0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})?:: [0-9A-Fa-f]{1,4}:
| (?:(?:[0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})?::
)
(?P<ls32>[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}
| (?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}
(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
)
| (?:(?:[0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})?:: [0-9A-Fa-f]{1,4}
| (?:(?:[0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})?::
)
| (?P<IPvFuture>[Vv][0-9A-Fa-f]+\.[A-Za-z0-9\-._~!$&\'()*+,;=:]+)
)
\]
)
| (?P<IPv4address>(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}
(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))
| (?P<regname>(?:[A-Za-z0-9\-._~!$&\'()*+,;=]|%[0-9A-Fa-f]{2})+)
)
(?::(?P<port>[0-9]*))?
)
(?P<path_abempty>(?:\/(?:[A-Za-z0-9\-._~!$&\'()*+,;=:@]|%[0-9A-Fa-f]{2})*)*)
(?:\?(?P<query> (?:[A-Za-z0-9\-._~!$&\'()*+,;=:@\\/?]|%[0-9A-Fa-f]{2})*))?
(?:\#(?P<fragment> (?:[A-Za-z0-9\-._~!$&\'()*+,;=:@\\/?]|%[0-9A-Fa-f]{2})*))?
$
/mx', $url, $m)) {
return false;
}
switch ($m['scheme']) {
case 'https':
case 'http':
if ($m['userinfo']) {
return false;
} // HTTP scheme does not allow userinfo.
break;
case 'ftps':
case 'ftp':
break;
default:
return false; // Unrecognised URI scheme. Default to FALSE.
}
// Validate host name conforms to DNS "dot-separated-parts".
if ($m{'regname'}) {
// If host regname specified, check for DNS conformance.
if (!preg_match('/# HTTP DNS host name.
^ # Anchor to beginning of string.
(?!.{256}) # Overall host length is less than 256 chars.
(?: # Group dot separated host part alternatives.
[0-9A-Za-z]\. # Either a single alphanum followed by dot
| # or... part has more than one char (63 chars max).
[0-9A-Za-z] # Part first char is alphanum (no dash).
[\-0-9A-Za-z]{0,61} # Internal chars are alphanum plus dash.
[0-9A-Za-z] # Part last char is alphanum (no dash).
\. # Each part followed by literal dot.
)* # One or more parts before top level domain.
(?: # Top level domains
[A-Za-z]{2,63}| # Country codes are exactly two alpha chars.
xn--[0-9A-Za-z]{4,59}) # Internationalized Domain Name (IDN)
$ # Anchor to end of string.
/ix', $m['host'])) {
return false;
}
}
$m['url'] = $url;
for ($i = 0; isset($m[$i]); ++$i) {
unset($m[$i]);
}
return $m; // return TRUE == array of useful named $matches plus the valid $url.
} | php | public static function isValidUrl($url)
{
if (strpos($url, 'www.') === 0) {
$url = 'http://'. $url;
}
if (strpos($url, 'ftp.') === 0) {
$url = 'ftp://'. $url;
}
if (!preg_match('/# Valid absolute URI having a non-empty, valid DNS host.
^
(?P<scheme>[A-Za-z][A-Za-z0-9+\-.]*):\/\/
(?P<authority>
(?:(?P<userinfo>(?:[A-Za-z0-9\-._~!$&\'()*+,;=:]|%[0-9A-Fa-f]{2})*)@)?
(?P<host>
(?P<IP_literal>
\[
(?:
(?P<IPV6address>
(?: (?:[0-9A-Fa-f]{1,4}:){6}
| ::(?:[0-9A-Fa-f]{1,4}:){5}
| (?: [0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){4}
| (?:(?:[0-9A-Fa-f]{1,4}:){0,1}[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){3}
| (?:(?:[0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){2}
| (?:(?:[0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})?:: [0-9A-Fa-f]{1,4}:
| (?:(?:[0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})?::
)
(?P<ls32>[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}
| (?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}
(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
)
| (?:(?:[0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})?:: [0-9A-Fa-f]{1,4}
| (?:(?:[0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})?::
)
| (?P<IPvFuture>[Vv][0-9A-Fa-f]+\.[A-Za-z0-9\-._~!$&\'()*+,;=:]+)
)
\]
)
| (?P<IPv4address>(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}
(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))
| (?P<regname>(?:[A-Za-z0-9\-._~!$&\'()*+,;=]|%[0-9A-Fa-f]{2})+)
)
(?::(?P<port>[0-9]*))?
)
(?P<path_abempty>(?:\/(?:[A-Za-z0-9\-._~!$&\'()*+,;=:@]|%[0-9A-Fa-f]{2})*)*)
(?:\?(?P<query> (?:[A-Za-z0-9\-._~!$&\'()*+,;=:@\\/?]|%[0-9A-Fa-f]{2})*))?
(?:\#(?P<fragment> (?:[A-Za-z0-9\-._~!$&\'()*+,;=:@\\/?]|%[0-9A-Fa-f]{2})*))?
$
/mx', $url, $m)) {
return false;
}
switch ($m['scheme']) {
case 'https':
case 'http':
if ($m['userinfo']) {
return false;
} // HTTP scheme does not allow userinfo.
break;
case 'ftps':
case 'ftp':
break;
default:
return false; // Unrecognised URI scheme. Default to FALSE.
}
// Validate host name conforms to DNS "dot-separated-parts".
if ($m{'regname'}) {
// If host regname specified, check for DNS conformance.
if (!preg_match('/# HTTP DNS host name.
^ # Anchor to beginning of string.
(?!.{256}) # Overall host length is less than 256 chars.
(?: # Group dot separated host part alternatives.
[0-9A-Za-z]\. # Either a single alphanum followed by dot
| # or... part has more than one char (63 chars max).
[0-9A-Za-z] # Part first char is alphanum (no dash).
[\-0-9A-Za-z]{0,61} # Internal chars are alphanum plus dash.
[0-9A-Za-z] # Part last char is alphanum (no dash).
\. # Each part followed by literal dot.
)* # One or more parts before top level domain.
(?: # Top level domains
[A-Za-z]{2,63}| # Country codes are exactly two alpha chars.
xn--[0-9A-Za-z]{4,59}) # Internationalized Domain Name (IDN)
$ # Anchor to end of string.
/ix', $m['host'])) {
return false;
}
}
$m['url'] = $url;
for ($i = 0; isset($m[$i]); ++$i) {
unset($m[$i]);
}
return $m; // return TRUE == array of useful named $matches plus the valid $url.
} | [
"public",
"static",
"function",
"isValidUrl",
"(",
"$",
"url",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"url",
",",
"'www.'",
")",
"===",
"0",
")",
"{",
"$",
"url",
"=",
"'http://'",
".",
"$",
"url",
";",
"}",
"if",
"(",
"strpos",
"(",
"$",
"ur... | ) | [
")"
] | train | https://github.com/runcmf/runbb/blob/d4f4098bcece48b78ea2d1ae5eeead7ac9a8b463/src/RunBB/Core/Url.php#L871-L962 |
someline/starter-framework | src/Someline/Base/Repositories/Eloquent/Repository.php | Repository.lists | public function lists($column, $key = null)
{
$this->applyCriteria();
$this->applyScope();
$lists = $this->model->lists($column, $key);
$this->resetModel();
return $lists;
} | php | public function lists($column, $key = null)
{
$this->applyCriteria();
$this->applyScope();
$lists = $this->model->lists($column, $key);
$this->resetModel();
return $lists;
} | [
"public",
"function",
"lists",
"(",
"$",
"column",
",",
"$",
"key",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"applyCriteria",
"(",
")",
";",
"$",
"this",
"->",
"applyScope",
"(",
")",
";",
"$",
"lists",
"=",
"$",
"this",
"->",
"model",
"->",
"li... | Retrieve data array for populate field select
@param string $column
@param string|null $key
@return \Illuminate\Support\Collection|array | [
"Retrieve",
"data",
"array",
"for",
"populate",
"field",
"select"
] | train | https://github.com/someline/starter-framework/blob/38d3e97ca75dadb05bdc9020f73c78653dbecf15/src/Someline/Base/Repositories/Eloquent/Repository.php#L131-L141 |
someline/starter-framework | src/Someline/Base/Repositories/Eloquent/Repository.php | Repository.all | public function all($columns = array('*'))
{
$this->applyCriteria();
$this->applyScope();
if ($this->model instanceof \Illuminate\Database\Eloquent\Builder
|| $this->model instanceof \Illuminate\Database\Eloquent\Relations\Relation
) {
$results = $this->model->get($columns);
} else {
$results = $this->model->all($columns);
}
$this->resetModel();
return $this->parserResult($results);
} | php | public function all($columns = array('*'))
{
$this->applyCriteria();
$this->applyScope();
if ($this->model instanceof \Illuminate\Database\Eloquent\Builder
|| $this->model instanceof \Illuminate\Database\Eloquent\Relations\Relation
) {
$results = $this->model->get($columns);
} else {
$results = $this->model->all($columns);
}
$this->resetModel();
return $this->parserResult($results);
} | [
"public",
"function",
"all",
"(",
"$",
"columns",
"=",
"array",
"(",
"'*'",
")",
")",
"{",
"$",
"this",
"->",
"applyCriteria",
"(",
")",
";",
"$",
"this",
"->",
"applyScope",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"model",
"instanceof",
"\\",... | Retrieve all data of repository
@param array $columns
@return mixed | [
"Retrieve",
"all",
"data",
"of",
"repository"
] | train | https://github.com/someline/starter-framework/blob/38d3e97ca75dadb05bdc9020f73c78653dbecf15/src/Someline/Base/Repositories/Eloquent/Repository.php#L149-L165 |
someline/starter-framework | src/Someline/Base/Repositories/Eloquent/Repository.php | Repository.modelWhere | protected function modelWhere($column, $value = null)
{
$this->model = $this->model->where($column, $value);
return $this;
} | php | protected function modelWhere($column, $value = null)
{
$this->model = $this->model->where($column, $value);
return $this;
} | [
"protected",
"function",
"modelWhere",
"(",
"$",
"column",
",",
"$",
"value",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"model",
"=",
"$",
"this",
"->",
"model",
"->",
"where",
"(",
"$",
"column",
",",
"$",
"value",
")",
";",
"return",
"$",
"this",... | Add a basic where clause to the model.
@param string|array|\Closure $column
@param mixed $value
@return $this | [
"Add",
"a",
"basic",
"where",
"clause",
"to",
"the",
"model",
"."
] | train | https://github.com/someline/starter-framework/blob/38d3e97ca75dadb05bdc9020f73c78653dbecf15/src/Someline/Base/Repositories/Eloquent/Repository.php#L175-L179 |
someline/starter-framework | src/Someline/Base/Repositories/Eloquent/Repository.php | Repository.where | public function where(array $where)
{
$this->applyCriteria();
$this->applyScope();
$this->applyConditions($where);
return $this;
} | php | public function where(array $where)
{
$this->applyCriteria();
$this->applyScope();
$this->applyConditions($where);
return $this;
} | [
"public",
"function",
"where",
"(",
"array",
"$",
"where",
")",
"{",
"$",
"this",
"->",
"applyCriteria",
"(",
")",
";",
"$",
"this",
"->",
"applyScope",
"(",
")",
";",
"$",
"this",
"->",
"applyConditions",
"(",
"$",
"where",
")",
";",
"return",
"$",
... | Find data by where conditions
@param array $where
@return $this | [
"Find",
"data",
"by",
"where",
"conditions"
] | train | https://github.com/someline/starter-framework/blob/38d3e97ca75dadb05bdc9020f73c78653dbecf15/src/Someline/Base/Repositories/Eloquent/Repository.php#L214-L222 |
someline/starter-framework | src/Someline/Base/Repositories/Eloquent/Repository.php | Repository.withoutGlobalScopes | public function withoutGlobalScopes(array $scopes = null)
{
$this->model = $this->model->withoutGlobalScopes($scopes);
return $this;
} | php | public function withoutGlobalScopes(array $scopes = null)
{
$this->model = $this->model->withoutGlobalScopes($scopes);
return $this;
} | [
"public",
"function",
"withoutGlobalScopes",
"(",
"array",
"$",
"scopes",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"model",
"=",
"$",
"this",
"->",
"model",
"->",
"withoutGlobalScopes",
"(",
"$",
"scopes",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Remove all or passed registered global scopes.
@param array|null $scopes
@return $this | [
"Remove",
"all",
"or",
"passed",
"registered",
"global",
"scopes",
"."
] | train | https://github.com/someline/starter-framework/blob/38d3e97ca75dadb05bdc9020f73c78653dbecf15/src/Someline/Base/Repositories/Eloquent/Repository.php#L273-L277 |
makinacorpus/drupal-ucms | ucms_tree/src/EventDispatcher/ContextPaneEventSubscriber.php | ContextPaneEventSubscriber.onContextPaneInit | public function onContextPaneInit(ContextPaneEvent $event)
{
$site = null;
$contextPane = $event->getContextPane();
if ($this->siteManager->hasContext()) {
$site = $this->siteManager->getContext();
}
// Add admin actions on the tree listing page
if ('admin/dashboard/tree' === current_path()) {
$canCreate = false;
if ($site) {
$canCreate = $this->menuAccess->canCreateMenu($this->currentUser, $site);
} else {
$canCreate = $this->menuAccess->canCreateMenu($this->currentUser);
}
if ($canCreate) {
$contextPane->addActions([
new Action($this->t("Create menu"), 'admin/dashboard/tree/add', [], 'plus', 0, true, true),
]);
}
}
if ($site) {
// Add the tree structure as a new tab
$contextPane
->addTab('tree', $this->t("Menu tree"), 'bars')
->add($this->renderCurrentTree(), 'tree')
;
if (preg_match('@^admin/dashboard/tree/(\d+)$@', current_path())) {
// Default tab on tree edit is the cart
$contextPane->setDefaultTab('cart');
} elseif (!$contextPane->getRealDefaultTab()) {
// Else it's the tree
$contextPane->setDefaultTab('tree');
}
}
} | php | public function onContextPaneInit(ContextPaneEvent $event)
{
$site = null;
$contextPane = $event->getContextPane();
if ($this->siteManager->hasContext()) {
$site = $this->siteManager->getContext();
}
// Add admin actions on the tree listing page
if ('admin/dashboard/tree' === current_path()) {
$canCreate = false;
if ($site) {
$canCreate = $this->menuAccess->canCreateMenu($this->currentUser, $site);
} else {
$canCreate = $this->menuAccess->canCreateMenu($this->currentUser);
}
if ($canCreate) {
$contextPane->addActions([
new Action($this->t("Create menu"), 'admin/dashboard/tree/add', [], 'plus', 0, true, true),
]);
}
}
if ($site) {
// Add the tree structure as a new tab
$contextPane
->addTab('tree', $this->t("Menu tree"), 'bars')
->add($this->renderCurrentTree(), 'tree')
;
if (preg_match('@^admin/dashboard/tree/(\d+)$@', current_path())) {
// Default tab on tree edit is the cart
$contextPane->setDefaultTab('cart');
} elseif (!$contextPane->getRealDefaultTab()) {
// Else it's the tree
$contextPane->setDefaultTab('tree');
}
}
} | [
"public",
"function",
"onContextPaneInit",
"(",
"ContextPaneEvent",
"$",
"event",
")",
"{",
"$",
"site",
"=",
"null",
";",
"$",
"contextPane",
"=",
"$",
"event",
"->",
"getContextPane",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"siteManager",
"->",
"h... | On context pane init.
@param ContextPaneEvent $event | [
"On",
"context",
"pane",
"init",
"."
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_tree/src/EventDispatcher/ContextPaneEventSubscriber.php#L54-L93 |
makinacorpus/drupal-ucms | ucms_tree/src/EventDispatcher/ContextPaneEventSubscriber.php | ContextPaneEventSubscriber.renderCurrentTree | private function renderCurrentTree()
{
$site = $this->siteManager->getContext();
// Get all trees for this site
$menus = $this
->treeManager
->getMenuStorage()
->loadWithConditions(['site_id' => $site->getId()])
;
$build = [
'#prefix' => '<div class="col-xs-12">',
'#suffix' => '</div>',
'#attached' => [
'css' => [
drupal_get_path('module', 'ucms_tree').'/ucms_tree.css',
],
],
];
foreach ($menus as $menu) {
$build[$menu->getName()] = [
'#theme' => 'umenu__context_pane',
'#tree' => $this->treeManager->buildTree($menu->getId(), false),
'#prefix' => "<h3>" . $menu->getTitle() . "</h3>",
];
}
return $build;
} | php | private function renderCurrentTree()
{
$site = $this->siteManager->getContext();
// Get all trees for this site
$menus = $this
->treeManager
->getMenuStorage()
->loadWithConditions(['site_id' => $site->getId()])
;
$build = [
'#prefix' => '<div class="col-xs-12">',
'#suffix' => '</div>',
'#attached' => [
'css' => [
drupal_get_path('module', 'ucms_tree').'/ucms_tree.css',
],
],
];
foreach ($menus as $menu) {
$build[$menu->getName()] = [
'#theme' => 'umenu__context_pane',
'#tree' => $this->treeManager->buildTree($menu->getId(), false),
'#prefix' => "<h3>" . $menu->getTitle() . "</h3>",
];
}
return $build;
} | [
"private",
"function",
"renderCurrentTree",
"(",
")",
"{",
"$",
"site",
"=",
"$",
"this",
"->",
"siteManager",
"->",
"getContext",
"(",
")",
";",
"// Get all trees for this site",
"$",
"menus",
"=",
"$",
"this",
"->",
"treeManager",
"->",
"getMenuStorage",
"("... | Render current tree | [
"Render",
"current",
"tree"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_tree/src/EventDispatcher/ContextPaneEventSubscriber.php#L98-L128 |
artkonekt/gears | src/UI/BaseItem.php | BaseItem.createWidget | protected function createWidget($widget): Widget
{
if (is_string($widget)) {
return new Widget($widget);
} elseif (is_array($widget)) {
return new Widget($widget[0], $widget[1]);
}
throw new \InvalidArgumentException('Could not create widget from the passed arguments');
} | php | protected function createWidget($widget): Widget
{
if (is_string($widget)) {
return new Widget($widget);
} elseif (is_array($widget)) {
return new Widget($widget[0], $widget[1]);
}
throw new \InvalidArgumentException('Could not create widget from the passed arguments');
} | [
"protected",
"function",
"createWidget",
"(",
"$",
"widget",
")",
":",
"Widget",
"{",
"if",
"(",
"is_string",
"(",
"$",
"widget",
")",
")",
"{",
"return",
"new",
"Widget",
"(",
"$",
"widget",
")",
";",
"}",
"elseif",
"(",
"is_array",
"(",
"$",
"widge... | @param string|array $widget
@return Widget | [
"@param",
"string|array",
"$widget"
] | train | https://github.com/artkonekt/gears/blob/6c006a3e8e334d8100aab768a2a5e807bcac5695/src/UI/BaseItem.php#L123-L132 |
makinacorpus/drupal-ucms | ucms_group/src/Controller/AutocompleteController.php | AutocompleteController.siteAddAutocompleteAction | public function siteAddAutocompleteAction(Request $request, Group $group, $string)
{
if (!$this->isGranted(Access::ACL_PERM_MANAGE_SITES, $group)) {
throw $this->createAccessDeniedException();
}
$database = $this->getDatabaseConnection();
$q = $database
->select('ucms_site', 's')
->fields('s', ['id', 'title_admin'])
->isNull('s.group_id')
->condition(
(new \DatabaseCondition('OR'))
->condition('s.title', '%' . $database->escapeLike($string) . '%', 'LIKE')
->condition('s.title_admin', '%' . $database->escapeLike($string) . '%', 'LIKE')
->condition('s.http_host', '%' . $database->escapeLike($string) . '%', 'LIKE')
)
->orderBy('s.title_admin', 'asc')
->groupBy('s.id')
->range(0, 16)
->addTag('ucms_site_access')
;
$suggest = [];
foreach ($q->execute()->fetchAll() as $record) {
$key = $record->title_admin . ' [' . $record->id . ']';
$suggest[$key] = check_plain($record->title_admin);
}
return new JsonResponse($suggest);
} | php | public function siteAddAutocompleteAction(Request $request, Group $group, $string)
{
if (!$this->isGranted(Access::ACL_PERM_MANAGE_SITES, $group)) {
throw $this->createAccessDeniedException();
}
$database = $this->getDatabaseConnection();
$q = $database
->select('ucms_site', 's')
->fields('s', ['id', 'title_admin'])
->isNull('s.group_id')
->condition(
(new \DatabaseCondition('OR'))
->condition('s.title', '%' . $database->escapeLike($string) . '%', 'LIKE')
->condition('s.title_admin', '%' . $database->escapeLike($string) . '%', 'LIKE')
->condition('s.http_host', '%' . $database->escapeLike($string) . '%', 'LIKE')
)
->orderBy('s.title_admin', 'asc')
->groupBy('s.id')
->range(0, 16)
->addTag('ucms_site_access')
;
$suggest = [];
foreach ($q->execute()->fetchAll() as $record) {
$key = $record->title_admin . ' [' . $record->id . ']';
$suggest[$key] = check_plain($record->title_admin);
}
return new JsonResponse($suggest);
} | [
"public",
"function",
"siteAddAutocompleteAction",
"(",
"Request",
"$",
"request",
",",
"Group",
"$",
"group",
",",
"$",
"string",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isGranted",
"(",
"Access",
"::",
"ACL_PERM_MANAGE_SITES",
",",
"$",
"group",
")... | Autocomplete action for adding sites into group | [
"Autocomplete",
"action",
"for",
"adding",
"sites",
"into",
"group"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_group/src/Controller/AutocompleteController.php#L27-L58 |
makinacorpus/drupal-ucms | ucms_group/src/Controller/AutocompleteController.php | AutocompleteController.siteAttachAutocompleteAction | public function siteAttachAutocompleteAction(Request $request, Site $site, $string)
{
if (!$this->isGranted(Access::PERM_GROUP_MANAGE_ALL)) {
throw $this->createAccessDeniedException();
}
$database = $this->getDatabaseConnection();
$q = $database
->select('ucms_group', 'g')
->fields('g', ['id', 'title'])
->condition(
(new \DatabaseCondition('OR'))
->condition('g.title', '%' . $database->escapeLike($string) . '%', 'LIKE')
)
->orderBy('g.title', 'asc')
->groupBy('g.id')
->range(0, 16)
->addTag('ucms_group_access')
;
$suggest = [];
foreach ($q->execute()->fetchAll() as $record) {
$key = $record->title . ' [' . $record->id . ']';
$suggest[$key] = check_plain($record->title);
}
return new JsonResponse($suggest);
} | php | public function siteAttachAutocompleteAction(Request $request, Site $site, $string)
{
if (!$this->isGranted(Access::PERM_GROUP_MANAGE_ALL)) {
throw $this->createAccessDeniedException();
}
$database = $this->getDatabaseConnection();
$q = $database
->select('ucms_group', 'g')
->fields('g', ['id', 'title'])
->condition(
(new \DatabaseCondition('OR'))
->condition('g.title', '%' . $database->escapeLike($string) . '%', 'LIKE')
)
->orderBy('g.title', 'asc')
->groupBy('g.id')
->range(0, 16)
->addTag('ucms_group_access')
;
$suggest = [];
foreach ($q->execute()->fetchAll() as $record) {
$key = $record->title . ' [' . $record->id . ']';
$suggest[$key] = check_plain($record->title);
}
return new JsonResponse($suggest);
} | [
"public",
"function",
"siteAttachAutocompleteAction",
"(",
"Request",
"$",
"request",
",",
"Site",
"$",
"site",
",",
"$",
"string",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isGranted",
"(",
"Access",
"::",
"PERM_GROUP_MANAGE_ALL",
")",
")",
"{",
"thro... | Autocomplete action for attaching group to site | [
"Autocomplete",
"action",
"for",
"attaching",
"group",
"to",
"site"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_group/src/Controller/AutocompleteController.php#L63-L91 |
fintech-fab/bank-emulator | src/FintechFab/BankEmulator/Components/Processor/Payment.php | Payment.saveAsInit | public function saveAsInit()
{
$this->initDoubleBeforeSave();
if (empty($this->payment->rrn)) {
$this->payment->rrn = mt_rand(111111111111, 999999999999);
}
if (empty($this->payment->irn)) {
$this->payment->irn = substr(strtoupper(md5($this->payment->rrn . time())), 10, 10);
}
$this->payment->status = Status::PROCESSED;
$this->payment->save();
} | php | public function saveAsInit()
{
$this->initDoubleBeforeSave();
if (empty($this->payment->rrn)) {
$this->payment->rrn = mt_rand(111111111111, 999999999999);
}
if (empty($this->payment->irn)) {
$this->payment->irn = substr(strtoupper(md5($this->payment->rrn . time())), 10, 10);
}
$this->payment->status = Status::PROCESSED;
$this->payment->save();
} | [
"public",
"function",
"saveAsInit",
"(",
")",
"{",
"$",
"this",
"->",
"initDoubleBeforeSave",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"payment",
"->",
"rrn",
")",
")",
"{",
"$",
"this",
"->",
"payment",
"->",
"rrn",
"=",
"mt_rand",... | first, save payment | [
"first",
"save",
"payment"
] | train | https://github.com/fintech-fab/bank-emulator/blob/6256be98509de0ff8e96b5683a0b0197acd67b9e/src/FintechFab/BankEmulator/Components/Processor/Payment.php#L75-L88 |
fintech-fab/bank-emulator | src/FintechFab/BankEmulator/Components/Processor/Payment.php | Payment.initDoubleBeforeSave | private function initDoubleBeforeSave()
{
$type = new Type($this->payment->type, $this->payment->toArray());
switch ($type->sid()) {
case Type::COMPLETE:
case Type::REFUND:
$payment = self::find(
$this->payment->term,
$this->payment->order,
$this->payment->irn,
$this->payment->rrn,
$type->sid(),
array(Status::SUCCESS)
);
if ($payment) {
$this->payment = $payment;
}
break;
}
} | php | private function initDoubleBeforeSave()
{
$type = new Type($this->payment->type, $this->payment->toArray());
switch ($type->sid()) {
case Type::COMPLETE:
case Type::REFUND:
$payment = self::find(
$this->payment->term,
$this->payment->order,
$this->payment->irn,
$this->payment->rrn,
$type->sid(),
array(Status::SUCCESS)
);
if ($payment) {
$this->payment = $payment;
}
break;
}
} | [
"private",
"function",
"initDoubleBeforeSave",
"(",
")",
"{",
"$",
"type",
"=",
"new",
"Type",
"(",
"$",
"this",
"->",
"payment",
"->",
"type",
",",
"$",
"this",
"->",
"payment",
"->",
"toArray",
"(",
")",
")",
";",
"switch",
"(",
"$",
"type",
"->",
... | Init exists payment if double operation | [
"Init",
"exists",
"payment",
"if",
"double",
"operation"
] | train | https://github.com/fintech-fab/bank-emulator/blob/6256be98509de0ff8e96b5683a0b0197acd67b9e/src/FintechFab/BankEmulator/Components/Processor/Payment.php#L101-L128 |
fintech-fab/bank-emulator | src/FintechFab/BankEmulator/Components/Processor/Payment.php | Payment.doProcess | public function doProcess()
{
// card errors
$rc = $this->doProcessCards();
if ($rc !== '00') {
$this->payment->rc = $rc;
$this->payment->rrn = '';
$this->payment->irn = '';
$this->payment->status = Status::ERROR;
$this->payment->save();
return;
}
// process type errors
$rc = $this->doProcessType();
if ($rc !== '00') {
$this->payment->rc = $rc;
$this->payment->status = Status::ERROR;
$this->payment->save();
return;
}
// auth
$this->doDetectAuth();
// approved
if($this->payment->status != Status::AUTHORIZATION){
$this->payment->status = Status::SUCCESS;
}
$this->payment->rc = '00';
$this->payment->approval = mt_rand(100000, 999999);
$this->payment->save();
} | php | public function doProcess()
{
// card errors
$rc = $this->doProcessCards();
if ($rc !== '00') {
$this->payment->rc = $rc;
$this->payment->rrn = '';
$this->payment->irn = '';
$this->payment->status = Status::ERROR;
$this->payment->save();
return;
}
// process type errors
$rc = $this->doProcessType();
if ($rc !== '00') {
$this->payment->rc = $rc;
$this->payment->status = Status::ERROR;
$this->payment->save();
return;
}
// auth
$this->doDetectAuth();
// approved
if($this->payment->status != Status::AUTHORIZATION){
$this->payment->status = Status::SUCCESS;
}
$this->payment->rc = '00';
$this->payment->approval = mt_rand(100000, 999999);
$this->payment->save();
} | [
"public",
"function",
"doProcess",
"(",
")",
"{",
"// card errors",
"$",
"rc",
"=",
"$",
"this",
"->",
"doProcessCards",
"(",
")",
";",
"if",
"(",
"$",
"rc",
"!==",
"'00'",
")",
"{",
"$",
"this",
"->",
"payment",
"->",
"rc",
"=",
"$",
"rc",
";",
... | payment processing | [
"payment",
"processing"
] | train | https://github.com/fintech-fab/bank-emulator/blob/6256be98509de0ff8e96b5683a0b0197acd67b9e/src/FintechFab/BankEmulator/Components/Processor/Payment.php#L133-L169 |
fintech-fab/bank-emulator | src/FintechFab/BankEmulator/Components/Processor/Payment.php | Payment.doProcessCards | public function doProcessCards()
{
$pan = $this->payment->pan;
$this->payment->mask('pan');
$type = new Type($this->payment->type, $this->payment->toArray());
$fields = $type->fields();
if (!in_array('pan', $fields)) {
return '00';
}
$cvc = $this->payment->cvc;
$rc = BankCard::doCheckCard($pan, $cvc);
if ($rc !== '00') {
return $rc;
}
if ($type->sid() == Type::SALE) {
$to = $this->payment->to;
if ($to) {
$rc = BankCard::doCheckCard($to);
}
}
return $rc;
} | php | public function doProcessCards()
{
$pan = $this->payment->pan;
$this->payment->mask('pan');
$type = new Type($this->payment->type, $this->payment->toArray());
$fields = $type->fields();
if (!in_array('pan', $fields)) {
return '00';
}
$cvc = $this->payment->cvc;
$rc = BankCard::doCheckCard($pan, $cvc);
if ($rc !== '00') {
return $rc;
}
if ($type->sid() == Type::SALE) {
$to = $this->payment->to;
if ($to) {
$rc = BankCard::doCheckCard($to);
}
}
return $rc;
} | [
"public",
"function",
"doProcessCards",
"(",
")",
"{",
"$",
"pan",
"=",
"$",
"this",
"->",
"payment",
"->",
"pan",
";",
"$",
"this",
"->",
"payment",
"->",
"mask",
"(",
"'pan'",
")",
";",
"$",
"type",
"=",
"new",
"Type",
"(",
"$",
"this",
"->",
"... | RC process code by card numbers
@return string $rc | [
"RC",
"process",
"code",
"by",
"card",
"numbers"
] | train | https://github.com/fintech-fab/bank-emulator/blob/6256be98509de0ff8e96b5683a0b0197acd67b9e/src/FintechFab/BankEmulator/Components/Processor/Payment.php#L176-L203 |
fintech-fab/bank-emulator | src/FintechFab/BankEmulator/Components/Processor/Payment.php | Payment.doProcessType | private function doProcessType()
{
$type = new Type($this->payment->type, $this->payment->toArray());
$paymentExist = self::findDouble(
$this->payment->id,
$this->payment->term,
$this->payment->order,
$this->payment->amount,
$type->sid(),
array(Status::SUCCESS, Status::PROCESSED)
);
if ($paymentExist) {
return '-3';
}
switch ($type->sid()) {
case Type::AUTH:
case Type::SALE:
case Type::PAYMENT:
break;
case Type::COMPLETE:
// completing auth request
$payment = self::find(
$this->payment->term,
$this->payment->order,
$this->payment->irn,
$this->payment->rrn,
Type::AUTH,
Status::SUCCESS
);
if (!$payment) {
return '-2';
}
break;
case Type::REFUND:
// refund for finished processing: sale, complete, payment
$payment = self::find(
$this->payment->term,
$this->payment->order,
$this->payment->irn,
$this->payment->rrn,
array(Type::SALE, Type::COMPLETE, Type::PAYMENT),
Status::SUCCESS
);
if (!$payment) {
// refund for not finishing processing: auth
$payment = self::find(
$this->payment->term,
$this->payment->order,
$this->payment->irn,
$this->payment->rrn,
Type::AUTH,
Status::SUCCESS
);
if (!$payment) {
return '-2';
}
}
break;
}
return '00';
} | php | private function doProcessType()
{
$type = new Type($this->payment->type, $this->payment->toArray());
$paymentExist = self::findDouble(
$this->payment->id,
$this->payment->term,
$this->payment->order,
$this->payment->amount,
$type->sid(),
array(Status::SUCCESS, Status::PROCESSED)
);
if ($paymentExist) {
return '-3';
}
switch ($type->sid()) {
case Type::AUTH:
case Type::SALE:
case Type::PAYMENT:
break;
case Type::COMPLETE:
// completing auth request
$payment = self::find(
$this->payment->term,
$this->payment->order,
$this->payment->irn,
$this->payment->rrn,
Type::AUTH,
Status::SUCCESS
);
if (!$payment) {
return '-2';
}
break;
case Type::REFUND:
// refund for finished processing: sale, complete, payment
$payment = self::find(
$this->payment->term,
$this->payment->order,
$this->payment->irn,
$this->payment->rrn,
array(Type::SALE, Type::COMPLETE, Type::PAYMENT),
Status::SUCCESS
);
if (!$payment) {
// refund for not finishing processing: auth
$payment = self::find(
$this->payment->term,
$this->payment->order,
$this->payment->irn,
$this->payment->rrn,
Type::AUTH,
Status::SUCCESS
);
if (!$payment) {
return '-2';
}
}
break;
}
return '00';
} | [
"private",
"function",
"doProcessType",
"(",
")",
"{",
"$",
"type",
"=",
"new",
"Type",
"(",
"$",
"this",
"->",
"payment",
"->",
"type",
",",
"$",
"this",
"->",
"payment",
"->",
"toArray",
"(",
")",
")",
";",
"$",
"paymentExist",
"=",
"self",
"::",
... | Process logic by payment Type
@return string $rc | [
"Process",
"logic",
"by",
"payment",
"Type"
] | train | https://github.com/fintech-fab/bank-emulator/blob/6256be98509de0ff8e96b5683a0b0197acd67b9e/src/FintechFab/BankEmulator/Components/Processor/Payment.php#L210-L286 |
fintech-fab/bank-emulator | src/FintechFab/BankEmulator/Components/Processor/Payment.php | Payment.find | public static function find($term, $order, $irn, $rrn, $type = null, $status = null)
{
$payment = PaymentModel::whereTerm($term)
->whereOrder($order)
->whereIrn($irn)
->whereRrn($rrn);
if (!is_array($type)) {
$type = (array)$type;
}
if (!is_array($status)) {
$status = (array)$status;
}
if ($type) {
$payment->whereIn('type', $type);
}
if ($status) {
$payment->whereIn('status', $status);
}
$payment->orderBy('id', 'desc');
$payment = $payment->first();
return $payment;
} | php | public static function find($term, $order, $irn, $rrn, $type = null, $status = null)
{
$payment = PaymentModel::whereTerm($term)
->whereOrder($order)
->whereIrn($irn)
->whereRrn($rrn);
if (!is_array($type)) {
$type = (array)$type;
}
if (!is_array($status)) {
$status = (array)$status;
}
if ($type) {
$payment->whereIn('type', $type);
}
if ($status) {
$payment->whereIn('status', $status);
}
$payment->orderBy('id', 'desc');
$payment = $payment->first();
return $payment;
} | [
"public",
"static",
"function",
"find",
"(",
"$",
"term",
",",
"$",
"order",
",",
"$",
"irn",
",",
"$",
"rrn",
",",
"$",
"type",
"=",
"null",
",",
"$",
"status",
"=",
"null",
")",
"{",
"$",
"payment",
"=",
"PaymentModel",
"::",
"whereTerm",
"(",
... | search payment
@param string $term
@param string $order
@param string $irn
@param string $rrn
@param string|array $type
@param string|array $status
@return PaymentModel|null | [
"search",
"payment"
] | train | https://github.com/fintech-fab/bank-emulator/blob/6256be98509de0ff8e96b5683a0b0197acd67b9e/src/FintechFab/BankEmulator/Components/Processor/Payment.php#L309-L336 |
fintech-fab/bank-emulator | src/FintechFab/BankEmulator/Components/Processor/Payment.php | Payment.findDouble | public static function findDouble($id, $term, $order, $amount, $type = null, $status = null)
{
$payment = PaymentModel::whereTerm($term)
->whereOrder($order)
->whereAmount($amount)
->where('id', '!=', $id);
if (!is_array($type)) {
$type = (array)$type;
}
if (!is_array($status)) {
$status = (array)$status;
}
if ($status) {
$payment->whereIn('status', $status);
}
if ($type) {
$payment->whereIn('type', $type);
}
// last hour
$payment->whereRaw('created_at >= DATE_SUB(NOW(), INTERVAL 1 HOUR)');
$payment = $payment->first();
return $payment;
} | php | public static function findDouble($id, $term, $order, $amount, $type = null, $status = null)
{
$payment = PaymentModel::whereTerm($term)
->whereOrder($order)
->whereAmount($amount)
->where('id', '!=', $id);
if (!is_array($type)) {
$type = (array)$type;
}
if (!is_array($status)) {
$status = (array)$status;
}
if ($status) {
$payment->whereIn('status', $status);
}
if ($type) {
$payment->whereIn('type', $type);
}
// last hour
$payment->whereRaw('created_at >= DATE_SUB(NOW(), INTERVAL 1 HOUR)');
$payment = $payment->first();
return $payment;
} | [
"public",
"static",
"function",
"findDouble",
"(",
"$",
"id",
",",
"$",
"term",
",",
"$",
"order",
",",
"$",
"amount",
",",
"$",
"type",
"=",
"null",
",",
"$",
"status",
"=",
"null",
")",
"{",
"$",
"payment",
"=",
"PaymentModel",
"::",
"whereTerm",
... | search double payment
@param int $id current payment id
@param string $term
@param string $order
@param string $amount
@param string|array $type
@param string|array $status
@return PaymentModel|null | [
"search",
"double",
"payment"
] | train | https://github.com/fintech-fab/bank-emulator/blob/6256be98509de0ff8e96b5683a0b0197acd67b9e/src/FintechFab/BankEmulator/Components/Processor/Payment.php#L350-L378 |
fintech-fab/bank-emulator | src/FintechFab/BankEmulator/Components/Processor/Payment.php | Payment.doDetectAuth | private function doDetectAuth()
{
if ($this->payment->cvc == '333') {
$this->auth = Url::route('ff-bank-em-pay-auth', array(
'payment' => Crypt::encrypt($this->payment->id),
'back' => urlencode(Url::route('ff-bank-em-endpoint-auth-result')),
));
$this->payment->status = Status::AUTHORIZATION;
}
} | php | private function doDetectAuth()
{
if ($this->payment->cvc == '333') {
$this->auth = Url::route('ff-bank-em-pay-auth', array(
'payment' => Crypt::encrypt($this->payment->id),
'back' => urlencode(Url::route('ff-bank-em-endpoint-auth-result')),
));
$this->payment->status = Status::AUTHORIZATION;
}
} | [
"private",
"function",
"doDetectAuth",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"payment",
"->",
"cvc",
"==",
"'333'",
")",
"{",
"$",
"this",
"->",
"auth",
"=",
"Url",
"::",
"route",
"(",
"'ff-bank-em-pay-auth'",
",",
"array",
"(",
"'payment'",
"=>... | Init url payment authorization | [
"Init",
"url",
"payment",
"authorization"
] | train | https://github.com/fintech-fab/bank-emulator/blob/6256be98509de0ff8e96b5683a0b0197acd67b9e/src/FintechFab/BankEmulator/Components/Processor/Payment.php#L383-L392 |
accompli/accompli | src/Task/MaintenanceModeTask.php | MaintenanceModeTask.onPrepareWorkspaceUploadMaintenancePage | public function onPrepareWorkspaceUploadMaintenancePage(WorkspaceEvent $event, $eventName, EventDispatcherInterface $eventDispatcher)
{
$host = $event->getWorkspace()->getHost();
$connection = $this->ensureConnection($host);
$directory = sprintf('%s/maintenance/%s', $host->getPath(), $this->documentRoot);
$context = array('directory' => $directory, 'event.task.action' => TaskInterface::ACTION_IN_PROGRESS);
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::NOTICE, 'Creating directory "{directory}".', $eventName, $this, $context));
if ($connection->isDirectory($directory) === false) {
if ($connection->createDirectory($directory, 0770, true)) {
$context['event.task.action'] = TaskInterface::ACTION_COMPLETED;
$context['output.resetLine'] = true;
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::NOTICE, 'Created directory "{directory}".', $eventName, $this, $context));
} else {
$context['event.task.action'] = TaskInterface::ACTION_FAILED;
$context['output.resetLine'] = true;
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::WARNING, 'Failed creating directory "{directory}".', $eventName, $this, $context));
}
} else {
$context['event.task.action'] = TaskInterface::ACTION_COMPLETED;
$context['output.resetLine'] = true;
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::NOTICE, 'Directory "{directory}" exists.', $eventName, $this, $context));
}
if ($connection->isDirectory($directory)) {
$files = array_diff(scandir($this->localMaintenanceDirectory), array('.', '..'));
foreach ($files as $file) {
$localFile = $this->localMaintenanceDirectory.'/'.$file;
if (is_file($localFile)) {
$context = array('file' => $localFile, 'event.task.action' => TaskInterface::ACTION_COMPLETED);
$uploaded = $connection->putFile($localFile, $directory.'/'.$file);
if ($uploaded === true) {
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::INFO, 'Uploaded file "{file}".', $eventName, $this, $context));
}
}
}
}
} | php | public function onPrepareWorkspaceUploadMaintenancePage(WorkspaceEvent $event, $eventName, EventDispatcherInterface $eventDispatcher)
{
$host = $event->getWorkspace()->getHost();
$connection = $this->ensureConnection($host);
$directory = sprintf('%s/maintenance/%s', $host->getPath(), $this->documentRoot);
$context = array('directory' => $directory, 'event.task.action' => TaskInterface::ACTION_IN_PROGRESS);
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::NOTICE, 'Creating directory "{directory}".', $eventName, $this, $context));
if ($connection->isDirectory($directory) === false) {
if ($connection->createDirectory($directory, 0770, true)) {
$context['event.task.action'] = TaskInterface::ACTION_COMPLETED;
$context['output.resetLine'] = true;
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::NOTICE, 'Created directory "{directory}".', $eventName, $this, $context));
} else {
$context['event.task.action'] = TaskInterface::ACTION_FAILED;
$context['output.resetLine'] = true;
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::WARNING, 'Failed creating directory "{directory}".', $eventName, $this, $context));
}
} else {
$context['event.task.action'] = TaskInterface::ACTION_COMPLETED;
$context['output.resetLine'] = true;
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::NOTICE, 'Directory "{directory}" exists.', $eventName, $this, $context));
}
if ($connection->isDirectory($directory)) {
$files = array_diff(scandir($this->localMaintenanceDirectory), array('.', '..'));
foreach ($files as $file) {
$localFile = $this->localMaintenanceDirectory.'/'.$file;
if (is_file($localFile)) {
$context = array('file' => $localFile, 'event.task.action' => TaskInterface::ACTION_COMPLETED);
$uploaded = $connection->putFile($localFile, $directory.'/'.$file);
if ($uploaded === true) {
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::INFO, 'Uploaded file "{file}".', $eventName, $this, $context));
}
}
}
}
} | [
"public",
"function",
"onPrepareWorkspaceUploadMaintenancePage",
"(",
"WorkspaceEvent",
"$",
"event",
",",
"$",
"eventName",
",",
"EventDispatcherInterface",
"$",
"eventDispatcher",
")",
"{",
"$",
"host",
"=",
"$",
"event",
"->",
"getWorkspace",
"(",
")",
"->",
"g... | Uploads the maintenance page (and related resources).
@param WorkspaceEvent $event
@param string $eventName
@param EventDispatcherInterface $eventDispatcher | [
"Uploads",
"the",
"maintenance",
"page",
"(",
"and",
"related",
"resources",
")",
"."
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Task/MaintenanceModeTask.php#L84-L126 |
accompli/accompli | src/Task/MaintenanceModeTask.php | MaintenanceModeTask.onPrepareDeployReleaseLinkMaintenancePageToStage | public function onPrepareDeployReleaseLinkMaintenancePageToStage(PrepareDeployReleaseEvent $event, $eventName, EventDispatcherInterface $eventDispatcher)
{
if (VersionCategoryComparator::matchesStrategy($this->strategy, $event->getRelease(), $event->getCurrentRelease()) === false) {
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::INFO, 'Skipped linking maintenance page according to strategy.', $eventName, $this));
return;
}
$host = $event->getWorkspace()->getHost();
$connection = $this->ensureConnection($host);
$linkSource = $host->getPath().'/maintenance/';
$linkTarget = $host->getPath().'/'.$host->getStage();
$context = array('linkTarget' => $linkTarget);
if ($connection->isLink($linkTarget) && $connection->delete($linkTarget, false) === false) {
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::WARNING, 'Failed to remove existing "{linkTarget}" link.', $eventName, $this, $context));
}
$context['event.task.action'] = TaskInterface::ACTION_IN_PROGRESS;
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::INFO, 'Linking "{linkTarget}" to maintenance page.', $eventName, $this, $context));
if ($connection->link($linkSource, $linkTarget)) {
$context['event.task.action'] = TaskInterface::ACTION_COMPLETED;
$context['output.resetLine'] = true;
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::INFO, 'Linked "{linkTarget}" to maintenance page.', $eventName, $this, $context));
} else {
$context['event.task.action'] = TaskInterface::ACTION_FAILED;
$context['output.resetLine'] = true;
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::INFO, 'Linking "{linkTarget}" to maintenance page failed.', $eventName, $this, $context));
throw new TaskRuntimeException(sprintf('Linking "%s" to maintenance page failed.', $context['linkTarget']), $this);
}
} | php | public function onPrepareDeployReleaseLinkMaintenancePageToStage(PrepareDeployReleaseEvent $event, $eventName, EventDispatcherInterface $eventDispatcher)
{
if (VersionCategoryComparator::matchesStrategy($this->strategy, $event->getRelease(), $event->getCurrentRelease()) === false) {
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::INFO, 'Skipped linking maintenance page according to strategy.', $eventName, $this));
return;
}
$host = $event->getWorkspace()->getHost();
$connection = $this->ensureConnection($host);
$linkSource = $host->getPath().'/maintenance/';
$linkTarget = $host->getPath().'/'.$host->getStage();
$context = array('linkTarget' => $linkTarget);
if ($connection->isLink($linkTarget) && $connection->delete($linkTarget, false) === false) {
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::WARNING, 'Failed to remove existing "{linkTarget}" link.', $eventName, $this, $context));
}
$context['event.task.action'] = TaskInterface::ACTION_IN_PROGRESS;
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::INFO, 'Linking "{linkTarget}" to maintenance page.', $eventName, $this, $context));
if ($connection->link($linkSource, $linkTarget)) {
$context['event.task.action'] = TaskInterface::ACTION_COMPLETED;
$context['output.resetLine'] = true;
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::INFO, 'Linked "{linkTarget}" to maintenance page.', $eventName, $this, $context));
} else {
$context['event.task.action'] = TaskInterface::ACTION_FAILED;
$context['output.resetLine'] = true;
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::INFO, 'Linking "{linkTarget}" to maintenance page failed.', $eventName, $this, $context));
throw new TaskRuntimeException(sprintf('Linking "%s" to maintenance page failed.', $context['linkTarget']), $this);
}
} | [
"public",
"function",
"onPrepareDeployReleaseLinkMaintenancePageToStage",
"(",
"PrepareDeployReleaseEvent",
"$",
"event",
",",
"$",
"eventName",
",",
"EventDispatcherInterface",
"$",
"eventDispatcher",
")",
"{",
"if",
"(",
"VersionCategoryComparator",
"::",
"matchesStrategy",... | Links the maintenance page to the stage being deployed.
@param PrepareDeployReleaseEvent $event
@param string $eventName
@param EventDispatcherInterface $eventDispatcher
@throws TaskRuntimeException when not able to link the maintenance page | [
"Links",
"the",
"maintenance",
"page",
"to",
"the",
"stage",
"being",
"deployed",
"."
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Task/MaintenanceModeTask.php#L137-L173 |
shopgate/cart-integration-sdk | src/helper/Pricing.php | Shopgate_Helper_Pricing.formatPriceNumber | public function formatPriceNumber($price, $digits = 2, $decimalPoint = ".", $thousandPoints = "")
{
$price = round($price, $digits);
$price = number_format($price, $digits, $decimalPoint, $thousandPoints);
return $price;
} | php | public function formatPriceNumber($price, $digits = 2, $decimalPoint = ".", $thousandPoints = "")
{
$price = round($price, $digits);
$price = number_format($price, $digits, $decimalPoint, $thousandPoints);
return $price;
} | [
"public",
"function",
"formatPriceNumber",
"(",
"$",
"price",
",",
"$",
"digits",
"=",
"2",
",",
"$",
"decimalPoint",
"=",
"\".\"",
",",
"$",
"thousandPoints",
"=",
"\"\"",
")",
"{",
"$",
"price",
"=",
"round",
"(",
"$",
"price",
",",
"$",
"digits",
... | Rounds and formats a price.
@param float $price The price of an item.
@param int $digits The number of digits after the decimal separator.
@param string $decimalPoint The decimal separator.
@param string $thousandPoints The thousands separator.
@return float|string | [
"Rounds",
"and",
"formats",
"a",
"price",
"."
] | train | https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/helper/Pricing.php#L34-L40 |
shopgate/cart-integration-sdk | src/models/catalog/Category.php | Shopgate_Model_Catalog_Category.asXml | public function asXml(Shopgate_Model_XmlResultObject $itemNode)
{
/**
* @var Shopgate_Model_XmlResultObject $categoryNode
*/
$categoryNode = $itemNode->addChild('category');
$categoryNode->addAttribute('uid', $this->getUid());
$categoryNode->addAttribute('sort_order', (int)$this->getSortOrder());
$categoryNode->addAttribute(
'parent_uid',
$this->getParentUid()
? $this->getParentUid()
: null
);
$categoryNode->addAttribute('is_active', (int)$this->getIsActive());
$categoryNode->addAttribute('is_anchor', (int)$this->getIsAnchor());
$categoryNode->addChildWithCDATA('name', $this->getName());
$categoryNode->addChildWithCDATA('deeplink', $this->getDeeplink());
if ($this->getImage()) {
$this->getImage()->asXml($categoryNode);
}
return $itemNode;
} | php | public function asXml(Shopgate_Model_XmlResultObject $itemNode)
{
/**
* @var Shopgate_Model_XmlResultObject $categoryNode
*/
$categoryNode = $itemNode->addChild('category');
$categoryNode->addAttribute('uid', $this->getUid());
$categoryNode->addAttribute('sort_order', (int)$this->getSortOrder());
$categoryNode->addAttribute(
'parent_uid',
$this->getParentUid()
? $this->getParentUid()
: null
);
$categoryNode->addAttribute('is_active', (int)$this->getIsActive());
$categoryNode->addAttribute('is_anchor', (int)$this->getIsAnchor());
$categoryNode->addChildWithCDATA('name', $this->getName());
$categoryNode->addChildWithCDATA('deeplink', $this->getDeeplink());
if ($this->getImage()) {
$this->getImage()->asXml($categoryNode);
}
return $itemNode;
} | [
"public",
"function",
"asXml",
"(",
"Shopgate_Model_XmlResultObject",
"$",
"itemNode",
")",
"{",
"/**\n * @var Shopgate_Model_XmlResultObject $categoryNode\n */",
"$",
"categoryNode",
"=",
"$",
"itemNode",
"->",
"addChild",
"(",
"'category'",
")",
";",
"$",
... | @param Shopgate_Model_XmlResultObject $itemNode
@return Shopgate_Model_XmlResultObject | [
"@param",
"Shopgate_Model_XmlResultObject",
"$itemNode"
] | train | https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/models/catalog/Category.php#L113-L137 |
silverstripe/silverstripe-versionfeed | src/Filters/ContentFilter.php | ContentFilter.getContent | public function getContent($key, $callback)
{
if ($this->nestedContentFilter) {
return $this->nestedContentFilter->getContent($key, $callback);
} else {
return call_user_func($callback);
}
} | php | public function getContent($key, $callback)
{
if ($this->nestedContentFilter) {
return $this->nestedContentFilter->getContent($key, $callback);
} else {
return call_user_func($callback);
}
} | [
"public",
"function",
"getContent",
"(",
"$",
"key",
",",
"$",
"callback",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"nestedContentFilter",
")",
"{",
"return",
"$",
"this",
"->",
"nestedContentFilter",
"->",
"getContent",
"(",
"$",
"key",
",",
"$",
"callba... | Evaluates the result of the given callback
@param string $key Unique key for this
@param callable $callback Callback for evaluating the content
@return mixed Result of $callback() | [
"Evaluates",
"the",
"result",
"of",
"the",
"given",
"callback"
] | train | https://github.com/silverstripe/silverstripe-versionfeed/blob/831f03a2b85602c7a7fba110e0ef51c36ad4f204/src/Filters/ContentFilter.php#L58-L65 |
heidilabs/markov-php | src/MarkovPHP/WordChain.php | WordChain.getThemedLink | public function getThemedLink($string)
{
$search = preg_grep('/\b' . preg_quote($string, '/') . '\b/', $this->words);
return $search[array_rand($search)];
} | php | public function getThemedLink($string)
{
$search = preg_grep('/\b' . preg_quote($string, '/') . '\b/', $this->words);
return $search[array_rand($search)];
} | [
"public",
"function",
"getThemedLink",
"(",
"$",
"string",
")",
"{",
"$",
"search",
"=",
"preg_grep",
"(",
"'/\\b'",
".",
"preg_quote",
"(",
"$",
"string",
",",
"'/'",
")",
".",
"'\\b/'",
",",
"$",
"this",
"->",
"words",
")",
";",
"return",
"$",
"sea... | Gets a chain link based on a string search
@param $string | [
"Gets",
"a",
"chain",
"link",
"based",
"on",
"a",
"string",
"search"
] | train | https://github.com/heidilabs/markov-php/blob/d29546f0a8f2ec831e12001d43eef1e79b950c24/src/MarkovPHP/WordChain.php#L60-L64 |
makinacorpus/drupal-ucms | ucms_site/src/NodeAccessService.php | NodeAccessService.findMostRelevantEnabledSiteFor | public function findMostRelevantEnabledSiteFor(NodeInterface $node)
{
if (empty($node->ucms_enabled_sites)) {
return; // Node cannot be viewed
}
if (in_array($node->site_id, $node->ucms_enabled_sites)) {
// Per default, the primary site seems the best to work with
return $node->site_id;
}
return reset($node->ucms_enabled_sites); // Fallback on first
} | php | public function findMostRelevantEnabledSiteFor(NodeInterface $node)
{
if (empty($node->ucms_enabled_sites)) {
return; // Node cannot be viewed
}
if (in_array($node->site_id, $node->ucms_enabled_sites)) {
// Per default, the primary site seems the best to work with
return $node->site_id;
}
return reset($node->ucms_enabled_sites); // Fallback on first
} | [
"public",
"function",
"findMostRelevantEnabledSiteFor",
"(",
"NodeInterface",
"$",
"node",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"node",
"->",
"ucms_enabled_sites",
")",
")",
"{",
"return",
";",
"// Node cannot be viewed",
"}",
"if",
"(",
"in_array",
"(",
"$... | Find the most revelant ENABLED site to view the node in
@param NodeInterface $node
@see \MakinaCorpus\Ucms\Site\EventDispatcher\NodeEventSubscriber::onLoad()
@return int
The site identifier is returned, we don't need to load it to build
a node route | [
"Find",
"the",
"most",
"revelant",
"ENABLED",
"site",
"to",
"view",
"the",
"node",
"in"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/NodeAccessService.php#L38-L50 |
makinacorpus/drupal-ucms | ucms_site/src/NodeAccessService.php | NodeAccessService.findMostRelevantSiteFor | public function findMostRelevantSiteFor(NodeInterface $node)
{
if ($siteId = $this->findMostRelevantEnabledSiteFor($node)) {
return $siteId;
}
if (empty($node->ucms_allowed_sites)) {
return; // Node cannot be viewed
}
if (in_array($node->site_id, $node->ucms_allowed_sites)) {
// Per default, the primary site seems the best to work with
return $node->site_id;
}
return reset($node->ucms_allowed_sites); // Fallback on first
} | php | public function findMostRelevantSiteFor(NodeInterface $node)
{
if ($siteId = $this->findMostRelevantEnabledSiteFor($node)) {
return $siteId;
}
if (empty($node->ucms_allowed_sites)) {
return; // Node cannot be viewed
}
if (in_array($node->site_id, $node->ucms_allowed_sites)) {
// Per default, the primary site seems the best to work with
return $node->site_id;
}
return reset($node->ucms_allowed_sites); // Fallback on first
} | [
"public",
"function",
"findMostRelevantSiteFor",
"(",
"NodeInterface",
"$",
"node",
")",
"{",
"if",
"(",
"$",
"siteId",
"=",
"$",
"this",
"->",
"findMostRelevantEnabledSiteFor",
"(",
"$",
"node",
")",
")",
"{",
"return",
"$",
"siteId",
";",
"}",
"if",
"(",... | Find the most revelant site to view the node in
@param NodeInterface $node
@param bool $onlyEnabled
Search only in enabled sites
@see \MakinaCorpus\Ucms\Site\EventDispatcher\NodeEventSubscriber::onLoad()
@return int
The site identifier is returned, we don't need to load it to build
a node route | [
"Find",
"the",
"most",
"revelant",
"site",
"to",
"view",
"the",
"node",
"in"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/NodeAccessService.php#L65-L80 |
makinacorpus/drupal-ucms | ucms_site/src/NodeAccessService.php | NodeAccessService.userCanReference | public function userCanReference(AccountInterface $account, NodeInterface $node)
{
return $node->access(Permission::VIEW, $account) && $this->manager->getAccess()->userIsWebmaster($account);
} | php | public function userCanReference(AccountInterface $account, NodeInterface $node)
{
return $node->access(Permission::VIEW, $account) && $this->manager->getAccess()->userIsWebmaster($account);
} | [
"public",
"function",
"userCanReference",
"(",
"AccountInterface",
"$",
"account",
",",
"NodeInterface",
"$",
"node",
")",
"{",
"return",
"$",
"node",
"->",
"access",
"(",
"Permission",
"::",
"VIEW",
",",
"$",
"account",
")",
"&&",
"$",
"this",
"->",
"mana... | Can the user reference this node on one of his sites
@param AccountInterface $account
@param NodeInterface $node
@return boolean | [
"Can",
"the",
"user",
"reference",
"this",
"node",
"on",
"one",
"of",
"his",
"sites"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/NodeAccessService.php#L90-L93 |
makinacorpus/drupal-ucms | ucms_site/src/NodeAccessService.php | NodeAccessService.userCanDereference | public function userCanDereference(AccountInterface $account, NodeInterface $node, Site $site)
{
return $node->access(Permission::VIEW, $account) && in_array($site->getId(), $node->ucms_sites) && $this->manager->getAccess()->userIsWebmaster($account, $site);
} | php | public function userCanDereference(AccountInterface $account, NodeInterface $node, Site $site)
{
return $node->access(Permission::VIEW, $account) && in_array($site->getId(), $node->ucms_sites) && $this->manager->getAccess()->userIsWebmaster($account, $site);
} | [
"public",
"function",
"userCanDereference",
"(",
"AccountInterface",
"$",
"account",
",",
"NodeInterface",
"$",
"node",
",",
"Site",
"$",
"site",
")",
"{",
"return",
"$",
"node",
"->",
"access",
"(",
"Permission",
"::",
"VIEW",
",",
"$",
"account",
")",
"&... | Can the user dereference the current content from the given site
@param AccountInterface $account
@param NodeInterface $node
@param Site $site
@return boolean | [
"Can",
"the",
"user",
"dereference",
"the",
"current",
"content",
"from",
"the",
"given",
"site"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/NodeAccessService.php#L104-L107 |
makinacorpus/drupal-ucms | ucms_site/src/NodeAccessService.php | NodeAccessService.userCanCreateInSite | public function userCanCreateInSite(AccountInterface $account, $type, Site $site)
{
// Damn this is ugly
if ($this->manager->hasContext()) {
$previous = $this->manager->getContext();
$this->manager->setContext($site, new Request());
$result = $this->userCanCreate($account, $type);
$this->manager->setContext($previous, new Request());
} else {
$this->manager->setContext($site, new Request());
$result = $this->userCanCreate($account, $type);
$this->manager->dropContext();
}
return $result;
} | php | public function userCanCreateInSite(AccountInterface $account, $type, Site $site)
{
// Damn this is ugly
if ($this->manager->hasContext()) {
$previous = $this->manager->getContext();
$this->manager->setContext($site, new Request());
$result = $this->userCanCreate($account, $type);
$this->manager->setContext($previous, new Request());
} else {
$this->manager->setContext($site, new Request());
$result = $this->userCanCreate($account, $type);
$this->manager->dropContext();
}
return $result;
} | [
"public",
"function",
"userCanCreateInSite",
"(",
"AccountInterface",
"$",
"account",
",",
"$",
"type",
",",
"Site",
"$",
"site",
")",
"{",
"// Damn this is ugly",
"if",
"(",
"$",
"this",
"->",
"manager",
"->",
"hasContext",
"(",
")",
")",
"{",
"$",
"previ... | Can user create nodes with the given type in the given site context
@param AccountInterface $account
@param string $type
@param Site $site
@return bool
@deprecated | [
"Can",
"user",
"create",
"nodes",
"with",
"the",
"given",
"type",
"in",
"the",
"given",
"site",
"context"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/NodeAccessService.php#L133-L147 |
makinacorpus/drupal-ucms | ucms_site/src/NodeAccessService.php | NodeAccessService.userCanCreateInAnySite | public function userCanCreateInAnySite(AccountInterface $account, $type)
{
// Check for global contribs
if ($this->userCanCreate($account, $type)) {
return true;
}
// Iterate over all sites, check if type creation is possible in context
$sites = $this->manager->loadOwnSites($account);
foreach ($sites as $site) {
if ($this->userCanCreateInSite($account, $type, $site)) {
return true;
}
}
return false;
} | php | public function userCanCreateInAnySite(AccountInterface $account, $type)
{
// Check for global contribs
if ($this->userCanCreate($account, $type)) {
return true;
}
// Iterate over all sites, check if type creation is possible in context
$sites = $this->manager->loadOwnSites($account);
foreach ($sites as $site) {
if ($this->userCanCreateInSite($account, $type, $site)) {
return true;
}
}
return false;
} | [
"public",
"function",
"userCanCreateInAnySite",
"(",
"AccountInterface",
"$",
"account",
",",
"$",
"type",
")",
"{",
"// Check for global contribs",
"if",
"(",
"$",
"this",
"->",
"userCanCreate",
"(",
"$",
"account",
",",
"$",
"type",
")",
")",
"{",
"return",
... | Can user create type in our platform
@param \Drupal\Core\Session\AccountInterface $account
@param string $type
@return bool | [
"Can",
"user",
"create",
"type",
"in",
"our",
"platform"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/NodeAccessService.php#L156-L172 |
despark/ignicms | public/admin_assets/plugins/tinymce/plugins/jbimages/ci/application/controllers/uploader.php | Uploader._lang_set | private function _lang_set($lang)
{
// We accept any language set as lang_id in **_dlg.js
// Therefore an error will occur if language file doesn't exist
$this->config->set_item('language', $lang);
$this->lang->load('jbstrings', $lang);
} | php | private function _lang_set($lang)
{
// We accept any language set as lang_id in **_dlg.js
// Therefore an error will occur if language file doesn't exist
$this->config->set_item('language', $lang);
$this->lang->load('jbstrings', $lang);
} | [
"private",
"function",
"_lang_set",
"(",
"$",
"lang",
")",
"{",
"// We accept any language set as lang_id in **_dlg.js",
"// Therefore an error will occur if language file doesn't exist",
"$",
"this",
"->",
"config",
"->",
"set_item",
"(",
"'language'",
",",
"$",
"lang",
")... | /* Language set | [
"/",
"*",
"Language",
"set"
] | train | https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/public/admin_assets/plugins/tinymce/plugins/jbimages/ci/application/controllers/uploader.php#L26-L33 |
despark/ignicms | public/admin_assets/plugins/tinymce/plugins/jbimages/ci/application/controllers/uploader.php | Uploader.upload | public function upload ($lang='english')
{
// Set language
$this->_lang_set($lang);
// Get configuartion data (we fill up 2 arrays - $config and $conf)
$conf['img_path'] = $this->config->item('img_path', 'uploader_settings');
$conf['allow_resize'] = $this->config->item('allow_resize', 'uploader_settings');
$config['allowed_types'] = $this->config->item('allowed_types', 'uploader_settings');
$config['max_size'] = $this->config->item('max_size', 'uploader_settings');
$config['encrypt_name'] = $this->config->item('encrypt_name', 'uploader_settings');
$config['overwrite'] = $this->config->item('overwrite', 'uploader_settings');
$config['upload_path'] = $this->config->item('upload_path', 'uploader_settings');
if (!$conf['allow_resize'])
{
$config['max_width'] = $this->config->item('max_width', 'uploader_settings');
$config['max_height'] = $this->config->item('max_height', 'uploader_settings');
}
else
{
$conf['max_width'] = $this->config->item('max_width', 'uploader_settings');
$conf['max_height'] = $this->config->item('max_height', 'uploader_settings');
if ($conf['max_width'] == 0 and $conf['max_height'] == 0)
{
$conf['allow_resize'] = FALSE;
}
}
// Load uploader
$this->load->library('upload', $config);
if ($this->upload->do_upload()) // Success
{
// General result data
$result = $this->upload->data();
// Shall we resize an image?
if ($conf['allow_resize'] and $conf['max_width'] > 0 and $conf['max_height'] > 0 and (($result['image_width'] > $conf['max_width']) or ($result['image_height'] > $conf['max_height'])))
{
// Resizing parameters
$resizeParams = array
(
'source_image' => $result['full_path'],
'new_image' => $result['full_path'],
'width' => $conf['max_width'],
'height' => $conf['max_height']
);
// Load resize library
$this->load->library('image_lib', $resizeParams);
// Do resize
$this->image_lib->resize();
}
// Add our stuff
$result['result'] = "file_uploaded";
$result['resultcode'] = 'ok';
$result['file_name'] = $conf['img_path'] . '/' . $result['file_name'];
// Output to user
$this->load->view('ajax_upload_result', $result);
}
else // Failure
{
// Compile data for output
$result['result'] = $this->upload->display_errors(' ', ' ');
$result['resultcode'] = 'failed';
// Output to user
$this->load->view('ajax_upload_result', $result);
}
} | php | public function upload ($lang='english')
{
// Set language
$this->_lang_set($lang);
// Get configuartion data (we fill up 2 arrays - $config and $conf)
$conf['img_path'] = $this->config->item('img_path', 'uploader_settings');
$conf['allow_resize'] = $this->config->item('allow_resize', 'uploader_settings');
$config['allowed_types'] = $this->config->item('allowed_types', 'uploader_settings');
$config['max_size'] = $this->config->item('max_size', 'uploader_settings');
$config['encrypt_name'] = $this->config->item('encrypt_name', 'uploader_settings');
$config['overwrite'] = $this->config->item('overwrite', 'uploader_settings');
$config['upload_path'] = $this->config->item('upload_path', 'uploader_settings');
if (!$conf['allow_resize'])
{
$config['max_width'] = $this->config->item('max_width', 'uploader_settings');
$config['max_height'] = $this->config->item('max_height', 'uploader_settings');
}
else
{
$conf['max_width'] = $this->config->item('max_width', 'uploader_settings');
$conf['max_height'] = $this->config->item('max_height', 'uploader_settings');
if ($conf['max_width'] == 0 and $conf['max_height'] == 0)
{
$conf['allow_resize'] = FALSE;
}
}
// Load uploader
$this->load->library('upload', $config);
if ($this->upload->do_upload()) // Success
{
// General result data
$result = $this->upload->data();
// Shall we resize an image?
if ($conf['allow_resize'] and $conf['max_width'] > 0 and $conf['max_height'] > 0 and (($result['image_width'] > $conf['max_width']) or ($result['image_height'] > $conf['max_height'])))
{
// Resizing parameters
$resizeParams = array
(
'source_image' => $result['full_path'],
'new_image' => $result['full_path'],
'width' => $conf['max_width'],
'height' => $conf['max_height']
);
// Load resize library
$this->load->library('image_lib', $resizeParams);
// Do resize
$this->image_lib->resize();
}
// Add our stuff
$result['result'] = "file_uploaded";
$result['resultcode'] = 'ok';
$result['file_name'] = $conf['img_path'] . '/' . $result['file_name'];
// Output to user
$this->load->view('ajax_upload_result', $result);
}
else // Failure
{
// Compile data for output
$result['result'] = $this->upload->display_errors(' ', ' ');
$result['resultcode'] = 'failed';
// Output to user
$this->load->view('ajax_upload_result', $result);
}
} | [
"public",
"function",
"upload",
"(",
"$",
"lang",
"=",
"'english'",
")",
"{",
"// Set language",
"$",
"this",
"->",
"_lang_set",
"(",
"$",
"lang",
")",
";",
"// Get configuartion data (we fill up 2 arrays - $config and $conf)",
"$",
"conf",
"[",
"'img_path'",
"]",
... | /* Default upload routine | [
"/",
"*",
"Default",
"upload",
"routine"
] | train | https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/public/admin_assets/plugins/tinymce/plugins/jbimages/ci/application/controllers/uploader.php#L37-L113 |
makinacorpus/drupal-ucms | ucms_label/src/Form/LabelEdit.php | LabelEdit.buildForm | public function buildForm(array $form, FormStateInterface $form_state, \stdClass $label = null)
{
if ($label === null) {
$label = new \stdClass();
}
$form_state->setTemporaryValue('label', $label);
$form['#form_horizontal'] = true;
$form['name'] = array(
'#type' => 'textfield',
'#title' => $this->t('Name'),
'#default_value' => isset($label->name) ? $label->name : '',
'#maxlength' => 255,
'#required' => true,
'#weight' => -5,
);
// $form['description'] = array(
// '#type' => 'text_format',
// '#title' => $this->t('Description'),
// '#default_value' => isset($label->description) ? $label->description : '',
// '#format' => isset($label->format) ? $label->format : '',
// '#weight' => 0,
// );
// taxonomy_get_tree and taxonomy_get_parents may contain large numbers of
// items so we check for taxonomy_override_selector before loading the
// full vocabulary. Contrib modules can then intercept before
// hook_form_alter to provide scalable alternatives.
if (!variable_get('taxonomy_override_selector', FALSE)) {
$has_children = false;
if (isset($label->tid)) {
$parent = $this->manager->loadParent($label);
$has_children = $this->manager->hasChildren($label);
}
$options = [];
foreach ($this->manager->loadRootLabels() as $root_label) {
if (!isset($label->tid) || $label->tid != $root_label->tid) {
$options[$root_label->tid] = $root_label->name;
}
}
$form['parent'] = array(
'#type' => 'select',
'#title' => $this->t('Parent label'),
'#options' => $options,
'#empty_value' => '0',
'#empty_option' => $this->t("- None -"),
'#default_value' => !empty($parent) ? $parent->tid : null,
'#multiple' => false,
);
if ($has_children) {
$form['parent']['#disabled'] = true;
$form['parent']['#description'] = $this->t("You must move or delete the children labels if you want to define a parent label for this one.");
}
}
if ($this->manager->canEditLockedLabels()) {
$form['locked'] = array(
'#type' => 'checkbox',
'#title' => $this->t('Non editable label'),
'#default_value' => isset($label->is_locked) ? $label->is_locked : 0,
);
if (!$this->manager->canEditNonLockedLabels()) {
$form['locked']['#disabled'] = true;
$form['locked']['#default_value'] = 1;
}
}
$form['actions'] = array(
'#type' => 'actions',
);
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => $this->t('Save'),
);
return $form;
} | php | public function buildForm(array $form, FormStateInterface $form_state, \stdClass $label = null)
{
if ($label === null) {
$label = new \stdClass();
}
$form_state->setTemporaryValue('label', $label);
$form['#form_horizontal'] = true;
$form['name'] = array(
'#type' => 'textfield',
'#title' => $this->t('Name'),
'#default_value' => isset($label->name) ? $label->name : '',
'#maxlength' => 255,
'#required' => true,
'#weight' => -5,
);
// $form['description'] = array(
// '#type' => 'text_format',
// '#title' => $this->t('Description'),
// '#default_value' => isset($label->description) ? $label->description : '',
// '#format' => isset($label->format) ? $label->format : '',
// '#weight' => 0,
// );
// taxonomy_get_tree and taxonomy_get_parents may contain large numbers of
// items so we check for taxonomy_override_selector before loading the
// full vocabulary. Contrib modules can then intercept before
// hook_form_alter to provide scalable alternatives.
if (!variable_get('taxonomy_override_selector', FALSE)) {
$has_children = false;
if (isset($label->tid)) {
$parent = $this->manager->loadParent($label);
$has_children = $this->manager->hasChildren($label);
}
$options = [];
foreach ($this->manager->loadRootLabels() as $root_label) {
if (!isset($label->tid) || $label->tid != $root_label->tid) {
$options[$root_label->tid] = $root_label->name;
}
}
$form['parent'] = array(
'#type' => 'select',
'#title' => $this->t('Parent label'),
'#options' => $options,
'#empty_value' => '0',
'#empty_option' => $this->t("- None -"),
'#default_value' => !empty($parent) ? $parent->tid : null,
'#multiple' => false,
);
if ($has_children) {
$form['parent']['#disabled'] = true;
$form['parent']['#description'] = $this->t("You must move or delete the children labels if you want to define a parent label for this one.");
}
}
if ($this->manager->canEditLockedLabels()) {
$form['locked'] = array(
'#type' => 'checkbox',
'#title' => $this->t('Non editable label'),
'#default_value' => isset($label->is_locked) ? $label->is_locked : 0,
);
if (!$this->manager->canEditNonLockedLabels()) {
$form['locked']['#disabled'] = true;
$form['locked']['#default_value'] = 1;
}
}
$form['actions'] = array(
'#type' => 'actions',
);
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => $this->t('Save'),
);
return $form;
} | [
"public",
"function",
"buildForm",
"(",
"array",
"$",
"form",
",",
"FormStateInterface",
"$",
"form_state",
",",
"\\",
"stdClass",
"$",
"label",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"label",
"===",
"null",
")",
"{",
"$",
"label",
"=",
"new",
"\\",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_label/src/Form/LabelEdit.php#L63-L147 |
makinacorpus/drupal-ucms | ucms_label/src/Form/LabelEdit.php | LabelEdit.submitForm | public function submitForm(array &$form, FormStateInterface $form_state)
{
try {
$label = $form_state->getTemporaryValue('label');
$label->name = $form_state->getValue('name');
$label->is_locked = ($form_state->getValue('locked') === null) ? 0 : $form_state->getValue('locked');
$label->parent = ($parent = $form_state->getValue('parent')) ? $parent : 0;
$label->vid = $this->manager->getVocabularyId();
$label->vocabulary_machine_name = $this->manager->getVocabularyMachineName();
$op = $this->manager->saveLabel($label);
if ($op == SAVED_NEW) {
drupal_set_message($this->t("The new \"@name\" label has been created.", array('@name' => $label->name)));
$this->dispatcher->dispatch('label:add', new ResourceEvent('label', $label->tid, $this->currentUser()->uid));
} else {
drupal_set_message($this->t("The \"@name\" label has been updated.", array('@name' => $label->name)));
$this->dispatcher->dispatch('label:edit', new ResourceEvent('label', $label->tid, $this->currentUser()->uid));
}
}
catch (\Exception $e) {
drupal_set_message($this->t("An error occured during the edition of the \"@name\" label. Please try again.", array('@name' => $label->name)), 'error');
}
$form_state->setRedirect('admin/dashboard/label');
} | php | public function submitForm(array &$form, FormStateInterface $form_state)
{
try {
$label = $form_state->getTemporaryValue('label');
$label->name = $form_state->getValue('name');
$label->is_locked = ($form_state->getValue('locked') === null) ? 0 : $form_state->getValue('locked');
$label->parent = ($parent = $form_state->getValue('parent')) ? $parent : 0;
$label->vid = $this->manager->getVocabularyId();
$label->vocabulary_machine_name = $this->manager->getVocabularyMachineName();
$op = $this->manager->saveLabel($label);
if ($op == SAVED_NEW) {
drupal_set_message($this->t("The new \"@name\" label has been created.", array('@name' => $label->name)));
$this->dispatcher->dispatch('label:add', new ResourceEvent('label', $label->tid, $this->currentUser()->uid));
} else {
drupal_set_message($this->t("The \"@name\" label has been updated.", array('@name' => $label->name)));
$this->dispatcher->dispatch('label:edit', new ResourceEvent('label', $label->tid, $this->currentUser()->uid));
}
}
catch (\Exception $e) {
drupal_set_message($this->t("An error occured during the edition of the \"@name\" label. Please try again.", array('@name' => $label->name)), 'error');
}
$form_state->setRedirect('admin/dashboard/label');
} | [
"public",
"function",
"submitForm",
"(",
"array",
"&",
"$",
"form",
",",
"FormStateInterface",
"$",
"form_state",
")",
"{",
"try",
"{",
"$",
"label",
"=",
"$",
"form_state",
"->",
"getTemporaryValue",
"(",
"'label'",
")",
";",
"$",
"label",
"->",
"name",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_label/src/Form/LabelEdit.php#L153-L178 |
shopgate/cart-integration-sdk | src/models/redirect/DeeplinkSuffix.php | Shopgate_Model_Redirect_DeeplinkSuffix.getValue | public function getValue($type)
{
if (!isset($this->valuesByType[$type]) || ($this->valuesByType[$type] === null)) {
return new Shopgate_Model_Redirect_DeeplinkSuffixValueUnset();
}
if ($this->valuesByType[$type] === false) {
return new Shopgate_Model_Redirect_DeeplinkSuffixValueDisabled();
}
return $this->valuesByType[$type];
} | php | public function getValue($type)
{
if (!isset($this->valuesByType[$type]) || ($this->valuesByType[$type] === null)) {
return new Shopgate_Model_Redirect_DeeplinkSuffixValueUnset();
}
if ($this->valuesByType[$type] === false) {
return new Shopgate_Model_Redirect_DeeplinkSuffixValueDisabled();
}
return $this->valuesByType[$type];
} | [
"public",
"function",
"getValue",
"(",
"$",
"type",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"valuesByType",
"[",
"$",
"type",
"]",
")",
"||",
"(",
"$",
"this",
"->",
"valuesByType",
"[",
"$",
"type",
"]",
"===",
"null",
")",
")... | @param string $type
@return Shopgate_Model_Redirect_DeeplinkSuffixValue | [
"@param",
"string",
"$type"
] | train | https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/models/redirect/DeeplinkSuffix.php#L41-L52 |
aimeos/ai-admin-extadm | controller/extjs/src/Controller/ExtJS/Common/Load/Text/Base.php | Base.importReferences | protected function importReferences( \Aimeos\MShop\Common\Manager\Iface $manager, array $itemTextMap, $domain )
{
$search = $manager->createSearch();
$search->setConditions( $search->compare( '==', $domain . '.code', array_keys( $itemTextMap ) ) );
$search->setSortations( array( $search->sort( '+', $domain . '.id' ) ) );
$start = 0;
$itemIdMap = $itemCodeMap = [];
do
{
$result = $manager->searchItems( $search );
foreach( $result as $item )
{
$itemIdMap[$item->getId()] = $item->getCode();
$itemCodeMap[$item->getCode()] = $item->getId();
}
$count = count( $result );
$start += $count;
$search->setSlice( $start );
}
while( $count > 0 );
$listManager = $manager->getSubManager( 'lists' );
$search = $listManager->createSearch();
$expr = array(
$search->compare( '==', $domain . '.lists.parentid', array_keys( $itemIdMap ) ),
$search->compare( '==', $domain . '.lists.domain', 'text' ),
);
$search->setConditions( $search->combine( '&&', $expr ) );
$search->setSortations( array( $search->sort( '+', $domain . '.lists.id' ) ) );
$start = 0;
do
{
$result = $listManager->searchItems( $search );
foreach( $result as $item ) {
unset( $itemTextMap[$itemIdMap[$item->getParentId()]][$item->getRefId()] );
}
$count = count( $result );
$start += $count;
$search->setSlice( $start );
}
while( $count > 0 );
$listTypes = $this->getTextListTypes( $manager, $domain );
foreach( $itemTextMap as $itemCode => $textIds )
{
foreach( $textIds as $textId => $listType )
{
try
{
$iface = '\\Aimeos\\MShop\\Common\\Item\\Type\\Iface';
if( !isset( $listTypes[$listType] ) || ( $listTypes[$listType] instanceof $iface ) === false ) {
throw new \Aimeos\Controller\ExtJS\Exception( sprintf( 'Invalid list type "%1$s"', $listType ) );
}
$item = $listManager->createItem();
$item->setParentId( $itemCodeMap[$itemCode] );
$item->setTypeId( $listTypes[$listType]->getId() );
$item->setDomain( 'text' );
$item->setRefId( $textId );
$listManager->saveItem( $item, false );
}
catch( \Exception $e ) {
$this->getContext()->getLogger()->log( 'text reference: ' . $e->getMessage(), \Aimeos\MW\Logger\Base::ERR, 'import' );
}
}
}
} | php | protected function importReferences( \Aimeos\MShop\Common\Manager\Iface $manager, array $itemTextMap, $domain )
{
$search = $manager->createSearch();
$search->setConditions( $search->compare( '==', $domain . '.code', array_keys( $itemTextMap ) ) );
$search->setSortations( array( $search->sort( '+', $domain . '.id' ) ) );
$start = 0;
$itemIdMap = $itemCodeMap = [];
do
{
$result = $manager->searchItems( $search );
foreach( $result as $item )
{
$itemIdMap[$item->getId()] = $item->getCode();
$itemCodeMap[$item->getCode()] = $item->getId();
}
$count = count( $result );
$start += $count;
$search->setSlice( $start );
}
while( $count > 0 );
$listManager = $manager->getSubManager( 'lists' );
$search = $listManager->createSearch();
$expr = array(
$search->compare( '==', $domain . '.lists.parentid', array_keys( $itemIdMap ) ),
$search->compare( '==', $domain . '.lists.domain', 'text' ),
);
$search->setConditions( $search->combine( '&&', $expr ) );
$search->setSortations( array( $search->sort( '+', $domain . '.lists.id' ) ) );
$start = 0;
do
{
$result = $listManager->searchItems( $search );
foreach( $result as $item ) {
unset( $itemTextMap[$itemIdMap[$item->getParentId()]][$item->getRefId()] );
}
$count = count( $result );
$start += $count;
$search->setSlice( $start );
}
while( $count > 0 );
$listTypes = $this->getTextListTypes( $manager, $domain );
foreach( $itemTextMap as $itemCode => $textIds )
{
foreach( $textIds as $textId => $listType )
{
try
{
$iface = '\\Aimeos\\MShop\\Common\\Item\\Type\\Iface';
if( !isset( $listTypes[$listType] ) || ( $listTypes[$listType] instanceof $iface ) === false ) {
throw new \Aimeos\Controller\ExtJS\Exception( sprintf( 'Invalid list type "%1$s"', $listType ) );
}
$item = $listManager->createItem();
$item->setParentId( $itemCodeMap[$itemCode] );
$item->setTypeId( $listTypes[$listType]->getId() );
$item->setDomain( 'text' );
$item->setRefId( $textId );
$listManager->saveItem( $item, false );
}
catch( \Exception $e ) {
$this->getContext()->getLogger()->log( 'text reference: ' . $e->getMessage(), \Aimeos\MW\Logger\Base::ERR, 'import' );
}
}
}
} | [
"protected",
"function",
"importReferences",
"(",
"\\",
"Aimeos",
"\\",
"MShop",
"\\",
"Common",
"\\",
"Manager",
"\\",
"Iface",
"$",
"manager",
",",
"array",
"$",
"itemTextMap",
",",
"$",
"domain",
")",
"{",
"$",
"search",
"=",
"$",
"manager",
"->",
"cr... | Associates the texts with the products.
@param \Aimeos\MShop\Common\Manager\Iface $manager Manager object (attribute, product, etc.) for associating the list items
@param array $itemTextMap Two dimensional associated list of codes and text IDs as key
@param string $domain Name of the domain this text belongs to, e.g. product, catalog, attribute | [
"Associates",
"the",
"texts",
"with",
"the",
"products",
"."
] | train | https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Common/Load/Text/Base.php#L106-L185 |
aimeos/ai-admin-extadm | controller/extjs/src/Controller/ExtJS/Common/Load/Text/Base.php | Base.getTextListTypes | protected function getTextListTypes( \Aimeos\MShop\Common\Manager\Iface $manager, $domain )
{
if( isset( $this->textListTypes[$domain] ) ) {
return $this->textListTypes[$domain];
}
$this->textListTypes[$domain] = [];
$typeManager = $manager->getSubManager( 'lists' )->getSubManager( 'type' );
$search = $typeManager->createSearch();
$search->setConditions( $search->compare( '==', $domain . '.lists.type.domain', 'text' ) );
$search->setSortations( array( $search->sort( '+', $domain . '.lists.type.code' ) ) );
$start = 0;
do
{
$result = $typeManager->searchItems( $search );
foreach( $result as $typeItem ) {
$this->textListTypes[$domain][$typeItem->getCode()] = $typeItem;
}
$count = count( $result );
$start += $count;
$search->setSlice( $start );
}
while( $count > 0 );
return $this->textListTypes[$domain];
} | php | protected function getTextListTypes( \Aimeos\MShop\Common\Manager\Iface $manager, $domain )
{
if( isset( $this->textListTypes[$domain] ) ) {
return $this->textListTypes[$domain];
}
$this->textListTypes[$domain] = [];
$typeManager = $manager->getSubManager( 'lists' )->getSubManager( 'type' );
$search = $typeManager->createSearch();
$search->setConditions( $search->compare( '==', $domain . '.lists.type.domain', 'text' ) );
$search->setSortations( array( $search->sort( '+', $domain . '.lists.type.code' ) ) );
$start = 0;
do
{
$result = $typeManager->searchItems( $search );
foreach( $result as $typeItem ) {
$this->textListTypes[$domain][$typeItem->getCode()] = $typeItem;
}
$count = count( $result );
$start += $count;
$search->setSlice( $start );
}
while( $count > 0 );
return $this->textListTypes[$domain];
} | [
"protected",
"function",
"getTextListTypes",
"(",
"\\",
"Aimeos",
"\\",
"MShop",
"\\",
"Common",
"\\",
"Manager",
"\\",
"Iface",
"$",
"manager",
",",
"$",
"domain",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"textListTypes",
"[",
"$",
"domain"... | Returns a list of list type items.
@param \Aimeos\MShop\Common\Manager\Iface $manager Manager object (attribute, product, etc.)
@param string $domain Domain the list items must be associated to
@return array Associative list of list type codes and items implementing \Aimeos\MShop\Common\Item\Type\Iface | [
"Returns",
"a",
"list",
"of",
"list",
"type",
"items",
"."
] | train | https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Common/Load/Text/Base.php#L195-L226 |
aimeos/ai-admin-extadm | controller/extjs/src/Controller/ExtJS/Common/Load/Text/Base.php | Base.getTextTypes | protected function getTextTypes( $domain )
{
if( isset( $this->textTypes[$domain] ) ) {
return $this->textTypes[$domain];
}
$this->textTypes[$domain] = [];
$textManager = \Aimeos\MShop\Text\Manager\Factory::createManager( $this->getContext() );
$manager = $textManager->getSubManager( 'type' );
$search = $manager->createSearch();
$search->setConditions( $search->compare( '==', 'text.type.domain', $domain ) );
$search->setSortations( array( $search->sort( '+', 'text.type.code' ) ) );
$start = 0;
do
{
$result = $manager->searchItems( $search );
$this->textTypes[$domain] = array_merge( $this->textTypes[$domain], $result );
$count = count( $result );
$start += $count;
$search->setSlice( $start );
}
while( $count > 0 );
return $this->textTypes[$domain];
} | php | protected function getTextTypes( $domain )
{
if( isset( $this->textTypes[$domain] ) ) {
return $this->textTypes[$domain];
}
$this->textTypes[$domain] = [];
$textManager = \Aimeos\MShop\Text\Manager\Factory::createManager( $this->getContext() );
$manager = $textManager->getSubManager( 'type' );
$search = $manager->createSearch();
$search->setConditions( $search->compare( '==', 'text.type.domain', $domain ) );
$search->setSortations( array( $search->sort( '+', 'text.type.code' ) ) );
$start = 0;
do
{
$result = $manager->searchItems( $search );
$this->textTypes[$domain] = array_merge( $this->textTypes[$domain], $result );
$count = count( $result );
$start += $count;
$search->setSlice( $start );
}
while( $count > 0 );
return $this->textTypes[$domain];
} | [
"protected",
"function",
"getTextTypes",
"(",
"$",
"domain",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"textTypes",
"[",
"$",
"domain",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"textTypes",
"[",
"$",
"domain",
"]",
";",
"}",
"$"... | Returns a list of text type items.
@param string $domain Domain the text items must be associated to
@return array List of text type items implementing \Aimeos\MShop\Common\Item\Type\Iface | [
"Returns",
"a",
"list",
"of",
"text",
"type",
"items",
"."
] | train | https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Common/Load/Text/Base.php#L235-L265 |
aimeos/ai-admin-extadm | controller/extjs/src/Controller/ExtJS/Common/Load/Text/Base.php | Base.setLocale | protected function setLocale( $site )
{
$context = $this->getContext();
$locale = $context->getLocale();
$siteItem = null;
$siteManager = \Aimeos\MShop\Locale\Manager\Factory::createManager( $context )->getSubManager( 'site' );
if( $site != '' )
{
$search = $siteManager->createSearch();
$search->setConditions( $search->compare( '==', 'locale.site.code', $site ) );
$sites = $siteManager->searchItems( $search );
if( ( $siteItem = reset( $sites ) ) === false ) {
throw new \Aimeos\Controller\ExtJS\Exception( 'Site item not found.' );
}
}
$localeItem = new \Aimeos\MShop\Locale\Item\Standard( [], $siteItem );
$localeItem->setLanguageId( $locale->getLanguageId() );
$localeItem->setCurrencyId( $locale->getCurrencyId() );
if( $siteItem !== null ) {
$localeItem->setSiteId( $siteItem->getId() );
}
$context->setLocale( $localeItem );
} | php | protected function setLocale( $site )
{
$context = $this->getContext();
$locale = $context->getLocale();
$siteItem = null;
$siteManager = \Aimeos\MShop\Locale\Manager\Factory::createManager( $context )->getSubManager( 'site' );
if( $site != '' )
{
$search = $siteManager->createSearch();
$search->setConditions( $search->compare( '==', 'locale.site.code', $site ) );
$sites = $siteManager->searchItems( $search );
if( ( $siteItem = reset( $sites ) ) === false ) {
throw new \Aimeos\Controller\ExtJS\Exception( 'Site item not found.' );
}
}
$localeItem = new \Aimeos\MShop\Locale\Item\Standard( [], $siteItem );
$localeItem->setLanguageId( $locale->getLanguageId() );
$localeItem->setCurrencyId( $locale->getCurrencyId() );
if( $siteItem !== null ) {
$localeItem->setSiteId( $siteItem->getId() );
}
$context->setLocale( $localeItem );
} | [
"protected",
"function",
"setLocale",
"(",
"$",
"site",
")",
"{",
"$",
"context",
"=",
"$",
"this",
"->",
"getContext",
"(",
")",
";",
"$",
"locale",
"=",
"$",
"context",
"->",
"getLocale",
"(",
")",
";",
"$",
"siteItem",
"=",
"null",
";",
"$",
"si... | Creates a new locale object and adds this object to the context.
@param string $site Site code | [
"Creates",
"a",
"new",
"locale",
"object",
"and",
"adds",
"this",
"object",
"to",
"the",
"context",
"."
] | train | https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Common/Load/Text/Base.php#L273-L301 |
aimeos/ai-admin-extadm | controller/extjs/src/Controller/ExtJS/Common/Load/Text/Base.php | Base.storeFile | protected function storeFile( \Psr\Http\Message\ServerRequestInterface $request, &$clientFilename = '' )
{
$context = $this->getContext();
$files = (array) $request->getUploadedFiles();
if( ( $file = reset( $files ) ) === false || $file->getError() !== UPLOAD_ERR_OK ) {
throw new \Aimeos\Controller\ExtJS\Exception( 'No file was uploaded or an error occured' );
}
$clientFilename = $file->getClientFilename();
$fileext = pathinfo( $clientFilename, PATHINFO_EXTENSION );
$dest = md5( $clientFilename . time() . getmypid() ) . '.' . $fileext;
$fs = $context->getFilesystemManager()->get( 'fs-admin' );
$fs->writes( $dest, $file->getStream()->detach() );
return $dest;
} | php | protected function storeFile( \Psr\Http\Message\ServerRequestInterface $request, &$clientFilename = '' )
{
$context = $this->getContext();
$files = (array) $request->getUploadedFiles();
if( ( $file = reset( $files ) ) === false || $file->getError() !== UPLOAD_ERR_OK ) {
throw new \Aimeos\Controller\ExtJS\Exception( 'No file was uploaded or an error occured' );
}
$clientFilename = $file->getClientFilename();
$fileext = pathinfo( $clientFilename, PATHINFO_EXTENSION );
$dest = md5( $clientFilename . time() . getmypid() ) . '.' . $fileext;
$fs = $context->getFilesystemManager()->get( 'fs-admin' );
$fs->writes( $dest, $file->getStream()->detach() );
return $dest;
} | [
"protected",
"function",
"storeFile",
"(",
"\\",
"Psr",
"\\",
"Http",
"\\",
"Message",
"\\",
"ServerRequestInterface",
"$",
"request",
",",
"&",
"$",
"clientFilename",
"=",
"''",
")",
"{",
"$",
"context",
"=",
"$",
"this",
"->",
"getContext",
"(",
")",
"... | Stores the uploaded file and returns the path to this file
@param \Psr\Http\Message\ServerRequestInterface $request PSR-7 request object
@param string $clientFilename Result parameter for the file name sent by the client
@throws \Aimeos\Controller\ExtJS\Exception If no file was uploaded or an error occured
@return string Path to the stored file | [
"Stores",
"the",
"uploaded",
"file",
"and",
"returns",
"the",
"path",
"to",
"this",
"file"
] | train | https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Common/Load/Text/Base.php#L312-L329 |
aimeos/ai-admin-extadm | controller/extjs/src/Controller/ExtJS/Common/Load/Text/Base.php | Base.importTextsFromContent | protected function importTextsFromContent( \Aimeos\MW\Container\Content\Iface $contentItem, array $textTypeMap, $domain )
{
$count = 0;
$codeIdMap = [];
$context = $this->getContext();
$textManager = \Aimeos\MShop\Text\Manager\Factory::createManager( $context );
$manager = \Aimeos\MShop\Factory::createManager( $context, $domain );
$contentItem->next(); // skip description row
while( ( $row = $contentItem->current() ) !== null )
{
$codeIdMap = $this->importTextRow( $textManager, $row, $textTypeMap, $codeIdMap, $domain );
if( ++$count == 1000 )
{
$this->importReferences( $manager, $codeIdMap, $domain );
$codeIdMap = [];
$count = 0;
}
$contentItem->next();
}
if( !empty( $codeIdMap ) ) {
$this->importReferences( $manager, $codeIdMap, $domain );
}
} | php | protected function importTextsFromContent( \Aimeos\MW\Container\Content\Iface $contentItem, array $textTypeMap, $domain )
{
$count = 0;
$codeIdMap = [];
$context = $this->getContext();
$textManager = \Aimeos\MShop\Text\Manager\Factory::createManager( $context );
$manager = \Aimeos\MShop\Factory::createManager( $context, $domain );
$contentItem->next(); // skip description row
while( ( $row = $contentItem->current() ) !== null )
{
$codeIdMap = $this->importTextRow( $textManager, $row, $textTypeMap, $codeIdMap, $domain );
if( ++$count == 1000 )
{
$this->importReferences( $manager, $codeIdMap, $domain );
$codeIdMap = [];
$count = 0;
}
$contentItem->next();
}
if( !empty( $codeIdMap ) ) {
$this->importReferences( $manager, $codeIdMap, $domain );
}
} | [
"protected",
"function",
"importTextsFromContent",
"(",
"\\",
"Aimeos",
"\\",
"MW",
"\\",
"Container",
"\\",
"Content",
"\\",
"Iface",
"$",
"contentItem",
",",
"array",
"$",
"textTypeMap",
",",
"$",
"domain",
")",
"{",
"$",
"count",
"=",
"0",
";",
"$",
"... | Imports the text content using the given text types.
@param \Aimeos\MW\Container\Content\Iface $contentItem Content item containing texts and associated data
@param array $textTypeMap Associative list of text type IDs as keys and text type codes as values
@param string $domain Name of the domain this text belongs to, e.g. product, catalog, attribute
@return void | [
"Imports",
"the",
"text",
"content",
"using",
"the",
"given",
"text",
"types",
"."
] | train | https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Common/Load/Text/Base.php#L340-L367 |
aimeos/ai-admin-extadm | controller/extjs/src/Controller/ExtJS/Common/Load/Text/Base.php | Base.importTextRow | private function importTextRow( \Aimeos\MShop\Common\Manager\Iface $textManager, array $row, array $textTypeMap,
array $codeIdMap, $domain )
{
if( count( $row ) !== 7 )
{
$msg = sprintf( 'Invalid row from %1$s text import: %2$s', $domain, print_r( $row, true ) );
$this->getContext()->getLogger()->log( $msg, \Aimeos\MW\Logger\Base::WARN, 'import' );
}
try
{
$textType = isset( $row[4] ) ? $row[4] : null;
if( !isset( $textTypeMap[$textType] ) ) {
throw new \Aimeos\Controller\ExtJS\Exception( sprintf( 'Invalid text type "%1$s"', $textType ) );
}
$codeIdMap = $this->saveTextItem( $textManager, $row, $textTypeMap, $codeIdMap, $domain );
}
catch( \Exception $e )
{
$msg = sprintf( 'Error in %1$s text import: %2$s', $domain, $e->getMessage() );
$this->getContext()->getLogger()->log( $msg, \Aimeos\MW\Logger\Base::ERR, 'import' );
}
return $codeIdMap;
} | php | private function importTextRow( \Aimeos\MShop\Common\Manager\Iface $textManager, array $row, array $textTypeMap,
array $codeIdMap, $domain )
{
if( count( $row ) !== 7 )
{
$msg = sprintf( 'Invalid row from %1$s text import: %2$s', $domain, print_r( $row, true ) );
$this->getContext()->getLogger()->log( $msg, \Aimeos\MW\Logger\Base::WARN, 'import' );
}
try
{
$textType = isset( $row[4] ) ? $row[4] : null;
if( !isset( $textTypeMap[$textType] ) ) {
throw new \Aimeos\Controller\ExtJS\Exception( sprintf( 'Invalid text type "%1$s"', $textType ) );
}
$codeIdMap = $this->saveTextItem( $textManager, $row, $textTypeMap, $codeIdMap, $domain );
}
catch( \Exception $e )
{
$msg = sprintf( 'Error in %1$s text import: %2$s', $domain, $e->getMessage() );
$this->getContext()->getLogger()->log( $msg, \Aimeos\MW\Logger\Base::ERR, 'import' );
}
return $codeIdMap;
} | [
"private",
"function",
"importTextRow",
"(",
"\\",
"Aimeos",
"\\",
"MShop",
"\\",
"Common",
"\\",
"Manager",
"\\",
"Iface",
"$",
"textManager",
",",
"array",
"$",
"row",
",",
"array",
"$",
"textTypeMap",
",",
"array",
"$",
"codeIdMap",
",",
"$",
"domain",
... | Inserts a single text item from the given import row.
@param \Aimeos\MShop\Common\Manager\Iface $textManager Text manager object
@param array $row Row from import file
@param array $codeIdMap Two dimensional associated list of codes and text IDs as key
@param array $textTypeMap Associative list of text type IDs as keys and text type codes as values
@param string $domain Name of the domain this text belongs to, e.g. product, catalog, attribute
@throws \Aimeos\Controller\ExtJS\Exception If text type is invalid | [
"Inserts",
"a",
"single",
"text",
"item",
"from",
"the",
"given",
"import",
"row",
"."
] | train | https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Common/Load/Text/Base.php#L380-L406 |
aimeos/ai-admin-extadm | controller/extjs/src/Controller/ExtJS/Common/Load/Text/Base.php | Base.saveTextItem | private function saveTextItem( \Aimeos\MShop\Common\Manager\Iface $textManager, array $row,
array $textTypeMap, array $codeIdMap, $domain )
{
$value = isset( $row[6] ) ? $row[6] : '';
$textId = isset( $row[5] ) ? $row[5] : '';
if( $textId != '' || $value != '' )
{
$item = $textManager->createItem();
if( $textId != '' ) {
$item->setId( $textId );
}
$item->setLanguageId( ( $row[0] != '' ? $row[0] : null ) );
$item->setTypeId( $textTypeMap[$row[4]] );
$item->setDomain( $domain );
$item->setLabel( mb_strcut( $value, 0, 255 ) );
$item->setContent( $value );
$item->setStatus( 1 );
$item = $textManager->saveItem( $item );
$codeIdMap[$row[2]][$item->getId()] = $row[3];
}
return $codeIdMap;
} | php | private function saveTextItem( \Aimeos\MShop\Common\Manager\Iface $textManager, array $row,
array $textTypeMap, array $codeIdMap, $domain )
{
$value = isset( $row[6] ) ? $row[6] : '';
$textId = isset( $row[5] ) ? $row[5] : '';
if( $textId != '' || $value != '' )
{
$item = $textManager->createItem();
if( $textId != '' ) {
$item->setId( $textId );
}
$item->setLanguageId( ( $row[0] != '' ? $row[0] : null ) );
$item->setTypeId( $textTypeMap[$row[4]] );
$item->setDomain( $domain );
$item->setLabel( mb_strcut( $value, 0, 255 ) );
$item->setContent( $value );
$item->setStatus( 1 );
$item = $textManager->saveItem( $item );
$codeIdMap[$row[2]][$item->getId()] = $row[3];
}
return $codeIdMap;
} | [
"private",
"function",
"saveTextItem",
"(",
"\\",
"Aimeos",
"\\",
"MShop",
"\\",
"Common",
"\\",
"Manager",
"\\",
"Iface",
"$",
"textManager",
",",
"array",
"$",
"row",
",",
"array",
"$",
"textTypeMap",
",",
"array",
"$",
"codeIdMap",
",",
"$",
"domain",
... | Saves a text item from the given data.
@param \Aimeos\MShop\Common\Manager\Iface $textManager Text manager object
@param array $row Row from import file
@param array $textTypeMap Associative list of text type IDs as keys and text type codes as values
@param array $codeIdMap Two dimensional associated list of codes and text IDs as key
@param string $domain Name of the domain this text belongs to, e.g. product, catalog, attribute
@return array Updated two dimensional associated list of codes and text IDs as key | [
"Saves",
"a",
"text",
"item",
"from",
"the",
"given",
"data",
"."
] | train | https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Common/Load/Text/Base.php#L419-L446 |
aimeos/ai-admin-extadm | controller/extjs/src/Controller/ExtJS/Common/Load/Text/Base.php | Base.createContainer | protected function createContainer( $resource, $key )
{
$config = $this->getContext()->getConfig();
$type = $config->get( $key . '/type', 'Zip' );
$format = $config->get( $key . '/format', 'CSV' );
$options = $config->get( $key . '/options', [] );
return \Aimeos\MW\Container\Factory::getContainer( $resource, $type, $format, $options );
} | php | protected function createContainer( $resource, $key )
{
$config = $this->getContext()->getConfig();
$type = $config->get( $key . '/type', 'Zip' );
$format = $config->get( $key . '/format', 'CSV' );
$options = $config->get( $key . '/options', [] );
return \Aimeos\MW\Container\Factory::getContainer( $resource, $type, $format, $options );
} | [
"protected",
"function",
"createContainer",
"(",
"$",
"resource",
",",
"$",
"key",
")",
"{",
"$",
"config",
"=",
"$",
"this",
"->",
"getContext",
"(",
")",
"->",
"getConfig",
"(",
")",
";",
"$",
"type",
"=",
"$",
"config",
"->",
"get",
"(",
"$",
"k... | Creates container for storing export files.
@param string $resource Path to the file
@param string $key Configuration key prefix for the container type/format/options keys
@return \Aimeos\MW\Container\Iface Container item | [
"Creates",
"container",
"for",
"storing",
"export",
"files",
"."
] | train | https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Common/Load/Text/Base.php#L456-L465 |
makinacorpus/drupal-ucms | ucms_contrib/src/Datasource/NodeDatasource.php | NodeDatasource.getFilters | public function getFilters()
{
$ret = parent::getFilters();
$ret[] = (new Filter('is_global', $this->t("Global")))->setChoicesMap([1 => t("Yes"), 0 => t("No")]);
$ret[] = (new Filter('is_flagged', $this->t("Flagged")))->setChoicesMap([1 => t("Yes"), 0 => t("No")]);
$ret[] = (new Filter('is_starred', $this->t("Starred")))->setChoicesMap([1 => t("Yes"), 0 => t("No")]);
$ret[] = (new Filter('is_clonable', $this->t("Locked")))->setChoicesMap([0 => t("Yes"), 1 => t("No")]);
$ret[] = (new Filter('is_corporate', $this->t("Corporate")))->setChoicesMap([1 => t("Yes"), 0 => t("No")]);
// @todo site_id
// @todo in my cart
return $ret;
} | php | public function getFilters()
{
$ret = parent::getFilters();
$ret[] = (new Filter('is_global', $this->t("Global")))->setChoicesMap([1 => t("Yes"), 0 => t("No")]);
$ret[] = (new Filter('is_flagged', $this->t("Flagged")))->setChoicesMap([1 => t("Yes"), 0 => t("No")]);
$ret[] = (new Filter('is_starred', $this->t("Starred")))->setChoicesMap([1 => t("Yes"), 0 => t("No")]);
$ret[] = (new Filter('is_clonable', $this->t("Locked")))->setChoicesMap([0 => t("Yes"), 1 => t("No")]);
$ret[] = (new Filter('is_corporate', $this->t("Corporate")))->setChoicesMap([1 => t("Yes"), 0 => t("No")]);
// @todo site_id
// @todo in my cart
return $ret;
} | [
"public",
"function",
"getFilters",
"(",
")",
"{",
"$",
"ret",
"=",
"parent",
"::",
"getFilters",
"(",
")",
";",
"$",
"ret",
"[",
"]",
"=",
"(",
"new",
"Filter",
"(",
"'is_global'",
",",
"$",
"this",
"->",
"t",
"(",
"\"Global\"",
")",
")",
")",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_contrib/src/Datasource/NodeDatasource.php#L37-L50 |
makinacorpus/drupal-ucms | ucms_contrib/src/Datasource/NodeDatasource.php | NodeDatasource.preloadDependencies | function preloadDependencies(array $nodeIdList)
{
$siteIdList = [];
$nodeList = parent::preloadDependencies($nodeIdList);
foreach ($nodeList as $node) {
foreach ($node->ucms_sites as $siteId) {
$siteIdList[$siteId] = $siteId;
}
}
if ($siteIdList) {
$this->siteManager->getStorage()->loadAll($siteIdList);
}
return $nodeList;
} | php | function preloadDependencies(array $nodeIdList)
{
$siteIdList = [];
$nodeList = parent::preloadDependencies($nodeIdList);
foreach ($nodeList as $node) {
foreach ($node->ucms_sites as $siteId) {
$siteIdList[$siteId] = $siteId;
}
}
if ($siteIdList) {
$this->siteManager->getStorage()->loadAll($siteIdList);
}
return $nodeList;
} | [
"function",
"preloadDependencies",
"(",
"array",
"$",
"nodeIdList",
")",
"{",
"$",
"siteIdList",
"=",
"[",
"]",
";",
"$",
"nodeList",
"=",
"parent",
"::",
"preloadDependencies",
"(",
"$",
"nodeIdList",
")",
";",
"foreach",
"(",
"$",
"nodeList",
"as",
"$",
... | Preload pretty much everything to make admin listing faster
You should call this.
@param int[] $nodeIdList
@return NodeInterface[]
The loaded nodes | [
"Preload",
"pretty",
"much",
"everything",
"to",
"make",
"admin",
"listing",
"faster"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_contrib/src/Datasource/NodeDatasource.php#L82-L99 |
makinacorpus/drupal-ucms | ucms_contrib/src/Datasource/NodeDatasource.php | NodeDatasource.applyFilters | protected function applyFilters(\SelectQuery $select, Query $query)
{
parent::applyFilters($select, $query);
if ($query->has('is_global')) {
$select->condition('n.is_global', $query->get('is_global'));
}
if ($query->has('is_flagged')) {
$select->condition('n.is_flagged', $query->get('is_flagged'));
}
if ($query->has('is_starred')) {
$select->condition('n.is_starred', $query->get('is_starred'));
}
if ($query->has('is_clonable')) {
$select->condition('n.is_clonable', $query->get('is_clonable'));
}
if ($this->isSiteContextDependent()) {
$select->addTag(Access::QUERY_TAG_CONTEXT_OPT_OUT);
}
} | php | protected function applyFilters(\SelectQuery $select, Query $query)
{
parent::applyFilters($select, $query);
if ($query->has('is_global')) {
$select->condition('n.is_global', $query->get('is_global'));
}
if ($query->has('is_flagged')) {
$select->condition('n.is_flagged', $query->get('is_flagged'));
}
if ($query->has('is_starred')) {
$select->condition('n.is_starred', $query->get('is_starred'));
}
if ($query->has('is_clonable')) {
$select->condition('n.is_clonable', $query->get('is_clonable'));
}
if ($this->isSiteContextDependent()) {
$select->addTag(Access::QUERY_TAG_CONTEXT_OPT_OUT);
}
} | [
"protected",
"function",
"applyFilters",
"(",
"\\",
"SelectQuery",
"$",
"select",
",",
"Query",
"$",
"query",
")",
"{",
"parent",
"::",
"applyFilters",
"(",
"$",
"select",
",",
"$",
"query",
")",
";",
"if",
"(",
"$",
"query",
"->",
"has",
"(",
"'is_glo... | {@inheritdoc} | [
"{"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_contrib/src/Datasource/NodeDatasource.php#L104-L124 |
accompli/accompli | src/Deployment/Connection/SSHConnectionAdapter.php | SSHConnectionAdapter.connect | public function connect()
{
if ($this->isConnected()) {
return true;
}
$this->connection = new SFTP($this->hostname);
return $this->connection->login($this->authenticationUsername, $this->authenticationCredentials);
} | php | public function connect()
{
if ($this->isConnected()) {
return true;
}
$this->connection = new SFTP($this->hostname);
return $this->connection->login($this->authenticationUsername, $this->authenticationCredentials);
} | [
"public",
"function",
"connect",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isConnected",
"(",
")",
")",
"{",
"return",
"true",
";",
"}",
"$",
"this",
"->",
"connection",
"=",
"new",
"SFTP",
"(",
"$",
"this",
"->",
"hostname",
")",
";",
"return"... | {@inheritdoc} | [
"{"
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Deployment/Connection/SSHConnectionAdapter.php#L99-L108 |
accompli/accompli | src/Deployment/Connection/SSHConnectionAdapter.php | SSHConnectionAdapter.changeWorkingDirectory | public function changeWorkingDirectory($remoteDirectory)
{
if ($this->isConnected()) {
$this->executeCommand('cd', array($remoteDirectory));
return $this->connection->chdir($remoteDirectory);
}
return false;
} | php | public function changeWorkingDirectory($remoteDirectory)
{
if ($this->isConnected()) {
$this->executeCommand('cd', array($remoteDirectory));
return $this->connection->chdir($remoteDirectory);
}
return false;
} | [
"public",
"function",
"changeWorkingDirectory",
"(",
"$",
"remoteDirectory",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isConnected",
"(",
")",
")",
"{",
"$",
"this",
"->",
"executeCommand",
"(",
"'cd'",
",",
"array",
"(",
"$",
"remoteDirectory",
")",
")",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Deployment/Connection/SSHConnectionAdapter.php#L187-L196 |
accompli/accompli | src/Deployment/Connection/SSHConnectionAdapter.php | SSHConnectionAdapter.executeCommand | public function executeCommand($command, array $arguments = array())
{
if ($this->isConnected()) {
$this->connection->enableQuietMode();
$this->connection->setTimeout(0);
if (empty($arguments) === false) {
$command = ProcessUtility::escapeArguments($arguments, $command);
}
if (isset($this->connection->server_channels[SFTP::CHANNEL_SHELL]) === false) {
$this->connection->read($this->getShellPromptRegex(), SFTP::READ_REGEX);
}
$this->connection->write($command."\n");
$output = $this->getFilteredOutput($this->connection->read($this->getShellPromptRegex(), SFTP::READ_REGEX), $command);
$this->connection->write("echo $?\n");
$exitCode = intval($this->getFilteredOutput($this->connection->read($this->getShellPromptRegex(), SFTP::READ_REGEX), 'echo $?'));
$errorOutput = strval($this->connection->getStdError());
$this->connection->disableQuietMode();
return new ProcessExecutionResult($exitCode, $output, $errorOutput);
}
return new ProcessExecutionResult(126, '', "Connection adapter not connected.\n");
} | php | public function executeCommand($command, array $arguments = array())
{
if ($this->isConnected()) {
$this->connection->enableQuietMode();
$this->connection->setTimeout(0);
if (empty($arguments) === false) {
$command = ProcessUtility::escapeArguments($arguments, $command);
}
if (isset($this->connection->server_channels[SFTP::CHANNEL_SHELL]) === false) {
$this->connection->read($this->getShellPromptRegex(), SFTP::READ_REGEX);
}
$this->connection->write($command."\n");
$output = $this->getFilteredOutput($this->connection->read($this->getShellPromptRegex(), SFTP::READ_REGEX), $command);
$this->connection->write("echo $?\n");
$exitCode = intval($this->getFilteredOutput($this->connection->read($this->getShellPromptRegex(), SFTP::READ_REGEX), 'echo $?'));
$errorOutput = strval($this->connection->getStdError());
$this->connection->disableQuietMode();
return new ProcessExecutionResult($exitCode, $output, $errorOutput);
}
return new ProcessExecutionResult(126, '', "Connection adapter not connected.\n");
} | [
"public",
"function",
"executeCommand",
"(",
"$",
"command",
",",
"array",
"$",
"arguments",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isConnected",
"(",
")",
")",
"{",
"$",
"this",
"->",
"connection",
"->",
"enableQuietMode",
"(... | {@inheritdoc} | [
"{"
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Deployment/Connection/SSHConnectionAdapter.php#L201-L229 |
accompli/accompli | src/Deployment/Connection/SSHConnectionAdapter.php | SSHConnectionAdapter.getDirectoryContentsList | public function getDirectoryContentsList($remoteDirectory)
{
if ($this->isConnected()) {
$contentsList = array_values(array_diff($this->connection->nlist($remoteDirectory), array('.', '..')));
sort($contentsList);
return $contentsList;
}
return array();
} | php | public function getDirectoryContentsList($remoteDirectory)
{
if ($this->isConnected()) {
$contentsList = array_values(array_diff($this->connection->nlist($remoteDirectory), array('.', '..')));
sort($contentsList);
return $contentsList;
}
return array();
} | [
"public",
"function",
"getDirectoryContentsList",
"(",
"$",
"remoteDirectory",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isConnected",
"(",
")",
")",
"{",
"$",
"contentsList",
"=",
"array_values",
"(",
"array_diff",
"(",
"$",
"this",
"->",
"connection",
"->",... | {@inheritdoc} | [
"{"
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Deployment/Connection/SSHConnectionAdapter.php#L246-L256 |
accompli/accompli | src/Deployment/Connection/SSHConnectionAdapter.php | SSHConnectionAdapter.getFile | public function getFile($remoteFilename, $localFilename)
{
if ($this->isConnected()) {
return $this->connection->get($remoteFilename, $localFilename);
}
return false;
} | php | public function getFile($remoteFilename, $localFilename)
{
if ($this->isConnected()) {
return $this->connection->get($remoteFilename, $localFilename);
}
return false;
} | [
"public",
"function",
"getFile",
"(",
"$",
"remoteFilename",
",",
"$",
"localFilename",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isConnected",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"connection",
"->",
"get",
"(",
"$",
"remoteFilename",
",",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Deployment/Connection/SSHConnectionAdapter.php#L273-L280 |
accompli/accompli | src/Deployment/Connection/SSHConnectionAdapter.php | SSHConnectionAdapter.createDirectory | public function createDirectory($remoteDirectory, $fileMode = 0770, $recursive = false)
{
if ($this->isConnected()) {
return $this->connection->mkdir($remoteDirectory, $fileMode, $recursive);
}
return false;
} | php | public function createDirectory($remoteDirectory, $fileMode = 0770, $recursive = false)
{
if ($this->isConnected()) {
return $this->connection->mkdir($remoteDirectory, $fileMode, $recursive);
}
return false;
} | [
"public",
"function",
"createDirectory",
"(",
"$",
"remoteDirectory",
",",
"$",
"fileMode",
"=",
"0770",
",",
"$",
"recursive",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isConnected",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"conne... | {@inheritdoc} | [
"{"
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Deployment/Connection/SSHConnectionAdapter.php#L285-L292 |
accompli/accompli | src/Deployment/Connection/SSHConnectionAdapter.php | SSHConnectionAdapter.createFile | public function createFile($remoteFilename, $fileMode = 0770)
{
if ($this->isConnected()) {
return ($this->connection->touch($remoteFilename) && $this->changePermissions($remoteFilename, $fileMode));
}
return false;
} | php | public function createFile($remoteFilename, $fileMode = 0770)
{
if ($this->isConnected()) {
return ($this->connection->touch($remoteFilename) && $this->changePermissions($remoteFilename, $fileMode));
}
return false;
} | [
"public",
"function",
"createFile",
"(",
"$",
"remoteFilename",
",",
"$",
"fileMode",
"=",
"0770",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isConnected",
"(",
")",
")",
"{",
"return",
"(",
"$",
"this",
"->",
"connection",
"->",
"touch",
"(",
"$",
"re... | {@inheritdoc} | [
"{"
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Deployment/Connection/SSHConnectionAdapter.php#L297-L304 |
accompli/accompli | src/Deployment/Connection/SSHConnectionAdapter.php | SSHConnectionAdapter.link | public function link($remoteSource, $remoteTarget)
{
if ($this->isConnected()) {
return $this->connection->symlink($remoteSource, $remoteTarget);
}
return false;
} | php | public function link($remoteSource, $remoteTarget)
{
if ($this->isConnected()) {
return $this->connection->symlink($remoteSource, $remoteTarget);
}
return false;
} | [
"public",
"function",
"link",
"(",
"$",
"remoteSource",
",",
"$",
"remoteTarget",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isConnected",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"connection",
"->",
"symlink",
"(",
"$",
"remoteSource",
",",
"$",... | {@inheritdoc} | [
"{"
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Deployment/Connection/SSHConnectionAdapter.php#L309-L316 |
accompli/accompli | src/Deployment/Connection/SSHConnectionAdapter.php | SSHConnectionAdapter.move | public function move($remoteSource, $remoteDestination)
{
if ($this->isConnected()) {
return $this->connection->rename($remoteSource, $remoteDestination);
}
return false;
} | php | public function move($remoteSource, $remoteDestination)
{
if ($this->isConnected()) {
return $this->connection->rename($remoteSource, $remoteDestination);
}
return false;
} | [
"public",
"function",
"move",
"(",
"$",
"remoteSource",
",",
"$",
"remoteDestination",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isConnected",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"connection",
"->",
"rename",
"(",
"$",
"remoteSource",
",",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Deployment/Connection/SSHConnectionAdapter.php#L321-L328 |
accompli/accompli | src/Deployment/Connection/SSHConnectionAdapter.php | SSHConnectionAdapter.copy | public function copy($remoteSource, $remoteDestination)
{
if ($this->isConnected()) {
$temporaryFile = tmpfile();
if ($this->getFile($remoteSource, $temporaryFile) === false) {
fclose($temporaryFile);
return false;
}
rewind($temporaryFile);
return $this->putContents($remoteDestination, $temporaryFile);
}
return false;
} | php | public function copy($remoteSource, $remoteDestination)
{
if ($this->isConnected()) {
$temporaryFile = tmpfile();
if ($this->getFile($remoteSource, $temporaryFile) === false) {
fclose($temporaryFile);
return false;
}
rewind($temporaryFile);
return $this->putContents($remoteDestination, $temporaryFile);
}
return false;
} | [
"public",
"function",
"copy",
"(",
"$",
"remoteSource",
",",
"$",
"remoteDestination",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isConnected",
"(",
")",
")",
"{",
"$",
"temporaryFile",
"=",
"tmpfile",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"getF... | {@inheritdoc} | [
"{"
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Deployment/Connection/SSHConnectionAdapter.php#L333-L350 |
accompli/accompli | src/Deployment/Connection/SSHConnectionAdapter.php | SSHConnectionAdapter.changePermissions | public function changePermissions($remoteTarget, $fileMode, $recursive = false)
{
if ($this->isConnected()) {
$result = $this->connection->chmod($fileMode, $remoteTarget, $recursive);
return ($result !== false);
}
return false;
} | php | public function changePermissions($remoteTarget, $fileMode, $recursive = false)
{
if ($this->isConnected()) {
$result = $this->connection->chmod($fileMode, $remoteTarget, $recursive);
return ($result !== false);
}
return false;
} | [
"public",
"function",
"changePermissions",
"(",
"$",
"remoteTarget",
",",
"$",
"fileMode",
",",
"$",
"recursive",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isConnected",
"(",
")",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"connectio... | {@inheritdoc} | [
"{"
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Deployment/Connection/SSHConnectionAdapter.php#L355-L364 |
accompli/accompli | src/Deployment/Connection/SSHConnectionAdapter.php | SSHConnectionAdapter.putContents | public function putContents($destinationFilename, $data)
{
if ($this->isConnected()) {
return $this->connection->put($destinationFilename, $data, SFTP::SOURCE_STRING);
}
return false;
} | php | public function putContents($destinationFilename, $data)
{
if ($this->isConnected()) {
return $this->connection->put($destinationFilename, $data, SFTP::SOURCE_STRING);
}
return false;
} | [
"public",
"function",
"putContents",
"(",
"$",
"destinationFilename",
",",
"$",
"data",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isConnected",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"connection",
"->",
"put",
"(",
"$",
"destinationFilename",
",... | {@inheritdoc} | [
"{"
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Deployment/Connection/SSHConnectionAdapter.php#L369-L376 |
accompli/accompli | src/Deployment/Connection/SSHConnectionAdapter.php | SSHConnectionAdapter.putFile | public function putFile($sourceFilename, $destinationFilename)
{
if ($this->isConnected()) {
return $this->connection->put($destinationFilename, $sourceFilename, SFTP::SOURCE_LOCAL_FILE);
}
return false;
} | php | public function putFile($sourceFilename, $destinationFilename)
{
if ($this->isConnected()) {
return $this->connection->put($destinationFilename, $sourceFilename, SFTP::SOURCE_LOCAL_FILE);
}
return false;
} | [
"public",
"function",
"putFile",
"(",
"$",
"sourceFilename",
",",
"$",
"destinationFilename",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isConnected",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"connection",
"->",
"put",
"(",
"$",
"destinationFilename"... | {@inheritdoc} | [
"{"
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Deployment/Connection/SSHConnectionAdapter.php#L381-L388 |
accompli/accompli | src/Deployment/Connection/SSHConnectionAdapter.php | SSHConnectionAdapter.delete | public function delete($remoteTarget, $recursive = false)
{
if ($this->isConnected()) {
return $this->connection->delete($remoteTarget, $recursive);
}
return false;
} | php | public function delete($remoteTarget, $recursive = false)
{
if ($this->isConnected()) {
return $this->connection->delete($remoteTarget, $recursive);
}
return false;
} | [
"public",
"function",
"delete",
"(",
"$",
"remoteTarget",
",",
"$",
"recursive",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isConnected",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"connection",
"->",
"delete",
"(",
"$",
"remoteTarget... | {@inheritdoc} | [
"{"
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Deployment/Connection/SSHConnectionAdapter.php#L393-L400 |
accompli/accompli | src/Deployment/Connection/SSHConnectionAdapter.php | SSHConnectionAdapter.getUserDirectory | private function getUserDirectory()
{
$userDirectory = null;
if (isset($_SERVER['HOME'])) {
$userDirectory = $_SERVER['HOME'];
} elseif (isset($_SERVER['USERPROFILE'])) {
$userDirectory = $_SERVER['USERPROFILE'];
}
$userDirectory = realpath($userDirectory.'/../');
$userDirectory .= '/'.$this->authenticationUsername;
return $userDirectory;
} | php | private function getUserDirectory()
{
$userDirectory = null;
if (isset($_SERVER['HOME'])) {
$userDirectory = $_SERVER['HOME'];
} elseif (isset($_SERVER['USERPROFILE'])) {
$userDirectory = $_SERVER['USERPROFILE'];
}
$userDirectory = realpath($userDirectory.'/../');
$userDirectory .= '/'.$this->authenticationUsername;
return $userDirectory;
} | [
"private",
"function",
"getUserDirectory",
"(",
")",
"{",
"$",
"userDirectory",
"=",
"null",
";",
"if",
"(",
"isset",
"(",
"$",
"_SERVER",
"[",
"'HOME'",
"]",
")",
")",
"{",
"$",
"userDirectory",
"=",
"$",
"_SERVER",
"[",
"'HOME'",
"]",
";",
"}",
"el... | Returns the 'home' directory for the user.
@return string|null | [
"Returns",
"the",
"home",
"directory",
"for",
"the",
"user",
"."
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Deployment/Connection/SSHConnectionAdapter.php#L417-L429 |
accompli/accompli | src/Deployment/Connection/SSHConnectionAdapter.php | SSHConnectionAdapter.getFilteredOutput | private function getFilteredOutput($output, $command)
{
$output = str_replace(array("\r\n", "\r"), array("\n", ''), $output);
$matches = array();
if (preg_match($this->getOutputFilterRegex($command), $output, $matches) === 1) {
$output = ltrim($matches[1]);
}
return $output;
} | php | private function getFilteredOutput($output, $command)
{
$output = str_replace(array("\r\n", "\r"), array("\n", ''), $output);
$matches = array();
if (preg_match($this->getOutputFilterRegex($command), $output, $matches) === 1) {
$output = ltrim($matches[1]);
}
return $output;
} | [
"private",
"function",
"getFilteredOutput",
"(",
"$",
"output",
",",
"$",
"command",
")",
"{",
"$",
"output",
"=",
"str_replace",
"(",
"array",
"(",
"\"\\r\\n\"",
",",
"\"\\r\"",
")",
",",
"array",
"(",
"\"\\n\"",
",",
"''",
")",
",",
"$",
"output",
")... | Returns the filtered output of the command.
Removes the command echo and shell prompt from the output.
@param string $output
@param string $command
@return string | [
"Returns",
"the",
"filtered",
"output",
"of",
"the",
"command",
".",
"Removes",
"the",
"command",
"echo",
"and",
"shell",
"prompt",
"from",
"the",
"output",
"."
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Deployment/Connection/SSHConnectionAdapter.php#L440-L450 |
accompli/accompli | src/Deployment/Connection/SSHConnectionAdapter.php | SSHConnectionAdapter.getOutputFilterRegex | private function getOutputFilterRegex($command)
{
$commandCharacters = str_split(preg_quote($command, '/'));
$commandCharacterRegexWhitespaceFunction = function ($value) {
if ($value !== '\\') {
$value .= '\s?';
}
return $value;
};
$commandCharacters = array_map($commandCharacterRegexWhitespaceFunction, $commandCharacters);
return sprintf('/%s(.*)%s/s', implode('', $commandCharacters), substr($this->getShellPromptRegex(), 1, -1));
} | php | private function getOutputFilterRegex($command)
{
$commandCharacters = str_split(preg_quote($command, '/'));
$commandCharacterRegexWhitespaceFunction = function ($value) {
if ($value !== '\\') {
$value .= '\s?';
}
return $value;
};
$commandCharacters = array_map($commandCharacterRegexWhitespaceFunction, $commandCharacters);
return sprintf('/%s(.*)%s/s', implode('', $commandCharacters), substr($this->getShellPromptRegex(), 1, -1));
} | [
"private",
"function",
"getOutputFilterRegex",
"(",
"$",
"command",
")",
"{",
"$",
"commandCharacters",
"=",
"str_split",
"(",
"preg_quote",
"(",
"$",
"command",
",",
"'/'",
")",
")",
";",
"$",
"commandCharacterRegexWhitespaceFunction",
"=",
"function",
"(",
"$"... | Returns the output filter regex to filter the output.
@param string $command
@return string | [
"Returns",
"the",
"output",
"filter",
"regex",
"to",
"filter",
"the",
"output",
"."
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Deployment/Connection/SSHConnectionAdapter.php#L459-L473 |
makinacorpus/drupal-ucms | ucms_seo/src/Path/AliasManager.php | AliasManager.computePathAlias | public function computePathAlias($nodeId, $siteId)
{
$nodeIdList = [];
$menuId = $this->treeProvider->findTreeForNode($nodeId, ['site_id' => $siteId]);
if ($menuId) {
// Load the tree, with no access checks, else some parents might
// be hidden from it and the resulting path would be a failure.
$tree = $this->treeProvider->buildTree($menuId, false);
$trail = $tree->getMostRevelantTrailForNode($nodeId);
if ($trail) {
foreach ($trail as $item) {
$nodeIdList[] = $item->getNodeId();
}
} else {
// This should not happen, but it still can be possible
$nodeIdList[] = $nodeId;
}
} else {
$nodeIdList[] = $nodeId;
}
// And now, query all at once.
$segments = $this
->database
->query(
"SELECT nid, alias_segment FROM {ucms_seo_node} WHERE nid IN (:nodes)",
[':nodes' => $nodeIdList]
)
->fetchAllKeyed()
;
// This rather unperforming, but it will only act on very small
// arrays, so I guess that for now, this is enough.
$pieces = [];
foreach ($nodeIdList as $nodeId) {
if (isset($segments[$nodeId])) {
$pieces[] = $segments[$nodeId];
}
}
// This is probably not supposed to happen, but it might
if (!$pieces) {
return null;
}
return implode('/', $pieces);
} | php | public function computePathAlias($nodeId, $siteId)
{
$nodeIdList = [];
$menuId = $this->treeProvider->findTreeForNode($nodeId, ['site_id' => $siteId]);
if ($menuId) {
// Load the tree, with no access checks, else some parents might
// be hidden from it and the resulting path would be a failure.
$tree = $this->treeProvider->buildTree($menuId, false);
$trail = $tree->getMostRevelantTrailForNode($nodeId);
if ($trail) {
foreach ($trail as $item) {
$nodeIdList[] = $item->getNodeId();
}
} else {
// This should not happen, but it still can be possible
$nodeIdList[] = $nodeId;
}
} else {
$nodeIdList[] = $nodeId;
}
// And now, query all at once.
$segments = $this
->database
->query(
"SELECT nid, alias_segment FROM {ucms_seo_node} WHERE nid IN (:nodes)",
[':nodes' => $nodeIdList]
)
->fetchAllKeyed()
;
// This rather unperforming, but it will only act on very small
// arrays, so I guess that for now, this is enough.
$pieces = [];
foreach ($nodeIdList as $nodeId) {
if (isset($segments[$nodeId])) {
$pieces[] = $segments[$nodeId];
}
}
// This is probably not supposed to happen, but it might
if (!$pieces) {
return null;
}
return implode('/', $pieces);
} | [
"public",
"function",
"computePathAlias",
"(",
"$",
"nodeId",
",",
"$",
"siteId",
")",
"{",
"$",
"nodeIdList",
"=",
"[",
"]",
";",
"$",
"menuId",
"=",
"$",
"this",
"->",
"treeProvider",
"->",
"findTreeForNode",
"(",
"$",
"nodeId",
",",
"[",
"'site_id'",
... | Compute alias for node on site
@todo this algorithm does up to 3 sql queries, one for finding the
correct menu tree, another for loading it, and the third to lookup
the segments, a better approach would be to merge this code in umenu
itself, buy adding the 'segment' column in the menu, with a unique
constraint on (parent_id, segment).
@param int $nodeId
@param int $siteId
@return null|string | [
"Compute",
"alias",
"for",
"node",
"on",
"site"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/Path/AliasManager.php#L62-L109 |
makinacorpus/drupal-ucms | ucms_seo/src/Path/AliasManager.php | AliasManager.deduplicate | private function deduplicate($nodeId, $siteId, $alias)
{
$dupFound = false;
$current = $alias;
$increment = 0;
do {
$dupFound = (bool)$this
->database
->query(
"SELECT 1 FROM {ucms_seo_route} WHERE route = :route AND site_id = :site",
[':route' => $current, ':site' => $siteId]
)
->fetchField()
;
if ($dupFound) {
$current = $alias . '-' . ($increment++);
}
} while ($dupFound);
return $current;
} | php | private function deduplicate($nodeId, $siteId, $alias)
{
$dupFound = false;
$current = $alias;
$increment = 0;
do {
$dupFound = (bool)$this
->database
->query(
"SELECT 1 FROM {ucms_seo_route} WHERE route = :route AND site_id = :site",
[':route' => $current, ':site' => $siteId]
)
->fetchField()
;
if ($dupFound) {
$current = $alias . '-' . ($increment++);
}
} while ($dupFound);
return $current;
} | [
"private",
"function",
"deduplicate",
"(",
"$",
"nodeId",
",",
"$",
"siteId",
",",
"$",
"alias",
")",
"{",
"$",
"dupFound",
"=",
"false",
";",
"$",
"current",
"=",
"$",
"alias",
";",
"$",
"increment",
"=",
"0",
";",
"do",
"{",
"$",
"dupFound",
"=",... | Deduplicate alias if one or more already exsist
@param int $nodeId
@param int $siteId
@param string $alias
@return string | [
"Deduplicate",
"alias",
"if",
"one",
"or",
"more",
"already",
"exsist"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/Path/AliasManager.php#L120-L143 |
makinacorpus/drupal-ucms | ucms_seo/src/Path/AliasManager.php | AliasManager.computeAndStorePathAlias | private function computeAndStorePathAlias($nodeId, $siteId, $outdated = null)
{
$transaction = null;
try {
$transaction = $this->database->startTransaction();
$computed = $this->computePathAlias($nodeId, $siteId);
// In all cases, delete outdated item if exists and backup
// it into the {ucms_seo_redirect} table with an expire. Not
// for self, and for all people still using MySQL, RETURNING
// clause would have been great here.
$this
->database
->query(
"DELETE FROM {ucms_seo_route} WHERE node_id = :node AND site_id = :site",
[':node' => $nodeId, ':site' => $siteId]
)
;
// @todo ucms_seo_redirect does not handle duplicates at all
// and will let you insert pretty much everything, we'll see
// later for this; but this is bad, we cannot deduplicate what
// are old sites urls and expired urls from us
if ($outdated) {
$this
->database
->insert('ucms_seo_redirect')
->fields([
'nid' => $nodeId,
'site_id' => $siteId,
'path' => '/' . $outdated,
'expires' => (new \DateTime(self::DEFAULT_EXPIRE))->format('Y-m-d H:i:s'),
])
->execute()
;
}
if ($computed) {
$computed = $this->deduplicate($nodeId, $siteId, $computed);
$this
->database
->insert('ucms_seo_route')
->fields([
'node_id' => $nodeId,
'site_id' => $siteId,
'route' => $computed,
'is_protected' => 0,
'is_outdated' => 0,
])
->execute()
;
}
// Explicit commit
unset($transaction);
return $computed;
} catch (\PDOException $e) {
try {
if ($transaction) {
$transaction->rollback();
}
} catch (\Exception $e2) {
// You are fucked.
watchdog_exception(__FUNCTION__, $e2);
}
throw $e;
}
} | php | private function computeAndStorePathAlias($nodeId, $siteId, $outdated = null)
{
$transaction = null;
try {
$transaction = $this->database->startTransaction();
$computed = $this->computePathAlias($nodeId, $siteId);
// In all cases, delete outdated item if exists and backup
// it into the {ucms_seo_redirect} table with an expire. Not
// for self, and for all people still using MySQL, RETURNING
// clause would have been great here.
$this
->database
->query(
"DELETE FROM {ucms_seo_route} WHERE node_id = :node AND site_id = :site",
[':node' => $nodeId, ':site' => $siteId]
)
;
// @todo ucms_seo_redirect does not handle duplicates at all
// and will let you insert pretty much everything, we'll see
// later for this; but this is bad, we cannot deduplicate what
// are old sites urls and expired urls from us
if ($outdated) {
$this
->database
->insert('ucms_seo_redirect')
->fields([
'nid' => $nodeId,
'site_id' => $siteId,
'path' => '/' . $outdated,
'expires' => (new \DateTime(self::DEFAULT_EXPIRE))->format('Y-m-d H:i:s'),
])
->execute()
;
}
if ($computed) {
$computed = $this->deduplicate($nodeId, $siteId, $computed);
$this
->database
->insert('ucms_seo_route')
->fields([
'node_id' => $nodeId,
'site_id' => $siteId,
'route' => $computed,
'is_protected' => 0,
'is_outdated' => 0,
])
->execute()
;
}
// Explicit commit
unset($transaction);
return $computed;
} catch (\PDOException $e) {
try {
if ($transaction) {
$transaction->rollback();
}
} catch (\Exception $e2) {
// You are fucked.
watchdog_exception(__FUNCTION__, $e2);
}
throw $e;
}
} | [
"private",
"function",
"computeAndStorePathAlias",
"(",
"$",
"nodeId",
",",
"$",
"siteId",
",",
"$",
"outdated",
"=",
"null",
")",
"{",
"$",
"transaction",
"=",
"null",
";",
"try",
"{",
"$",
"transaction",
"=",
"$",
"this",
"->",
"database",
"->",
"start... | Store given node alias in given site
@param int $nodeId
@param int $siteId
@param string $outdated
Outdated route if exists
@return string | [
"Store",
"given",
"node",
"alias",
"in",
"given",
"site"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/Path/AliasManager.php#L155-L227 |
makinacorpus/drupal-ucms | ucms_seo/src/Path/AliasManager.php | AliasManager.invalidate | public function invalidate(array $conditions)
{
if (empty($conditions)) {
throw new \InvalidArgumentException("cannot invalidate aliases with no conditions");
}
$query = $this
->database
->update('ucms_seo_route')
->fields(['is_outdated' => 1])
->condition('is_protected', 0)
;
foreach ($conditions as $key => $value) {
switch ($key) {
case 'node_id':
$query->condition('node_id', $value);
break;
case 'site_id':
$query->condition('site_id', $value);
break;
default:
throw new \InvalidArgumentException(sprintf("condition '%s' is not supported for aliases invalidation", $key));
}
}
$query->execute();
} | php | public function invalidate(array $conditions)
{
if (empty($conditions)) {
throw new \InvalidArgumentException("cannot invalidate aliases with no conditions");
}
$query = $this
->database
->update('ucms_seo_route')
->fields(['is_outdated' => 1])
->condition('is_protected', 0)
;
foreach ($conditions as $key => $value) {
switch ($key) {
case 'node_id':
$query->condition('node_id', $value);
break;
case 'site_id':
$query->condition('site_id', $value);
break;
default:
throw new \InvalidArgumentException(sprintf("condition '%s' is not supported for aliases invalidation", $key));
}
}
$query->execute();
} | [
"public",
"function",
"invalidate",
"(",
"array",
"$",
"conditions",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"conditions",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"cannot invalidate aliases with no conditions\"",
")",
";",
"}",
"$... | Invalidate aliases with the given conditions
@param array $conditions
Keys are column names, values are either single value or an array of
value to match to invalidate; allowed keys are:
- node_id: one or more node identifiers
- site_id: one or more site identifiers | [
"Invalidate",
"aliases",
"with",
"the",
"given",
"conditions"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/Path/AliasManager.php#L238-L268 |
makinacorpus/drupal-ucms | ucms_seo/src/Path/AliasManager.php | AliasManager.invalidateRelated | public function invalidateRelated($nodeIdList)
{
if (!$nodeIdList) {
return;
}
$this
->database
->query("
UPDATE {ucms_seo_route}
SET
is_outdated = 1
WHERE
is_outdated = 0
AND is_protected = 0
AND menu_id IS NOT NULL
AND menu_id IN (
SELECT
DISTINCT(i.menu_id)
FROM {umenu_item} i
WHERE
i.node_id IN (:nodeIdList)
)
", [':nodeIdList' => $nodeIdList])
;
// This is sad, but when data is not consistent and menu identifier
// is not set, we must wipe out the complete site cache instead, but
// hopefully, it won't happen again once we'll have fixed the item
// insertion.
$this
->database
->query("
UPDATE {ucms_seo_route}
SET
is_outdated = 1
WHERE
is_outdated = 0
AND is_protected = 0
AND menu_id IS NULL
AND site_id IN (
SELECT
DISTINCT(i.site_id)
FROM {umenu_item} i
WHERE
i.node_id IN (:nodeIdList)
)
", [':nodeIdList' => $nodeIdList])
;
} | php | public function invalidateRelated($nodeIdList)
{
if (!$nodeIdList) {
return;
}
$this
->database
->query("
UPDATE {ucms_seo_route}
SET
is_outdated = 1
WHERE
is_outdated = 0
AND is_protected = 0
AND menu_id IS NOT NULL
AND menu_id IN (
SELECT
DISTINCT(i.menu_id)
FROM {umenu_item} i
WHERE
i.node_id IN (:nodeIdList)
)
", [':nodeIdList' => $nodeIdList])
;
// This is sad, but when data is not consistent and menu identifier
// is not set, we must wipe out the complete site cache instead, but
// hopefully, it won't happen again once we'll have fixed the item
// insertion.
$this
->database
->query("
UPDATE {ucms_seo_route}
SET
is_outdated = 1
WHERE
is_outdated = 0
AND is_protected = 0
AND menu_id IS NULL
AND site_id IN (
SELECT
DISTINCT(i.site_id)
FROM {umenu_item} i
WHERE
i.node_id IN (:nodeIdList)
)
", [':nodeIdList' => $nodeIdList])
;
} | [
"public",
"function",
"invalidateRelated",
"(",
"$",
"nodeIdList",
")",
"{",
"if",
"(",
"!",
"$",
"nodeIdList",
")",
"{",
"return",
";",
"}",
"$",
"this",
"->",
"database",
"->",
"query",
"(",
"\"\n UPDATE {ucms_seo_route}\n SET\n ... | Invalidate aliases related with the given node
@todo this will a few SQL indices
@param int[] $nodeIdList | [
"Invalidate",
"aliases",
"related",
"with",
"the",
"given",
"node"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/Path/AliasManager.php#L277-L326 |
makinacorpus/drupal-ucms | ucms_seo/src/Path/AliasManager.php | AliasManager.setCustomAlias | public function setCustomAlias($nodeId, $siteId, $alias)
{
$this
->database
->merge('ucms_seo_route')
->key([
'node_id' => $nodeId,
'site_id' => $siteId,
])
->fields([
'route' => $alias,
'is_protected' => 1,
'is_outdated' => 0,
])
->execute()
;
} | php | public function setCustomAlias($nodeId, $siteId, $alias)
{
$this
->database
->merge('ucms_seo_route')
->key([
'node_id' => $nodeId,
'site_id' => $siteId,
])
->fields([
'route' => $alias,
'is_protected' => 1,
'is_outdated' => 0,
])
->execute()
;
} | [
"public",
"function",
"setCustomAlias",
"(",
"$",
"nodeId",
",",
"$",
"siteId",
",",
"$",
"alias",
")",
"{",
"$",
"this",
"->",
"database",
"->",
"merge",
"(",
"'ucms_seo_route'",
")",
"->",
"key",
"(",
"[",
"'node_id'",
"=>",
"$",
"nodeId",
",",
"'sit... | Set custom alias for
@param int $nodeId
@param int $siteId
@param string $siteId | [
"Set",
"custom",
"alias",
"for"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/Path/AliasManager.php#L335-L351 |
makinacorpus/drupal-ucms | ucms_seo/src/Path/AliasManager.php | AliasManager.removeCustomAlias | public function removeCustomAlias($nodeId, $siteId)
{
$this
->database
->update('ucms_seo_route')
->condition('node_id', $nodeId)
->condition('site_id', $siteId)
->fields(['is_protected' => 0, 'is_outdated' => 1])
->execute()
;
} | php | public function removeCustomAlias($nodeId, $siteId)
{
$this
->database
->update('ucms_seo_route')
->condition('node_id', $nodeId)
->condition('site_id', $siteId)
->fields(['is_protected' => 0, 'is_outdated' => 1])
->execute()
;
} | [
"public",
"function",
"removeCustomAlias",
"(",
"$",
"nodeId",
",",
"$",
"siteId",
")",
"{",
"$",
"this",
"->",
"database",
"->",
"update",
"(",
"'ucms_seo_route'",
")",
"->",
"condition",
"(",
"'node_id'",
",",
"$",
"nodeId",
")",
"->",
"condition",
"(",
... | Remove custom alias for
@param int $nodeId
@param int $siteId | [
"Remove",
"custom",
"alias",
"for"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/Path/AliasManager.php#L359-L369 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.