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 |
|---|---|---|---|---|---|---|---|---|---|---|
CampaignChain/core | Entity/CampaignModule.php | CampaignModule.addCampaign | public function addCampaign(\CampaignChain\CoreBundle\Entity\Campaign $campaigns)
{
$this->campaigns[] = $campaigns;
return $this;
} | php | public function addCampaign(\CampaignChain\CoreBundle\Entity\Campaign $campaigns)
{
$this->campaigns[] = $campaigns;
return $this;
} | [
"public",
"function",
"addCampaign",
"(",
"\\",
"CampaignChain",
"\\",
"CoreBundle",
"\\",
"Entity",
"\\",
"Campaign",
"$",
"campaigns",
")",
"{",
"$",
"this",
"->",
"campaigns",
"[",
"]",
"=",
"$",
"campaigns",
";",
"return",
"$",
"this",
";",
"}"
] | Add campaigns
@param \CampaignChain\CoreBundle\Entity\Campaign $campaigns
@return CampaignModule | [
"Add",
"campaigns"
] | train | https://github.com/CampaignChain/core/blob/82526548a223ed49fcd65ed7c23638544499775f/Entity/CampaignModule.php#L46-L51 |
CampaignChain/core | Entity/CampaignModule.php | CampaignModule.removeCampaign | public function removeCampaign(\CampaignChain\CoreBundle\Entity\Campaign $campaigns)
{
$this->campaigns->removeElement($campaigns);
} | php | public function removeCampaign(\CampaignChain\CoreBundle\Entity\Campaign $campaigns)
{
$this->campaigns->removeElement($campaigns);
} | [
"public",
"function",
"removeCampaign",
"(",
"\\",
"CampaignChain",
"\\",
"CoreBundle",
"\\",
"Entity",
"\\",
"Campaign",
"$",
"campaigns",
")",
"{",
"$",
"this",
"->",
"campaigns",
"->",
"removeElement",
"(",
"$",
"campaigns",
")",
";",
"}"
] | Remove campaigns
@param \CampaignChain\CoreBundle\Entity\Campaign $campaigns | [
"Remove",
"campaigns"
] | train | https://github.com/CampaignChain/core/blob/82526548a223ed49fcd65ed7c23638544499775f/Entity/CampaignModule.php#L58-L61 |
tableau-mkt/elomentary | src/Client.php | Client.api | public function api($name) {
switch ($name) {
case 'campaign':
case 'campaigns':
$api = new Api\Assets\Campaign($this);
break;
case 'contact':
case 'contacts':
$api = new Api\Data\Contact($this);
break;
case 'email':
case 'emails':
$api = new Api\Assets\Email($this);
break;
case 'customObject':
case 'customObjects':
$api = new Api\Assets\CustomObject($this);
break;
case 'optionList':
case 'optionLists':
$api = new Api\Assets\OptionList($this);
break;
case 'program':
case 'programs':
$api = new Api\Assets\Program($this);
break;
case 'visitor':
case 'visitors':
$api = new Api\Data\Visitor($this);
break;
default:
throw new InvalidArgumentException(sprintf('Undefined API instance: "%s"', $name));
}
return $api;
} | php | public function api($name) {
switch ($name) {
case 'campaign':
case 'campaigns':
$api = new Api\Assets\Campaign($this);
break;
case 'contact':
case 'contacts':
$api = new Api\Data\Contact($this);
break;
case 'email':
case 'emails':
$api = new Api\Assets\Email($this);
break;
case 'customObject':
case 'customObjects':
$api = new Api\Assets\CustomObject($this);
break;
case 'optionList':
case 'optionLists':
$api = new Api\Assets\OptionList($this);
break;
case 'program':
case 'programs':
$api = new Api\Assets\Program($this);
break;
case 'visitor':
case 'visitors':
$api = new Api\Data\Visitor($this);
break;
default:
throw new InvalidArgumentException(sprintf('Undefined API instance: "%s"', $name));
}
return $api;
} | [
"public",
"function",
"api",
"(",
"$",
"name",
")",
"{",
"switch",
"(",
"$",
"name",
")",
"{",
"case",
"'campaign'",
":",
"case",
"'campaigns'",
":",
"$",
"api",
"=",
"new",
"Api",
"\\",
"Assets",
"\\",
"Campaign",
"(",
"$",
"this",
")",
";",
"brea... | The primary interface for interacting with different Eloqua objects.
@param string $name
The name of the API instance to return. One of:
- contact: To interact with Eloqua contacts.
- contact_subscription: To interact with Eloqua contact subscriptions.
@return ApiInterface
@throws InvalidArgumentException | [
"The",
"primary",
"interface",
"for",
"interacting",
"with",
"different",
"Eloqua",
"objects",
"."
] | train | https://github.com/tableau-mkt/elomentary/blob/c9e8e67f8239cfd813fae59fe665ed7130c439d2/src/Client.php#L60-L102 |
tableau-mkt/elomentary | src/Client.php | Client.authenticate | public function authenticate($site, $login, $password, $baseUrl = null, $version = null) {
if (empty($site) || empty($login) || empty($password)) {
throw new InvalidArgumentException('You must specify authentication details.');
}
if (isset($baseUrl)) {
$this->setOption('base_url', $baseUrl);
}
if (isset($version)) {
$this->setOption('version', $version);
}
$this->getHttpClient()->authenticate($site, $login, $password);
} | php | public function authenticate($site, $login, $password, $baseUrl = null, $version = null) {
if (empty($site) || empty($login) || empty($password)) {
throw new InvalidArgumentException('You must specify authentication details.');
}
if (isset($baseUrl)) {
$this->setOption('base_url', $baseUrl);
}
if (isset($version)) {
$this->setOption('version', $version);
}
$this->getHttpClient()->authenticate($site, $login, $password);
} | [
"public",
"function",
"authenticate",
"(",
"$",
"site",
",",
"$",
"login",
",",
"$",
"password",
",",
"$",
"baseUrl",
"=",
"null",
",",
"$",
"version",
"=",
"null",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"site",
")",
"||",
"empty",
"(",
"$",
"lo... | Authenticate a user for all subsequent requests.
@param string $site
Eloqua site name for the instance against which requests should be made.
@param string $login
Eloqua user name with which requests should be made.
@param string $password
Password associated with the aforementioned Eloqua user.
@param string $baseUrl
Endpoint associated with the aforementioned Eloqua user.
@param string $version
API version to use.
@throws InvalidArgumentException if any arguments are not specified. | [
"Authenticate",
"a",
"user",
"for",
"all",
"subsequent",
"requests",
"."
] | train | https://github.com/tableau-mkt/elomentary/blob/c9e8e67f8239cfd813fae59fe665ed7130c439d2/src/Client.php#L124-L138 |
tableau-mkt/elomentary | src/Client.php | Client.getRestEndpoints | public function getRestEndpoints($site, $login, $password, HttpClientInterface $client = null) {
$client = $client ?: new HttpClient(array (
'base_url' => 'https://login.eloqua.com/id', // @codeCoverageIgnore
'version' => '', // @codeCoverageIgnore
));
$authHeader = array (
'Authorization' => sprintf('Basic %s', base64_encode("$site\\$login:$password")),
);
$response = $client->get('https://login.eloqua.com/id', array(), $authHeader);
$loginObj = $response->json();
$urls = $loginObj['urls']['apis']['rest'];
$stripVersion = function($url) {
return str_replace('/{version}/', '/', $url);
};
return array_map($stripVersion, $urls);
} | php | public function getRestEndpoints($site, $login, $password, HttpClientInterface $client = null) {
$client = $client ?: new HttpClient(array (
'base_url' => 'https://login.eloqua.com/id', // @codeCoverageIgnore
'version' => '', // @codeCoverageIgnore
));
$authHeader = array (
'Authorization' => sprintf('Basic %s', base64_encode("$site\\$login:$password")),
);
$response = $client->get('https://login.eloqua.com/id', array(), $authHeader);
$loginObj = $response->json();
$urls = $loginObj['urls']['apis']['rest'];
$stripVersion = function($url) {
return str_replace('/{version}/', '/', $url);
};
return array_map($stripVersion, $urls);
} | [
"public",
"function",
"getRestEndpoints",
"(",
"$",
"site",
",",
"$",
"login",
",",
"$",
"password",
",",
"HttpClientInterface",
"$",
"client",
"=",
"null",
")",
"{",
"$",
"client",
"=",
"$",
"client",
"?",
":",
"new",
"HttpClient",
"(",
"array",
"(",
... | Gets REST endpoints associated with authentication parameters
@param string $site
Eloqua site name for the instance against which requests should be made.
@param string $login
Eloqua user name with which requests should be made.
@param string $password
Password associated with the aforementioned Eloqua user.
@param HttpClientInterface $client
Provides HttpClientInterface dependency injection.
@returns array
The list of urls associated with the aforementioned Eloqua user, with the
'/{version}/' part removed.
@see http://topliners.eloqua.com/community/code_it/blog/2012/11/30/using-the-eloqua-api--determining-endpoint-urls-logineloquacom | [
"Gets",
"REST",
"endpoints",
"associated",
"with",
"authentication",
"parameters"
] | train | https://github.com/tableau-mkt/elomentary/blob/c9e8e67f8239cfd813fae59fe665ed7130c439d2/src/Client.php#L161-L181 |
tableau-mkt/elomentary | src/Client.php | Client.getHttpClient | public function getHttpClient() {
if ($this->httpClient === NULL) {
$this->httpClient = new HttpClient($this->options);
}
return $this->httpClient;
} | php | public function getHttpClient() {
if ($this->httpClient === NULL) {
$this->httpClient = new HttpClient($this->options);
}
return $this->httpClient;
} | [
"public",
"function",
"getHttpClient",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"httpClient",
"===",
"NULL",
")",
"{",
"$",
"this",
"->",
"httpClient",
"=",
"new",
"HttpClient",
"(",
"$",
"this",
"->",
"options",
")",
";",
"}",
"return",
"$",
"th... | Returns the HttpClient.
@return HttpClient | [
"Returns",
"the",
"HttpClient",
"."
] | train | https://github.com/tableau-mkt/elomentary/blob/c9e8e67f8239cfd813fae59fe665ed7130c439d2/src/Client.php#L188-L194 |
tableau-mkt/elomentary | src/Client.php | Client.getOption | public function getOption($name) {
if (!array_key_exists($name, $this->options)) {
throw new InvalidArgumentException(sprintf('Undefined option: "%s"', $name));
}
return $this->options[$name];
} | php | public function getOption($name) {
if (!array_key_exists($name, $this->options)) {
throw new InvalidArgumentException(sprintf('Undefined option: "%s"', $name));
}
return $this->options[$name];
} | [
"public",
"function",
"getOption",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"name",
",",
"$",
"this",
"->",
"options",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Undefined option: \"%s\"... | Returns a named option.
@param string $name
@return mixed
@throws InvalidArgumentException | [
"Returns",
"a",
"named",
"option",
"."
] | train | https://github.com/tableau-mkt/elomentary/blob/c9e8e67f8239cfd813fae59fe665ed7130c439d2/src/Client.php#L230-L236 |
tableau-mkt/elomentary | src/Client.php | Client.setOption | public function setOption($name, $value) {
if (!array_key_exists($name, $this->options)) {
throw new InvalidArgumentException(sprintf('Undefined option: "%s"', $name));
}
$this->options[$name] = $value;
$this->getHttpClient()->setOption($name, $value);
} | php | public function setOption($name, $value) {
if (!array_key_exists($name, $this->options)) {
throw new InvalidArgumentException(sprintf('Undefined option: "%s"', $name));
}
$this->options[$name] = $value;
$this->getHttpClient()->setOption($name, $value);
} | [
"public",
"function",
"setOption",
"(",
"$",
"name",
",",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"name",
",",
"$",
"this",
"->",
"options",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"... | Sets a named option.
@param string $name
@param mixed $value
@throws InvalidArgumentException | [
"Sets",
"a",
"named",
"option",
"."
] | train | https://github.com/tableau-mkt/elomentary/blob/c9e8e67f8239cfd813fae59fe665ed7130c439d2/src/Client.php#L246-L253 |
kgilden/php-digidoc | src/Soap/Wsdl/DigiDocService.php | DigiDocService.StartSession | public function StartSession($SigningProfile, $SigDocXML, $bHoldSession, DataFileData $datafile)
{
return $this->__soapCall('StartSession', array($SigningProfile, $SigDocXML, $bHoldSession, $datafile));
} | php | public function StartSession($SigningProfile, $SigDocXML, $bHoldSession, DataFileData $datafile)
{
return $this->__soapCall('StartSession', array($SigningProfile, $SigDocXML, $bHoldSession, $datafile));
} | [
"public",
"function",
"StartSession",
"(",
"$",
"SigningProfile",
",",
"$",
"SigDocXML",
",",
"$",
"bHoldSession",
",",
"DataFileData",
"$",
"datafile",
")",
"{",
"return",
"$",
"this",
"->",
"__soapCall",
"(",
"'StartSession'",
",",
"array",
"(",
"$",
"Sign... | Service definition of function d__StartSession
@param string $SigningProfile
@param string $SigDocXML
@param boolean $bHoldSession
@param DataFileData $datafile
@access public
@return list(string $Status, int $Sesscode, SignedDocInfo $SignedDocInfo) | [
"Service",
"definition",
"of",
"function",
"d__StartSession"
] | train | https://github.com/kgilden/php-digidoc/blob/88112ba05688fc1d32c0ff948cb8e1f4d2f264d3/src/Soap/Wsdl/DigiDocService.php#L74-L77 |
kgilden/php-digidoc | src/Soap/Wsdl/DigiDocService.php | DigiDocService.AddDataFile | public function AddDataFile($Sesscode, $FileName, $MimeType, $ContentType, $Size, $DigestType, $DigestValue, $Content)
{
return $this->__soapCall('AddDataFile', array($Sesscode, $FileName, $MimeType, $ContentType, $Size, $DigestType, $DigestValue, $Content));
} | php | public function AddDataFile($Sesscode, $FileName, $MimeType, $ContentType, $Size, $DigestType, $DigestValue, $Content)
{
return $this->__soapCall('AddDataFile', array($Sesscode, $FileName, $MimeType, $ContentType, $Size, $DigestType, $DigestValue, $Content));
} | [
"public",
"function",
"AddDataFile",
"(",
"$",
"Sesscode",
",",
"$",
"FileName",
",",
"$",
"MimeType",
",",
"$",
"ContentType",
",",
"$",
"Size",
",",
"$",
"DigestType",
",",
"$",
"DigestValue",
",",
"$",
"Content",
")",
"{",
"return",
"$",
"this",
"->... | Service definition of function d__AddDataFile
@param int $Sesscode
@param string $FileName
@param string $MimeType
@param string $ContentType
@param int $Size
@param string $DigestType
@param string $DigestValue
@param string $Content
@access public
@return list(string $Status, SignedDocInfo $SignedDocInfo) | [
"Service",
"definition",
"of",
"function",
"d__AddDataFile"
] | train | https://github.com/kgilden/php-digidoc/blob/88112ba05688fc1d32c0ff948cb8e1f4d2f264d3/src/Soap/Wsdl/DigiDocService.php#L119-L122 |
kgilden/php-digidoc | src/Soap/Wsdl/DigiDocService.php | DigiDocService.GetSignatureModules | public function GetSignatureModules($Sesscode, $Platform, $Phase, $Type)
{
return $this->__soapCall('GetSignatureModules', array($Sesscode, $Platform, $Phase, $Type));
} | php | public function GetSignatureModules($Sesscode, $Platform, $Phase, $Type)
{
return $this->__soapCall('GetSignatureModules', array($Sesscode, $Platform, $Phase, $Type));
} | [
"public",
"function",
"GetSignatureModules",
"(",
"$",
"Sesscode",
",",
"$",
"Platform",
",",
"$",
"Phase",
",",
"$",
"Type",
")",
"{",
"return",
"$",
"this",
"->",
"__soapCall",
"(",
"'GetSignatureModules'",
",",
"array",
"(",
"$",
"Sesscode",
",",
"$",
... | Service definition of function d__GetSignatureModules
@param int $Sesscode
@param string $Platform
@param string $Phase
@param string $Type
@access public
@return list(string $Status, SignatureModulesArray $Modules) | [
"Service",
"definition",
"of",
"function",
"d__GetSignatureModules"
] | train | https://github.com/kgilden/php-digidoc/blob/88112ba05688fc1d32c0ff948cb8e1f4d2f264d3/src/Soap/Wsdl/DigiDocService.php#L262-L265 |
kgilden/php-digidoc | src/Soap/Wsdl/DigiDocService.php | DigiDocService.PrepareSignature | public function PrepareSignature($Sesscode, $SignersCertificate, $SignersTokenId, $Role, $City, $State, $PostalCode, $Country, $SigningProfile)
{
return $this->__soapCall('PrepareSignature', array($Sesscode, $SignersCertificate, $SignersTokenId, $Role, $City, $State, $PostalCode, $Country, $SigningProfile));
} | php | public function PrepareSignature($Sesscode, $SignersCertificate, $SignersTokenId, $Role, $City, $State, $PostalCode, $Country, $SigningProfile)
{
return $this->__soapCall('PrepareSignature', array($Sesscode, $SignersCertificate, $SignersTokenId, $Role, $City, $State, $PostalCode, $Country, $SigningProfile));
} | [
"public",
"function",
"PrepareSignature",
"(",
"$",
"Sesscode",
",",
"$",
"SignersCertificate",
",",
"$",
"SignersTokenId",
",",
"$",
"Role",
",",
"$",
"City",
",",
"$",
"State",
",",
"$",
"PostalCode",
",",
"$",
"Country",
",",
"$",
"SigningProfile",
")",... | Service definition of function d__PrepareSignature
@param int $Sesscode
@param string $SignersCertificate
@param string $SignersTokenId
@param string $Role
@param string $City
@param string $State
@param string $PostalCode
@param string $Country
@param string $SigningProfile
@access public
@return list(string $Status, string $SignatureId, string $SignedInfoDigest) | [
"Service",
"definition",
"of",
"function",
"d__PrepareSignature"
] | train | https://github.com/kgilden/php-digidoc/blob/88112ba05688fc1d32c0ff948cb8e1f4d2f264d3/src/Soap/Wsdl/DigiDocService.php#L282-L285 |
kgilden/php-digidoc | src/Soap/Wsdl/DigiDocService.php | DigiDocService.MobileSign | public function MobileSign($Sesscode, $SignerIDCode, $SignersCountry, $SignerPhoneNo, $ServiceName, $AdditionalDataToBeDisplayed, $Language, $Role, $City, $StateOrProvince, $PostalCode, $CountryName, $SigningProfile, $MessagingMode, $AsyncConfiguration, $ReturnDocInfo, $ReturnDocData)
{
return $this->__soapCall('MobileSign', array($Sesscode, $SignerIDCode, $SignersCountry, $SignerPhoneNo, $ServiceName, $AdditionalDataToBeDisplayed, $Language, $Role, $City, $StateOrProvince, $PostalCode, $CountryName, $SigningProfile, $MessagingMode, $AsyncConfiguration, $ReturnDocInfo, $ReturnDocData));
} | php | public function MobileSign($Sesscode, $SignerIDCode, $SignersCountry, $SignerPhoneNo, $ServiceName, $AdditionalDataToBeDisplayed, $Language, $Role, $City, $StateOrProvince, $PostalCode, $CountryName, $SigningProfile, $MessagingMode, $AsyncConfiguration, $ReturnDocInfo, $ReturnDocData)
{
return $this->__soapCall('MobileSign', array($Sesscode, $SignerIDCode, $SignersCountry, $SignerPhoneNo, $ServiceName, $AdditionalDataToBeDisplayed, $Language, $Role, $City, $StateOrProvince, $PostalCode, $CountryName, $SigningProfile, $MessagingMode, $AsyncConfiguration, $ReturnDocInfo, $ReturnDocData));
} | [
"public",
"function",
"MobileSign",
"(",
"$",
"Sesscode",
",",
"$",
"SignerIDCode",
",",
"$",
"SignersCountry",
",",
"$",
"SignerPhoneNo",
",",
"$",
"ServiceName",
",",
"$",
"AdditionalDataToBeDisplayed",
",",
"$",
"Language",
",",
"$",
"Role",
",",
"$",
"Ci... | Service definition of function d__MobileSign
@param int $Sesscode
@param string $SignerIDCode
@param string $SignersCountry
@param string $SignerPhoneNo
@param string $ServiceName
@param string $AdditionalDataToBeDisplayed
@param string $Language
@param string $Role
@param string $City
@param string $StateOrProvince
@param string $PostalCode
@param string $CountryName
@param string $SigningProfile
@param string $MessagingMode
@param int $AsyncConfiguration
@param boolean $ReturnDocInfo
@param boolean $ReturnDocData
@access public
@return list(string $Status, string $StatusCode, string $ChallengeID) | [
"Service",
"definition",
"of",
"function",
"d__MobileSign"
] | train | https://github.com/kgilden/php-digidoc/blob/88112ba05688fc1d32c0ff948cb8e1f4d2f264d3/src/Soap/Wsdl/DigiDocService.php#L348-L351 |
kgilden/php-digidoc | src/Soap/Wsdl/DigiDocService.php | DigiDocService.MobileAuthenticate | public function MobileAuthenticate($IDCode, $CountryCode, $PhoneNo, $Language, $ServiceName, $MessageToDisplay, $SPChallenge, $MessagingMode, $AsyncConfiguration, $ReturnCertData, $ReturnRevocationData)
{
return $this->__soapCall('MobileAuthenticate', array($IDCode, $CountryCode, $PhoneNo, $Language, $ServiceName, $MessageToDisplay, $SPChallenge, $MessagingMode, $AsyncConfiguration, $ReturnCertData, $ReturnRevocationData));
} | php | public function MobileAuthenticate($IDCode, $CountryCode, $PhoneNo, $Language, $ServiceName, $MessageToDisplay, $SPChallenge, $MessagingMode, $AsyncConfiguration, $ReturnCertData, $ReturnRevocationData)
{
return $this->__soapCall('MobileAuthenticate', array($IDCode, $CountryCode, $PhoneNo, $Language, $ServiceName, $MessageToDisplay, $SPChallenge, $MessagingMode, $AsyncConfiguration, $ReturnCertData, $ReturnRevocationData));
} | [
"public",
"function",
"MobileAuthenticate",
"(",
"$",
"IDCode",
",",
"$",
"CountryCode",
",",
"$",
"PhoneNo",
",",
"$",
"Language",
",",
"$",
"ServiceName",
",",
"$",
"MessageToDisplay",
",",
"$",
"SPChallenge",
",",
"$",
"MessagingMode",
",",
"$",
"AsyncCon... | Service definition of function d__MobileAuthenticate
@param string $IDCode
@param string $CountryCode
@param string $PhoneNo
@param string $Language
@param string $ServiceName
@param string $MessageToDisplay
@param string $SPChallenge
@param string $MessagingMode
@param int $AsyncConfiguration
@param boolean $ReturnCertData
@param boolean $ReturnRevocationData
@access public
@return list(int $Sesscode, string $Status, string $UserIDCode, string $UserGivenname, string $UserSurname, string $UserCountry, string $UserCN, string $CertificateData, string $ChallengeID, string $Challenge, string $RevocationData) | [
"Service",
"definition",
"of",
"function",
"d__MobileAuthenticate"
] | train | https://github.com/kgilden/php-digidoc/blob/88112ba05688fc1d32c0ff948cb8e1f4d2f264d3/src/Soap/Wsdl/DigiDocService.php#L384-L387 |
kgilden/php-digidoc | src/Soap/Wsdl/DigiDocService.php | DigiDocService.MobileCreateSignature | public function MobileCreateSignature($IDCode, $SignersCountry, $PhoneNo, $Language, $ServiceName, $MessageToDisplay, $Role, $City, $StateOrProvince, $PostalCode, $CountryName, $SigningProfile, DataFileDigestList $DataFiles, $Format, $Version, $SignatureID, $MessagingMode, $AsyncConfiguration)
{
return $this->__soapCall('MobileCreateSignature', array($IDCode, $SignersCountry, $PhoneNo, $Language, $ServiceName, $MessageToDisplay, $Role, $City, $StateOrProvince, $PostalCode, $CountryName, $SigningProfile, $DataFiles, $Format, $Version, $SignatureID, $MessagingMode, $AsyncConfiguration));
} | php | public function MobileCreateSignature($IDCode, $SignersCountry, $PhoneNo, $Language, $ServiceName, $MessageToDisplay, $Role, $City, $StateOrProvince, $PostalCode, $CountryName, $SigningProfile, DataFileDigestList $DataFiles, $Format, $Version, $SignatureID, $MessagingMode, $AsyncConfiguration)
{
return $this->__soapCall('MobileCreateSignature', array($IDCode, $SignersCountry, $PhoneNo, $Language, $ServiceName, $MessageToDisplay, $Role, $City, $StateOrProvince, $PostalCode, $CountryName, $SigningProfile, $DataFiles, $Format, $Version, $SignatureID, $MessagingMode, $AsyncConfiguration));
} | [
"public",
"function",
"MobileCreateSignature",
"(",
"$",
"IDCode",
",",
"$",
"SignersCountry",
",",
"$",
"PhoneNo",
",",
"$",
"Language",
",",
"$",
"ServiceName",
",",
"$",
"MessageToDisplay",
",",
"$",
"Role",
",",
"$",
"City",
",",
"$",
"StateOrProvince",
... | Service definition of function d__MobileCreateSignature
@param string $IDCode
@param string $SignersCountry
@param string $PhoneNo
@param string $Language
@param string $ServiceName
@param string $MessageToDisplay
@param string $Role
@param string $City
@param string $StateOrProvince
@param string $PostalCode
@param string $CountryName
@param string $SigningProfile
@param DataFileDigestList $DataFiles
@param string $Format
@param string $Version
@param string $SignatureID
@param string $MessagingMode
@param int $AsyncConfiguration
@access public
@return list(int $Sesscode, string $ChallengeID, string $Status) | [
"Service",
"definition",
"of",
"function",
"d__MobileCreateSignature"
] | train | https://github.com/kgilden/php-digidoc/blob/88112ba05688fc1d32c0ff948cb8e1f4d2f264d3/src/Soap/Wsdl/DigiDocService.php#L426-L429 |
kgilden/php-digidoc | src/Soap/Wsdl/DigiDocService.php | DigiDocService.GetMobileCertificate | public function GetMobileCertificate($IDCode, $Country, $PhoneNo, $ReturnCertData)
{
return $this->__soapCall('GetMobileCertificate', array($IDCode, $Country, $PhoneNo, $ReturnCertData));
} | php | public function GetMobileCertificate($IDCode, $Country, $PhoneNo, $ReturnCertData)
{
return $this->__soapCall('GetMobileCertificate', array($IDCode, $Country, $PhoneNo, $ReturnCertData));
} | [
"public",
"function",
"GetMobileCertificate",
"(",
"$",
"IDCode",
",",
"$",
"Country",
",",
"$",
"PhoneNo",
",",
"$",
"ReturnCertData",
")",
"{",
"return",
"$",
"this",
"->",
"__soapCall",
"(",
"'GetMobileCertificate'",
",",
"array",
"(",
"$",
"IDCode",
",",... | Service definition of function d__GetMobileCertificate
@param string $IDCode
@param string $Country
@param string $PhoneNo
@param string $ReturnCertData
@access public
@return list(string $AuthCertStatus, string $SignCertStatus, string $AuthCertData, string $SignCertData) | [
"Service",
"definition",
"of",
"function",
"d__GetMobileCertificate"
] | train | https://github.com/kgilden/php-digidoc/blob/88112ba05688fc1d32c0ff948cb8e1f4d2f264d3/src/Soap/Wsdl/DigiDocService.php#L454-L457 |
corycollier/markdown-blogger | src/Blog.php | Blog.setData | protected function setData($data = [])
{
$defaults = [
'content' => '',
'data' => null,
];
$this->data = array_merge($defaults, $data);
return $this;
} | php | protected function setData($data = [])
{
$defaults = [
'content' => '',
'data' => null,
];
$this->data = array_merge($defaults, $data);
return $this;
} | [
"protected",
"function",
"setData",
"(",
"$",
"data",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'content'",
"=>",
"''",
",",
"'data'",
"=>",
"null",
",",
"]",
";",
"$",
"this",
"->",
"data",
"=",
"array_merge",
"(",
"$",
"defaults",
",",... | Setter for the data property
@param Array $data the array of data for the blog Instance. | [
"Setter",
"for",
"the",
"data",
"property"
] | train | https://github.com/corycollier/markdown-blogger/blob/111553ec6be90c5af4af47909fb67ee176dc0ec0/src/Blog.php#L26-L36 |
corycollier/markdown-blogger | src/Blog.php | Blog.getTitle | public function getTitle()
{
$crawler = $this->getCrawler();
$result = $crawler->filter('h1');
if ($result->count()) {
return $result->html();
}
} | php | public function getTitle()
{
$crawler = $this->getCrawler();
$result = $crawler->filter('h1');
if ($result->count()) {
return $result->html();
}
} | [
"public",
"function",
"getTitle",
"(",
")",
"{",
"$",
"crawler",
"=",
"$",
"this",
"->",
"getCrawler",
"(",
")",
";",
"$",
"result",
"=",
"$",
"crawler",
"->",
"filter",
"(",
"'h1'",
")",
";",
"if",
"(",
"$",
"result",
"->",
"count",
"(",
")",
")... | Gets the title of the blog post
@return string | [
"Gets",
"the",
"title",
"of",
"the",
"blog",
"post"
] | train | https://github.com/corycollier/markdown-blogger/blob/111553ec6be90c5af4af47909fb67ee176dc0ec0/src/Blog.php#L73-L81 |
corycollier/markdown-blogger | src/Blog.php | Blog.getKeywords | public function getKeywords()
{
$results = [];
$data = $this->getData();
$text = strip_tags($data['content']);
$words = str_word_count($text, 1);
foreach ($words as $word) {
if (strlen($word) < 4) {
continue;
}
if (! array_key_exists($word, $results)) {
$results[$word] = 0;
}
$results[$word]++;
}
arsort($results);
$results = array_slice(array_keys($results), 0, 20);
return implode(', ', $results);
} | php | public function getKeywords()
{
$results = [];
$data = $this->getData();
$text = strip_tags($data['content']);
$words = str_word_count($text, 1);
foreach ($words as $word) {
if (strlen($word) < 4) {
continue;
}
if (! array_key_exists($word, $results)) {
$results[$word] = 0;
}
$results[$word]++;
}
arsort($results);
$results = array_slice(array_keys($results), 0, 20);
return implode(', ', $results);
} | [
"public",
"function",
"getKeywords",
"(",
")",
"{",
"$",
"results",
"=",
"[",
"]",
";",
"$",
"data",
"=",
"$",
"this",
"->",
"getData",
"(",
")",
";",
"$",
"text",
"=",
"strip_tags",
"(",
"$",
"data",
"[",
"'content'",
"]",
")",
";",
"$",
"words"... | Gets the keywords of the blog post, by finding the most common words in the post
@return array | [
"Gets",
"the",
"keywords",
"of",
"the",
"blog",
"post",
"by",
"finding",
"the",
"most",
"common",
"words",
"in",
"the",
"post"
] | train | https://github.com/corycollier/markdown-blogger/blob/111553ec6be90c5af4af47909fb67ee176dc0ec0/src/Blog.php#L138-L157 |
swoft-cloud/swoft-console | src/Style/Color.php | Color.make | public static function make(string $fg = '', string $bg = '', array $options = []): Color
{
return new self($fg, $bg, $options);
} | php | public static function make(string $fg = '', string $bg = '', array $options = []): Color
{
return new self($fg, $bg, $options);
} | [
"public",
"static",
"function",
"make",
"(",
"string",
"$",
"fg",
"=",
"''",
",",
"string",
"$",
"bg",
"=",
"''",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
":",
"Color",
"{",
"return",
"new",
"self",
"(",
"$",
"fg",
",",
"$",
"bg",
",",... | 新建一个颜色
@param string $fg 前景色
@param string $bg 背景色
@param array $options 选项
@return Color
@throws \InvalidArgumentException | [
"新建一个颜色"
] | train | https://github.com/swoft-cloud/swoft-console/blob/d7153f56505a9be420ebae9eb29f7e45bfb2982e/src/Style/Color.php#L96-L99 |
swoft-cloud/swoft-console | src/Style/Color.php | Color.getStyle | public function getStyle(): string
{
$values = $this->options;
if ($this->bgColor > 0) {
array_unshift($values, $this->bgColor);
}
if ($this->fgColor > 0) {
array_unshift($values, $this->fgColor);
}
return implode(';', $values);
} | php | public function getStyle(): string
{
$values = $this->options;
if ($this->bgColor > 0) {
array_unshift($values, $this->bgColor);
}
if ($this->fgColor > 0) {
array_unshift($values, $this->fgColor);
}
return implode(';', $values);
} | [
"public",
"function",
"getStyle",
"(",
")",
":",
"string",
"{",
"$",
"values",
"=",
"$",
"this",
"->",
"options",
";",
"if",
"(",
"$",
"this",
"->",
"bgColor",
">",
"0",
")",
"{",
"array_unshift",
"(",
"$",
"values",
",",
"$",
"this",
"->",
"bgColo... | 获取当前颜色值
@return string | [
"获取当前颜色值"
] | train | https://github.com/swoft-cloud/swoft-console/blob/d7153f56505a9be420ebae9eb29f7e45bfb2982e/src/Style/Color.php#L152-L164 |
CampaignChain/core | EventListener/UserAvatarListener.php | UserAvatarListener.prePersist | public function prePersist(User $user, LifecycleEventArgs $event)
{
$avatarImage = $user->getAvatarImage();
if (empty($avatarImage)) {
$this->userService->downloadAndSetGravatarImage($user);
}
} | php | public function prePersist(User $user, LifecycleEventArgs $event)
{
$avatarImage = $user->getAvatarImage();
if (empty($avatarImage)) {
$this->userService->downloadAndSetGravatarImage($user);
}
} | [
"public",
"function",
"prePersist",
"(",
"User",
"$",
"user",
",",
"LifecycleEventArgs",
"$",
"event",
")",
"{",
"$",
"avatarImage",
"=",
"$",
"user",
"->",
"getAvatarImage",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"avatarImage",
")",
")",
"{",
"$... | Download avatar image from Gravatar if there wasn't one uploaded
@param User $user
@param LifecycleEventArgs $event | [
"Download",
"avatar",
"image",
"from",
"Gravatar",
"if",
"there",
"wasn",
"t",
"one",
"uploaded"
] | train | https://github.com/CampaignChain/core/blob/82526548a223ed49fcd65ed7c23638544499775f/EventListener/UserAvatarListener.php#L51-L57 |
CampaignChain/core | EventListener/UserAvatarListener.php | UserAvatarListener.preUpdate | public function preUpdate(User $user, PreUpdateEventArgs $event)
{
if ($event->hasChangedField('avatarImage')) {
$oldAvatarImage = $event->getOldValue('avatarImage');
if (!empty($oldAvatarImage)) {
$this->userService->deleteAvatar($oldAvatarImage);
}
}
} | php | public function preUpdate(User $user, PreUpdateEventArgs $event)
{
if ($event->hasChangedField('avatarImage')) {
$oldAvatarImage = $event->getOldValue('avatarImage');
if (!empty($oldAvatarImage)) {
$this->userService->deleteAvatar($oldAvatarImage);
}
}
} | [
"public",
"function",
"preUpdate",
"(",
"User",
"$",
"user",
",",
"PreUpdateEventArgs",
"$",
"event",
")",
"{",
"if",
"(",
"$",
"event",
"->",
"hasChangedField",
"(",
"'avatarImage'",
")",
")",
"{",
"$",
"oldAvatarImage",
"=",
"$",
"event",
"->",
"getOldVa... | Delete old avatar image from disk if it has been changed
@param User $user
@param PreUpdateEventArgs $event | [
"Delete",
"old",
"avatar",
"image",
"from",
"disk",
"if",
"it",
"has",
"been",
"changed"
] | train | https://github.com/CampaignChain/core/blob/82526548a223ed49fcd65ed7c23638544499775f/EventListener/UserAvatarListener.php#L65-L73 |
CampaignChain/core | EventListener/UserAvatarListener.php | UserAvatarListener.preRemove | public function preRemove(User $user, LifecycleEventArgs $event)
{
$oldAvatarImage = $user->getAvatarImage();
if (!empty($oldAvatarImage)) {
$this->userService->deleteAvatar($oldAvatarImage);
}
} | php | public function preRemove(User $user, LifecycleEventArgs $event)
{
$oldAvatarImage = $user->getAvatarImage();
if (!empty($oldAvatarImage)) {
$this->userService->deleteAvatar($oldAvatarImage);
}
} | [
"public",
"function",
"preRemove",
"(",
"User",
"$",
"user",
",",
"LifecycleEventArgs",
"$",
"event",
")",
"{",
"$",
"oldAvatarImage",
"=",
"$",
"user",
"->",
"getAvatarImage",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"oldAvatarImage",
")",
")",... | Delete avatar image from disk on user deletion
@param User $user
@param LifecycleEventArgs $event | [
"Delete",
"avatar",
"image",
"from",
"disk",
"on",
"user",
"deletion"
] | train | https://github.com/CampaignChain/core/blob/82526548a223ed49fcd65ed7c23638544499775f/EventListener/UserAvatarListener.php#L81-L87 |
CampaignChain/core | Controller/Module/ActivityModuleController.php | ActivityModuleController.newAction | public function newAction(Request $request)
{
$operation = null;
/*
* Set Activity's context from user's choice.
*/
/** @var ActivityWizard $wizard */
$wizard = $this->get('campaignchain.core.activity.wizard');
if (!$wizard->getCampaign()) {
return $this->redirectToRoute('campaignchain_core_activities_new');
}
$campaignService = $this->get('campaignchain.core.campaign');
$campaign = $campaignService->getCampaign($wizard->getCampaign());
$locationService = $this->get('campaignchain.core.location');
if($wizard->getLocation()) {
$location = $locationService->getLocation($wizard->getLocation());
} else {
$location = null;
}
$this->setActivityContext($campaign, $location);
$activity = $wizard->getNewActivity();
$activity->setEqualsOperation($this->parameters['equals_operation']);
$form = $this->createForm(
ActivityType::class,
$activity,
$this->getActivityFormTypeOptions('new')
);
$form->handleRequest($request);
$em = $this->getDoctrine()->getManager();
if ($form->isValid()) {
try {
$em->getConnection()->beginTransaction();
$activity = $this->createActivity($activity, $form);
$this->addFlash(
'success',
'Your new activity <a href="' . $this->generateUrl('campaignchain_core_activity_edit', array('id' => $activity->getId())) . '">' . $activity->getName() . '</a> was created successfully.'
);
$wizard->end();
$em->getConnection()->commit();
return $this->redirect($this->generateUrl('campaignchain_core_activities'));
} catch(\Exception $e) {
$em->getConnection()->rollback();
if($this->get('kernel')->getEnvironment() == 'dev'){
$message = $e->getMessage().' '.$e->getFile().' '.$e->getLine().'<br/>'.$e->getTraceAsString();
} else {
$message = $e->getMessage();
}
$this->addFlash(
'warning',
$message
);
$this->getLogger()->error($e->getMessage(), array(
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTrace(),
));
}
}
if($location){
$channelModule = $wizard->getChannelModule();
$channelModuleBundle = $wizard->getChannelModuleBundle();
} else {
$channelModule = null;
$channelModuleBundle = null;
}
/*
* Define default rendering options and then apply those defined by the
* module's handler if applicable.
*/
$defaultRenderOptions = array(
'template' => 'CampaignChainCoreBundle:Operation:new.html.twig',
'vars' => array(
'page_title' => 'New Activity',
'activity' => $activity,
'campaign' => $this->campaign,
'campaign_module' => $this->campaign->getCampaignModule(),
'channel_module' => $channelModule,
'channel_module_bundle' => $channelModuleBundle,
'location' => $this->location,
'form' => $form->createView(),
'form_submit_label' => 'Save',
'form_cancel_route' => 'campaignchain_core_activities_new'
)
);
$handlerRenderOptions = $this->handler->getNewRenderOptions();
return $this->renderWithHandlerOptions($defaultRenderOptions, $handlerRenderOptions);
} | php | public function newAction(Request $request)
{
$operation = null;
/*
* Set Activity's context from user's choice.
*/
/** @var ActivityWizard $wizard */
$wizard = $this->get('campaignchain.core.activity.wizard');
if (!$wizard->getCampaign()) {
return $this->redirectToRoute('campaignchain_core_activities_new');
}
$campaignService = $this->get('campaignchain.core.campaign');
$campaign = $campaignService->getCampaign($wizard->getCampaign());
$locationService = $this->get('campaignchain.core.location');
if($wizard->getLocation()) {
$location = $locationService->getLocation($wizard->getLocation());
} else {
$location = null;
}
$this->setActivityContext($campaign, $location);
$activity = $wizard->getNewActivity();
$activity->setEqualsOperation($this->parameters['equals_operation']);
$form = $this->createForm(
ActivityType::class,
$activity,
$this->getActivityFormTypeOptions('new')
);
$form->handleRequest($request);
$em = $this->getDoctrine()->getManager();
if ($form->isValid()) {
try {
$em->getConnection()->beginTransaction();
$activity = $this->createActivity($activity, $form);
$this->addFlash(
'success',
'Your new activity <a href="' . $this->generateUrl('campaignchain_core_activity_edit', array('id' => $activity->getId())) . '">' . $activity->getName() . '</a> was created successfully.'
);
$wizard->end();
$em->getConnection()->commit();
return $this->redirect($this->generateUrl('campaignchain_core_activities'));
} catch(\Exception $e) {
$em->getConnection()->rollback();
if($this->get('kernel')->getEnvironment() == 'dev'){
$message = $e->getMessage().' '.$e->getFile().' '.$e->getLine().'<br/>'.$e->getTraceAsString();
} else {
$message = $e->getMessage();
}
$this->addFlash(
'warning',
$message
);
$this->getLogger()->error($e->getMessage(), array(
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTrace(),
));
}
}
if($location){
$channelModule = $wizard->getChannelModule();
$channelModuleBundle = $wizard->getChannelModuleBundle();
} else {
$channelModule = null;
$channelModuleBundle = null;
}
/*
* Define default rendering options and then apply those defined by the
* module's handler if applicable.
*/
$defaultRenderOptions = array(
'template' => 'CampaignChainCoreBundle:Operation:new.html.twig',
'vars' => array(
'page_title' => 'New Activity',
'activity' => $activity,
'campaign' => $this->campaign,
'campaign_module' => $this->campaign->getCampaignModule(),
'channel_module' => $channelModule,
'channel_module_bundle' => $channelModuleBundle,
'location' => $this->location,
'form' => $form->createView(),
'form_submit_label' => 'Save',
'form_cancel_route' => 'campaignchain_core_activities_new'
)
);
$handlerRenderOptions = $this->handler->getNewRenderOptions();
return $this->renderWithHandlerOptions($defaultRenderOptions, $handlerRenderOptions);
} | [
"public",
"function",
"newAction",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"operation",
"=",
"null",
";",
"/*\n * Set Activity's context from user's choice.\n */",
"/** @var ActivityWizard $wizard */",
"$",
"wizard",
"=",
"$",
"this",
"->",
"get",
... | Symfony controller action for creating a new CampaignChain Activity.
@param Request $request
@return \Symfony\Component\HttpFoundation\RedirectResponse|Response
@throws \Exception | [
"Symfony",
"controller",
"action",
"for",
"creating",
"a",
"new",
"CampaignChain",
"Activity",
"."
] | train | https://github.com/CampaignChain/core/blob/82526548a223ed49fcd65ed7c23638544499775f/Controller/Module/ActivityModuleController.php#L152-L257 |
CampaignChain/core | Controller/Module/ActivityModuleController.php | ActivityModuleController.editAction | public function editAction(Request $request, $id)
{
$activityService = $this->get('campaignchain.core.activity');
$this->activity = $activityService->getActivity($id);
$this->campaign = $this->activity->getCampaign();
$this->location = $this->activity->getLocation();
if($this->parameters['equals_operation']) {
// Get the one operation.
$this->operations[0] = $activityService->getOperation($id);
} else {
throw new \Exception(
'Multiple Operations for one Activity not implemented yet.'
);
}
$content = $this->handler->preFormSubmitEditEvent($this->operations[0]);
$form = $this->createForm(
ActivityType::class,
$this->activity,
$this->getActivityFormTypeOptions('edit')
);
$form->handleRequest($request);
if ($form->isValid()) {
try {
$this->activity = $this->editActivity($this->activity, $form, $content);
$this->addFlash(
'success',
'Your activity <a href="'.$this->generateUrl('campaignchain_core_activity_edit', array('id' => $this->activity->getId())).'">'.$this->activity->getName().'</a> was edited successfully.'
);
return $this->redirect($this->generateUrl('campaignchain_core_activities'));
} catch(\Exception $e) {
$this->addFlash(
'warning',
$e->getMessage()
);
$this->getLogger()->error($e->getMessage(), array(
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTrace(),
));
}
}
/*
* Define default rendering options and then apply those defined by the
* module's handler if applicable.
*/
$defaultRenderOptions = array(
'template' => 'CampaignChainCoreBundle:Operation:new.html.twig',
'vars' => array(
'page_title' => 'Edit Activity',
'activity' => $this->activity,
'form' => $form->createView(),
'form_submit_label' => 'Save',
'form_cancel_route' => 'campaignchain_core_activities'
)
);
$handlerRenderOptions = $this->handler->getEditRenderOptions(
$this->operations[0]
);
return $this->renderWithHandlerOptions($defaultRenderOptions, $handlerRenderOptions);
} | php | public function editAction(Request $request, $id)
{
$activityService = $this->get('campaignchain.core.activity');
$this->activity = $activityService->getActivity($id);
$this->campaign = $this->activity->getCampaign();
$this->location = $this->activity->getLocation();
if($this->parameters['equals_operation']) {
// Get the one operation.
$this->operations[0] = $activityService->getOperation($id);
} else {
throw new \Exception(
'Multiple Operations for one Activity not implemented yet.'
);
}
$content = $this->handler->preFormSubmitEditEvent($this->operations[0]);
$form = $this->createForm(
ActivityType::class,
$this->activity,
$this->getActivityFormTypeOptions('edit')
);
$form->handleRequest($request);
if ($form->isValid()) {
try {
$this->activity = $this->editActivity($this->activity, $form, $content);
$this->addFlash(
'success',
'Your activity <a href="'.$this->generateUrl('campaignchain_core_activity_edit', array('id' => $this->activity->getId())).'">'.$this->activity->getName().'</a> was edited successfully.'
);
return $this->redirect($this->generateUrl('campaignchain_core_activities'));
} catch(\Exception $e) {
$this->addFlash(
'warning',
$e->getMessage()
);
$this->getLogger()->error($e->getMessage(), array(
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTrace(),
));
}
}
/*
* Define default rendering options and then apply those defined by the
* module's handler if applicable.
*/
$defaultRenderOptions = array(
'template' => 'CampaignChainCoreBundle:Operation:new.html.twig',
'vars' => array(
'page_title' => 'Edit Activity',
'activity' => $this->activity,
'form' => $form->createView(),
'form_submit_label' => 'Save',
'form_cancel_route' => 'campaignchain_core_activities'
)
);
$handlerRenderOptions = $this->handler->getEditRenderOptions(
$this->operations[0]
);
return $this->renderWithHandlerOptions($defaultRenderOptions, $handlerRenderOptions);
} | [
"public",
"function",
"editAction",
"(",
"Request",
"$",
"request",
",",
"$",
"id",
")",
"{",
"$",
"activityService",
"=",
"$",
"this",
"->",
"get",
"(",
"'campaignchain.core.activity'",
")",
";",
"$",
"this",
"->",
"activity",
"=",
"$",
"activityService",
... | Symfony controller action for editing a CampaignChain Activity.
@param Request $request
@param $id
@return \Symfony\Component\HttpFoundation\RedirectResponse|Response
@throws \Exception | [
"Symfony",
"controller",
"action",
"for",
"editing",
"a",
"CampaignChain",
"Activity",
"."
] | train | https://github.com/CampaignChain/core/blob/82526548a223ed49fcd65ed7c23638544499775f/Controller/Module/ActivityModuleController.php#L451-L522 |
CampaignChain/core | Controller/Module/ActivityModuleController.php | ActivityModuleController.editModalAction | public function editModalAction(Request $request, $id)
{
$activityService = $this->get('campaignchain.core.activity');
$this->activity = $activityService->getActivity($id);
$this->location = $this->activity->getLocation();
$this->campaign = $this->activity->getCampaign();
if($this->parameters['equals_operation']) {
// Get the one operation.
$this->operations[0] = $activityService->getOperation($id);
} else {
throw new \Exception(
'Multiple Operations for one Activity not implemented yet.'
);
}
$this->handler->preFormSubmitEditModalEvent($this->operations[0]);
$form = $this->createForm(
ActivityType::class,
$this->activity,
$this->getActivityFormTypeOptions('default')
);
$form->handleRequest($request);
/*
* Define default rendering options and then apply those defined by the
* module's handler if applicable.
*/
$defaultRenderOptions = array(
'template' => 'CampaignChainCoreBundle:Base:new_modal.html.twig',
'vars' => array(
'page_title' => 'Edit Activity',
'form' => $form->createView()
)
);
$handlerRenderOptions = $this->handler->getEditModalRenderOptions(
$this->operations[0]
);
return $this->renderWithHandlerOptions($defaultRenderOptions, $handlerRenderOptions);
} | php | public function editModalAction(Request $request, $id)
{
$activityService = $this->get('campaignchain.core.activity');
$this->activity = $activityService->getActivity($id);
$this->location = $this->activity->getLocation();
$this->campaign = $this->activity->getCampaign();
if($this->parameters['equals_operation']) {
// Get the one operation.
$this->operations[0] = $activityService->getOperation($id);
} else {
throw new \Exception(
'Multiple Operations for one Activity not implemented yet.'
);
}
$this->handler->preFormSubmitEditModalEvent($this->operations[0]);
$form = $this->createForm(
ActivityType::class,
$this->activity,
$this->getActivityFormTypeOptions('default')
);
$form->handleRequest($request);
/*
* Define default rendering options and then apply those defined by the
* module's handler if applicable.
*/
$defaultRenderOptions = array(
'template' => 'CampaignChainCoreBundle:Base:new_modal.html.twig',
'vars' => array(
'page_title' => 'Edit Activity',
'form' => $form->createView()
)
);
$handlerRenderOptions = $this->handler->getEditModalRenderOptions(
$this->operations[0]
);
return $this->renderWithHandlerOptions($defaultRenderOptions, $handlerRenderOptions);
} | [
"public",
"function",
"editModalAction",
"(",
"Request",
"$",
"request",
",",
"$",
"id",
")",
"{",
"$",
"activityService",
"=",
"$",
"this",
"->",
"get",
"(",
"'campaignchain.core.activity'",
")",
";",
"$",
"this",
"->",
"activity",
"=",
"$",
"activityServic... | Symfony controller action for editing a CampaignChain Activity in a
pop-up window.
@param Request $request
@param $id
@return Response
@throws \Exception | [
"Symfony",
"controller",
"action",
"for",
"editing",
"a",
"CampaignChain",
"Activity",
"in",
"a",
"pop",
"-",
"up",
"window",
"."
] | train | https://github.com/CampaignChain/core/blob/82526548a223ed49fcd65ed7c23638544499775f/Controller/Module/ActivityModuleController.php#L605-L648 |
CampaignChain/core | Controller/Module/ActivityModuleController.php | ActivityModuleController.editApiAction | public function editApiAction(Request $request, $id)
{
$responseData = array();
$data = $request->get('campaignchain_core_activity');
$activityService = $this->get('campaignchain.core.activity');
$this->activity = $activityService->getActivity($id);
$this->activity->setName($data['name']);
// Remember original dates.
$responseData['start_date'] =
$responseData['end_date'] =
$this->activity->getStartDate()->format(\DateTime::ISO8601);
// Clear all flash bags.
$this->get('session')->getFlashBag()->clear();
$em = $this->getDoctrine()->getManager();
// Make sure that data stays intact by using transactions.
try {
$em->getConnection()->beginTransaction();
if($this->parameters['equals_operation']) {
/** @var Operation $operation */
$operation = $activityService->getOperation($id);
// The activity equals the operation. Thus, we update the operation
// with the same data.
$operation->setName($data['name']);
$this->operations[0] = $operation;
if($this->handler->hasContent('editModal')){
$content = $this->handler->processContent(
$this->operations[0],
$data[$this->contentModuleFormName]
);
} else {
$content = null;
}
} else {
throw new \Exception(
'Multiple Operations for one Activity not implemented yet.'
);
}
$em = $this->getDoctrine()->getManager();
$em->persist($this->activity);
$em->persist($this->operations[0]);
if($this->handler->hasContent('editModal')) {
$em->persist($content);
}
/** @var HookService $hookService */
$hookService = $this->get('campaignchain.core.hook');
$hookService->processHooks(
$this->parameters['bundle_name'],
$this->parameters['module_identifier'],
$this->activity,
$data
);
/** @var Activity activity */
$this->activity = $hookService->getEntity();
$em->flush();
// The module tries to execute the job immediately.
$this->handler->postPersistEditEvent($operation, $content);
$responseData['start_date'] =
$responseData['end_date'] =
$this->activity->getStartDate()->format(\DateTime::ISO8601);
$responseData['success'] = true;
$em->getConnection()->commit();
} catch (\Exception $e) {
$em->getConnection()->rollback();
if($this->get('kernel')->getEnvironment() == 'dev'){
$message = $e->getMessage().' '.$e->getFile().' '.$e->getLine().'<br/>'.$e->getTraceAsString();
} else {
$message = $e->getMessage();
}
$this->addFlash(
'warning',
$message
);
$this->getLogger()->error($e->getMessage(), array(
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTrace(),
));
$responseData['message'] = $e->getMessage();
$responseData['success'] = false;
}
$responseData['status'] = $this->activity->getStatus();
$serializer = $this->get('campaignchain.core.serializer.default');
return new Response($serializer->serialize($responseData, 'json'));
} | php | public function editApiAction(Request $request, $id)
{
$responseData = array();
$data = $request->get('campaignchain_core_activity');
$activityService = $this->get('campaignchain.core.activity');
$this->activity = $activityService->getActivity($id);
$this->activity->setName($data['name']);
// Remember original dates.
$responseData['start_date'] =
$responseData['end_date'] =
$this->activity->getStartDate()->format(\DateTime::ISO8601);
// Clear all flash bags.
$this->get('session')->getFlashBag()->clear();
$em = $this->getDoctrine()->getManager();
// Make sure that data stays intact by using transactions.
try {
$em->getConnection()->beginTransaction();
if($this->parameters['equals_operation']) {
/** @var Operation $operation */
$operation = $activityService->getOperation($id);
// The activity equals the operation. Thus, we update the operation
// with the same data.
$operation->setName($data['name']);
$this->operations[0] = $operation;
if($this->handler->hasContent('editModal')){
$content = $this->handler->processContent(
$this->operations[0],
$data[$this->contentModuleFormName]
);
} else {
$content = null;
}
} else {
throw new \Exception(
'Multiple Operations for one Activity not implemented yet.'
);
}
$em = $this->getDoctrine()->getManager();
$em->persist($this->activity);
$em->persist($this->operations[0]);
if($this->handler->hasContent('editModal')) {
$em->persist($content);
}
/** @var HookService $hookService */
$hookService = $this->get('campaignchain.core.hook');
$hookService->processHooks(
$this->parameters['bundle_name'],
$this->parameters['module_identifier'],
$this->activity,
$data
);
/** @var Activity activity */
$this->activity = $hookService->getEntity();
$em->flush();
// The module tries to execute the job immediately.
$this->handler->postPersistEditEvent($operation, $content);
$responseData['start_date'] =
$responseData['end_date'] =
$this->activity->getStartDate()->format(\DateTime::ISO8601);
$responseData['success'] = true;
$em->getConnection()->commit();
} catch (\Exception $e) {
$em->getConnection()->rollback();
if($this->get('kernel')->getEnvironment() == 'dev'){
$message = $e->getMessage().' '.$e->getFile().' '.$e->getLine().'<br/>'.$e->getTraceAsString();
} else {
$message = $e->getMessage();
}
$this->addFlash(
'warning',
$message
);
$this->getLogger()->error($e->getMessage(), array(
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTrace(),
));
$responseData['message'] = $e->getMessage();
$responseData['success'] = false;
}
$responseData['status'] = $this->activity->getStatus();
$serializer = $this->get('campaignchain.core.serializer.default');
return new Response($serializer->serialize($responseData, 'json'));
} | [
"public",
"function",
"editApiAction",
"(",
"Request",
"$",
"request",
",",
"$",
"id",
")",
"{",
"$",
"responseData",
"=",
"array",
"(",
")",
";",
"$",
"data",
"=",
"$",
"request",
"->",
"get",
"(",
"'campaignchain_core_activity'",
")",
";",
"$",
"activi... | Symfony controller action that takes the data posted by the editModalAction
and persists it.
@param Request $request
@param $id
@return Response
@throws \Exception | [
"Symfony",
"controller",
"action",
"that",
"takes",
"the",
"data",
"posted",
"by",
"the",
"editModalAction",
"and",
"persists",
"it",
"."
] | train | https://github.com/CampaignChain/core/blob/82526548a223ed49fcd65ed7c23638544499775f/Controller/Module/ActivityModuleController.php#L659-L764 |
CampaignChain/core | Controller/Module/ActivityModuleController.php | ActivityModuleController.readAction | public function readAction(Request $request, $id, $isModal = false)
{
$activityService = $this->get('campaignchain.core.activity');
$this->activity = $activityService->getActivity($id);
if($this->parameters['equals_operation']) {
// Get the one operation.
$this->operations[0] = $activityService->getOperation($id);
} else {
throw new \Exception(
'Multiple Operations for one Activity not implemented yet.'
);
}
if($this->handler){
return $this->handler->readAction($this->operations[0], $isModal);
} else {
throw new \Exception('No read handler defined.');
}
} | php | public function readAction(Request $request, $id, $isModal = false)
{
$activityService = $this->get('campaignchain.core.activity');
$this->activity = $activityService->getActivity($id);
if($this->parameters['equals_operation']) {
// Get the one operation.
$this->operations[0] = $activityService->getOperation($id);
} else {
throw new \Exception(
'Multiple Operations for one Activity not implemented yet.'
);
}
if($this->handler){
return $this->handler->readAction($this->operations[0], $isModal);
} else {
throw new \Exception('No read handler defined.');
}
} | [
"public",
"function",
"readAction",
"(",
"Request",
"$",
"request",
",",
"$",
"id",
",",
"$",
"isModal",
"=",
"false",
")",
"{",
"$",
"activityService",
"=",
"$",
"this",
"->",
"get",
"(",
"'campaignchain.core.activity'",
")",
";",
"$",
"this",
"->",
"ac... | Symfony controller action for viewing the data of a CampaignChain Activity.
@param Request $request
@param $id
@param bool $isModal Modal view yes or no?
@return mixed
@throws \Exception | [
"Symfony",
"controller",
"action",
"for",
"viewing",
"the",
"data",
"of",
"a",
"CampaignChain",
"Activity",
"."
] | train | https://github.com/CampaignChain/core/blob/82526548a223ed49fcd65ed7c23638544499775f/Controller/Module/ActivityModuleController.php#L775-L794 |
CampaignChain/core | Controller/Module/ActivityModuleController.php | ActivityModuleController.getActivityFormTypeOptions | public function getActivityFormTypeOptions($view = 'default')
{
$options['view'] = $this->view = $view;
$options['bundle_name'] = $this->parameters['bundle_name'];
$options['module_identifier'] = $this->parameters['module_identifier'];
if (isset($this->parameters['hooks_options'])) {
$options['hooks_options'] = $this->parameters['hooks_options'];
}
if($this->handler->hasContent($this->view)) {
$options['content_forms'] = $this->getContentFormTypesOptions();
}
$options['campaign'] = $this->campaign;
return $options;
} | php | public function getActivityFormTypeOptions($view = 'default')
{
$options['view'] = $this->view = $view;
$options['bundle_name'] = $this->parameters['bundle_name'];
$options['module_identifier'] = $this->parameters['module_identifier'];
if (isset($this->parameters['hooks_options'])) {
$options['hooks_options'] = $this->parameters['hooks_options'];
}
if($this->handler->hasContent($this->view)) {
$options['content_forms'] = $this->getContentFormTypesOptions();
}
$options['campaign'] = $this->campaign;
return $options;
} | [
"public",
"function",
"getActivityFormTypeOptions",
"(",
"$",
"view",
"=",
"'default'",
")",
"{",
"$",
"options",
"[",
"'view'",
"]",
"=",
"$",
"this",
"->",
"view",
"=",
"$",
"view",
";",
"$",
"options",
"[",
"'bundle_name'",
"]",
"=",
"$",
"this",
"-... | Configure an Activity's form type.
@return object | [
"Configure",
"an",
"Activity",
"s",
"form",
"type",
"."
] | train | https://github.com/CampaignChain/core/blob/82526548a223ed49fcd65ed7c23638544499775f/Controller/Module/ActivityModuleController.php#L815-L829 |
CampaignChain/core | Controller/Module/ActivityModuleController.php | ActivityModuleController.getContentFormTypesOptions | private function getContentFormTypesOptions()
{
foreach($this->parameters['operations'] as $operationParams){
$operationForms[] = $this->getContentFormTypeOptions($operationParams);
}
return $operationForms;
} | php | private function getContentFormTypesOptions()
{
foreach($this->parameters['operations'] as $operationParams){
$operationForms[] = $this->getContentFormTypeOptions($operationParams);
}
return $operationForms;
} | [
"private",
"function",
"getContentFormTypesOptions",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"parameters",
"[",
"'operations'",
"]",
"as",
"$",
"operationParams",
")",
"{",
"$",
"operationForms",
"[",
"]",
"=",
"$",
"this",
"->",
"getContentFormTypeO... | Set the Operation forms for this Activity.
@return array
@throws \Exception | [
"Set",
"the",
"Operation",
"forms",
"for",
"this",
"Activity",
"."
] | train | https://github.com/CampaignChain/core/blob/82526548a223ed49fcd65ed7c23638544499775f/Controller/Module/ActivityModuleController.php#L837-L844 |
CampaignChain/core | Controller/Module/ActivityModuleController.php | ActivityModuleController.renderWithHandlerOptions | private function renderWithHandlerOptions($default, $handler)
{
if(
$handler && is_array($handler) && count($handler) &&
$default && is_array($default) && count($default)
){
if(isset($handler['template'])){
$default['template'] = $handler['template'];
}
if(isset($handler['vars'])) {
$default['vars'] = $default['vars'] + $handler['vars'];
}
}
return $this->render($default['template'], $default['vars']);
} | php | private function renderWithHandlerOptions($default, $handler)
{
if(
$handler && is_array($handler) && count($handler) &&
$default && is_array($default) && count($default)
){
if(isset($handler['template'])){
$default['template'] = $handler['template'];
}
if(isset($handler['vars'])) {
$default['vars'] = $default['vars'] + $handler['vars'];
}
}
return $this->render($default['template'], $default['vars']);
} | [
"private",
"function",
"renderWithHandlerOptions",
"(",
"$",
"default",
",",
"$",
"handler",
")",
"{",
"if",
"(",
"$",
"handler",
"&&",
"is_array",
"(",
"$",
"handler",
")",
"&&",
"count",
"(",
"$",
"handler",
")",
"&&",
"$",
"default",
"&&",
"is_array",... | Applies handler's template render options to default ones.
@param $default
@param $handler
@return array | [
"Applies",
"handler",
"s",
"template",
"render",
"options",
"to",
"default",
"ones",
"."
] | train | https://github.com/CampaignChain/core/blob/82526548a223ed49fcd65ed7c23638544499775f/Controller/Module/ActivityModuleController.php#L880-L895 |
CampaignChain/core | Controller/Module/ActivityModuleController.php | ActivityModuleController.isValidLocation | public function isValidLocation($id)
{
$qb = $this->getDoctrine()->getEntityManager()->createQueryBuilder();
$qb->select('b.name, am.identifier');
$qb->from('CampaignChain\CoreBundle\Entity\Activity', 'a');
$qb->from('CampaignChain\CoreBundle\Entity\ActivityModule', 'am');
$qb->from('CampaignChain\CoreBundle\Entity\Bundle', 'b');
$qb->from('CampaignChain\CoreBundle\Entity\Module', 'm');
$qb->from('CampaignChain\CoreBundle\Entity\Location', 'l');
$qb->from('CampaignChain\CoreBundle\Entity\Channel', 'c');
$qb->innerJoin('am.channelModules', 'cm');
$qb->where('cm.id = c.channelModule');
$qb->andWhere('l.id = :location');
$qb->andWhere('l.channel = c.id');
$qb->andWhere('a.activityModule = am.id');
$qb->andWhere('am.bundle = b.id');
$qb->setParameter('location', $id);
$qb->groupBy('b.name');
$query = $qb->getQuery();
$result = $query->getResult();
if(
!is_array($result) || !count($result) ||
$result[0]['name'] != $this->activityBundleName ||
$result[0]['identifier'] != $this->activityModuleIdentifier
){
return false;
} else {
return true;
}
} | php | public function isValidLocation($id)
{
$qb = $this->getDoctrine()->getEntityManager()->createQueryBuilder();
$qb->select('b.name, am.identifier');
$qb->from('CampaignChain\CoreBundle\Entity\Activity', 'a');
$qb->from('CampaignChain\CoreBundle\Entity\ActivityModule', 'am');
$qb->from('CampaignChain\CoreBundle\Entity\Bundle', 'b');
$qb->from('CampaignChain\CoreBundle\Entity\Module', 'm');
$qb->from('CampaignChain\CoreBundle\Entity\Location', 'l');
$qb->from('CampaignChain\CoreBundle\Entity\Channel', 'c');
$qb->innerJoin('am.channelModules', 'cm');
$qb->where('cm.id = c.channelModule');
$qb->andWhere('l.id = :location');
$qb->andWhere('l.channel = c.id');
$qb->andWhere('a.activityModule = am.id');
$qb->andWhere('am.bundle = b.id');
$qb->setParameter('location', $id);
$qb->groupBy('b.name');
$query = $qb->getQuery();
$result = $query->getResult();
if(
!is_array($result) || !count($result) ||
$result[0]['name'] != $this->activityBundleName ||
$result[0]['identifier'] != $this->activityModuleIdentifier
){
return false;
} else {
return true;
}
} | [
"public",
"function",
"isValidLocation",
"(",
"$",
"id",
")",
"{",
"$",
"qb",
"=",
"$",
"this",
"->",
"getDoctrine",
"(",
")",
"->",
"getEntityManager",
"(",
")",
"->",
"createQueryBuilder",
"(",
")",
";",
"$",
"qb",
"->",
"select",
"(",
"'b.name, am.ide... | This method checks whether the given Location is within a Channel
that the module's Activity is related to.
@param $id The Location ID.
@return bool | [
"This",
"method",
"checks",
"whether",
"the",
"given",
"Location",
"is",
"within",
"a",
"Channel",
"that",
"the",
"module",
"s",
"Activity",
"is",
"related",
"to",
"."
] | train | https://github.com/CampaignChain/core/blob/82526548a223ed49fcd65ed7c23638544499775f/Controller/Module/ActivityModuleController.php#L904-L934 |
KnightSwarm/laravel-saml | src/KnightSwarm/LaravelSaml/LaravelSamlServiceProvider.php | LaravelSamlServiceProvider.register | public function register()
{
$this->app->bind('SamlSpResolver', function($app) {
return new SamlSpResolver($app);
});
$this->app->bind('Saml', function()
{
$sp_resolver = $this->app->make('SamlSpResolver');
$samlboot = new Saml\SamlBoot($sp_resolver->getSPName());
return $samlboot->getSimpleSaml();
});
} | php | public function register()
{
$this->app->bind('SamlSpResolver', function($app) {
return new SamlSpResolver($app);
});
$this->app->bind('Saml', function()
{
$sp_resolver = $this->app->make('SamlSpResolver');
$samlboot = new Saml\SamlBoot($sp_resolver->getSPName());
return $samlboot->getSimpleSaml();
});
} | [
"public",
"function",
"register",
"(",
")",
"{",
"$",
"this",
"->",
"app",
"->",
"bind",
"(",
"'SamlSpResolver'",
",",
"function",
"(",
"$",
"app",
")",
"{",
"return",
"new",
"SamlSpResolver",
"(",
"$",
"app",
")",
";",
"}",
")",
";",
"$",
"this",
... | Register the service provider.
@return void | [
"Register",
"the",
"service",
"provider",
"."
] | train | https://github.com/KnightSwarm/laravel-saml/blob/712d02f6edae914db7b48438361444b2daf66930/src/KnightSwarm/LaravelSaml/LaravelSamlServiceProvider.php#L34-L46 |
CampaignChain/core | Wizard/Install/Validator/Constraints/IsValidBitlyTokenValidator.php | IsValidBitlyTokenValidator.validate | public function validate($value, Constraint $constraint)
{
$bitlyProvider = new BitlyProvider(new GenericAccessTokenAuthenticator($value));
$urlShortener = new UrlShortenerService($bitlyProvider);
$link = new Link();
$link->setLongUrl('http://www.campaignchain.com');
try {
$urlShortener->shorten($link);
} catch (ExternalApiException $e) {
$this->context->buildViolation($constraint->message)
->setParameter('%string%', $value)
->addViolation();
} catch (\Exception $e) {
// rethrow it
throw $e;
}
} | php | public function validate($value, Constraint $constraint)
{
$bitlyProvider = new BitlyProvider(new GenericAccessTokenAuthenticator($value));
$urlShortener = new UrlShortenerService($bitlyProvider);
$link = new Link();
$link->setLongUrl('http://www.campaignchain.com');
try {
$urlShortener->shorten($link);
} catch (ExternalApiException $e) {
$this->context->buildViolation($constraint->message)
->setParameter('%string%', $value)
->addViolation();
} catch (\Exception $e) {
// rethrow it
throw $e;
}
} | [
"public",
"function",
"validate",
"(",
"$",
"value",
",",
"Constraint",
"$",
"constraint",
")",
"{",
"$",
"bitlyProvider",
"=",
"new",
"BitlyProvider",
"(",
"new",
"GenericAccessTokenAuthenticator",
"(",
"$",
"value",
")",
")",
";",
"$",
"urlShortener",
"=",
... | Test if the provided token is not empty and working with bitly
@param mixed $value
@param Constraint $constraint
@throws \Exception | [
"Test",
"if",
"the",
"provided",
"token",
"is",
"not",
"empty",
"and",
"working",
"with",
"bitly"
] | train | https://github.com/CampaignChain/core/blob/82526548a223ed49fcd65ed7c23638544499775f/Wizard/Install/Validator/Constraints/IsValidBitlyTokenValidator.php#L40-L60 |
wisp-x/hopephp | hopephp/library/hope/Session.php | Session.init | public static function init()
{
if (is_null(self::$init)) {
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
self::$init = true;
}
} | php | public static function init()
{
if (is_null(self::$init)) {
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
self::$init = true;
}
} | [
"public",
"static",
"function",
"init",
"(",
")",
"{",
"if",
"(",
"is_null",
"(",
"self",
"::",
"$",
"init",
")",
")",
"{",
"if",
"(",
"session_status",
"(",
")",
"!==",
"PHP_SESSION_ACTIVE",
")",
"{",
"session_start",
"(",
")",
";",
"}",
"self",
"::... | 初始化Session | [
"初始化Session"
] | train | https://github.com/wisp-x/hopephp/blob/5d4ec0fdb847772783259c16c97e9843b81df3c9/hopephp/library/hope/Session.php#L26-L34 |
wisp-x/hopephp | hopephp/library/hope/Session.php | Session.set | public static function set($name, $value = '')
{
empty(self::$init) && self::init();
if (is_string($name)) {
$_SESSION[$name] = $value;
}
if (is_array($name)) {
foreach ($name as $item => $val) {
$_SESSION[$item] = $val;
}
}
} | php | public static function set($name, $value = '')
{
empty(self::$init) && self::init();
if (is_string($name)) {
$_SESSION[$name] = $value;
}
if (is_array($name)) {
foreach ($name as $item => $val) {
$_SESSION[$item] = $val;
}
}
} | [
"public",
"static",
"function",
"set",
"(",
"$",
"name",
",",
"$",
"value",
"=",
"''",
")",
"{",
"empty",
"(",
"self",
"::",
"$",
"init",
")",
"&&",
"self",
"::",
"init",
"(",
")",
";",
"if",
"(",
"is_string",
"(",
"$",
"name",
")",
")",
"{",
... | 设置Session
@param $name string|array Session值|['session名' => 'session值']
@param string $value Session值 | [
"设置Session"
] | train | https://github.com/wisp-x/hopephp/blob/5d4ec0fdb847772783259c16c97e9843b81df3c9/hopephp/library/hope/Session.php#L41-L54 |
wisp-x/hopephp | hopephp/library/hope/Session.php | Session.get | public static function get($name = '')
{
empty(self::$init) && self::init();
return empty($name) ? $_SESSION : (isset($_SESSION[$name]) ? $_SESSION[$name] : false);
} | php | public static function get($name = '')
{
empty(self::$init) && self::init();
return empty($name) ? $_SESSION : (isset($_SESSION[$name]) ? $_SESSION[$name] : false);
} | [
"public",
"static",
"function",
"get",
"(",
"$",
"name",
"=",
"''",
")",
"{",
"empty",
"(",
"self",
"::",
"$",
"init",
")",
"&&",
"self",
"::",
"init",
"(",
")",
";",
"return",
"empty",
"(",
"$",
"name",
")",
"?",
"$",
"_SESSION",
":",
"(",
"is... | 获取Session
@param string $name 为空获取所有Session
@return bool|array|string | [
"获取Session"
] | train | https://github.com/wisp-x/hopephp/blob/5d4ec0fdb847772783259c16c97e9843b81df3c9/hopephp/library/hope/Session.php#L61-L66 |
wisp-x/hopephp | hopephp/library/hope/Session.php | Session.has | public static function has($name)
{
empty(self::$init) && self::init();
return isset($_SESSION[$name]) ? true : false;
} | php | public static function has($name)
{
empty(self::$init) && self::init();
return isset($_SESSION[$name]) ? true : false;
} | [
"public",
"static",
"function",
"has",
"(",
"$",
"name",
")",
"{",
"empty",
"(",
"self",
"::",
"$",
"init",
")",
"&&",
"self",
"::",
"init",
"(",
")",
";",
"return",
"isset",
"(",
"$",
"_SESSION",
"[",
"$",
"name",
"]",
")",
"?",
"true",
":",
"... | 判断Session是否设置
@param $name Session名
@return bool | [
"判断Session是否设置"
] | train | https://github.com/wisp-x/hopephp/blob/5d4ec0fdb847772783259c16c97e9843b81df3c9/hopephp/library/hope/Session.php#L73-L78 |
wisp-x/hopephp | hopephp/library/hope/Session.php | Session.pull | public static function pull($name)
{
empty(self::$init) && self::init();
$session = self::get($name);
if ($session) {
self::delete($name);
return $session;
}
return false;
} | php | public static function pull($name)
{
empty(self::$init) && self::init();
$session = self::get($name);
if ($session) {
self::delete($name);
return $session;
}
return false;
} | [
"public",
"static",
"function",
"pull",
"(",
"$",
"name",
")",
"{",
"empty",
"(",
"self",
"::",
"$",
"init",
")",
"&&",
"self",
"::",
"init",
"(",
")",
";",
"$",
"session",
"=",
"self",
"::",
"get",
"(",
"$",
"name",
")",
";",
"if",
"(",
"$",
... | 取出Session值并删除
@param $name
@return array|bool|string | [
"取出Session值并删除"
] | train | https://github.com/wisp-x/hopephp/blob/5d4ec0fdb847772783259c16c97e9843b81df3c9/hopephp/library/hope/Session.php#L85-L95 |
wisp-x/hopephp | hopephp/library/hope/Session.php | Session.delete | public static function delete($name)
{
empty(self::$init) && self::init();
$session = self::get($name);
if (is_string($session)) {
unset($_SESSION[$name]);
}
if (is_array($session)) {
$_SESSION[$name] = [];
}
return true;
} | php | public static function delete($name)
{
empty(self::$init) && self::init();
$session = self::get($name);
if (is_string($session)) {
unset($_SESSION[$name]);
}
if (is_array($session)) {
$_SESSION[$name] = [];
}
return true;
} | [
"public",
"static",
"function",
"delete",
"(",
"$",
"name",
")",
"{",
"empty",
"(",
"self",
"::",
"$",
"init",
")",
"&&",
"self",
"::",
"init",
"(",
")",
";",
"$",
"session",
"=",
"self",
"::",
"get",
"(",
"$",
"name",
")",
";",
"if",
"(",
"is_... | 删除Session
@param $name Session名
@return bool | [
"删除Session"
] | train | https://github.com/wisp-x/hopephp/blob/5d4ec0fdb847772783259c16c97e9843b81df3c9/hopephp/library/hope/Session.php#L102-L115 |
CampaignChain/core | Repository/CampaignRepository.php | CampaignRepository.getCampaigns | public function getCampaigns() {
return $this->createQueryBuilder('campaign')
->where('campaign.status != :statusBackgroundProcess')
->setParameter('statusBackgroundProcess', Action::STATUS_BACKGROUND_PROCESS)
->orderBy('campaign.startDate', 'DESC')
->getQuery()
->getResult();
} | php | public function getCampaigns() {
return $this->createQueryBuilder('campaign')
->where('campaign.status != :statusBackgroundProcess')
->setParameter('statusBackgroundProcess', Action::STATUS_BACKGROUND_PROCESS)
->orderBy('campaign.startDate', 'DESC')
->getQuery()
->getResult();
} | [
"public",
"function",
"getCampaigns",
"(",
")",
"{",
"return",
"$",
"this",
"->",
"createQueryBuilder",
"(",
"'campaign'",
")",
"->",
"where",
"(",
"'campaign.status != :statusBackgroundProcess'",
")",
"->",
"setParameter",
"(",
"'statusBackgroundProcess'",
",",
"Acti... | get a list of all campaigns
@return array | [
"get",
"a",
"list",
"of",
"all",
"campaigns"
] | train | https://github.com/CampaignChain/core/blob/82526548a223ed49fcd65ed7c23638544499775f/Repository/CampaignRepository.php#L40-L48 |
CampaignChain/core | Repository/CampaignRepository.php | CampaignRepository.getLastAction | public function getLastAction(Campaign $campaign)
{
$lastAction = $this->getEdgeAction($campaign, 'last');
// If there is a last action, make sure it does not equal the first action.
if($lastAction){
$firstAction = $this->getFirstAction($campaign);
if($lastAction->getId() == $firstAction->getId()){
return null;
} else {
return $lastAction;
}
}
} | php | public function getLastAction(Campaign $campaign)
{
$lastAction = $this->getEdgeAction($campaign, 'last');
// If there is a last action, make sure it does not equal the first action.
if($lastAction){
$firstAction = $this->getFirstAction($campaign);
if($lastAction->getId() == $firstAction->getId()){
return null;
} else {
return $lastAction;
}
}
} | [
"public",
"function",
"getLastAction",
"(",
"Campaign",
"$",
"campaign",
")",
"{",
"$",
"lastAction",
"=",
"$",
"this",
"->",
"getEdgeAction",
"(",
"$",
"campaign",
",",
"'last'",
")",
";",
"// If there is a last action, make sure it does not equal the first action.",
... | Get the last Action, i.e. Activity or Milestone.
@param Campaign $campaign
@return Activity|Milestone|null | [
"Get",
"the",
"last",
"Action",
"i",
".",
"e",
".",
"Activity",
"or",
"Milestone",
"."
] | train | https://github.com/CampaignChain/core/blob/82526548a223ed49fcd65ed7c23638544499775f/Repository/CampaignRepository.php#L137-L151 |
CampaignChain/core | Repository/CampaignRepository.php | CampaignRepository.getEdgeAction | private function getEdgeAction(Campaign $campaign, $position)
{
if($position != 'first' && $position != 'last'){
throw new \Exception('Position must be either "first" or "last"');
}
if($position == 'first'){
$order = 'ASC';
} else {
$order = 'DESC';
}
// Get first Activity
/** @var Activity $activity */
$activity = $this->createQueryBuilder('c')
->select('a')
->from('CampaignChain\CoreBundle\Entity\Activity', 'a')
->where('a.campaign = :campaign')
->setParameter('campaign', $campaign)
->orderBy('a.startDate', $order)
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();
// Get first Milestone
/** @var Milestone $milestone */
$milestone = $this->createQueryBuilder('c')
->select('m')
->from('CampaignChain\CoreBundle\Entity\Milestone', 'm')
->where('m.campaign = :campaign')
->setParameter('campaign', $campaign)
->orderBy('m.startDate', $order)
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();
// Does Activity or Milestone exist?
if($activity == null && $milestone == null){
return null;
}
if($milestone == null){
return $activity;
}
if($activity == null){
return $milestone;
}
// Does Activity or Milestone come first/last?
if($position == 'first') {
if ($activity->getStartDate() < $milestone->getStartDate()) {
return $activity;
} else {
return $milestone;
}
} else {
if ($activity->getStartDate() > $milestone->getStartDate()) {
return $activity;
} else {
return $milestone;
}
}
} | php | private function getEdgeAction(Campaign $campaign, $position)
{
if($position != 'first' && $position != 'last'){
throw new \Exception('Position must be either "first" or "last"');
}
if($position == 'first'){
$order = 'ASC';
} else {
$order = 'DESC';
}
// Get first Activity
/** @var Activity $activity */
$activity = $this->createQueryBuilder('c')
->select('a')
->from('CampaignChain\CoreBundle\Entity\Activity', 'a')
->where('a.campaign = :campaign')
->setParameter('campaign', $campaign)
->orderBy('a.startDate', $order)
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();
// Get first Milestone
/** @var Milestone $milestone */
$milestone = $this->createQueryBuilder('c')
->select('m')
->from('CampaignChain\CoreBundle\Entity\Milestone', 'm')
->where('m.campaign = :campaign')
->setParameter('campaign', $campaign)
->orderBy('m.startDate', $order)
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();
// Does Activity or Milestone exist?
if($activity == null && $milestone == null){
return null;
}
if($milestone == null){
return $activity;
}
if($activity == null){
return $milestone;
}
// Does Activity or Milestone come first/last?
if($position == 'first') {
if ($activity->getStartDate() < $milestone->getStartDate()) {
return $activity;
} else {
return $milestone;
}
} else {
if ($activity->getStartDate() > $milestone->getStartDate()) {
return $activity;
} else {
return $milestone;
}
}
} | [
"private",
"function",
"getEdgeAction",
"(",
"Campaign",
"$",
"campaign",
",",
"$",
"position",
")",
"{",
"if",
"(",
"$",
"position",
"!=",
"'first'",
"&&",
"$",
"position",
"!=",
"'last'",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'Position must ... | Retrieve the first or last Action, i.e. an Activity or Milestone.
@param Campaign $campaign
@param string $position first|last
@return Activity|Milestone|null | [
"Retrieve",
"the",
"first",
"or",
"last",
"Action",
"i",
".",
"e",
".",
"an",
"Activity",
"or",
"Milestone",
"."
] | train | https://github.com/CampaignChain/core/blob/82526548a223ed49fcd65ed7c23638544499775f/Repository/CampaignRepository.php#L160-L220 |
rosell-dk/webp-convert-and-serve | src/WebPConvertAndServe.php | WebPConvertAndServe.convertAndServe | public static function convertAndServe($source, $destination, $options)
{
$options = array_merge(self::$defaultOptions, $options);
$failCodes = [
"original" => -1,
"404" => -2,
"report-as-image" => -3,
"report" => -4,
];
$failAction = $options['fail'];
$criticalFailAction = $options['critical-fail'];
if (is_string($failAction)) {
$failAction = $failCodes[$failAction];
}
if (is_string($criticalFailAction)) {
$criticalFailAction = $failCodes[$criticalFailAction];
}
$criticalFail = false;
$success = false;
$bufferLogger = new BufferLogger();
try {
$success = WebPConvert::convert($source, $destination, $options, $bufferLogger);
if ($success) {
$status = 'Success';
$msg = 'Success';
} else {
$status = 'Failure (no converters are operational)';
$msg = 'No converters are operational';
}
} catch (\WebPConvert\Exceptions\InvalidFileExtensionException $e) {
$criticalFail = true;
$status = 'Failure (invalid file extension)';
$msg = $e->getMessage();
} catch (\WebPConvert\Exceptions\TargetNotFoundException $e) {
$criticalFail = true;
$status = 'Failure (target file not found)';
$msg = $e->getMessage();
} catch (\WebPConvert\Converters\Exceptions\ConverterFailedException $e) {
// No converters could convert the image. At least one converter failed, even though it appears to be
// operational
$status = 'Failure (no converters could convert the image)';
$msg = $e->getMessage();
} catch (\WebPConvert\Converters\Exceptions\ConversionDeclinedException $e) {
// (no converters could convert the image. At least one converter declined
$status = 'Failure (no converters could/wanted to convert the image)';
$msg = $e->getMessage();
} catch (\WebPConvert\Exceptions\ConverterNotFoundException $e) {
$status = 'Failure (a converter was not found!)';
$msg = $e->getMessage();
} catch (\WebPConvert\Exceptions\CreateDestinationFileException $e) {
$status = 'Failure (cannot create destination file)';
$msg = $e->getMessage();
} catch (\WebPConvert\Exceptions\CreateDestinationFolderException $e) {
$status = 'Failure (cannot create destination folder)';
$msg = $e->getMessage();
} catch (\Exception $e) {
$status = 'Failure (an unanticipated exception was thrown)';
$msg = $e->getMessage();
}
$optionsForPrint = [];
foreach (self::getPrintableOptions($options) as $optionName => $optionValue) {
if ($optionName == 'converters') {
$converterNames = [];
$extraConvertOptions = [];
foreach ($optionValue as $converter) {
if (is_array($converter)) {
$converterNames[] = $converter['converter'];
if (isset($converter['options'])) {
$extraConvertOptions[$converter['converter']] = $converter['options'];
}
} else {
$converterNames[] = $converter;
}
}
$optionsForPrint[] = 'converters:' . implode(',', $converterNames);
foreach ($extraConvertOptions as $converter => $extraOptions) {
$opt = [];
foreach ($extraOptions as $oName => $oValue) {
$opt[] = $oName . ':"' . $oValue . '"';
}
$optionsForPrint[] = $converter . ' options:(' . implode($opt, ', ') . ')';
}
} else {
$optionsForPrint[] = $optionName . ':' . $optionValue ;
}
}
header('X-WebP-Convert-And-Serve-Options:' . implode('. ', $optionsForPrint));
header('X-WebP-Convert-And-Serve-Status: ' . $status);
// Next line is commented out, because we need to be absolute sure that the details does not violate syntax
// We could either try to filter it, or we could change WebPConvert, such that it only provides safe texts.
// header('X-WebP-Convert-And-Serve-Details: ' . $bufferLogger->getText());
if ($success) {
header('Content-type: image/webp');
// Should we add Content-Length header?
// header('Content-Length: ' . filesize($file));
readfile($destination);
return self::$CONVERTED_IMAGE;
} else {
$action = ($criticalFail ? $criticalFailAction : $failAction);
switch ($action) {
case WebPConvertAndServe::$ORIGINAL:
self::serveOriginal($source);
break;
case WebPConvertAndServe::$HTTP_404:
self::serve404();
break;
case WebPConvertAndServe::$REPORT_AS_IMAGE:
self::serveErrorMessageImage($status . '. ' . $msg);
break;
case WebPConvertAndServe::$REPORT:
echo '<h1>' . $status . '</h1>';
echo $msg;
echo '<p>This is how conversion process went:</p>' . $bufferLogger->getHtml();
break;
}
return $action;
}
} | php | public static function convertAndServe($source, $destination, $options)
{
$options = array_merge(self::$defaultOptions, $options);
$failCodes = [
"original" => -1,
"404" => -2,
"report-as-image" => -3,
"report" => -4,
];
$failAction = $options['fail'];
$criticalFailAction = $options['critical-fail'];
if (is_string($failAction)) {
$failAction = $failCodes[$failAction];
}
if (is_string($criticalFailAction)) {
$criticalFailAction = $failCodes[$criticalFailAction];
}
$criticalFail = false;
$success = false;
$bufferLogger = new BufferLogger();
try {
$success = WebPConvert::convert($source, $destination, $options, $bufferLogger);
if ($success) {
$status = 'Success';
$msg = 'Success';
} else {
$status = 'Failure (no converters are operational)';
$msg = 'No converters are operational';
}
} catch (\WebPConvert\Exceptions\InvalidFileExtensionException $e) {
$criticalFail = true;
$status = 'Failure (invalid file extension)';
$msg = $e->getMessage();
} catch (\WebPConvert\Exceptions\TargetNotFoundException $e) {
$criticalFail = true;
$status = 'Failure (target file not found)';
$msg = $e->getMessage();
} catch (\WebPConvert\Converters\Exceptions\ConverterFailedException $e) {
// No converters could convert the image. At least one converter failed, even though it appears to be
// operational
$status = 'Failure (no converters could convert the image)';
$msg = $e->getMessage();
} catch (\WebPConvert\Converters\Exceptions\ConversionDeclinedException $e) {
// (no converters could convert the image. At least one converter declined
$status = 'Failure (no converters could/wanted to convert the image)';
$msg = $e->getMessage();
} catch (\WebPConvert\Exceptions\ConverterNotFoundException $e) {
$status = 'Failure (a converter was not found!)';
$msg = $e->getMessage();
} catch (\WebPConvert\Exceptions\CreateDestinationFileException $e) {
$status = 'Failure (cannot create destination file)';
$msg = $e->getMessage();
} catch (\WebPConvert\Exceptions\CreateDestinationFolderException $e) {
$status = 'Failure (cannot create destination folder)';
$msg = $e->getMessage();
} catch (\Exception $e) {
$status = 'Failure (an unanticipated exception was thrown)';
$msg = $e->getMessage();
}
$optionsForPrint = [];
foreach (self::getPrintableOptions($options) as $optionName => $optionValue) {
if ($optionName == 'converters') {
$converterNames = [];
$extraConvertOptions = [];
foreach ($optionValue as $converter) {
if (is_array($converter)) {
$converterNames[] = $converter['converter'];
if (isset($converter['options'])) {
$extraConvertOptions[$converter['converter']] = $converter['options'];
}
} else {
$converterNames[] = $converter;
}
}
$optionsForPrint[] = 'converters:' . implode(',', $converterNames);
foreach ($extraConvertOptions as $converter => $extraOptions) {
$opt = [];
foreach ($extraOptions as $oName => $oValue) {
$opt[] = $oName . ':"' . $oValue . '"';
}
$optionsForPrint[] = $converter . ' options:(' . implode($opt, ', ') . ')';
}
} else {
$optionsForPrint[] = $optionName . ':' . $optionValue ;
}
}
header('X-WebP-Convert-And-Serve-Options:' . implode('. ', $optionsForPrint));
header('X-WebP-Convert-And-Serve-Status: ' . $status);
// Next line is commented out, because we need to be absolute sure that the details does not violate syntax
// We could either try to filter it, or we could change WebPConvert, such that it only provides safe texts.
// header('X-WebP-Convert-And-Serve-Details: ' . $bufferLogger->getText());
if ($success) {
header('Content-type: image/webp');
// Should we add Content-Length header?
// header('Content-Length: ' . filesize($file));
readfile($destination);
return self::$CONVERTED_IMAGE;
} else {
$action = ($criticalFail ? $criticalFailAction : $failAction);
switch ($action) {
case WebPConvertAndServe::$ORIGINAL:
self::serveOriginal($source);
break;
case WebPConvertAndServe::$HTTP_404:
self::serve404();
break;
case WebPConvertAndServe::$REPORT_AS_IMAGE:
self::serveErrorMessageImage($status . '. ' . $msg);
break;
case WebPConvertAndServe::$REPORT:
echo '<h1>' . $status . '</h1>';
echo $msg;
echo '<p>This is how conversion process went:</p>' . $bufferLogger->getHtml();
break;
}
return $action;
}
} | [
"public",
"static",
"function",
"convertAndServe",
"(",
"$",
"source",
",",
"$",
"destination",
",",
"$",
"options",
")",
"{",
"$",
"options",
"=",
"array_merge",
"(",
"self",
"::",
"$",
"defaultOptions",
",",
"$",
"options",
")",
";",
"$",
"failCodes",
... | Main method | [
"Main",
"method"
] | train | https://github.com/rosell-dk/webp-convert-and-serve/blob/029b97646942b4e02413b565fa45f46adcc51182/src/WebPConvertAndServe.php#L94-L223 |
rosell-dk/webp-convert-and-serve | src/WebPConvertAndServe.php | WebPConvertAndServe.getPrintableOptions | private static function getPrintableOptions($options)
{
$printable_options = [];
// (psst: the is_callable check is needed in order to work with WebPConvert v1.0)
if (is_callable('ConverterHelper', 'getClassNameOfConverter')) {
$printable_options = $options;
if (isset($printable_options['converters'])) {
foreach ($printable_options['converters'] as &$converter) {
if (is_array($converter)) {
//echo '::' . $converter['converter'] . '<br>';
$className = ConverterHelper::getClassNameOfConverter($converter['converter']);
// (pstt: the isset check is needed in order to work with WebPConvert v1.0)
if (isset($className::$extraOptions)) {
foreach ($className::$extraOptions as $extraOption) {
if ($extraOption['sensitive']) {
if (isset($converter['options'][$extraOption['name']])) {
$converter['options'][$extraOption['name']] = '*******';
}
}
}
}
}
}
}
}
return $printable_options;
} | php | private static function getPrintableOptions($options)
{
$printable_options = [];
// (psst: the is_callable check is needed in order to work with WebPConvert v1.0)
if (is_callable('ConverterHelper', 'getClassNameOfConverter')) {
$printable_options = $options;
if (isset($printable_options['converters'])) {
foreach ($printable_options['converters'] as &$converter) {
if (is_array($converter)) {
//echo '::' . $converter['converter'] . '<br>';
$className = ConverterHelper::getClassNameOfConverter($converter['converter']);
// (pstt: the isset check is needed in order to work with WebPConvert v1.0)
if (isset($className::$extraOptions)) {
foreach ($className::$extraOptions as $extraOption) {
if ($extraOption['sensitive']) {
if (isset($converter['options'][$extraOption['name']])) {
$converter['options'][$extraOption['name']] = '*******';
}
}
}
}
}
}
}
}
return $printable_options;
} | [
"private",
"static",
"function",
"getPrintableOptions",
"(",
"$",
"options",
")",
"{",
"$",
"printable_options",
"=",
"[",
"]",
";",
"// (psst: the is_callable check is needed in order to work with WebPConvert v1.0)",
"if",
"(",
"is_callable",
"(",
"'ConverterHelper'",
",",... | /* Hides sensitive options | [
"/",
"*",
"Hides",
"sensitive",
"options"
] | train | https://github.com/rosell-dk/webp-convert-and-serve/blob/029b97646942b4e02413b565fa45f46adcc51182/src/WebPConvertAndServe.php#L226-L254 |
netgen/ngpush | classes/facebook.php | Facebook.getSignedRequest | public function getSignedRequest() {
if (!$this->signedRequest) {
if (isset($_REQUEST['signed_request'])) {
$this->signedRequest = $this->parseSignedRequest(
$_REQUEST['signed_request']);
}
}
return $this->signedRequest;
} | php | public function getSignedRequest() {
if (!$this->signedRequest) {
if (isset($_REQUEST['signed_request'])) {
$this->signedRequest = $this->parseSignedRequest(
$_REQUEST['signed_request']);
}
}
return $this->signedRequest;
} | [
"public",
"function",
"getSignedRequest",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"signedRequest",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"_REQUEST",
"[",
"'signed_request'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"signedRequest",
"=",
"$",
... | Get the data from a signed_request token
@return String the base domain | [
"Get",
"the",
"data",
"from",
"a",
"signed_request",
"token"
] | train | https://github.com/netgen/ngpush/blob/0e12d13876b34ae2a1bf51cee35b44736cefba0b/classes/facebook.php#L251-L259 |
netgen/ngpush | classes/facebook.php | Facebook.setSession | public function setSession($session=null, $write_cookie=true) {
$session = $this->validateSessionObject($session);
$this->sessionLoaded = true;
$this->session = $session;
if ($write_cookie) {
$this->setCookieFromSession($session);
}
return $this;
} | php | public function setSession($session=null, $write_cookie=true) {
$session = $this->validateSessionObject($session);
$this->sessionLoaded = true;
$this->session = $session;
if ($write_cookie) {
$this->setCookieFromSession($session);
}
return $this;
} | [
"public",
"function",
"setSession",
"(",
"$",
"session",
"=",
"null",
",",
"$",
"write_cookie",
"=",
"true",
")",
"{",
"$",
"session",
"=",
"$",
"this",
"->",
"validateSessionObject",
"(",
"$",
"session",
")",
";",
"$",
"this",
"->",
"sessionLoaded",
"="... | Set the Session.
@param Array $session the session
@param Boolean $write_cookie indicate if a cookie should be written. this
value is ignored if cookie support has been disabled. | [
"Set",
"the",
"Session",
"."
] | train | https://github.com/netgen/ngpush/blob/0e12d13876b34ae2a1bf51cee35b44736cefba0b/classes/facebook.php#L268-L276 |
netgen/ngpush | classes/facebook.php | Facebook.getSession | public function getSession() {
if (!$this->sessionLoaded) {
$session = null;
$write_cookie = true;
// try loading session from signed_request in $_REQUEST
$signedRequest = $this->getSignedRequest();
if ($signedRequest) {
// sig is good, use the signedRequest
$session = $this->createSessionFromSignedRequest($signedRequest);
}
// try loading session from $_REQUEST
if (!$session && isset($_REQUEST['session'])) {
$session = json_decode(
get_magic_quotes_gpc()
? stripslashes($_REQUEST['session'])
: $_REQUEST['session'],
true
);
$session = $this->validateSessionObject($session);
}
// try loading session from cookie if necessary
if (!$session && $this->useCookieSupport()) {
$cookieName = $this->getSessionCookieName();
if (isset($_COOKIE[$cookieName])) {
$session = array();
parse_str(trim(
get_magic_quotes_gpc()
? stripslashes($_COOKIE[$cookieName])
: $_COOKIE[$cookieName],
'"'
), $session);
$session = $this->validateSessionObject($session);
// write only if we need to delete a invalid session cookie
$write_cookie = empty($session);
}
}
$this->setSession($session, $write_cookie);
}
return $this->session;
} | php | public function getSession() {
if (!$this->sessionLoaded) {
$session = null;
$write_cookie = true;
// try loading session from signed_request in $_REQUEST
$signedRequest = $this->getSignedRequest();
if ($signedRequest) {
// sig is good, use the signedRequest
$session = $this->createSessionFromSignedRequest($signedRequest);
}
// try loading session from $_REQUEST
if (!$session && isset($_REQUEST['session'])) {
$session = json_decode(
get_magic_quotes_gpc()
? stripslashes($_REQUEST['session'])
: $_REQUEST['session'],
true
);
$session = $this->validateSessionObject($session);
}
// try loading session from cookie if necessary
if (!$session && $this->useCookieSupport()) {
$cookieName = $this->getSessionCookieName();
if (isset($_COOKIE[$cookieName])) {
$session = array();
parse_str(trim(
get_magic_quotes_gpc()
? stripslashes($_COOKIE[$cookieName])
: $_COOKIE[$cookieName],
'"'
), $session);
$session = $this->validateSessionObject($session);
// write only if we need to delete a invalid session cookie
$write_cookie = empty($session);
}
}
$this->setSession($session, $write_cookie);
}
return $this->session;
} | [
"public",
"function",
"getSession",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"sessionLoaded",
")",
"{",
"$",
"session",
"=",
"null",
";",
"$",
"write_cookie",
"=",
"true",
";",
"// try loading session from signed_request in $_REQUEST",
"$",
"signedReque... | Get the session object. This will automatically look for a signed session
sent via the signed_request, Cookie or Query Parameters if needed.
@return Array the session | [
"Get",
"the",
"session",
"object",
".",
"This",
"will",
"automatically",
"look",
"for",
"a",
"signed",
"session",
"sent",
"via",
"the",
"signed_request",
"Cookie",
"or",
"Query",
"Parameters",
"if",
"needed",
"."
] | train | https://github.com/netgen/ngpush/blob/0e12d13876b34ae2a1bf51cee35b44736cefba0b/classes/facebook.php#L284-L328 |
netgen/ngpush | classes/facebook.php | Facebook.getAccessToken | public function getAccessToken() {
$session = $this->getSession();
// either user session signed, or app signed
if ($session) {
return $session['access_token'];
} else {
return $this->getAppId() .'|'. $this->getApiSecret();
}
} | php | public function getAccessToken() {
$session = $this->getSession();
// either user session signed, or app signed
if ($session) {
return $session['access_token'];
} else {
return $this->getAppId() .'|'. $this->getApiSecret();
}
} | [
"public",
"function",
"getAccessToken",
"(",
")",
"{",
"$",
"session",
"=",
"$",
"this",
"->",
"getSession",
"(",
")",
";",
"// either user session signed, or app signed",
"if",
"(",
"$",
"session",
")",
"{",
"return",
"$",
"session",
"[",
"'access_token'",
"]... | Gets a OAuth access token.
@return String the access token | [
"Gets",
"a",
"OAuth",
"access",
"token",
"."
] | train | https://github.com/netgen/ngpush/blob/0e12d13876b34ae2a1bf51cee35b44736cefba0b/classes/facebook.php#L345-L353 |
netgen/ngpush | classes/facebook.php | Facebook.getLoginUrl | public function getLoginUrl($params=array()) {
$currentUrl = $this->getCurrentUrl();
return $this->getUrl(
'www',
'dialog/oauth',
array_merge(array(
'client_id' => $this->getAppId(),
'redirect_uri' => $currentUrl,
'scope' => ''
), $params)
);
} | php | public function getLoginUrl($params=array()) {
$currentUrl = $this->getCurrentUrl();
return $this->getUrl(
'www',
'dialog/oauth',
array_merge(array(
'client_id' => $this->getAppId(),
'redirect_uri' => $currentUrl,
'scope' => ''
), $params)
);
} | [
"public",
"function",
"getLoginUrl",
"(",
"$",
"params",
"=",
"array",
"(",
")",
")",
"{",
"$",
"currentUrl",
"=",
"$",
"this",
"->",
"getCurrentUrl",
"(",
")",
";",
"return",
"$",
"this",
"->",
"getUrl",
"(",
"'www'",
",",
"'dialog/oauth'",
",",
"arra... | Get a Login URL for use with redirects.
By default, full page redirect is assumed.
The parameters:
- client_id: Facebook application ID
- redirect_uri: The URL to go to after a successful login
- state: An arbitrary but unique string that will be returned
at the end of the login flow. It allows the app to protect
against Cross-Site Request Forgery.
- scope: Comma separated list of requested extended permissions
@param Array $params parameters to override
@return String the URL for the login flow | [
"Get",
"a",
"Login",
"URL",
"for",
"use",
"with",
"redirects",
".",
"By",
"default",
"full",
"page",
"redirect",
"is",
"assumed",
"."
] | train | https://github.com/netgen/ngpush/blob/0e12d13876b34ae2a1bf51cee35b44736cefba0b/classes/facebook.php#L370-L381 |
netgen/ngpush | classes/facebook.php | Facebook.getLogoutUrl | public function getLogoutUrl($params=array()) {
return $this->getUrl(
'www',
'logout.php',
array_merge(array(
'next' => $this->getCurrentUrl(),
'access_token' => $this->getAccessToken(),
), $params)
);
} | php | public function getLogoutUrl($params=array()) {
return $this->getUrl(
'www',
'logout.php',
array_merge(array(
'next' => $this->getCurrentUrl(),
'access_token' => $this->getAccessToken(),
), $params)
);
} | [
"public",
"function",
"getLogoutUrl",
"(",
"$",
"params",
"=",
"array",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"getUrl",
"(",
"'www'",
",",
"'logout.php'",
",",
"array_merge",
"(",
"array",
"(",
"'next'",
"=>",
"$",
"this",
"->",
"getCurrentUrl... | Get a Logout URL suitable for use with redirects.
The parameters:
- next: the url to go to after a successful logout
@param Array $params provide custom parameters
@return String the URL for the logout flow | [
"Get",
"a",
"Logout",
"URL",
"suitable",
"for",
"use",
"with",
"redirects",
"."
] | train | https://github.com/netgen/ngpush/blob/0e12d13876b34ae2a1bf51cee35b44736cefba0b/classes/facebook.php#L392-L401 |
netgen/ngpush | classes/facebook.php | Facebook._restserver | protected function _restserver($params) {
// generic application level parameters
$params['api_key'] = $this->getAppId();
$params['format'] = 'json-strings';
$result = json_decode($this->_oauthRequest(
$this->getApiUrl($params['method']),
$params
), true);
// results are returned, errors are thrown
if (is_array($result) && isset($result['error_code'])) {
throw new FacebookApiException($result);
}
return $result;
} | php | protected function _restserver($params) {
// generic application level parameters
$params['api_key'] = $this->getAppId();
$params['format'] = 'json-strings';
$result = json_decode($this->_oauthRequest(
$this->getApiUrl($params['method']),
$params
), true);
// results are returned, errors are thrown
if (is_array($result) && isset($result['error_code'])) {
throw new FacebookApiException($result);
}
return $result;
} | [
"protected",
"function",
"_restserver",
"(",
"$",
"params",
")",
"{",
"// generic application level parameters",
"$",
"params",
"[",
"'api_key'",
"]",
"=",
"$",
"this",
"->",
"getAppId",
"(",
")",
";",
"$",
"params",
"[",
"'format'",
"]",
"=",
"'json-strings'"... | Invoke the old restserver.php endpoint.
@param Array $params method call object
@return the decoded response object
@throws FacebookApiException | [
"Invoke",
"the",
"old",
"restserver",
".",
"php",
"endpoint",
"."
] | train | https://github.com/netgen/ngpush/blob/0e12d13876b34ae2a1bf51cee35b44736cefba0b/classes/facebook.php#L450-L465 |
netgen/ngpush | classes/facebook.php | Facebook._graph | protected function _graph($path, $method='GET', $params=array()) {
if (is_array($method) && empty($params)) {
$params = $method;
$method = 'GET';
}
$params['method'] = $method; // method override as we always do a POST
$result = json_decode($this->_oauthRequest(
$this->getUrl('graph', $path),
$params
), true);
// results are returned, errors are thrown
if (is_array($result) && isset($result['error'])) {
$e = new FacebookApiException($result);
if ($e->getType() === 'OAuthException') {
$this->setSession(null);
}
throw $e;
}
return $result;
} | php | protected function _graph($path, $method='GET', $params=array()) {
if (is_array($method) && empty($params)) {
$params = $method;
$method = 'GET';
}
$params['method'] = $method; // method override as we always do a POST
$result = json_decode($this->_oauthRequest(
$this->getUrl('graph', $path),
$params
), true);
// results are returned, errors are thrown
if (is_array($result) && isset($result['error'])) {
$e = new FacebookApiException($result);
if ($e->getType() === 'OAuthException') {
$this->setSession(null);
}
throw $e;
}
return $result;
} | [
"protected",
"function",
"_graph",
"(",
"$",
"path",
",",
"$",
"method",
"=",
"'GET'",
",",
"$",
"params",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"method",
")",
"&&",
"empty",
"(",
"$",
"params",
")",
")",
"{",
"$",
... | Invoke the Graph API.
@param String $path the path (required)
@param String $method the http method (default 'GET')
@param Array $params the query/post data
@return the decoded response object
@throws FacebookApiException | [
"Invoke",
"the",
"Graph",
"API",
"."
] | train | https://github.com/netgen/ngpush/blob/0e12d13876b34ae2a1bf51cee35b44736cefba0b/classes/facebook.php#L476-L497 |
netgen/ngpush | classes/facebook.php | Facebook.makeRequest | protected function makeRequest($url, $params, $ch=null) {
if (!$ch) {
$ch = curl_init();
}
$opts = self::$CURL_OPTS;
$opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
$opts[CURLOPT_URL] = $url;
// disable the 'Expect: 100-continue' behaviour. This causes CURL to wait
// for 2 seconds if the server does not support this header.
if (isset($opts[CURLOPT_HTTPHEADER])) {
$existing_headers = $opts[CURLOPT_HTTPHEADER];
$existing_headers[] = 'Expect:';
$opts[CURLOPT_HTTPHEADER] = $existing_headers;
} else {
$opts[CURLOPT_HTTPHEADER] = array('Expect:');
}
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
if ($result === false) {
$e = new FacebookApiException(array(
'error_code' => curl_errno($ch),
'error' => array(
'message' => curl_error($ch),
'type' => 'CurlException',
),
));
curl_close($ch);
throw $e;
}
curl_close($ch);
return $result;
} | php | protected function makeRequest($url, $params, $ch=null) {
if (!$ch) {
$ch = curl_init();
}
$opts = self::$CURL_OPTS;
$opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
$opts[CURLOPT_URL] = $url;
// disable the 'Expect: 100-continue' behaviour. This causes CURL to wait
// for 2 seconds if the server does not support this header.
if (isset($opts[CURLOPT_HTTPHEADER])) {
$existing_headers = $opts[CURLOPT_HTTPHEADER];
$existing_headers[] = 'Expect:';
$opts[CURLOPT_HTTPHEADER] = $existing_headers;
} else {
$opts[CURLOPT_HTTPHEADER] = array('Expect:');
}
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
if ($result === false) {
$e = new FacebookApiException(array(
'error_code' => curl_errno($ch),
'error' => array(
'message' => curl_error($ch),
'type' => 'CurlException',
),
));
curl_close($ch);
throw $e;
}
curl_close($ch);
return $result;
} | [
"protected",
"function",
"makeRequest",
"(",
"$",
"url",
",",
"$",
"params",
",",
"$",
"ch",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"ch",
")",
"{",
"$",
"ch",
"=",
"curl_init",
"(",
")",
";",
"}",
"$",
"opts",
"=",
"self",
"::",
"$",
"CU... | Makes an HTTP request. This method can be overriden by subclasses if
developers want to do fancier things or use something other than curl to
make the request.
@param String $url the URL to make the request to
@param Array $params the parameters to use for the POST body
@param CurlHandler $ch optional initialized curl handle
@return String the response text | [
"Makes",
"an",
"HTTP",
"request",
".",
"This",
"method",
"can",
"be",
"overriden",
"by",
"subclasses",
"if",
"developers",
"want",
"to",
"do",
"fancier",
"things",
"or",
"use",
"something",
"other",
"than",
"curl",
"to",
"make",
"the",
"request",
"."
] | train | https://github.com/netgen/ngpush/blob/0e12d13876b34ae2a1bf51cee35b44736cefba0b/classes/facebook.php#L531-L565 |
netgen/ngpush | classes/facebook.php | Facebook.setCookieFromSession | protected function setCookieFromSession($session=null) {
if (!$this->useCookieSupport()) {
return;
}
$cookieName = $this->getSessionCookieName();
$value = 'deleted';
$expires = time() - 3600;
$domain = $this->getBaseDomain();
if ($session) {
$value = '"' . http_build_query($session, null, '&') . '"';
if (isset($session['base_domain'])) {
$domain = $session['base_domain'];
}
$expires = $session['expires'];
}
// prepend dot if a domain is found
if ($domain) {
$domain = '.' . $domain;
}
// if an existing cookie is not set, we dont need to delete it
if ($value == 'deleted' && empty($_COOKIE[$cookieName])) {
return;
}
if (headers_sent()) {
self::errorLog('Could not set cookie. Headers already sent.');
// ignore for code coverage as we will never be able to setcookie in a CLI
// environment
// @codeCoverageIgnoreStart
} else {
setcookie($cookieName, $value, $expires, '/', $domain);
}
// @codeCoverageIgnoreEnd
} | php | protected function setCookieFromSession($session=null) {
if (!$this->useCookieSupport()) {
return;
}
$cookieName = $this->getSessionCookieName();
$value = 'deleted';
$expires = time() - 3600;
$domain = $this->getBaseDomain();
if ($session) {
$value = '"' . http_build_query($session, null, '&') . '"';
if (isset($session['base_domain'])) {
$domain = $session['base_domain'];
}
$expires = $session['expires'];
}
// prepend dot if a domain is found
if ($domain) {
$domain = '.' . $domain;
}
// if an existing cookie is not set, we dont need to delete it
if ($value == 'deleted' && empty($_COOKIE[$cookieName])) {
return;
}
if (headers_sent()) {
self::errorLog('Could not set cookie. Headers already sent.');
// ignore for code coverage as we will never be able to setcookie in a CLI
// environment
// @codeCoverageIgnoreStart
} else {
setcookie($cookieName, $value, $expires, '/', $domain);
}
// @codeCoverageIgnoreEnd
} | [
"protected",
"function",
"setCookieFromSession",
"(",
"$",
"session",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"useCookieSupport",
"(",
")",
")",
"{",
"return",
";",
"}",
"$",
"cookieName",
"=",
"$",
"this",
"->",
"getSessionCookieName",
... | Set a JS Cookie based on the _passed in_ session. It does not use the
currently stored session -- you need to explicitly pass it in.
@param Array $session the session to use for setting the cookie | [
"Set",
"a",
"JS",
"Cookie",
"based",
"on",
"the",
"_passed",
"in_",
"session",
".",
"It",
"does",
"not",
"use",
"the",
"currently",
"stored",
"session",
"--",
"you",
"need",
"to",
"explicitly",
"pass",
"it",
"in",
"."
] | train | https://github.com/netgen/ngpush/blob/0e12d13876b34ae2a1bf51cee35b44736cefba0b/classes/facebook.php#L582-L619 |
netgen/ngpush | classes/facebook.php | Facebook.validateSessionObject | protected function validateSessionObject($session) {
// make sure some essential fields exist
if (is_array($session) &&
isset($session['uid']) &&
isset($session['access_token']) &&
isset($session['sig'])) {
// validate the signature
$session_without_sig = $session;
unset($session_without_sig['sig']);
$expected_sig = self::generateSignature(
$session_without_sig,
$this->getApiSecret()
);
if ($session['sig'] != $expected_sig) {
self::errorLog('Got invalid session signature in cookie.');
$session = null;
}
// check expiry time
} else {
$session = null;
}
return $session;
} | php | protected function validateSessionObject($session) {
// make sure some essential fields exist
if (is_array($session) &&
isset($session['uid']) &&
isset($session['access_token']) &&
isset($session['sig'])) {
// validate the signature
$session_without_sig = $session;
unset($session_without_sig['sig']);
$expected_sig = self::generateSignature(
$session_without_sig,
$this->getApiSecret()
);
if ($session['sig'] != $expected_sig) {
self::errorLog('Got invalid session signature in cookie.');
$session = null;
}
// check expiry time
} else {
$session = null;
}
return $session;
} | [
"protected",
"function",
"validateSessionObject",
"(",
"$",
"session",
")",
"{",
"// make sure some essential fields exist",
"if",
"(",
"is_array",
"(",
"$",
"session",
")",
"&&",
"isset",
"(",
"$",
"session",
"[",
"'uid'",
"]",
")",
"&&",
"isset",
"(",
"$",
... | Validates a session_version=3 style session object.
@param Array $session the session object
@return Array the session object if it validates, null otherwise | [
"Validates",
"a",
"session_version",
"=",
"3",
"style",
"session",
"object",
"."
] | train | https://github.com/netgen/ngpush/blob/0e12d13876b34ae2a1bf51cee35b44736cefba0b/classes/facebook.php#L627-L649 |
netgen/ngpush | classes/facebook.php | Facebook.createSessionFromSignedRequest | protected function createSessionFromSignedRequest($data) {
if (!isset($data['oauth_token'])) {
return null;
}
$session = array(
'uid' => $data['user_id'],
'access_token' => $data['oauth_token'],
'expires' => $data['expires'],
);
// put a real sig, so that validateSignature works
$session['sig'] = self::generateSignature(
$session,
$this->getApiSecret()
);
return $session;
} | php | protected function createSessionFromSignedRequest($data) {
if (!isset($data['oauth_token'])) {
return null;
}
$session = array(
'uid' => $data['user_id'],
'access_token' => $data['oauth_token'],
'expires' => $data['expires'],
);
// put a real sig, so that validateSignature works
$session['sig'] = self::generateSignature(
$session,
$this->getApiSecret()
);
return $session;
} | [
"protected",
"function",
"createSessionFromSignedRequest",
"(",
"$",
"data",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"data",
"[",
"'oauth_token'",
"]",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"session",
"=",
"array",
"(",
"'uid'",
"=>",
"$... | Returns something that looks like our JS session object from the
signed token's data
TODO: Nuke this once the login flow uses OAuth2
@param Array the output of getSignedRequest
@return Array Something that will work as a session | [
"Returns",
"something",
"that",
"looks",
"like",
"our",
"JS",
"session",
"object",
"from",
"the",
"signed",
"token",
"s",
"data"
] | train | https://github.com/netgen/ngpush/blob/0e12d13876b34ae2a1bf51cee35b44736cefba0b/classes/facebook.php#L660-L678 |
netgen/ngpush | classes/facebook.php | Facebook.parseSignedRequest | protected function parseSignedRequest($signed_request) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = self::base64UrlDecode($encoded_sig);
$data = json_decode(self::base64UrlDecode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
self::errorLog('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload,
$this->getApiSecret(), $raw = true);
if ($sig !== $expected_sig) {
self::errorLog('Bad Signed JSON signature!');
return null;
}
return $data;
} | php | protected function parseSignedRequest($signed_request) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = self::base64UrlDecode($encoded_sig);
$data = json_decode(self::base64UrlDecode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
self::errorLog('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload,
$this->getApiSecret(), $raw = true);
if ($sig !== $expected_sig) {
self::errorLog('Bad Signed JSON signature!');
return null;
}
return $data;
} | [
"protected",
"function",
"parseSignedRequest",
"(",
"$",
"signed_request",
")",
"{",
"list",
"(",
"$",
"encoded_sig",
",",
"$",
"payload",
")",
"=",
"explode",
"(",
"'.'",
",",
"$",
"signed_request",
",",
"2",
")",
";",
"// decode the data",
"$",
"sig",
"=... | Parses a signed_request and validates the signature.
Then saves it in $this->signed_data
@param String A signed token
@param Boolean Should we remove the parts of the payload that
are used by the algorithm?
@return Array the payload inside it or null if the sig is wrong | [
"Parses",
"a",
"signed_request",
"and",
"validates",
"the",
"signature",
".",
"Then",
"saves",
"it",
"in",
"$this",
"-",
">",
"signed_data"
] | train | https://github.com/netgen/ngpush/blob/0e12d13876b34ae2a1bf51cee35b44736cefba0b/classes/facebook.php#L689-L710 |
netgen/ngpush | classes/facebook.php | Facebook.getCurrentUrl | protected function getCurrentUrl() {
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'
? 'https://'
: 'http://';
$currentUrl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$parts = parse_url($currentUrl);
// drop known fb params
$query = '';
if (!empty($parts['query'])) {
$params = array();
parse_str($parts['query'], $params);
foreach(self::$DROP_QUERY_PARAMS as $key) {
unset($params[$key]);
}
if (!empty($params)) {
$query = '?' . http_build_query($params, null, '&');
}
}
// use port if non default
$port =
isset($parts['port']) &&
(($protocol === 'http://' && $parts['port'] !== 80) ||
($protocol === 'https://' && $parts['port'] !== 443))
? ':' . $parts['port'] : '';
// rebuild
return $protocol . $parts['host'] . $port . $parts['path'] . $query;
} | php | protected function getCurrentUrl() {
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'
? 'https://'
: 'http://';
$currentUrl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$parts = parse_url($currentUrl);
// drop known fb params
$query = '';
if (!empty($parts['query'])) {
$params = array();
parse_str($parts['query'], $params);
foreach(self::$DROP_QUERY_PARAMS as $key) {
unset($params[$key]);
}
if (!empty($params)) {
$query = '?' . http_build_query($params, null, '&');
}
}
// use port if non default
$port =
isset($parts['port']) &&
(($protocol === 'http://' && $parts['port'] !== 80) ||
($protocol === 'https://' && $parts['port'] !== 443))
? ':' . $parts['port'] : '';
// rebuild
return $protocol . $parts['host'] . $port . $parts['path'] . $query;
} | [
"protected",
"function",
"getCurrentUrl",
"(",
")",
"{",
"$",
"protocol",
"=",
"isset",
"(",
"$",
"_SERVER",
"[",
"'HTTPS'",
"]",
")",
"&&",
"$",
"_SERVER",
"[",
"'HTTPS'",
"]",
"==",
"'on'",
"?",
"'https://'",
":",
"'http://'",
";",
"$",
"currentUrl",
... | Returns the Current URL, stripping it of known FB parameters that should
not persist.
@return String the current URL | [
"Returns",
"the",
"Current",
"URL",
"stripping",
"it",
"of",
"known",
"FB",
"parameters",
"that",
"should",
"not",
"persist",
"."
] | train | https://github.com/netgen/ngpush/blob/0e12d13876b34ae2a1bf51cee35b44736cefba0b/classes/facebook.php#L815-L844 |
notthatbad/silverstripe-rest-api | code/formatters/SessionFormatter.php | SessionFormatter.format | public static function format($data, $access=null, $fields=null) {
return [
'user' => $data->User->URLSegment,
'token' => $data->Token
];
} | php | public static function format($data, $access=null, $fields=null) {
return [
'user' => $data->User->URLSegment,
'token' => $data->Token
];
} | [
"public",
"static",
"function",
"format",
"(",
"$",
"data",
",",
"$",
"access",
"=",
"null",
",",
"$",
"fields",
"=",
"null",
")",
"{",
"return",
"[",
"'user'",
"=>",
"$",
"data",
"->",
"User",
"->",
"URLSegment",
",",
"'token'",
"=>",
"$",
"data",
... | Returns an array with entries for `user`.
@param ApiSession $data
@param array $access
@param array $fields
@return array the user data in a serializable structure | [
"Returns",
"an",
"array",
"with",
"entries",
"for",
"user",
"."
] | train | https://github.com/notthatbad/silverstripe-rest-api/blob/aed8e9812a01d4ab1e7cdfe7c3e0161ca368e621/code/formatters/SessionFormatter.php#L19-L24 |
czukowski/I18n_Plural | classes/I18n/Plural/Factory.php | Factory.create_rules | public function create_rules($prefix)
{
if ($prefix === 'pl')
{
return new Polish;
}
elseif (in_array($prefix, array('cs', 'sk'), TRUE))
{
return new Czech;
}
elseif (in_array($prefix, array('fr', 'ff', 'kab'), TRUE))
{
return new French;
}
elseif (in_array($prefix, array('ru', 'sr', 'uk', 'sh', 'be', 'hr', 'bs'), TRUE))
{
return new Balkan;
}
elseif (in_array($prefix, array(
'en', 'ny', 'nr', 'no', 'om', 'os', 'ps', 'pa', 'nn', 'or', 'nl', 'lg', 'lb', 'ky', 'ml', 'mr',
'ne', 'nd', 'nb', 'pt', 'rm', 'ts', 'tn', 'tk', 'ur', 'vo', 'zu', 'xh', 've', 'te', 'ta', 'sq',
'so', 'sn', 'ss', 'st', 'sw', 'sv', 'ku', 'mn', 'et', 'eo', 'el', 'eu', 'fi', 'fy', 'fo', 'ee',
'dv', 'bg', 'af', 'bn', 'ca', 'de', 'da', 'gl', 'es', 'it', 'is', 'ks', 'ha', 'kk', 'kl', 'gu',
'brx', 'mas', 'teo', 'chr', 'cgg', 'tig', 'wae', 'xog', 'ast', 'vun', 'bem', 'syr', 'bez', 'asa',
'rof', 'ksb', 'rwk', 'haw', 'pap', 'gsw', 'fur', 'saq', 'seh', 'nyn', 'kcg', 'ssy', 'kaj', 'jmc',
'nah', 'ckb'), TRUE))
{
return new One;
}
elseif ($prefix === 'mt')
{
return new Maltese;
}
elseif ($prefix === 'gv')
{
return new Manx;
}
elseif ($prefix === 'sl')
{
return new Slovenian;
}
elseif ($prefix === 'cy')
{
return new Welsh;
}
elseif ($prefix === 'ar')
{
return new Arabic;
}
elseif ($prefix === 'shi')
{
return new Tachelhit;
}
elseif ($prefix === 'tzm')
{
return new Tamazight;
}
elseif ($prefix === 'mk')
{
return new Macedonian;
}
elseif ($prefix === 'lt')
{
return new Lithuanian;
}
elseif ($prefix === 'he')
{
return new Hebrew;
}
elseif ($prefix === 'gd')
{
return new Gaelic;
}
elseif ($prefix === 'ga')
{
return new Irish;
}
elseif ($prefix === 'lag')
{
return new Langi;
}
elseif ($prefix === 'lv')
{
return new Latvian;
}
elseif ($prefix === 'br')
{
return new Breton;
}
elseif ($prefix === 'ksh')
{
return new Colognian;
}
elseif (in_array($prefix, array('mo', 'ro'), TRUE))
{
return new Romanian;
}
elseif (in_array($prefix, array(
'se', 'kw', 'iu', 'smn', 'sms', 'smj', 'sma', 'naq', 'smi'), TRUE))
{
return new Two;
}
elseif (in_array($prefix, array(
'hi', 'ln', 'mg', 'ak', 'tl', 'am', 'bh', 'wa', 'ti', 'guw', 'fil', 'nso'), TRUE))
{
return new Zero;
}
elseif (in_array($prefix, array(
'my', 'sg', 'ms', 'lo', 'kn', 'ko', 'th', 'to', 'yo', 'zh', 'wo', 'vi', 'tr', 'az', 'km', 'id',
'ig', 'fa', 'dz', 'bm', 'bo', 'ii', 'hu', 'ka', 'jv', 'ja', 'kde', 'ses', 'sah', 'kea'), TRUE))
{
return new None;
}
throw new \InvalidArgumentException('Unknown language prefix: '.$prefix.'.');
} | php | public function create_rules($prefix)
{
if ($prefix === 'pl')
{
return new Polish;
}
elseif (in_array($prefix, array('cs', 'sk'), TRUE))
{
return new Czech;
}
elseif (in_array($prefix, array('fr', 'ff', 'kab'), TRUE))
{
return new French;
}
elseif (in_array($prefix, array('ru', 'sr', 'uk', 'sh', 'be', 'hr', 'bs'), TRUE))
{
return new Balkan;
}
elseif (in_array($prefix, array(
'en', 'ny', 'nr', 'no', 'om', 'os', 'ps', 'pa', 'nn', 'or', 'nl', 'lg', 'lb', 'ky', 'ml', 'mr',
'ne', 'nd', 'nb', 'pt', 'rm', 'ts', 'tn', 'tk', 'ur', 'vo', 'zu', 'xh', 've', 'te', 'ta', 'sq',
'so', 'sn', 'ss', 'st', 'sw', 'sv', 'ku', 'mn', 'et', 'eo', 'el', 'eu', 'fi', 'fy', 'fo', 'ee',
'dv', 'bg', 'af', 'bn', 'ca', 'de', 'da', 'gl', 'es', 'it', 'is', 'ks', 'ha', 'kk', 'kl', 'gu',
'brx', 'mas', 'teo', 'chr', 'cgg', 'tig', 'wae', 'xog', 'ast', 'vun', 'bem', 'syr', 'bez', 'asa',
'rof', 'ksb', 'rwk', 'haw', 'pap', 'gsw', 'fur', 'saq', 'seh', 'nyn', 'kcg', 'ssy', 'kaj', 'jmc',
'nah', 'ckb'), TRUE))
{
return new One;
}
elseif ($prefix === 'mt')
{
return new Maltese;
}
elseif ($prefix === 'gv')
{
return new Manx;
}
elseif ($prefix === 'sl')
{
return new Slovenian;
}
elseif ($prefix === 'cy')
{
return new Welsh;
}
elseif ($prefix === 'ar')
{
return new Arabic;
}
elseif ($prefix === 'shi')
{
return new Tachelhit;
}
elseif ($prefix === 'tzm')
{
return new Tamazight;
}
elseif ($prefix === 'mk')
{
return new Macedonian;
}
elseif ($prefix === 'lt')
{
return new Lithuanian;
}
elseif ($prefix === 'he')
{
return new Hebrew;
}
elseif ($prefix === 'gd')
{
return new Gaelic;
}
elseif ($prefix === 'ga')
{
return new Irish;
}
elseif ($prefix === 'lag')
{
return new Langi;
}
elseif ($prefix === 'lv')
{
return new Latvian;
}
elseif ($prefix === 'br')
{
return new Breton;
}
elseif ($prefix === 'ksh')
{
return new Colognian;
}
elseif (in_array($prefix, array('mo', 'ro'), TRUE))
{
return new Romanian;
}
elseif (in_array($prefix, array(
'se', 'kw', 'iu', 'smn', 'sms', 'smj', 'sma', 'naq', 'smi'), TRUE))
{
return new Two;
}
elseif (in_array($prefix, array(
'hi', 'ln', 'mg', 'ak', 'tl', 'am', 'bh', 'wa', 'ti', 'guw', 'fil', 'nso'), TRUE))
{
return new Zero;
}
elseif (in_array($prefix, array(
'my', 'sg', 'ms', 'lo', 'kn', 'ko', 'th', 'to', 'yo', 'zh', 'wo', 'vi', 'tr', 'az', 'km', 'id',
'ig', 'fa', 'dz', 'bm', 'bo', 'ii', 'hu', 'ka', 'jv', 'ja', 'kde', 'ses', 'sah', 'kea'), TRUE))
{
return new None;
}
throw new \InvalidArgumentException('Unknown language prefix: '.$prefix.'.');
} | [
"public",
"function",
"create_rules",
"(",
"$",
"prefix",
")",
"{",
"if",
"(",
"$",
"prefix",
"===",
"'pl'",
")",
"{",
"return",
"new",
"Polish",
";",
"}",
"elseif",
"(",
"in_array",
"(",
"$",
"prefix",
",",
"array",
"(",
"'cs'",
",",
"'sk'",
")",
... | Chooses inflection class to use according to CLDR plural rules
@param string $prefix
@return Plural\PluralInterface | [
"Chooses",
"inflection",
"class",
"to",
"use",
"according",
"to",
"CLDR",
"plural",
"rules"
] | train | https://github.com/czukowski/I18n_Plural/blob/6782aeac50e22a194d3840759c9da97d1f9c50d0/classes/I18n/Plural/Factory.php#L20-L134 |
Patroklo/yii2-comments | controllers/ManageController.php | ManageController.actionIndex | public function actionIndex()
{
/* @var $module Module */
$module = Yii::$app->getModule(Module::$name);
$commentSearchModelData = $module->model('commentSearch');
/** @var CommentSearchModel $searchModel */
$searchModel = Yii::createObject($commentSearchModelData);
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$commentModelData = $module->model('comment');
/** @var CommentModel $commentModel */
$commentModel = Yii::createObject($commentModelData);
return $this->render($this->indexView, [
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
'commentModel' => $commentModel
]);
} | php | public function actionIndex()
{
/* @var $module Module */
$module = Yii::$app->getModule(Module::$name);
$commentSearchModelData = $module->model('commentSearch');
/** @var CommentSearchModel $searchModel */
$searchModel = Yii::createObject($commentSearchModelData);
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$commentModelData = $module->model('comment');
/** @var CommentModel $commentModel */
$commentModel = Yii::createObject($commentModelData);
return $this->render($this->indexView, [
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
'commentModel' => $commentModel
]);
} | [
"public",
"function",
"actionIndex",
"(",
")",
"{",
"/* @var $module Module */",
"$",
"module",
"=",
"Yii",
"::",
"$",
"app",
"->",
"getModule",
"(",
"Module",
"::",
"$",
"name",
")",
";",
"$",
"commentSearchModelData",
"=",
"$",
"module",
"->",
"model",
"... | Lists all users.
@return mixed | [
"Lists",
"all",
"users",
"."
] | train | https://github.com/Patroklo/yii2-comments/blob/e06409ea52b12dc14d0594030088fd7d2c2e160a/controllers/ManageController.php#L52-L71 |
Patroklo/yii2-comments | controllers/ManageController.php | ManageController.actionUpdate | public function actionUpdate($id)
{
$model = $this->findModel($id);
// if the model has an anonymousUsername value
// we will consider it as an anonymous message
if (!is_null($model->anonymousUsername))
{
$model->scenario = $model::SCENARIO_ANONYMOUS;
}
if ($model->load(Yii::$app->request->post()) && $model->save())
{
Yii::$app->session->setFlash('success', Yii::t('app', 'Comment has been saved.'));
return $this->redirect(['index']);
}
return $this->render($this->updateView, [
'model' => $model,
]);
} | php | public function actionUpdate($id)
{
$model = $this->findModel($id);
// if the model has an anonymousUsername value
// we will consider it as an anonymous message
if (!is_null($model->anonymousUsername))
{
$model->scenario = $model::SCENARIO_ANONYMOUS;
}
if ($model->load(Yii::$app->request->post()) && $model->save())
{
Yii::$app->session->setFlash('success', Yii::t('app', 'Comment has been saved.'));
return $this->redirect(['index']);
}
return $this->render($this->updateView, [
'model' => $model,
]);
} | [
"public",
"function",
"actionUpdate",
"(",
"$",
"id",
")",
"{",
"$",
"model",
"=",
"$",
"this",
"->",
"findModel",
"(",
"$",
"id",
")",
";",
"// if the model has an anonymousUsername value",
"// we will consider it as an anonymous message",
"if",
"(",
"!",
"is_null"... | Updates an existing CommentModel model.
If update is successful, the browser will be redirected to the 'view' page.
@param integer $id
@return mixed | [
"Updates",
"an",
"existing",
"CommentModel",
"model",
".",
"If",
"update",
"is",
"successful",
"the",
"browser",
"will",
"be",
"redirected",
"to",
"the",
"view",
"page",
"."
] | train | https://github.com/Patroklo/yii2-comments/blob/e06409ea52b12dc14d0594030088fd7d2c2e160a/controllers/ManageController.php#L79-L102 |
ionux/phactor | src/Wallet.php | Wallet.getWIF | public function getWIF($private_key = null, $network = 'main', $public_key_format = 'compressed')
{
if (empty($private_key) === true) {
return ($this->WIF_address != '') ? $this->WIF_address : '';
} else {
return $this->encodeWIF($private_key, $network, $public_key_format);
}
} | php | public function getWIF($private_key = null, $network = 'main', $public_key_format = 'compressed')
{
if (empty($private_key) === true) {
return ($this->WIF_address != '') ? $this->WIF_address : '';
} else {
return $this->encodeWIF($private_key, $network, $public_key_format);
}
} | [
"public",
"function",
"getWIF",
"(",
"$",
"private_key",
"=",
"null",
",",
"$",
"network",
"=",
"'main'",
",",
"$",
"public_key_format",
"=",
"'compressed'",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"private_key",
")",
"===",
"true",
")",
"{",
"return",
... | Retrieves or generates a WIF-encoded private key from hex.
@param string $private_key The hex-formatted private key.
@param string $network Network type (test or main).
@param string $public_key_format Format of the corresponding public key.
@return string $WIF_address The Base58-encoded private key. | [
"Retrieves",
"or",
"generates",
"a",
"WIF",
"-",
"encoded",
"private",
"key",
"from",
"hex",
"."
] | train | https://github.com/ionux/phactor/blob/667064d3930e043fd78abed9a2324aee52466fa5/src/Wallet.php#L100-L107 |
ionux/phactor | src/Wallet.php | Wallet.getWIFPrivateKey | public function getWIFPrivateKey($WIF_address = null)
{
if (empty($WIF_address) === true) {
return ($this->private_key != '') ? $this->private_key : '';
} else {
return $this->decodeWIF($WIF_address);
}
} | php | public function getWIFPrivateKey($WIF_address = null)
{
if (empty($WIF_address) === true) {
return ($this->private_key != '') ? $this->private_key : '';
} else {
return $this->decodeWIF($WIF_address);
}
} | [
"public",
"function",
"getWIFPrivateKey",
"(",
"$",
"WIF_address",
"=",
"null",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"WIF_address",
")",
"===",
"true",
")",
"{",
"return",
"(",
"$",
"this",
"->",
"private_key",
"!=",
"''",
")",
"?",
"$",
"this",
"... | Retrieves or generates a hex encoded private key from WIF.
@param string $WIF_address The WIF-encoded private key.
@return string The private key in hex format. | [
"Retrieves",
"or",
"generates",
"a",
"hex",
"encoded",
"private",
"key",
"from",
"WIF",
"."
] | train | https://github.com/ionux/phactor/blob/667064d3930e043fd78abed9a2324aee52466fa5/src/Wallet.php#L115-L122 |
ionux/phactor | src/Wallet.php | Wallet.getChecksum | public function getChecksum($private_key = null, $needs_hashed = false)
{
$private_key = ($this->testIfWIF($private_key) === true) ? $this->decodeWIF($private_key) : $private_key;
if (empty($private_key) === true) {
return ($this->checksum != '') ? $this->checksum : '';
} else {
return $this->calculateChecksum($private_key, true);
}
} | php | public function getChecksum($private_key = null, $needs_hashed = false)
{
$private_key = ($this->testIfWIF($private_key) === true) ? $this->decodeWIF($private_key) : $private_key;
if (empty($private_key) === true) {
return ($this->checksum != '') ? $this->checksum : '';
} else {
return $this->calculateChecksum($private_key, true);
}
} | [
"public",
"function",
"getChecksum",
"(",
"$",
"private_key",
"=",
"null",
",",
"$",
"needs_hashed",
"=",
"false",
")",
"{",
"$",
"private_key",
"=",
"(",
"$",
"this",
"->",
"testIfWIF",
"(",
"$",
"private_key",
")",
"===",
"true",
")",
"?",
"$",
"this... | Retrieves or generates the WIF-encoded private key's checksum in hex.
If you also need the raw hex data hashed to generate the checksum,
set the $needs_hashed parameter to true. This function can also use
the private key in plain hex format.
@param string $private_key The private key to analyze.
@param string $needs_hashed Whether or not to hash the data.
@return string The 4-byte checksum in hex format. | [
"Retrieves",
"or",
"generates",
"the",
"WIF",
"-",
"encoded",
"private",
"key",
"s",
"checksum",
"in",
"hex",
".",
"If",
"you",
"also",
"need",
"the",
"raw",
"hex",
"data",
"hashed",
"to",
"generate",
"the",
"checksum",
"set",
"the",
"$needs_hashed",
"para... | train | https://github.com/ionux/phactor/blob/667064d3930e043fd78abed9a2324aee52466fa5/src/Wallet.php#L134-L143 |
ionux/phactor | src/Wallet.php | Wallet.getPubkeyFormat | public function getPubkeyFormat($private_key = null)
{
$private_key = ($this->testIfWIF($private_key) === true) ? $this->decodeWIF($private_key) : $private_key;
if (empty($private_key) === true) {
return ($this->compressed_pubkey_format != '') ? $this->compressed_pubkey_format : '';
} else {
return $this->calculatePubKeyFormat($private_key);
}
} | php | public function getPubkeyFormat($private_key = null)
{
$private_key = ($this->testIfWIF($private_key) === true) ? $this->decodeWIF($private_key) : $private_key;
if (empty($private_key) === true) {
return ($this->compressed_pubkey_format != '') ? $this->compressed_pubkey_format : '';
} else {
return $this->calculatePubKeyFormat($private_key);
}
} | [
"public",
"function",
"getPubkeyFormat",
"(",
"$",
"private_key",
"=",
"null",
")",
"{",
"$",
"private_key",
"=",
"(",
"$",
"this",
"->",
"testIfWIF",
"(",
"$",
"private_key",
")",
"===",
"true",
")",
"?",
"$",
"this",
"->",
"decodeWIF",
"(",
"$",
"pri... | Retrieves or generates the corresponding public key's format.
@param string $private_key The private key to analyze.
@return string The public key's format. | [
"Retrieves",
"or",
"generates",
"the",
"corresponding",
"public",
"key",
"s",
"format",
"."
] | train | https://github.com/ionux/phactor/blob/667064d3930e043fd78abed9a2324aee52466fa5/src/Wallet.php#L151-L160 |
ionux/phactor | src/Wallet.php | Wallet.getNetworkType | public function getNetworkType($private_key = null)
{
$private_key = ($this->testIfWIF($private_key) === true) ? $this->decodeWIF($private_key) : $private_key;
if (empty($private_key) === true) {
return ($this->network_type != '') ? $this->network_type : '';
} else {
return $this->calculateNetworkType($private_key);
}
} | php | public function getNetworkType($private_key = null)
{
$private_key = ($this->testIfWIF($private_key) === true) ? $this->decodeWIF($private_key) : $private_key;
if (empty($private_key) === true) {
return ($this->network_type != '') ? $this->network_type : '';
} else {
return $this->calculateNetworkType($private_key);
}
} | [
"public",
"function",
"getNetworkType",
"(",
"$",
"private_key",
"=",
"null",
")",
"{",
"$",
"private_key",
"=",
"(",
"$",
"this",
"->",
"testIfWIF",
"(",
"$",
"private_key",
")",
"===",
"true",
")",
"?",
"$",
"this",
"->",
"decodeWIF",
"(",
"$",
"priv... | Retrieves or generates the WIF-encoded private key's network type.
@param string $private_key The private key to analyze.
@return string The address network type. | [
"Retrieves",
"or",
"generates",
"the",
"WIF",
"-",
"encoded",
"private",
"key",
"s",
"network",
"type",
"."
] | train | https://github.com/ionux/phactor/blob/667064d3930e043fd78abed9a2324aee52466fa5/src/Wallet.php#L168-L177 |
ionux/phactor | src/Wallet.php | Wallet.calculateNetworkType | private function calculateNetworkType($data)
{
$temp = strtolower(substr(trim($data), 0, 2));
switch ($temp) {
case '80':
$this->network_type = 'main';
break;
case 'ef':
$this->network_type = 'test';
break;
default:
$this->network_type = 'unknown';
break;
}
return $this->network_type;
} | php | private function calculateNetworkType($data)
{
$temp = strtolower(substr(trim($data), 0, 2));
switch ($temp) {
case '80':
$this->network_type = 'main';
break;
case 'ef':
$this->network_type = 'test';
break;
default:
$this->network_type = 'unknown';
break;
}
return $this->network_type;
} | [
"private",
"function",
"calculateNetworkType",
"(",
"$",
"data",
")",
"{",
"$",
"temp",
"=",
"strtolower",
"(",
"substr",
"(",
"trim",
"(",
"$",
"data",
")",
",",
"0",
",",
"2",
")",
")",
";",
"switch",
"(",
"$",
"temp",
")",
"{",
"case",
"'80'",
... | Retrieves or generates the WIF-encoded private key's network type.
@param string $data The data to analyze.
@return string $network_type The address network type. | [
"Retrieves",
"or",
"generates",
"the",
"WIF",
"-",
"encoded",
"private",
"key",
"s",
"network",
"type",
"."
] | train | https://github.com/ionux/phactor/blob/667064d3930e043fd78abed9a2324aee52466fa5/src/Wallet.php#L248-L265 |
ionux/phactor | src/Wallet.php | Wallet.calculatePubkeyFormat | private function calculatePubkeyFormat($data)
{
$temp = strtolower(substr(trim($data), -2));
switch ($temp) {
case '01':
$this->compressed_pubkey_format = 'compressed';
break;
default:
$this->compressed_pubkey_format = 'uncompressed';
break;
}
return $this->compressed_pubkey_format;
} | php | private function calculatePubkeyFormat($data)
{
$temp = strtolower(substr(trim($data), -2));
switch ($temp) {
case '01':
$this->compressed_pubkey_format = 'compressed';
break;
default:
$this->compressed_pubkey_format = 'uncompressed';
break;
}
return $this->compressed_pubkey_format;
} | [
"private",
"function",
"calculatePubkeyFormat",
"(",
"$",
"data",
")",
"{",
"$",
"temp",
"=",
"strtolower",
"(",
"substr",
"(",
"trim",
"(",
"$",
"data",
")",
",",
"-",
"2",
")",
")",
";",
"switch",
"(",
"$",
"temp",
")",
"{",
"case",
"'01'",
":",
... | Retrieves or generates the corresponding public key's format.
@param string $data The data to analyze.
@return string $compressed_pubkey_format The public key's format. | [
"Retrieves",
"or",
"generates",
"the",
"corresponding",
"public",
"key",
"s",
"format",
"."
] | train | https://github.com/ionux/phactor/blob/667064d3930e043fd78abed9a2324aee52466fa5/src/Wallet.php#L273-L287 |
ionux/phactor | src/Wallet.php | Wallet.calculateChecksum | private function calculateChecksum($data, $needs_hashed = false)
{
$data = $this->stripHexPrefix(trim($data));
if ($needs_hashed === false) {
$this->checksum = substr($data, 0, 8);
} else {
$this->checksum = substr(hash('sha256', hash('sha256', $this->binConv($data), true)), 0, 8);
}
return $this->checksum;
} | php | private function calculateChecksum($data, $needs_hashed = false)
{
$data = $this->stripHexPrefix(trim($data));
if ($needs_hashed === false) {
$this->checksum = substr($data, 0, 8);
} else {
$this->checksum = substr(hash('sha256', hash('sha256', $this->binConv($data), true)), 0, 8);
}
return $this->checksum;
} | [
"private",
"function",
"calculateChecksum",
"(",
"$",
"data",
",",
"$",
"needs_hashed",
"=",
"false",
")",
"{",
"$",
"data",
"=",
"$",
"this",
"->",
"stripHexPrefix",
"(",
"trim",
"(",
"$",
"data",
")",
")",
";",
"if",
"(",
"$",
"needs_hashed",
"===",
... | Retrieves or generates the WIF-encoded private key's checksum in hex.
If you also need the raw hex data hashed to generate the checksum,
set the $needs_hashed parameter to true.
@param string $data The data to checksum.
@param boolean $needs_hashed Whether or not to hash the data.
@return string $checksum The 4-byte checksum in hex format. | [
"Retrieves",
"or",
"generates",
"the",
"WIF",
"-",
"encoded",
"private",
"key",
"s",
"checksum",
"in",
"hex",
".",
"If",
"you",
"also",
"need",
"the",
"raw",
"hex",
"data",
"hashed",
"to",
"generate",
"the",
"checksum",
"set",
"the",
"$needs_hashed",
"para... | train | https://github.com/ionux/phactor/blob/667064d3930e043fd78abed9a2324aee52466fa5/src/Wallet.php#L298-L309 |
ionux/phactor | src/Wallet.php | Wallet.encodeWIF | private function encodeWIF($private_key, $network = 'main', $public_key_format = 'compressed')
{
/*
* WIF uses base58Check encoding on an private key much like standard Bitcoin addresses.
*
* 1. Take a private key.
*/
$step1 = $this->stripHexPrefix(trim($private_key));
/*
* 2. Add a 0x80 byte in front of it for mainnet addresses or 0xef for testnet addresses.
*/
$step2 = ($network == 'main') ? '80' . $step1 : 'ef' . $step1;
/*
* 3. Append a 0x01 byte after it if it should be used with compressed public keys. Nothing is appended
* if it is used with uncompressed public keys.
*/
$step3 = ($public_key_format == 'compressed') ? $step2 . '01' : $step2;
/*
* 4. Perform a SHA-256 hash on the extended key.
*/
$step4 = hash('sha256', $this->binConv($step3), true);
/*
* 5. Perform a SHA-256 hash on result of SHA-256 hash.
*/
$step5 = hash('sha256', $step4);
/*
* 6. Take the first four bytes of the second SHA-256 hash; this is the checksum.
*/
$this->checksum = substr($step5, 0, 8);
/*
* 7. Add the four checksum bytes from step 6 at the end of the extended key from step 3.
*/
$step7 = $step3 . $this->checksum;
/*
* 8. Convert the result from a byte string into a Base58 string using Base58Check encoding.
*/
$this->WIF_address = $this->encodeBase58($step7);
/*
* The process is easily reversible, using the Base58 decoding function, and removing the padding.
*/
return $this->WIF_address;
} | php | private function encodeWIF($private_key, $network = 'main', $public_key_format = 'compressed')
{
/*
* WIF uses base58Check encoding on an private key much like standard Bitcoin addresses.
*
* 1. Take a private key.
*/
$step1 = $this->stripHexPrefix(trim($private_key));
/*
* 2. Add a 0x80 byte in front of it for mainnet addresses or 0xef for testnet addresses.
*/
$step2 = ($network == 'main') ? '80' . $step1 : 'ef' . $step1;
/*
* 3. Append a 0x01 byte after it if it should be used with compressed public keys. Nothing is appended
* if it is used with uncompressed public keys.
*/
$step3 = ($public_key_format == 'compressed') ? $step2 . '01' : $step2;
/*
* 4. Perform a SHA-256 hash on the extended key.
*/
$step4 = hash('sha256', $this->binConv($step3), true);
/*
* 5. Perform a SHA-256 hash on result of SHA-256 hash.
*/
$step5 = hash('sha256', $step4);
/*
* 6. Take the first four bytes of the second SHA-256 hash; this is the checksum.
*/
$this->checksum = substr($step5, 0, 8);
/*
* 7. Add the four checksum bytes from step 6 at the end of the extended key from step 3.
*/
$step7 = $step3 . $this->checksum;
/*
* 8. Convert the result from a byte string into a Base58 string using Base58Check encoding.
*/
$this->WIF_address = $this->encodeBase58($step7);
/*
* The process is easily reversible, using the Base58 decoding function, and removing the padding.
*/
return $this->WIF_address;
} | [
"private",
"function",
"encodeWIF",
"(",
"$",
"private_key",
",",
"$",
"network",
"=",
"'main'",
",",
"$",
"public_key_format",
"=",
"'compressed'",
")",
"{",
"/*\n * WIF uses base58Check encoding on an private key much like standard Bitcoin addresses.\n *\n ... | Encodes a hex-formatted private key into Wallet Import Format (WIF).
@see: https://bitcoin.org/en/developer-guide#wallet-import-format-wif
@param string $private_key The hex-formatted private key.
@param string $network Network type (test or main).
@param string $public_key_format Format of the corresponding public key.
@return string $WIF_address The Base58-encoded private key. | [
"Encodes",
"a",
"hex",
"-",
"formatted",
"private",
"key",
"into",
"Wallet",
"Import",
"Format",
"(",
"WIF",
")",
".",
"@see",
":",
"https",
":",
"//",
"bitcoin",
".",
"org",
"/",
"en",
"/",
"developer",
"-",
"guide#wallet",
"-",
"import",
"-",
"format... | train | https://github.com/ionux/phactor/blob/667064d3930e043fd78abed9a2324aee52466fa5/src/Wallet.php#L320-L370 |
ionux/phactor | src/Wallet.php | Wallet.decodeWIF | private function decodeWIF($WIF_encoded_key)
{
/* Using the Base58 decoding function and remove the padding. */
$decoded_key = $this->stripHexPrefix($this->decodeBase58(trim($WIF_encoded_key)));
list($private_key, $checksum_provided) = array(
substr($decoded_key, 0, -8),
substr($decoded_key, strlen($decoded_key) - 8)
);
$private_key_type = substr($private_key, 0, 2);
if ($private_key_type != '80' && $private_key_type != 'ef') {
throw new \Exception('Invalid WIF encoded private key! Network type was not present in value provided. Checked ' . $private_key . ' and found ' . $private_key_type);
}
$private_key = substr($private_key, 2);
$compressed_public_key = (substr($private_key, strlen($private_key) - 2) == '01') ? '01' : '';
$private_key = ($compressed_public_key == '01') ? substr($private_key, 0, -2) : $private_key;
/* Now let's check our private key against the checksum provided. */
$new_checksum = substr(hash('sha256', hash('sha256', $this->binConv($private_key_type . $private_key . $compressed_public_key), true)), 0, 8);
if ($new_checksum != $checksum_provided) {
throw new \Exception('Invalid WIF encoded private key! Checksum is incorrect! Value encoded with key was: ' . $checksum_provided . ' but this does not match the recalculated value of: ' . $new_checksum . ' from the decoded provided value of: ' . $decoded_key);
}
return $private_key;
} | php | private function decodeWIF($WIF_encoded_key)
{
/* Using the Base58 decoding function and remove the padding. */
$decoded_key = $this->stripHexPrefix($this->decodeBase58(trim($WIF_encoded_key)));
list($private_key, $checksum_provided) = array(
substr($decoded_key, 0, -8),
substr($decoded_key, strlen($decoded_key) - 8)
);
$private_key_type = substr($private_key, 0, 2);
if ($private_key_type != '80' && $private_key_type != 'ef') {
throw new \Exception('Invalid WIF encoded private key! Network type was not present in value provided. Checked ' . $private_key . ' and found ' . $private_key_type);
}
$private_key = substr($private_key, 2);
$compressed_public_key = (substr($private_key, strlen($private_key) - 2) == '01') ? '01' : '';
$private_key = ($compressed_public_key == '01') ? substr($private_key, 0, -2) : $private_key;
/* Now let's check our private key against the checksum provided. */
$new_checksum = substr(hash('sha256', hash('sha256', $this->binConv($private_key_type . $private_key . $compressed_public_key), true)), 0, 8);
if ($new_checksum != $checksum_provided) {
throw new \Exception('Invalid WIF encoded private key! Checksum is incorrect! Value encoded with key was: ' . $checksum_provided . ' but this does not match the recalculated value of: ' . $new_checksum . ' from the decoded provided value of: ' . $decoded_key);
}
return $private_key;
} | [
"private",
"function",
"decodeWIF",
"(",
"$",
"WIF_encoded_key",
")",
"{",
"/* Using the Base58 decoding function and remove the padding. */",
"$",
"decoded_key",
"=",
"$",
"this",
"->",
"stripHexPrefix",
"(",
"$",
"this",
"->",
"decodeBase58",
"(",
"trim",
"(",
"$",
... | Decodes a WIF-encoded private key using Base58 decoding and removes the padding.
@param string $WIF_encoded_key The wallet address to decode.
@return string $private_key The decoded private key in hex format.
@throws \Exception | [
"Decodes",
"a",
"WIF",
"-",
"encoded",
"private",
"key",
"using",
"Base58",
"decoding",
"and",
"removes",
"the",
"padding",
"."
] | train | https://github.com/ionux/phactor/blob/667064d3930e043fd78abed9a2324aee52466fa5/src/Wallet.php#L379-L407 |
tableau-mkt/elomentary | src/Api/Assets/Email.php | Email.create | public function create($name, array $options = array()) {
$params = array_merge(array('name' => $name), $options);
// Validate the request before sending it.
$required = array('name', 'subject', 'folderId', 'emailGroupId');
foreach ($required as $key) {
$this->validateExists($params, $key);
}
return $this->post('assets/email', $params);
} | php | public function create($name, array $options = array()) {
$params = array_merge(array('name' => $name), $options);
// Validate the request before sending it.
$required = array('name', 'subject', 'folderId', 'emailGroupId');
foreach ($required as $key) {
$this->validateExists($params, $key);
}
return $this->post('assets/email', $params);
} | [
"public",
"function",
"create",
"(",
"$",
"name",
",",
"array",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"$",
"params",
"=",
"array_merge",
"(",
"array",
"(",
"'name'",
"=>",
"$",
"name",
")",
",",
"$",
"options",
")",
";",
"// Validate the ... | Create an email.
@param string $name
The desired name of the email.
@param array $options
An optional array of additional query parameters to be passed.
@return array
The created email record represented as an associative array.
@throws InvalidArgumentException | [
"Create",
"an",
"email",
"."
] | train | https://github.com/tableau-mkt/elomentary/blob/c9e8e67f8239cfd813fae59fe665ed7130c439d2/src/Api/Assets/Email.php#L141-L152 |
tableau-mkt/elomentary | src/Api/Assets/Email.php | Email.remove | public function remove($id) {
if (empty($id) || !is_numeric($id)) {
throw new InvalidArgumentException('ID must be numeric');
}
return $this->delete('assets/email/' . rawurlencode($id));
} | php | public function remove($id) {
if (empty($id) || !is_numeric($id)) {
throw new InvalidArgumentException('ID must be numeric');
}
return $this->delete('assets/email/' . rawurlencode($id));
} | [
"public",
"function",
"remove",
"(",
"$",
"id",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"id",
")",
"||",
"!",
"is_numeric",
"(",
"$",
"id",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'ID must be numeric'",
")",
";",
"}",
"return",... | Remove an email by its ID.
@param int $id
The ID associated with the desired email.
@throws InvalidArgumentException | [
"Remove",
"an",
"email",
"by",
"its",
"ID",
"."
] | train | https://github.com/tableau-mkt/elomentary/blob/c9e8e67f8239cfd813fae59fe665ed7130c439d2/src/Api/Assets/Email.php#L162-L167 |
swoft-cloud/swoft-console | src/Output/Output.php | Output.writeln | public function writeln($messages = '', $newline = true, $quit = false)
{
if (\is_array($messages)) {
$messages = \implode($newline ? PHP_EOL : '', $messages);
}
// 文字里面颜色标签翻译
$messages = \style()->t((string)$messages);
// 输出文字
echo $messages;
if ($newline) {
echo "\n";
}
// 是否退出
if ($quit) {
exit;
}
} | php | public function writeln($messages = '', $newline = true, $quit = false)
{
if (\is_array($messages)) {
$messages = \implode($newline ? PHP_EOL : '', $messages);
}
// 文字里面颜色标签翻译
$messages = \style()->t((string)$messages);
// 输出文字
echo $messages;
if ($newline) {
echo "\n";
}
// 是否退出
if ($quit) {
exit;
}
} | [
"public",
"function",
"writeln",
"(",
"$",
"messages",
"=",
"''",
",",
"$",
"newline",
"=",
"true",
",",
"$",
"quit",
"=",
"false",
")",
"{",
"if",
"(",
"\\",
"is_array",
"(",
"$",
"messages",
")",
")",
"{",
"$",
"messages",
"=",
"\\",
"implode",
... | 输出一行数据
@param string|array $messages 信息
@param bool $newline 是否换行
@param bool $quit 是否退出 | [
"输出一行数据"
] | train | https://github.com/swoft-cloud/swoft-console/blob/d7153f56505a9be420ebae9eb29f7e45bfb2982e/src/Output/Output.php#L30-L49 |
swoft-cloud/swoft-console | src/Output/Output.php | Output.writeList | public function writeList(array $list, $titleStyle = 'comment', string $cmdStyle = 'info', string $descStyle = null)
{
foreach ($list as $title => $items) {
// 标题
$title = "<$titleStyle>$title</$titleStyle>";
$this->writeln($title);
// 输出块内容
$this->writeItems((array)$items, $cmdStyle);
$this->writeln('');
}
} | php | public function writeList(array $list, $titleStyle = 'comment', string $cmdStyle = 'info', string $descStyle = null)
{
foreach ($list as $title => $items) {
// 标题
$title = "<$titleStyle>$title</$titleStyle>";
$this->writeln($title);
// 输出块内容
$this->writeItems((array)$items, $cmdStyle);
$this->writeln('');
}
} | [
"public",
"function",
"writeList",
"(",
"array",
"$",
"list",
",",
"$",
"titleStyle",
"=",
"'comment'",
",",
"string",
"$",
"cmdStyle",
"=",
"'info'",
",",
"string",
"$",
"descStyle",
"=",
"null",
")",
"{",
"foreach",
"(",
"$",
"list",
"as",
"$",
"titl... | 输出一个列表
@param array $list 列表数据
@param string $titleStyle 标题样式
@param string $cmdStyle 命令样式
@param string|null $descStyle 描述样式 | [
"输出一个列表"
] | train | https://github.com/swoft-cloud/swoft-console/blob/d7153f56505a9be420ebae9eb29f7e45bfb2982e/src/Output/Output.php#L83-L94 |
swoft-cloud/swoft-console | src/Output/Output.php | Output.writeItems | private function writeItems(array $items, string $cmdStyle)
{
foreach ($items as $cmd => $desc) {
// 没有命令,只是一行数据
if (\is_int($cmd)) {
$message = self::LEFT_CHAR . $desc;
$this->writeln($message);
continue;
}
// 命令和描述
$maxLength = $this->getCmdMaxLength(array_keys($items));
$cmd = \str_pad($cmd, $maxLength, ' ');
$cmd = "<$cmdStyle>$cmd</$cmdStyle>";
$message = self::LEFT_CHAR . $cmd . self::GAP_CHAR . $desc;
$this->writeln($message);
}
} | php | private function writeItems(array $items, string $cmdStyle)
{
foreach ($items as $cmd => $desc) {
// 没有命令,只是一行数据
if (\is_int($cmd)) {
$message = self::LEFT_CHAR . $desc;
$this->writeln($message);
continue;
}
// 命令和描述
$maxLength = $this->getCmdMaxLength(array_keys($items));
$cmd = \str_pad($cmd, $maxLength, ' ');
$cmd = "<$cmdStyle>$cmd</$cmdStyle>";
$message = self::LEFT_CHAR . $cmd . self::GAP_CHAR . $desc;
$this->writeln($message);
}
} | [
"private",
"function",
"writeItems",
"(",
"array",
"$",
"items",
",",
"string",
"$",
"cmdStyle",
")",
"{",
"foreach",
"(",
"$",
"items",
"as",
"$",
"cmd",
"=>",
"$",
"desc",
")",
"{",
"// 没有命令,只是一行数据",
"if",
"(",
"\\",
"is_int",
"(",
"$",
"cmd",
")",... | 显示命令列表一块数据
@param array $items 数据
@param string $cmdStyle 命令样式 | [
"显示命令列表一块数据"
] | train | https://github.com/swoft-cloud/swoft-console/blob/d7153f56505a9be420ebae9eb29f7e45bfb2982e/src/Output/Output.php#L102-L120 |
swoft-cloud/swoft-console | src/Output/Output.php | Output.getCmdMaxLength | private function getCmdMaxLength(array $commands): int
{
$max = 0;
foreach ($commands as $cmd) {
$length = \strlen($cmd);
if ($length > $max) {
$max = $length;
continue;
}
}
return $max;
} | php | private function getCmdMaxLength(array $commands): int
{
$max = 0;
foreach ($commands as $cmd) {
$length = \strlen($cmd);
if ($length > $max) {
$max = $length;
continue;
}
}
return $max;
} | [
"private",
"function",
"getCmdMaxLength",
"(",
"array",
"$",
"commands",
")",
":",
"int",
"{",
"$",
"max",
"=",
"0",
";",
"foreach",
"(",
"$",
"commands",
"as",
"$",
"cmd",
")",
"{",
"$",
"length",
"=",
"\\",
"strlen",
"(",
"$",
"cmd",
")",
";",
... | 所有命令最大宽度
@param array $commands 所有命令
@return int | [
"所有命令最大宽度"
] | train | https://github.com/swoft-cloud/swoft-console/blob/d7153f56505a9be420ebae9eb29f7e45bfb2982e/src/Output/Output.php#L128-L141 |
Deathnerd/php-wtforms | src/fields/core/Field.php | Field.validate | public function validate(Form $form, array $extra_validators = [])
{
$this->errors = $this->process_errors;
$stop_validation = false;
// Call pre-validate
try {
$this->preValidate($form);
} catch (StopValidation $e) {
$message = $e->getMessage();
if ($message != "") {
$this->errors[] = $message;
}
$stop_validation = true;
} catch (ValueError $e) {
$this->errors[] = $e->getMessage();
} catch (ValidationError $e) {
$this->errors[] = $e->getMessage();
}
if (!$stop_validation) {
$stop_validation = $this->runValidationChain($form, array_merge($this->validators, $extra_validators));
// && $this->runValidationChain($form, $extra_validators);
}
// Call post_validate
try {
$this->postValidate($form, $stop_validation);
} catch (ValueError $e) {
$this->errors[] = $e->getMessage();
}
return count($this->errors) == 0;
} | php | public function validate(Form $form, array $extra_validators = [])
{
$this->errors = $this->process_errors;
$stop_validation = false;
// Call pre-validate
try {
$this->preValidate($form);
} catch (StopValidation $e) {
$message = $e->getMessage();
if ($message != "") {
$this->errors[] = $message;
}
$stop_validation = true;
} catch (ValueError $e) {
$this->errors[] = $e->getMessage();
} catch (ValidationError $e) {
$this->errors[] = $e->getMessage();
}
if (!$stop_validation) {
$stop_validation = $this->runValidationChain($form, array_merge($this->validators, $extra_validators));
// && $this->runValidationChain($form, $extra_validators);
}
// Call post_validate
try {
$this->postValidate($form, $stop_validation);
} catch (ValueError $e) {
$this->errors[] = $e->getMessage();
}
return count($this->errors) == 0;
} | [
"public",
"function",
"validate",
"(",
"Form",
"$",
"form",
",",
"array",
"$",
"extra_validators",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"errors",
"=",
"$",
"this",
"->",
"process_errors",
";",
"$",
"stop_validation",
"=",
"false",
";",
"// Call pr... | Validates the field and returns true or false. {@link errors} will
contain any errors raised during validation. This is usually only
called by {@link Form\validate}
Subfields shouldn't override this, but rather override either
{@link pre_validate}, {@link post_validate}, or both, depending on needs.
@param Form $form The form the field belongs to.
@param Validator[] $extra_validators A sequence of extra validators to run
@return bool | [
"Validates",
"the",
"field",
"and",
"returns",
"true",
"or",
"false",
".",
"{",
"@link",
"errors",
"}",
"will",
"contain",
"any",
"errors",
"raised",
"during",
"validation",
".",
"This",
"is",
"usually",
"only",
"called",
"by",
"{",
"@link",
"Form",
"\\",
... | train | https://github.com/Deathnerd/php-wtforms/blob/2e1f9ad515f6241c9fac57edc472bf657267f4a1/src/fields/core/Field.php#L275-L308 |
Deathnerd/php-wtforms | src/fields/core/Field.php | Field.runValidationChain | protected function runValidationChain(Form $form, array $validators)
{
foreach ($validators as $v) {
try {
if (is_array($v)) {
call_user_func($v, $form, $this);
} else {
$v->__invoke($form, $this);
}
} catch (StopValidation $e) {
$message = $e->getMessage();
if ($message != "") {
$this->errors[] = $message;
}
return true;
} catch (ValidationError $e) {
$message = $e->getMessage();
if ($message != "") {
$this->errors[] = $message;
}
return true;
} catch (ValueError $e) {
$message = $e->getMessage();
if ($message != "") {
$this->errors[] = $message;
}
return true;
}
}
return false;
} | php | protected function runValidationChain(Form $form, array $validators)
{
foreach ($validators as $v) {
try {
if (is_array($v)) {
call_user_func($v, $form, $this);
} else {
$v->__invoke($form, $this);
}
} catch (StopValidation $e) {
$message = $e->getMessage();
if ($message != "") {
$this->errors[] = $message;
}
return true;
} catch (ValidationError $e) {
$message = $e->getMessage();
if ($message != "") {
$this->errors[] = $message;
}
return true;
} catch (ValueError $e) {
$message = $e->getMessage();
if ($message != "") {
$this->errors[] = $message;
}
return true;
}
}
return false;
} | [
"protected",
"function",
"runValidationChain",
"(",
"Form",
"$",
"form",
",",
"array",
"$",
"validators",
")",
"{",
"foreach",
"(",
"$",
"validators",
"as",
"$",
"v",
")",
"{",
"try",
"{",
"if",
"(",
"is_array",
"(",
"$",
"v",
")",
")",
"{",
"call_us... | Run a validation chain, stopping if any validator raises StopValidation
@param Form $form The form instance this field belongs to
@param Validator[] $validators A sequence or iterable of validator callables
@return bool True if the validation was stopped, False if otherwise | [
"Run",
"a",
"validation",
"chain",
"stopping",
"if",
"any",
"validator",
"raises",
"StopValidation"
] | train | https://github.com/Deathnerd/php-wtforms/blob/2e1f9ad515f6241c9fac57edc472bf657267f4a1/src/fields/core/Field.php#L328-L362 |
Deathnerd/php-wtforms | src/fields/core/Field.php | Field.process | public function process($formdata, $data = null)
{
$this->process_errors = [];
if ($data === null) {
if (is_callable($this->default)) {
$data = $this->default->__invoke();
} else {
$data = $this->default;
}
}
$this->object_data = $data;
try {
$this->processData($data);
} catch (ValueError $e) {
$this->process_errors[] = $e->getMessage();
}
if ($formdata) {
try {
if (array_key_exists($this->name, $formdata)) {
if (is_array($formdata[$this->name])) {
$this->raw_data = $formdata[$this->name];
} else {
$this->raw_data = [$formdata[$this->name]];
}
} else {
$this->raw_data = [];
}
$this->processFormData($this->raw_data);
} catch (ValueError $e) {
$this->process_errors[] = $e->getMessage();
}
}
try {
foreach ($this->filters as $filter) {
/** @var $filter callable */
$this->data = $filter($data);
}
} catch (ValueError $e) {
$this->process_errors[] = $e->getMessage();
}
} | php | public function process($formdata, $data = null)
{
$this->process_errors = [];
if ($data === null) {
if (is_callable($this->default)) {
$data = $this->default->__invoke();
} else {
$data = $this->default;
}
}
$this->object_data = $data;
try {
$this->processData($data);
} catch (ValueError $e) {
$this->process_errors[] = $e->getMessage();
}
if ($formdata) {
try {
if (array_key_exists($this->name, $formdata)) {
if (is_array($formdata[$this->name])) {
$this->raw_data = $formdata[$this->name];
} else {
$this->raw_data = [$formdata[$this->name]];
}
} else {
$this->raw_data = [];
}
$this->processFormData($this->raw_data);
} catch (ValueError $e) {
$this->process_errors[] = $e->getMessage();
}
}
try {
foreach ($this->filters as $filter) {
/** @var $filter callable */
$this->data = $filter($data);
}
} catch (ValueError $e) {
$this->process_errors[] = $e->getMessage();
}
} | [
"public",
"function",
"process",
"(",
"$",
"formdata",
",",
"$",
"data",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"process_errors",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"data",
"===",
"null",
")",
"{",
"if",
"(",
"is_callable",
"(",
"$",
"this",
... | Process incoming data, calling process_data, process_formdata as needed,
and run filters.
If `data` is not provided, process_data will be called on the field's
default.
Field subclasses usually won't override this, instead overriding the
process_formdata and process_data methods. Only override this for
special advanced processing, such as when a field encapsulates many
inputs.
@param $formdata
@param null|mixed $data | [
"Process",
"incoming",
"data",
"calling",
"process_data",
"process_formdata",
"as",
"needed",
"and",
"run",
"filters",
"."
] | train | https://github.com/Deathnerd/php-wtforms/blob/2e1f9ad515f6241c9fac57edc472bf657267f4a1/src/fields/core/Field.php#L390-L432 |
tableau-mkt/elomentary | src/Api/Assets/OptionList.php | OptionList.update | public function update($id, $optionList) {
if (!isset($optionList['id']) or $optionList['id'] != $id) {
throw new InvalidArgumentException('The id parameter in the optionList definition must match the $id parameter in function signature');
}
return $this->put('assets/optionList/' . rawurlencode($id), $optionList);
} | php | public function update($id, $optionList) {
if (!isset($optionList['id']) or $optionList['id'] != $id) {
throw new InvalidArgumentException('The id parameter in the optionList definition must match the $id parameter in function signature');
}
return $this->put('assets/optionList/' . rawurlencode($id), $optionList);
} | [
"public",
"function",
"update",
"(",
"$",
"id",
",",
"$",
"optionList",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"optionList",
"[",
"'id'",
"]",
")",
"or",
"$",
"optionList",
"[",
"'id'",
"]",
"!=",
"$",
"id",
")",
"{",
"throw",
"new",
"Inval... | {@inheritdoc} | [
"{"
] | train | https://github.com/tableau-mkt/elomentary/blob/c9e8e67f8239cfd813fae59fe665ed7130c439d2/src/Api/Assets/OptionList.php#L45-L50 |
tableau-mkt/elomentary | src/Api/Assets/OptionList.php | OptionList.create | public function create($optionsList) {
if (!isset($optionsList['name'])) {
throw new InvalidArgumentException('New OptionLists are required to have a name parameter');
}
if (isset($optionsList['elements'])) {
foreach ($optionsList['elements'] as $o) {
if (!isset($o['displayName'], $o['value'])) {
throw new InvalidArgumentException('Option fields are required to have a displayName and value parameter');
}
} // @codeCoverageIgnoreStart
} // @codeCoverageIgnoreEnd
return $this->post('assets/optionList', $optionsList);
} | php | public function create($optionsList) {
if (!isset($optionsList['name'])) {
throw new InvalidArgumentException('New OptionLists are required to have a name parameter');
}
if (isset($optionsList['elements'])) {
foreach ($optionsList['elements'] as $o) {
if (!isset($o['displayName'], $o['value'])) {
throw new InvalidArgumentException('Option fields are required to have a displayName and value parameter');
}
} // @codeCoverageIgnoreStart
} // @codeCoverageIgnoreEnd
return $this->post('assets/optionList', $optionsList);
} | [
"public",
"function",
"create",
"(",
"$",
"optionsList",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"optionsList",
"[",
"'name'",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'New OptionLists are required to have a name parameter'",
")",... | {@inheritdoc} | [
"{"
] | train | https://github.com/tableau-mkt/elomentary/blob/c9e8e67f8239cfd813fae59fe665ed7130c439d2/src/Api/Assets/OptionList.php#L55-L69 |
CampaignChain/core | EntityService/ChannelService.php | ChannelService.getRootLocations | public function getRootLocations($channel)
{
$repository = $this->em->getRepository('CampaignChainCoreBundle:Location');
$query = $repository->createQueryBuilder('l')
->where('l.channel = :channel')
->andWhere('l.parent IS NULL')
->orderBy('l.name', 'ASC')
->setParameter('channel', $channel)
->getQuery();
return $query->getResult();
} | php | public function getRootLocations($channel)
{
$repository = $this->em->getRepository('CampaignChainCoreBundle:Location');
$query = $repository->createQueryBuilder('l')
->where('l.channel = :channel')
->andWhere('l.parent IS NULL')
->orderBy('l.name', 'ASC')
->setParameter('channel', $channel)
->getQuery();
return $query->getResult();
} | [
"public",
"function",
"getRootLocations",
"(",
"$",
"channel",
")",
"{",
"$",
"repository",
"=",
"$",
"this",
"->",
"em",
"->",
"getRepository",
"(",
"'CampaignChainCoreBundle:Location'",
")",
";",
"$",
"query",
"=",
"$",
"repository",
"->",
"createQueryBuilder"... | /*
Generates a Tracking ID
This method also makes sure that the ID is unique, i.e. that it does
not yet exist for another Channel.
@return string | [
"/",
"*",
"Generates",
"a",
"Tracking",
"ID"
] | train | https://github.com/CampaignChain/core/blob/82526548a223ed49fcd65ed7c23638544499775f/EntityService/ChannelService.php#L84-L96 |
CampaignChain/core | EntityService/ChannelService.php | ChannelService.removeChannel | public function removeChannel($id)
{
$channel = $this->em
->getRepository('CampaignChainCoreBundle:Channel')
->find($id);
if (!$channel) {
throw new \Exception(
'No channel found for id '.$id
);
}
//
$locations = $channel->getLocations();
$openActivities = new ArrayCollection();
$closedActivities = new ArrayCollection();
foreach ($locations as $location) {
foreach ($location->getActivities() as $activity) {
if ($activity->getStatus() == 'closed') {
$closedActivities->add($activity);
} else {
$openActivities->add($activity);
}
}
}
if (!$closedActivities->isEmpty()) {
//deaktivieren
} else {
foreach ($openActivities as $activity) {
$this->activityService->removeActivity($activity);
}
foreach ($locations as $location) {
$this->locationService->removeLocation($location);
}
$this->em->remove($channel);
$this->em->flush();
}
} | php | public function removeChannel($id)
{
$channel = $this->em
->getRepository('CampaignChainCoreBundle:Channel')
->find($id);
if (!$channel) {
throw new \Exception(
'No channel found for id '.$id
);
}
//
$locations = $channel->getLocations();
$openActivities = new ArrayCollection();
$closedActivities = new ArrayCollection();
foreach ($locations as $location) {
foreach ($location->getActivities() as $activity) {
if ($activity->getStatus() == 'closed') {
$closedActivities->add($activity);
} else {
$openActivities->add($activity);
}
}
}
if (!$closedActivities->isEmpty()) {
//deaktivieren
} else {
foreach ($openActivities as $activity) {
$this->activityService->removeActivity($activity);
}
foreach ($locations as $location) {
$this->locationService->removeLocation($location);
}
$this->em->remove($channel);
$this->em->flush();
}
} | [
"public",
"function",
"removeChannel",
"(",
"$",
"id",
")",
"{",
"$",
"channel",
"=",
"$",
"this",
"->",
"em",
"->",
"getRepository",
"(",
"'CampaignChainCoreBundle:Channel'",
")",
"->",
"find",
"(",
"$",
"id",
")",
";",
"if",
"(",
"!",
"$",
"channel",
... | This method deletes a channel if there are no closed activities.
If there are open activities the location is deactivated.
@param $id
@throws \Exception | [
"This",
"method",
"deletes",
"a",
"channel",
"if",
"there",
"are",
"no",
"closed",
"activities",
".",
"If",
"there",
"are",
"open",
"activities",
"the",
"location",
"is",
"deactivated",
"."
] | train | https://github.com/CampaignChain/core/blob/82526548a223ed49fcd65ed7c23638544499775f/EntityService/ChannelService.php#L106-L144 |
CampaignChain/core | EntityService/ChannelService.php | ChannelService.isRemovable | public function isRemovable(Channel $channel)
{
foreach ($channel->getLocations() as $location) {
if (!$this->locationService->isRemovable($location)) {
return false;
}
}
return true;
} | php | public function isRemovable(Channel $channel)
{
foreach ($channel->getLocations() as $location) {
if (!$this->locationService->isRemovable($location)) {
return false;
}
}
return true;
} | [
"public",
"function",
"isRemovable",
"(",
"Channel",
"$",
"channel",
")",
"{",
"foreach",
"(",
"$",
"channel",
"->",
"getLocations",
"(",
")",
"as",
"$",
"location",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"locationService",
"->",
"isRemovable",
"("... | @param Channel $channel
@return bool | [
"@param",
"Channel",
"$channel"
] | train | https://github.com/CampaignChain/core/blob/82526548a223ed49fcd65ed7c23638544499775f/EntityService/ChannelService.php#L151-L160 |
joomla-framework/twitter-api | src/Lists.php | Lists.getStatuses | public function getStatuses($list, $owner = null, $sinceId = 0, $maxId = 0, $count = 0, $entities = null, $includeRts = null)
{
// Check the rate limit for remaining hits
$this->checkRateLimit('lists', 'statuses');
// Determine which type of data was passed for $list
if (is_numeric($list))
{
$data['list_id'] = $list;
}
elseif (\is_string($list))
{
$data['slug'] = $list;
// In this case the owner is required.
if (is_numeric($owner))
{
$data['owner_id'] = $owner;
}
elseif (\is_string($owner))
{
$data['owner_screen_name'] = $owner;
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified username is not in the correct format; must use integer or string');
}
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified list is not in the correct format; must use integer or string');
}
// Set the API path
$path = '/lists/statuses.json';
// Check if since_id is specified
if ($sinceId > 0)
{
$data['since_id'] = $sinceId;
}
// Check if max_id is specified
if ($maxId > 0)
{
$data['max_id'] = $maxId;
}
// Check if count is specified
if ($count > 0)
{
$data['count'] = $count;
}
// Check if entities is specified
if ($entities !== null)
{
$data['include_entities'] = $entities;
}
// Check if include_rts is specified
if ($includeRts !== null)
{
$data['include_rts'] = $includeRts;
}
// Send the request.
return $this->sendRequest($path, 'GET', $data);
} | php | public function getStatuses($list, $owner = null, $sinceId = 0, $maxId = 0, $count = 0, $entities = null, $includeRts = null)
{
// Check the rate limit for remaining hits
$this->checkRateLimit('lists', 'statuses');
// Determine which type of data was passed for $list
if (is_numeric($list))
{
$data['list_id'] = $list;
}
elseif (\is_string($list))
{
$data['slug'] = $list;
// In this case the owner is required.
if (is_numeric($owner))
{
$data['owner_id'] = $owner;
}
elseif (\is_string($owner))
{
$data['owner_screen_name'] = $owner;
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified username is not in the correct format; must use integer or string');
}
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified list is not in the correct format; must use integer or string');
}
// Set the API path
$path = '/lists/statuses.json';
// Check if since_id is specified
if ($sinceId > 0)
{
$data['since_id'] = $sinceId;
}
// Check if max_id is specified
if ($maxId > 0)
{
$data['max_id'] = $maxId;
}
// Check if count is specified
if ($count > 0)
{
$data['count'] = $count;
}
// Check if entities is specified
if ($entities !== null)
{
$data['include_entities'] = $entities;
}
// Check if include_rts is specified
if ($includeRts !== null)
{
$data['include_rts'] = $includeRts;
}
// Send the request.
return $this->sendRequest($path, 'GET', $data);
} | [
"public",
"function",
"getStatuses",
"(",
"$",
"list",
",",
"$",
"owner",
"=",
"null",
",",
"$",
"sinceId",
"=",
"0",
",",
"$",
"maxId",
"=",
"0",
",",
"$",
"count",
"=",
"0",
",",
"$",
"entities",
"=",
"null",
",",
"$",
"includeRts",
"=",
"null"... | Method to get tweet timeline for members of the specified list
@param mixed $list Either an integer containing the list ID or a string containing the list slug.
@param mixed $owner Either an integer containing the user ID or a string containing the screen name.
@param integer $sinceId Returns results with an ID greater than (that is, more recent than) the specified ID.
@param integer $maxId Returns results with an ID less than (that is, older than) or equal to the specified ID.
@param integer $count Specifies the number of results to retrieve per "page."
@param boolean $entities When set to either true, t or 1, each tweet will include a node called "entities". This node offers a variety
of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags.
@param boolean $includeRts When set to either true, t or 1, the list timeline will contain native retweets (if they exist) in addition
to the standard stream of tweets.
@return array The decoded JSON response
@since 1.0
@throws \RuntimeException | [
"Method",
"to",
"get",
"tweet",
"timeline",
"for",
"members",
"of",
"the",
"specified",
"list"
] | train | https://github.com/joomla-framework/twitter-api/blob/289719bbd67e83c7cfaf515b94b1d5497b1f0525/src/Lists.php#L82-L152 |
joomla-framework/twitter-api | src/Lists.php | Lists.deleteMember | public function deleteMember($list, $user, $owner = null)
{
// Determine which type of data was passed for $list
if (is_numeric($list))
{
$data['list_id'] = $list;
}
elseif (\is_string($list))
{
$data['slug'] = $list;
// In this case the owner is required.
if (is_numeric($owner))
{
$data['owner_id'] = $owner;
}
elseif (\is_string($owner))
{
$data['owner_screen_name'] = $owner;
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified username for owner is not in the correct format; must use integer or string');
}
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified list is not in the correct format; must use integer or string');
}
if (is_numeric($user))
{
$data['user_id'] = $user;
}
elseif (\is_string($user))
{
$data['screen_name'] = $user;
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified user is not in the correct format; must use integer or string');
}
// Set the API path
$path = '/lists/members/destroy.json';
// Send the request.
return $this->sendRequest($path, 'POST', $data);
} | php | public function deleteMember($list, $user, $owner = null)
{
// Determine which type of data was passed for $list
if (is_numeric($list))
{
$data['list_id'] = $list;
}
elseif (\is_string($list))
{
$data['slug'] = $list;
// In this case the owner is required.
if (is_numeric($owner))
{
$data['owner_id'] = $owner;
}
elseif (\is_string($owner))
{
$data['owner_screen_name'] = $owner;
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified username for owner is not in the correct format; must use integer or string');
}
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified list is not in the correct format; must use integer or string');
}
if (is_numeric($user))
{
$data['user_id'] = $user;
}
elseif (\is_string($user))
{
$data['screen_name'] = $user;
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified user is not in the correct format; must use integer or string');
}
// Set the API path
$path = '/lists/members/destroy.json';
// Send the request.
return $this->sendRequest($path, 'POST', $data);
} | [
"public",
"function",
"deleteMember",
"(",
"$",
"list",
",",
"$",
"user",
",",
"$",
"owner",
"=",
"null",
")",
"{",
"// Determine which type of data was passed for $list",
"if",
"(",
"is_numeric",
"(",
"$",
"list",
")",
")",
"{",
"$",
"data",
"[",
"'list_id'... | Method to remove individual members from a list.
@param mixed $list Either an integer containing the list ID or a string containing the list slug.
@param mixed $user Either an integer containing the user ID or a string containing the screen name.
@param mixed $owner Either an integer containing the user ID or a string containing the screen name of the owner.
@return array The decoded JSON response
@since 1.2.0
@throws \RuntimeException | [
"Method",
"to",
"remove",
"individual",
"members",
"from",
"a",
"list",
"."
] | train | https://github.com/joomla-framework/twitter-api/blob/289719bbd67e83c7cfaf515b94b1d5497b1f0525/src/Lists.php#L241-L292 |
joomla-framework/twitter-api | src/Lists.php | Lists.subscribe | public function subscribe($list, $owner = null)
{
// Check the rate limit for remaining hits
$this->checkRateLimit('lists', 'subscribers/create');
// Determine which type of data was passed for $list
if (is_numeric($list))
{
$data['list_id'] = $list;
}
elseif (\is_string($list))
{
$data['slug'] = $list;
// In this case the owner is required.
if (is_numeric($owner))
{
$data['owner_id'] = $owner;
}
elseif (\is_string($owner))
{
$data['owner_screen_name'] = $owner;
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified username for owner is not in the correct format; must use integer or string');
}
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified list is not in the correct format; must use integer or string');
}
// Set the API path
$path = '/lists/subscribers/create.json';
// Send the request.
return $this->sendRequest($path, 'POST', $data);
} | php | public function subscribe($list, $owner = null)
{
// Check the rate limit for remaining hits
$this->checkRateLimit('lists', 'subscribers/create');
// Determine which type of data was passed for $list
if (is_numeric($list))
{
$data['list_id'] = $list;
}
elseif (\is_string($list))
{
$data['slug'] = $list;
// In this case the owner is required.
if (is_numeric($owner))
{
$data['owner_id'] = $owner;
}
elseif (\is_string($owner))
{
$data['owner_screen_name'] = $owner;
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified username for owner is not in the correct format; must use integer or string');
}
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified list is not in the correct format; must use integer or string');
}
// Set the API path
$path = '/lists/subscribers/create.json';
// Send the request.
return $this->sendRequest($path, 'POST', $data);
} | [
"public",
"function",
"subscribe",
"(",
"$",
"list",
",",
"$",
"owner",
"=",
"null",
")",
"{",
"// Check the rate limit for remaining hits",
"$",
"this",
"->",
"checkRateLimit",
"(",
"'lists'",
",",
"'subscribers/create'",
")",
";",
"// Determine which type of data wa... | Method to subscribe the authenticated user to the specified list.
@param mixed $list Either an integer containing the list ID or a string containing the list slug.
@param mixed $owner Either an integer containing the user ID or a string containing the screen name of the owner.
@return array The decoded JSON response
@since 1.0
@throws \RuntimeException | [
"Method",
"to",
"subscribe",
"the",
"authenticated",
"user",
"to",
"the",
"specified",
"list",
"."
] | train | https://github.com/joomla-framework/twitter-api/blob/289719bbd67e83c7cfaf515b94b1d5497b1f0525/src/Lists.php#L424-L464 |
joomla-framework/twitter-api | src/Lists.php | Lists.isMember | public function isMember($list, $user, $owner = null, $entities = null, $skipStatus = null)
{
// Check the rate limit for remaining hits
$this->checkRateLimit('lists', 'members/show');
// Determine which type of data was passed for $list
if (is_numeric($list))
{
$data['list_id'] = $list;
}
elseif (\is_string($list))
{
$data['slug'] = $list;
// In this case the owner is required.
if (is_numeric($owner))
{
$data['owner_id'] = $owner;
}
elseif (\is_string($owner))
{
$data['owner_screen_name'] = $owner;
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified username is not in the correct format; must use integer or string');
}
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified list is not in the correct format; must use integer or string');
}
if (is_numeric($user))
{
$data['user_id'] = $user;
}
elseif (\is_string($user))
{
$data['screen_name'] = $user;
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified username is not in the correct format; must use integer or string');
}
// Set the API path
$path = '/lists/members/show.json';
// Check if entities is specified
if ($entities !== null)
{
$data['include_entities'] = $entities;
}
// Check if skip_status is specified
if ($skipStatus !== null)
{
$data['skip_status'] = $skipStatus;
}
// Send the request.
return $this->sendRequest($path, 'GET', $data);
} | php | public function isMember($list, $user, $owner = null, $entities = null, $skipStatus = null)
{
// Check the rate limit for remaining hits
$this->checkRateLimit('lists', 'members/show');
// Determine which type of data was passed for $list
if (is_numeric($list))
{
$data['list_id'] = $list;
}
elseif (\is_string($list))
{
$data['slug'] = $list;
// In this case the owner is required.
if (is_numeric($owner))
{
$data['owner_id'] = $owner;
}
elseif (\is_string($owner))
{
$data['owner_screen_name'] = $owner;
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified username is not in the correct format; must use integer or string');
}
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified list is not in the correct format; must use integer or string');
}
if (is_numeric($user))
{
$data['user_id'] = $user;
}
elseif (\is_string($user))
{
$data['screen_name'] = $user;
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified username is not in the correct format; must use integer or string');
}
// Set the API path
$path = '/lists/members/show.json';
// Check if entities is specified
if ($entities !== null)
{
$data['include_entities'] = $entities;
}
// Check if skip_status is specified
if ($skipStatus !== null)
{
$data['skip_status'] = $skipStatus;
}
// Send the request.
return $this->sendRequest($path, 'GET', $data);
} | [
"public",
"function",
"isMember",
"(",
"$",
"list",
",",
"$",
"user",
",",
"$",
"owner",
"=",
"null",
",",
"$",
"entities",
"=",
"null",
",",
"$",
"skipStatus",
"=",
"null",
")",
"{",
"// Check the rate limit for remaining hits",
"$",
"this",
"->",
"checkR... | Method to check if the specified user is a member of the specified list.
@param mixed $list Either an integer containing the list ID or a string containing the list slug.
@param mixed $user Either an integer containing the user ID or a string containing the screen name of the user to remove.
@param mixed $owner Either an integer containing the user ID or a string containing the screen name of the owner.
@param boolean $entities When set to either true, t or 1, each tweet will include a node called "entities". This node offers a
variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags.
@param boolean $skipStatus When set to either true, t or 1 statuses will not be included in the returned user objects.
@return array The decoded JSON response
@since 1.0
@throws \RuntimeException | [
"Method",
"to",
"check",
"if",
"the",
"specified",
"user",
"is",
"a",
"member",
"of",
"the",
"specified",
"list",
"."
] | train | https://github.com/joomla-framework/twitter-api/blob/289719bbd67e83c7cfaf515b94b1d5497b1f0525/src/Lists.php#L481-L547 |
joomla-framework/twitter-api | src/Lists.php | Lists.addMembers | public function addMembers($list, $userId = null, $screenName = null, $owner = null)
{
// Check the rate limit for remaining hits
$this->checkRateLimit('lists', 'members/create_all');
// Determine which type of data was passed for $list
if (is_numeric($list))
{
$data['list_id'] = $list;
}
elseif (\is_string($list))
{
$data['slug'] = $list;
// In this case the owner is required.
if (is_numeric($owner))
{
$data['owner_id'] = $owner;
}
elseif (\is_string($owner))
{
$data['owner_screen_name'] = $owner;
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified username is not in the correct format; must use integer or string');
}
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified list is not in the correct format; must use integer or string');
}
if ($userId)
{
$data['user_id'] = $userId;
}
if ($screenName)
{
$data['screen_name'] = $screenName;
}
if ($userId == null && $screenName == null)
{
// We don't have a valid entry
throw new \RuntimeException('You must specify either a comma separated list of screen names, user IDs, or a combination of the two');
}
// Set the API path
$path = '/lists/members/create_all.json';
// Send the request.
return $this->sendRequest($path, 'POST', $data);
} | php | public function addMembers($list, $userId = null, $screenName = null, $owner = null)
{
// Check the rate limit for remaining hits
$this->checkRateLimit('lists', 'members/create_all');
// Determine which type of data was passed for $list
if (is_numeric($list))
{
$data['list_id'] = $list;
}
elseif (\is_string($list))
{
$data['slug'] = $list;
// In this case the owner is required.
if (is_numeric($owner))
{
$data['owner_id'] = $owner;
}
elseif (\is_string($owner))
{
$data['owner_screen_name'] = $owner;
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified username is not in the correct format; must use integer or string');
}
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified list is not in the correct format; must use integer or string');
}
if ($userId)
{
$data['user_id'] = $userId;
}
if ($screenName)
{
$data['screen_name'] = $screenName;
}
if ($userId == null && $screenName == null)
{
// We don't have a valid entry
throw new \RuntimeException('You must specify either a comma separated list of screen names, user IDs, or a combination of the two');
}
// Set the API path
$path = '/lists/members/create_all.json';
// Send the request.
return $this->sendRequest($path, 'POST', $data);
} | [
"public",
"function",
"addMembers",
"(",
"$",
"list",
",",
"$",
"userId",
"=",
"null",
",",
"$",
"screenName",
"=",
"null",
",",
"$",
"owner",
"=",
"null",
")",
"{",
"// Check the rate limit for remaining hits",
"$",
"this",
"->",
"checkRateLimit",
"(",
"'li... | Method to add multiple members to a list, by specifying a comma-separated list of member ids or screen names.
@param mixed $list Either an integer containing the list ID or a string containing the list slug.
@param string $userId A comma separated list of user IDs, up to 100 are allowed in a single request.
@param string $screenName A comma separated list of screen names, up to 100 are allowed in a single request.
@param mixed $owner Either an integer containing the user ID or a string containing the screen name of the owner.
@return array The decoded JSON response
@since 1.0
@throws \RuntimeException | [
"Method",
"to",
"add",
"multiple",
"members",
"to",
"a",
"list",
"by",
"specifying",
"a",
"comma",
"-",
"separated",
"list",
"of",
"member",
"ids",
"or",
"screen",
"names",
"."
] | train | https://github.com/joomla-framework/twitter-api/blob/289719bbd67e83c7cfaf515b94b1d5497b1f0525/src/Lists.php#L698-L754 |
joomla-framework/twitter-api | src/Lists.php | Lists.update | public function update($list, $owner = null, $name = null, $mode = null, $description = null)
{
// Check the rate limit for remaining hits
$this->checkRateLimit('lists', 'update');
// Determine which type of data was passed for $list
if (is_numeric($list))
{
$data['list_id'] = $list;
}
elseif (\is_string($list))
{
$data['slug'] = $list;
// In this case the owner is required.
if (is_numeric($owner))
{
$data['owner_id'] = $owner;
}
elseif (\is_string($owner))
{
$data['owner_screen_name'] = $owner;
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified username is not in the correct format; must use integer or string');
}
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified list is not in the correct format; must use integer or string');
}
// Check if name is specified.
if ($name)
{
$data['name'] = $name;
}
// Check if mode is specified.
if ($mode)
{
$data['mode'] = $mode;
}
// Check if description is specified.
if ($description)
{
$data['description'] = $description;
}
// Set the API path
$path = '/lists/update.json';
// Send the request.
return $this->sendRequest($path, 'POST', $data);
} | php | public function update($list, $owner = null, $name = null, $mode = null, $description = null)
{
// Check the rate limit for remaining hits
$this->checkRateLimit('lists', 'update');
// Determine which type of data was passed for $list
if (is_numeric($list))
{
$data['list_id'] = $list;
}
elseif (\is_string($list))
{
$data['slug'] = $list;
// In this case the owner is required.
if (is_numeric($owner))
{
$data['owner_id'] = $owner;
}
elseif (\is_string($owner))
{
$data['owner_screen_name'] = $owner;
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified username is not in the correct format; must use integer or string');
}
}
else
{
// We don't have a valid entry
throw new \RuntimeException('The specified list is not in the correct format; must use integer or string');
}
// Check if name is specified.
if ($name)
{
$data['name'] = $name;
}
// Check if mode is specified.
if ($mode)
{
$data['mode'] = $mode;
}
// Check if description is specified.
if ($description)
{
$data['description'] = $description;
}
// Set the API path
$path = '/lists/update.json';
// Send the request.
return $this->sendRequest($path, 'POST', $data);
} | [
"public",
"function",
"update",
"(",
"$",
"list",
",",
"$",
"owner",
"=",
"null",
",",
"$",
"name",
"=",
"null",
",",
"$",
"mode",
"=",
"null",
",",
"$",
"description",
"=",
"null",
")",
"{",
"// Check the rate limit for remaining hits",
"$",
"this",
"->... | Method to update the specified list
@param mixed $list Either an integer containing the list ID or a string containing the list slug.
@param mixed $owner Either an integer containing the user ID or a string containing the screen name of the owner.
@param string $name The name of the list.
@param string $mode Whether your list is public or private. Values can be public or private. If no mode is
specified the list will be public.
@param string $description The description to give the list.
@return array The decoded JSON response
@since 1.0
@throws \RuntimeException | [
"Method",
"to",
"update",
"the",
"specified",
"list"
] | train | https://github.com/joomla-framework/twitter-api/blob/289719bbd67e83c7cfaf515b94b1d5497b1f0525/src/Lists.php#L994-L1052 |
diemuzi/mp3 | src/Mp3/Service/Index.php | Index.index | public function index(array $params)
{
try {
$directoryListing = $this->directoryListing($params);
$count = count($directoryListing);
/**
* Remove Last 2 arrays
*/
$output = array_slice(
$directoryListing,
0,
$count - 2
);
/**
* Paginate or Error if nothing found
*/
if (is_array($directoryListing) && $count > '0') {
$paginator = new Paginator(new ArrayAdapter($output));
$paginator->setDefaultItemCountPerPage($count);
} else {
throw new \Exception(
$directoryListing . ' ' . $this->translate->translate(
'was not found',
'mp3'
)
);
}
$path = (array_key_exists(
'dir',
$params
))
? $params['dir']
: null;
return [
'paginator' => $paginator,
'path' => $path,
'totalLength' => $directoryListing['totalLength'],
'totalFileSize' => $directoryListing['totalFileSize'],
'search' => (is_file($this->getSearchFile()))
];
} catch (\Exception $e) {
throw $e;
}
} | php | public function index(array $params)
{
try {
$directoryListing = $this->directoryListing($params);
$count = count($directoryListing);
/**
* Remove Last 2 arrays
*/
$output = array_slice(
$directoryListing,
0,
$count - 2
);
/**
* Paginate or Error if nothing found
*/
if (is_array($directoryListing) && $count > '0') {
$paginator = new Paginator(new ArrayAdapter($output));
$paginator->setDefaultItemCountPerPage($count);
} else {
throw new \Exception(
$directoryListing . ' ' . $this->translate->translate(
'was not found',
'mp3'
)
);
}
$path = (array_key_exists(
'dir',
$params
))
? $params['dir']
: null;
return [
'paginator' => $paginator,
'path' => $path,
'totalLength' => $directoryListing['totalLength'],
'totalFileSize' => $directoryListing['totalFileSize'],
'search' => (is_file($this->getSearchFile()))
];
} catch (\Exception $e) {
throw $e;
}
} | [
"public",
"function",
"index",
"(",
"array",
"$",
"params",
")",
"{",
"try",
"{",
"$",
"directoryListing",
"=",
"$",
"this",
"->",
"directoryListing",
"(",
"$",
"params",
")",
";",
"$",
"count",
"=",
"count",
"(",
"$",
"directoryListing",
")",
";",
"/*... | Directory Listing
@param array $params
@return array
@throws \Exception | [
"Directory",
"Listing"
] | train | https://github.com/diemuzi/mp3/blob/2093883ccdb473ab519a0d6f06bf6ee66e8c4a5f/src/Mp3/Service/Index.php#L31-L80 |
diemuzi/mp3 | src/Mp3/Service/Index.php | Index.playAll | public function playAll($base64)
{
try {
/**
* Decode Path
*/
$base64 = base64_decode($base64);
/**
* Path to File on Disk
*/
$path = $this->getSearchPath() . '/' . $base64;
/**
* Path to Web URL
*/
$file = ltrim($this->getBaseDir() . '/' . $base64, '/');
/**
* Server URL
*/
$serverUrl = $this->serverUrl->get('serverurl')
->__invoke('/');
clearstatcache();
if (is_dir($path)) {
$array = $this->directoryListing($base64);
if (is_array($array) && count($array) > '0') {
switch ($this->getFormat()) {
/**
* Windows Media Player
*/
case 'm3u':
$playlist = '#EXTM3U' . "\n";
foreach ($array as $value) {
$playlist .= '#EXTINF: ';
$playlist .= $value['name'];
$playlist .= "\n";
$playlist .= $serverUrl;
$playlist .= str_replace(' ', '%20', $file . '/' . $value['name']);
$playlist .= "\n\n";
}
header("Content-Type: audio/mpegurl");
header("Content-Disposition: attachment; filename=" . basename($path) . ".m3u");
echo $playlist;
exit;
break;
/**
* Winamp
*/
case 'pls':
$playlist = '[Playlist]' . "\n";
foreach ($array as $key => $value) {
$id3 = $this->getId3($path . '/' . $value['name']);
$name = !empty($id3['comments_html']['title'])
? implode(
'<br>',
$id3['comments_html']['title']
)
: basename($value['name']);
$length = !empty($id3['playtime_string'])
? $id3['playtime_string']
: '-1';
$keyNum = ($key + 1);
$playlist .= 'File';
$playlist .= $keyNum;
$playlist .= '=' . $serverUrl;
$playlist .= str_replace(' ', '%20', $file . '/' . $value['name']);
$playlist .= "\n";
$playlist .= 'Title' . $keyNum . '=' . $name . "\n";
$playlist .= 'Length' . $keyNum . '=' . $this->convertTime($length) . "\n";
}
$playlist .= 'Numberofentries=' . count($array) . "\n";
$playlist .= 'Version=2' . "\n";
header("Content-Type: audio/x-scpls");
header("Content-Disposition: attachment; filename=" . basename($path) . ".pls");
echo $playlist;
exit;
break;
/**
* Error
*/
default:
throw new \Exception(
$this->translate->translate(
'Format is not currently supported. Supported formats are: pls, m3u',
'mp3'
)
);
}
} else {
throw new \Exception(
$this->translate->translate(
'Something went wrong and we cannot play this folder',
'mp3'
)
);
}
} else {
throw new \Exception(
$path . ' ' . $this->translate->translate(
'was not found',
'mp3'
)
);
}
} catch (\Exception $e) {
throw $e;
}
} | php | public function playAll($base64)
{
try {
/**
* Decode Path
*/
$base64 = base64_decode($base64);
/**
* Path to File on Disk
*/
$path = $this->getSearchPath() . '/' . $base64;
/**
* Path to Web URL
*/
$file = ltrim($this->getBaseDir() . '/' . $base64, '/');
/**
* Server URL
*/
$serverUrl = $this->serverUrl->get('serverurl')
->__invoke('/');
clearstatcache();
if (is_dir($path)) {
$array = $this->directoryListing($base64);
if (is_array($array) && count($array) > '0') {
switch ($this->getFormat()) {
/**
* Windows Media Player
*/
case 'm3u':
$playlist = '#EXTM3U' . "\n";
foreach ($array as $value) {
$playlist .= '#EXTINF: ';
$playlist .= $value['name'];
$playlist .= "\n";
$playlist .= $serverUrl;
$playlist .= str_replace(' ', '%20', $file . '/' . $value['name']);
$playlist .= "\n\n";
}
header("Content-Type: audio/mpegurl");
header("Content-Disposition: attachment; filename=" . basename($path) . ".m3u");
echo $playlist;
exit;
break;
/**
* Winamp
*/
case 'pls':
$playlist = '[Playlist]' . "\n";
foreach ($array as $key => $value) {
$id3 = $this->getId3($path . '/' . $value['name']);
$name = !empty($id3['comments_html']['title'])
? implode(
'<br>',
$id3['comments_html']['title']
)
: basename($value['name']);
$length = !empty($id3['playtime_string'])
? $id3['playtime_string']
: '-1';
$keyNum = ($key + 1);
$playlist .= 'File';
$playlist .= $keyNum;
$playlist .= '=' . $serverUrl;
$playlist .= str_replace(' ', '%20', $file . '/' . $value['name']);
$playlist .= "\n";
$playlist .= 'Title' . $keyNum . '=' . $name . "\n";
$playlist .= 'Length' . $keyNum . '=' . $this->convertTime($length) . "\n";
}
$playlist .= 'Numberofentries=' . count($array) . "\n";
$playlist .= 'Version=2' . "\n";
header("Content-Type: audio/x-scpls");
header("Content-Disposition: attachment; filename=" . basename($path) . ".pls");
echo $playlist;
exit;
break;
/**
* Error
*/
default:
throw new \Exception(
$this->translate->translate(
'Format is not currently supported. Supported formats are: pls, m3u',
'mp3'
)
);
}
} else {
throw new \Exception(
$this->translate->translate(
'Something went wrong and we cannot play this folder',
'mp3'
)
);
}
} else {
throw new \Exception(
$path . ' ' . $this->translate->translate(
'was not found',
'mp3'
)
);
}
} catch (\Exception $e) {
throw $e;
}
} | [
"public",
"function",
"playAll",
"(",
"$",
"base64",
")",
"{",
"try",
"{",
"/**\n * Decode Path\n */",
"$",
"base64",
"=",
"base64_decode",
"(",
"$",
"base64",
")",
";",
"/**\n * Path to File on Disk\n */",
"$",
"path",
"=... | Play All
@param string $base64
@return null|string|void
@throws \Exception | [
"Play",
"All"
] | train | https://github.com/diemuzi/mp3/blob/2093883ccdb473ab519a0d6f06bf6ee66e8c4a5f/src/Mp3/Service/Index.php#L90-L218 |
diemuzi/mp3 | src/Mp3/Service/Index.php | Index.playSingle | public function playSingle($base64)
{
try {
/**
* Decode Path
*/
$base64 = base64_decode($base64);
/**
* Path to File on Disk
*/
$path = $this->getSearchPath() . '/' . $base64;
/**
* Path to Web URL
*/
$file = ltrim($this->getBaseDir() . '/' . $base64, '/');
/**
* Server URL
*/
$serverUrl = $this->serverUrl->get('serverurl')
->__invoke('/');
clearstatcache();
if (is_file($path)) {
switch ($this->getFormat()) {
/**
* The most common playlist format
*/
case 'm3u':
header("Content-Type: audio/mpegurl");
header("Content-Disposition: attachment; filename=" . basename($file) . ".m3u");
echo $serverUrl . str_replace(' ', '%20', $file);
exit;
break;
/**
* Shoutcast / Icecast / Winamp
*/
case 'pls':
header("Content-Type: audio/x-scpls");
header("Content-Disposition: attachment; filename=" . basename($file) . ".pls");
$id3 = $this->getId3($path);
$name = !empty($id3['comments_html']['title'])
? implode(
'<br>',
$id3['comments_html']['title']
)
: basename($path);
$playlist = '[Playlist]' . "\n";
$playlist .= 'File1=' . $serverUrl . str_replace(' ', '%20', $file) . "\n";
$playlist .= 'Title1=' . $name . "\n";
$playlist .= 'Length1=-1' . "\n";
$playlist .= 'Numberofentries=1' . "\n";
$playlist .= 'Version=2' . "\n";
echo $playlist;
exit;
break;
/**
* Error
*/
default:
throw new \Exception(
$this->translate->translate(
'Format is not currently supported. Supported formats are: pls, m3u',
'mp3'
)
);
}
} else {
throw new \Exception(
$path . ' ' . $this->translate->translate(
'was not found',
'mp3'
)
);
}
} catch (\Exception $e) {
throw $e;
}
} | php | public function playSingle($base64)
{
try {
/**
* Decode Path
*/
$base64 = base64_decode($base64);
/**
* Path to File on Disk
*/
$path = $this->getSearchPath() . '/' . $base64;
/**
* Path to Web URL
*/
$file = ltrim($this->getBaseDir() . '/' . $base64, '/');
/**
* Server URL
*/
$serverUrl = $this->serverUrl->get('serverurl')
->__invoke('/');
clearstatcache();
if (is_file($path)) {
switch ($this->getFormat()) {
/**
* The most common playlist format
*/
case 'm3u':
header("Content-Type: audio/mpegurl");
header("Content-Disposition: attachment; filename=" . basename($file) . ".m3u");
echo $serverUrl . str_replace(' ', '%20', $file);
exit;
break;
/**
* Shoutcast / Icecast / Winamp
*/
case 'pls':
header("Content-Type: audio/x-scpls");
header("Content-Disposition: attachment; filename=" . basename($file) . ".pls");
$id3 = $this->getId3($path);
$name = !empty($id3['comments_html']['title'])
? implode(
'<br>',
$id3['comments_html']['title']
)
: basename($path);
$playlist = '[Playlist]' . "\n";
$playlist .= 'File1=' . $serverUrl . str_replace(' ', '%20', $file) . "\n";
$playlist .= 'Title1=' . $name . "\n";
$playlist .= 'Length1=-1' . "\n";
$playlist .= 'Numberofentries=1' . "\n";
$playlist .= 'Version=2' . "\n";
echo $playlist;
exit;
break;
/**
* Error
*/
default:
throw new \Exception(
$this->translate->translate(
'Format is not currently supported. Supported formats are: pls, m3u',
'mp3'
)
);
}
} else {
throw new \Exception(
$path . ' ' . $this->translate->translate(
'was not found',
'mp3'
)
);
}
} catch (\Exception $e) {
throw $e;
}
} | [
"public",
"function",
"playSingle",
"(",
"$",
"base64",
")",
"{",
"try",
"{",
"/**\n * Decode Path\n */",
"$",
"base64",
"=",
"base64_decode",
"(",
"$",
"base64",
")",
";",
"/**\n * Path to File on Disk\n */",
"$",
"path",
... | Play Single Song
@param string $base64
@return null|string|void
@throws \Exception | [
"Play",
"Single",
"Song"
] | train | https://github.com/diemuzi/mp3/blob/2093883ccdb473ab519a0d6f06bf6ee66e8c4a5f/src/Mp3/Service/Index.php#L228-L320 |
diemuzi/mp3 | src/Mp3/Service/Index.php | Index.downloadFolder | public function downloadFolder(array $params)
{
try {
if (extension_loaded('Phar')) {
/**
* Decode Path
*/
$base64 = base64_decode($params['dir']);
/**
* Path to File on Disk
*/
$path = $this->getSearchPath() . '/' . $base64;
clearstatcache();
if (is_dir($path)) {
$array = $this->directoryListing($base64);
if (is_array($array) && count($array) > '0') {
unset($array['totalLength']);
unset($array['totalFileSize']);
$filename = $path . '.' . $params['format'];
$phar = new \PharData($filename);
foreach ($array as $value) {
$phar->addFile(
$value['fullPath'],
$value['name']
);
}
switch ($params['format']) {
case 'tar':
header('Content-Type: application/x-tar');
break;
case 'zip':
header('Content-Type: application/zip');
break;
case 'bz2':
header('Content-Type: application/x-bzip2');
break;
case 'rar':
header('Content-Type: x-rar-compressed');
break;
}
header('Content-disposition: attachment; filename=' . basename($filename));
header('Content-Length: ' . filesize($filename));
readfile($filename);
unlink($filename);
exit;
} else {
throw new \Exception(
$this->translate->translate(
'Something went wrong and we cannot download this folder',
'mp3'
)
);
}
} else {
throw new \Exception(
$path . ' ' . $this->translate->translate(
'was not found',
'mp3'
)
);
}
} else {
throw new \Exception(
$this->translate->translate('Phar Extension is not loaded')
);
}
} catch (\Exception $e) {
throw $e;
}
} | php | public function downloadFolder(array $params)
{
try {
if (extension_loaded('Phar')) {
/**
* Decode Path
*/
$base64 = base64_decode($params['dir']);
/**
* Path to File on Disk
*/
$path = $this->getSearchPath() . '/' . $base64;
clearstatcache();
if (is_dir($path)) {
$array = $this->directoryListing($base64);
if (is_array($array) && count($array) > '0') {
unset($array['totalLength']);
unset($array['totalFileSize']);
$filename = $path . '.' . $params['format'];
$phar = new \PharData($filename);
foreach ($array as $value) {
$phar->addFile(
$value['fullPath'],
$value['name']
);
}
switch ($params['format']) {
case 'tar':
header('Content-Type: application/x-tar');
break;
case 'zip':
header('Content-Type: application/zip');
break;
case 'bz2':
header('Content-Type: application/x-bzip2');
break;
case 'rar':
header('Content-Type: x-rar-compressed');
break;
}
header('Content-disposition: attachment; filename=' . basename($filename));
header('Content-Length: ' . filesize($filename));
readfile($filename);
unlink($filename);
exit;
} else {
throw new \Exception(
$this->translate->translate(
'Something went wrong and we cannot download this folder',
'mp3'
)
);
}
} else {
throw new \Exception(
$path . ' ' . $this->translate->translate(
'was not found',
'mp3'
)
);
}
} else {
throw new \Exception(
$this->translate->translate('Phar Extension is not loaded')
);
}
} catch (\Exception $e) {
throw $e;
}
} | [
"public",
"function",
"downloadFolder",
"(",
"array",
"$",
"params",
")",
"{",
"try",
"{",
"if",
"(",
"extension_loaded",
"(",
"'Phar'",
")",
")",
"{",
"/**\n * Decode Path\n */",
"$",
"base64",
"=",
"base64_decode",
"(",
"$",
"para... | Download Folder
@param array $params
@return void
@throws \Exception | [
"Download",
"Folder"
] | train | https://github.com/diemuzi/mp3/blob/2093883ccdb473ab519a0d6f06bf6ee66e8c4a5f/src/Mp3/Service/Index.php#L330-L414 |
diemuzi/mp3 | src/Mp3/Service/Index.php | Index.downloadSingle | public function downloadSingle($base64)
{
try {
/**
* Path to File on Disk
*/
$path = $this->getSearchPath() . '/' . base64_decode($base64);
clearstatcache();
if (is_file($path)) {
header("Content-Type: audio/mpeg");
header("Content-Disposition: attachment; filename=" . basename($this->cleanPath($path)));
header("Content-Length: " . filesize($path));
$handle = fopen(
$path,
'rb'
);
$contents = fread(
$handle,
filesize($path)
);
while ($contents) {
echo $contents;
}
fclose($handle);
} else {
throw new \Exception(
$path . ' ' . $this->translate->translate(
'was not found',
'mp3'
)
);
}
} catch (\Exception $e) {
throw $e;
}
} | php | public function downloadSingle($base64)
{
try {
/**
* Path to File on Disk
*/
$path = $this->getSearchPath() . '/' . base64_decode($base64);
clearstatcache();
if (is_file($path)) {
header("Content-Type: audio/mpeg");
header("Content-Disposition: attachment; filename=" . basename($this->cleanPath($path)));
header("Content-Length: " . filesize($path));
$handle = fopen(
$path,
'rb'
);
$contents = fread(
$handle,
filesize($path)
);
while ($contents) {
echo $contents;
}
fclose($handle);
} else {
throw new \Exception(
$path . ' ' . $this->translate->translate(
'was not found',
'mp3'
)
);
}
} catch (\Exception $e) {
throw $e;
}
} | [
"public",
"function",
"downloadSingle",
"(",
"$",
"base64",
")",
"{",
"try",
"{",
"/**\n * Path to File on Disk\n */",
"$",
"path",
"=",
"$",
"this",
"->",
"getSearchPath",
"(",
")",
".",
"'/'",
".",
"base64_decode",
"(",
"$",
"base64",
"... | Download Single
@param string $base64
@return void
@throws \Exception | [
"Download",
"Single"
] | train | https://github.com/diemuzi/mp3/blob/2093883ccdb473ab519a0d6f06bf6ee66e8c4a5f/src/Mp3/Service/Index.php#L424-L465 |
diemuzi/mp3 | src/Mp3/Service/Index.php | Index.directoryListing | private function directoryListing($params)
{
try {
/**
* Which path are we scanning?
*
* 1) Array
* 2) String
* 3) Default
*/
if (is_array($params) && !empty($params['dir'])) {
$path = scandir($this->getSearchPath() . '/' . base64_decode($params['dir']));
} elseif (!is_array($params) && !empty($params)) {
$path = scandir($this->getSearchPath() . '/' . $params);
} else {
$path = scandir($this->getSearchPath());
}
$array = [];
$totalLength = null;
$totalFileSize = null;
if (is_array($path) && count($path) > '0') {
foreach ($path as $name) {
if ($name != '.' && $name != '..') {
$fileExtension = substr(
strrchr(
$name,
'.'
),
1
);
/**
* Set Paths
*
* 1) Array
* 2) String
* 3) Default
*/
if (is_array($params) && !empty($params['dir'])) {
$basePath = base64_decode($params['dir']) . '/' . $name;
$fullPath = $this->getSearchPath() . '/' . base64_decode($params['dir']) . '/' . $name;
} elseif (is_string($params) && !empty($params)) {
$basePath = $params . '/' . $name;
$fullPath = $this->getSearchPath() . '/' . $params . '/' . $name;
} else {
$basePath = $name;
$fullPath = $this->getSearchPath() . '/' . $name;
}
clearstatcache();
/**
* Directory
*/
if (is_dir($fullPath)) {
$array[] = [
'name' => $name,
'basePath' => $basePath,
'base64' => base64_encode($basePath),
'fullPath' => $fullPath,
'type' => 'dir'
];
}
/**
* File
*/
if (is_file($fullPath) && in_array(
'.' . $fileExtension,
$this->getExtensions()
)
) {
$id3 = $this->getId3($fullPath);
$title = !empty($id3['comments_html']['title'])
? implode(
'<br>',
$id3['comments_html']['title']
)
: $name;
$bitRate = !empty($id3['audio']['bitrate'])
? round($id3['audio']['bitrate'] / '1000')
: '-';
$length = !empty($id3['playtime_string'])
? $id3['playtime_string']
: '-';
$fileSize = !empty($id3['filesize'])
? $id3['filesize']
: '-';
$totalLength += $this->convertTime($length);
$totalFileSize += $fileSize;
$array[] = [
'name' => $name,
'basePath' => $basePath,
'base64' => base64_encode($basePath),
'fullPath' => $fullPath,
'type' => 'file',
'id3' => [
'title' => $title,
'bitRate' => $bitRate,
'length' => $length,
'fileSize' => $fileSize
]
];
}
}
}
sort($array);
if ($totalLength > '0') {
$totalLength = sprintf(
"%d:%02d",
($totalLength / '60'),
$totalLength % '60'
);
}
$array['totalLength'] = $totalLength;
$array['totalFileSize'] = $totalFileSize;
}
return $array;
} catch (\Exception $e) {
throw $e;
}
} | php | private function directoryListing($params)
{
try {
/**
* Which path are we scanning?
*
* 1) Array
* 2) String
* 3) Default
*/
if (is_array($params) && !empty($params['dir'])) {
$path = scandir($this->getSearchPath() . '/' . base64_decode($params['dir']));
} elseif (!is_array($params) && !empty($params)) {
$path = scandir($this->getSearchPath() . '/' . $params);
} else {
$path = scandir($this->getSearchPath());
}
$array = [];
$totalLength = null;
$totalFileSize = null;
if (is_array($path) && count($path) > '0') {
foreach ($path as $name) {
if ($name != '.' && $name != '..') {
$fileExtension = substr(
strrchr(
$name,
'.'
),
1
);
/**
* Set Paths
*
* 1) Array
* 2) String
* 3) Default
*/
if (is_array($params) && !empty($params['dir'])) {
$basePath = base64_decode($params['dir']) . '/' . $name;
$fullPath = $this->getSearchPath() . '/' . base64_decode($params['dir']) . '/' . $name;
} elseif (is_string($params) && !empty($params)) {
$basePath = $params . '/' . $name;
$fullPath = $this->getSearchPath() . '/' . $params . '/' . $name;
} else {
$basePath = $name;
$fullPath = $this->getSearchPath() . '/' . $name;
}
clearstatcache();
/**
* Directory
*/
if (is_dir($fullPath)) {
$array[] = [
'name' => $name,
'basePath' => $basePath,
'base64' => base64_encode($basePath),
'fullPath' => $fullPath,
'type' => 'dir'
];
}
/**
* File
*/
if (is_file($fullPath) && in_array(
'.' . $fileExtension,
$this->getExtensions()
)
) {
$id3 = $this->getId3($fullPath);
$title = !empty($id3['comments_html']['title'])
? implode(
'<br>',
$id3['comments_html']['title']
)
: $name;
$bitRate = !empty($id3['audio']['bitrate'])
? round($id3['audio']['bitrate'] / '1000')
: '-';
$length = !empty($id3['playtime_string'])
? $id3['playtime_string']
: '-';
$fileSize = !empty($id3['filesize'])
? $id3['filesize']
: '-';
$totalLength += $this->convertTime($length);
$totalFileSize += $fileSize;
$array[] = [
'name' => $name,
'basePath' => $basePath,
'base64' => base64_encode($basePath),
'fullPath' => $fullPath,
'type' => 'file',
'id3' => [
'title' => $title,
'bitRate' => $bitRate,
'length' => $length,
'fileSize' => $fileSize
]
];
}
}
}
sort($array);
if ($totalLength > '0') {
$totalLength = sprintf(
"%d:%02d",
($totalLength / '60'),
$totalLength % '60'
);
}
$array['totalLength'] = $totalLength;
$array['totalFileSize'] = $totalFileSize;
}
return $array;
} catch (\Exception $e) {
throw $e;
}
} | [
"private",
"function",
"directoryListing",
"(",
"$",
"params",
")",
"{",
"try",
"{",
"/**\n * Which path are we scanning?\n *\n * 1) Array\n * 2) String\n * 3) Default\n */",
"if",
"(",
"is_array",
"(",
"$",
"par... | Directory Listing
@param array $params
@return array
@throws \Exception | [
"Directory",
"Listing"
] | train | https://github.com/diemuzi/mp3/blob/2093883ccdb473ab519a0d6f06bf6ee66e8c4a5f/src/Mp3/Service/Index.php#L475-L615 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.