repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1 value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
Rudloff/alltube | classes/Video.php | Video.getAudioStream | public function getAudioStream($from = null, $to = null)
{
if (isset($this->_type) && $this->_type == 'playlist') {
throw new Exception(_('Conversion of playlists is not supported.'));
}
if (isset($this->protocol)) {
if (in_array($this->protocol, ['m3u8', 'm3u8_native'])) {
throw new Exception(_('Conversion of M3U8 files is not supported.'));
} elseif ($this->protocol == 'http_dash_segments') {
throw new Exception(_('Conversion of DASH segments is not supported.'));
}
}
$avconvProc = $this->getAvconvProcess($this->config->audioBitrate, 'mp3', true, $from, $to);
$stream = popen($avconvProc->getCommandLine(), 'r');
if (!is_resource($stream)) {
throw new Exception(_('Could not open popen stream.'));
}
return $stream;
} | php | public function getAudioStream($from = null, $to = null)
{
if (isset($this->_type) && $this->_type == 'playlist') {
throw new Exception(_('Conversion of playlists is not supported.'));
}
if (isset($this->protocol)) {
if (in_array($this->protocol, ['m3u8', 'm3u8_native'])) {
throw new Exception(_('Conversion of M3U8 files is not supported.'));
} elseif ($this->protocol == 'http_dash_segments') {
throw new Exception(_('Conversion of DASH segments is not supported.'));
}
}
$avconvProc = $this->getAvconvProcess($this->config->audioBitrate, 'mp3', true, $from, $to);
$stream = popen($avconvProc->getCommandLine(), 'r');
if (!is_resource($stream)) {
throw new Exception(_('Could not open popen stream.'));
}
return $stream;
} | [
"public",
"function",
"getAudioStream",
"(",
"$",
"from",
"=",
"null",
",",
"$",
"to",
"=",
"null",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"_type",
")",
"&&",
"$",
"this",
"->",
"_type",
"==",
"'playlist'",
")",
"{",
"throw",
"new",
"Exception",
"(",
"_",
"(",
"'Conversion of playlists is not supported.'",
")",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"protocol",
")",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"this",
"->",
"protocol",
",",
"[",
"'m3u8'",
",",
"'m3u8_native'",
"]",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"_",
"(",
"'Conversion of M3U8 files is not supported.'",
")",
")",
";",
"}",
"elseif",
"(",
"$",
"this",
"->",
"protocol",
"==",
"'http_dash_segments'",
")",
"{",
"throw",
"new",
"Exception",
"(",
"_",
"(",
"'Conversion of DASH segments is not supported.'",
")",
")",
";",
"}",
"}",
"$",
"avconvProc",
"=",
"$",
"this",
"->",
"getAvconvProcess",
"(",
"$",
"this",
"->",
"config",
"->",
"audioBitrate",
",",
"'mp3'",
",",
"true",
",",
"$",
"from",
",",
"$",
"to",
")",
";",
"$",
"stream",
"=",
"popen",
"(",
"$",
"avconvProc",
"->",
"getCommandLine",
"(",
")",
",",
"'r'",
")",
";",
"if",
"(",
"!",
"is_resource",
"(",
"$",
"stream",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"_",
"(",
"'Could not open popen stream.'",
")",
")",
";",
"}",
"return",
"$",
"stream",
";",
"}"
] | Get audio stream of converted video.
@param string $from Start the conversion at this time
@param string $to End the conversion at this time
@throws Exception If your try to convert an M3U8 video
@throws Exception If the popen stream was not created correctly
@return resource popen stream | [
"Get",
"audio",
"stream",
"of",
"converted",
"video",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/classes/Video.php#L407-L430 | train |
Rudloff/alltube | classes/Video.php | Video.getM3uStream | public function getM3uStream()
{
if (!$this->checkCommand([$this->config->avconv, '-version'])) {
throw new Exception(_('Can\'t find avconv or ffmpeg at ').$this->config->avconv.'.');
}
$urls = $this->getUrl();
$process = new Process(
[
$this->config->avconv,
'-v', $this->config->avconvVerbosity,
'-i', $urls[0],
'-f', $this->ext,
'-c', 'copy',
'-bsf:a', 'aac_adtstoasc',
'-movflags', 'frag_keyframe+empty_moov',
'pipe:1',
]
);
$stream = popen($process->getCommandLine(), 'r');
if (!is_resource($stream)) {
throw new Exception(_('Could not open popen stream.'));
}
return $stream;
} | php | public function getM3uStream()
{
if (!$this->checkCommand([$this->config->avconv, '-version'])) {
throw new Exception(_('Can\'t find avconv or ffmpeg at ').$this->config->avconv.'.');
}
$urls = $this->getUrl();
$process = new Process(
[
$this->config->avconv,
'-v', $this->config->avconvVerbosity,
'-i', $urls[0],
'-f', $this->ext,
'-c', 'copy',
'-bsf:a', 'aac_adtstoasc',
'-movflags', 'frag_keyframe+empty_moov',
'pipe:1',
]
);
$stream = popen($process->getCommandLine(), 'r');
if (!is_resource($stream)) {
throw new Exception(_('Could not open popen stream.'));
}
return $stream;
} | [
"public",
"function",
"getM3uStream",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"checkCommand",
"(",
"[",
"$",
"this",
"->",
"config",
"->",
"avconv",
",",
"'-version'",
"]",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"_",
"(",
"'Can\\'t find avconv or ffmpeg at '",
")",
".",
"$",
"this",
"->",
"config",
"->",
"avconv",
".",
"'.'",
")",
";",
"}",
"$",
"urls",
"=",
"$",
"this",
"->",
"getUrl",
"(",
")",
";",
"$",
"process",
"=",
"new",
"Process",
"(",
"[",
"$",
"this",
"->",
"config",
"->",
"avconv",
",",
"'-v'",
",",
"$",
"this",
"->",
"config",
"->",
"avconvVerbosity",
",",
"'-i'",
",",
"$",
"urls",
"[",
"0",
"]",
",",
"'-f'",
",",
"$",
"this",
"->",
"ext",
",",
"'-c'",
",",
"'copy'",
",",
"'-bsf:a'",
",",
"'aac_adtstoasc'",
",",
"'-movflags'",
",",
"'frag_keyframe+empty_moov'",
",",
"'pipe:1'",
",",
"]",
")",
";",
"$",
"stream",
"=",
"popen",
"(",
"$",
"process",
"->",
"getCommandLine",
"(",
")",
",",
"'r'",
")",
";",
"if",
"(",
"!",
"is_resource",
"(",
"$",
"stream",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"_",
"(",
"'Could not open popen stream.'",
")",
")",
";",
"}",
"return",
"$",
"stream",
";",
"}"
] | Get video stream from an M3U playlist.
@throws Exception If avconv/ffmpeg is missing
@throws Exception If the popen stream was not created correctly
@return resource popen stream | [
"Get",
"video",
"stream",
"from",
"an",
"M3U",
"playlist",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/classes/Video.php#L440-L467 | train |
Rudloff/alltube | classes/Video.php | Video.getRemuxStream | public function getRemuxStream()
{
$urls = $this->getUrl();
if (!isset($urls[0]) || !isset($urls[1])) {
throw new Exception(_('This video does not have two URLs.'));
}
$process = new Process(
[
$this->config->avconv,
'-v', $this->config->avconvVerbosity,
'-i', $urls[0],
'-i', $urls[1],
'-c', 'copy',
'-map', '0:v:0 ',
'-map', '1:a:0',
'-f', 'matroska',
'pipe:1',
]
);
$stream = popen($process->getCommandLine(), 'r');
if (!is_resource($stream)) {
throw new Exception(_('Could not open popen stream.'));
}
return $stream;
} | php | public function getRemuxStream()
{
$urls = $this->getUrl();
if (!isset($urls[0]) || !isset($urls[1])) {
throw new Exception(_('This video does not have two URLs.'));
}
$process = new Process(
[
$this->config->avconv,
'-v', $this->config->avconvVerbosity,
'-i', $urls[0],
'-i', $urls[1],
'-c', 'copy',
'-map', '0:v:0 ',
'-map', '1:a:0',
'-f', 'matroska',
'pipe:1',
]
);
$stream = popen($process->getCommandLine(), 'r');
if (!is_resource($stream)) {
throw new Exception(_('Could not open popen stream.'));
}
return $stream;
} | [
"public",
"function",
"getRemuxStream",
"(",
")",
"{",
"$",
"urls",
"=",
"$",
"this",
"->",
"getUrl",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"urls",
"[",
"0",
"]",
")",
"||",
"!",
"isset",
"(",
"$",
"urls",
"[",
"1",
"]",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"_",
"(",
"'This video does not have two URLs.'",
")",
")",
";",
"}",
"$",
"process",
"=",
"new",
"Process",
"(",
"[",
"$",
"this",
"->",
"config",
"->",
"avconv",
",",
"'-v'",
",",
"$",
"this",
"->",
"config",
"->",
"avconvVerbosity",
",",
"'-i'",
",",
"$",
"urls",
"[",
"0",
"]",
",",
"'-i'",
",",
"$",
"urls",
"[",
"1",
"]",
",",
"'-c'",
",",
"'copy'",
",",
"'-map'",
",",
"'0:v:0 '",
",",
"'-map'",
",",
"'1:a:0'",
",",
"'-f'",
",",
"'matroska'",
",",
"'pipe:1'",
",",
"]",
")",
";",
"$",
"stream",
"=",
"popen",
"(",
"$",
"process",
"->",
"getCommandLine",
"(",
")",
",",
"'r'",
")",
";",
"if",
"(",
"!",
"is_resource",
"(",
"$",
"stream",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"_",
"(",
"'Could not open popen stream.'",
")",
")",
";",
"}",
"return",
"$",
"stream",
";",
"}"
] | Get an avconv stream to remux audio and video.
@throws Exception If the popen stream was not created correctly
@return resource popen stream | [
"Get",
"an",
"avconv",
"stream",
"to",
"remux",
"audio",
"and",
"video",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/classes/Video.php#L476-L504 | train |
Rudloff/alltube | classes/Video.php | Video.getRtmpStream | public function getRtmpStream()
{
$urls = $this->getUrl();
$process = new Process(
array_merge(
[
$this->config->avconv,
'-v', $this->config->avconvVerbosity,
],
$this->getRtmpArguments(),
[
'-i', $urls[0],
'-f', $this->ext,
'pipe:1',
]
)
);
$stream = popen($process->getCommandLine(), 'r');
if (!is_resource($stream)) {
throw new Exception(_('Could not open popen stream.'));
}
return $stream;
} | php | public function getRtmpStream()
{
$urls = $this->getUrl();
$process = new Process(
array_merge(
[
$this->config->avconv,
'-v', $this->config->avconvVerbosity,
],
$this->getRtmpArguments(),
[
'-i', $urls[0],
'-f', $this->ext,
'pipe:1',
]
)
);
$stream = popen($process->getCommandLine(), 'r');
if (!is_resource($stream)) {
throw new Exception(_('Could not open popen stream.'));
}
return $stream;
} | [
"public",
"function",
"getRtmpStream",
"(",
")",
"{",
"$",
"urls",
"=",
"$",
"this",
"->",
"getUrl",
"(",
")",
";",
"$",
"process",
"=",
"new",
"Process",
"(",
"array_merge",
"(",
"[",
"$",
"this",
"->",
"config",
"->",
"avconv",
",",
"'-v'",
",",
"$",
"this",
"->",
"config",
"->",
"avconvVerbosity",
",",
"]",
",",
"$",
"this",
"->",
"getRtmpArguments",
"(",
")",
",",
"[",
"'-i'",
",",
"$",
"urls",
"[",
"0",
"]",
",",
"'-f'",
",",
"$",
"this",
"->",
"ext",
",",
"'pipe:1'",
",",
"]",
")",
")",
";",
"$",
"stream",
"=",
"popen",
"(",
"$",
"process",
"->",
"getCommandLine",
"(",
")",
",",
"'r'",
")",
";",
"if",
"(",
"!",
"is_resource",
"(",
"$",
"stream",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"_",
"(",
"'Could not open popen stream.'",
")",
")",
";",
"}",
"return",
"$",
"stream",
";",
"}"
] | Get video stream from an RTMP video.
@throws Exception If the popen stream was not created correctly
@return resource popen stream | [
"Get",
"video",
"stream",
"from",
"an",
"RTMP",
"video",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/classes/Video.php#L513-L537 | train |
Rudloff/alltube | classes/Video.php | Video.getConvertedStream | public function getConvertedStream($audioBitrate, $filetype)
{
if (in_array($this->protocol, ['m3u8', 'm3u8_native'])) {
throw new Exception(_('Conversion of M3U8 files is not supported.'));
}
$avconvProc = $this->getAvconvProcess($audioBitrate, $filetype, false);
$stream = popen($avconvProc->getCommandLine(), 'r');
if (!is_resource($stream)) {
throw new Exception(_('Could not open popen stream.'));
}
return $stream;
} | php | public function getConvertedStream($audioBitrate, $filetype)
{
if (in_array($this->protocol, ['m3u8', 'm3u8_native'])) {
throw new Exception(_('Conversion of M3U8 files is not supported.'));
}
$avconvProc = $this->getAvconvProcess($audioBitrate, $filetype, false);
$stream = popen($avconvProc->getCommandLine(), 'r');
if (!is_resource($stream)) {
throw new Exception(_('Could not open popen stream.'));
}
return $stream;
} | [
"public",
"function",
"getConvertedStream",
"(",
"$",
"audioBitrate",
",",
"$",
"filetype",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"this",
"->",
"protocol",
",",
"[",
"'m3u8'",
",",
"'m3u8_native'",
"]",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"_",
"(",
"'Conversion of M3U8 files is not supported.'",
")",
")",
";",
"}",
"$",
"avconvProc",
"=",
"$",
"this",
"->",
"getAvconvProcess",
"(",
"$",
"audioBitrate",
",",
"$",
"filetype",
",",
"false",
")",
";",
"$",
"stream",
"=",
"popen",
"(",
"$",
"avconvProc",
"->",
"getCommandLine",
"(",
")",
",",
"'r'",
")",
";",
"if",
"(",
"!",
"is_resource",
"(",
"$",
"stream",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"_",
"(",
"'Could not open popen stream.'",
")",
")",
";",
"}",
"return",
"$",
"stream",
";",
"}"
] | Get the stream of a converted video.
@param int $audioBitrate Audio bitrate of the converted file
@param string $filetype Filetype of the converted file
@throws Exception If your try to convert and M3U8 video
@throws Exception If the popen stream was not created correctly
@return resource popen stream | [
"Get",
"the",
"stream",
"of",
"a",
"converted",
"video",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/classes/Video.php#L550-L565 | train |
Rudloff/alltube | classes/Video.php | Video.getHttpResponse | public function getHttpResponse(array $headers = [])
{
$client = new Client();
$urls = $this->getUrl();
return $client->request('GET', $urls[0], ['stream' => true, 'headers' => $headers]);
} | php | public function getHttpResponse(array $headers = [])
{
$client = new Client();
$urls = $this->getUrl();
return $client->request('GET', $urls[0], ['stream' => true, 'headers' => $headers]);
} | [
"public",
"function",
"getHttpResponse",
"(",
"array",
"$",
"headers",
"=",
"[",
"]",
")",
"{",
"$",
"client",
"=",
"new",
"Client",
"(",
")",
";",
"$",
"urls",
"=",
"$",
"this",
"->",
"getUrl",
"(",
")",
";",
"return",
"$",
"client",
"->",
"request",
"(",
"'GET'",
",",
"$",
"urls",
"[",
"0",
"]",
",",
"[",
"'stream'",
"=>",
"true",
",",
"'headers'",
"=>",
"$",
"headers",
"]",
")",
";",
"}"
] | Get a HTTP response containing the video.
@param array $headers HTTP headers of the request
@return Response | [
"Get",
"a",
"HTTP",
"response",
"containing",
"the",
"video",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/classes/Video.php#L586-L592 | train |
Rudloff/alltube | classes/streams/PlaylistArchiveStream.php | PlaylistArchiveStream.send | protected function send($data)
{
$pos = $this->tell();
// Add data to the end of the buffer.
$this->seek(0, SEEK_END);
$this->write($data);
if ($pos !== false) {
// Rewind so that read() can later read this data.
$this->seek($pos);
}
} | php | protected function send($data)
{
$pos = $this->tell();
// Add data to the end of the buffer.
$this->seek(0, SEEK_END);
$this->write($data);
if ($pos !== false) {
// Rewind so that read() can later read this data.
$this->seek($pos);
}
} | [
"protected",
"function",
"send",
"(",
"$",
"data",
")",
"{",
"$",
"pos",
"=",
"$",
"this",
"->",
"tell",
"(",
")",
";",
"// Add data to the end of the buffer.",
"$",
"this",
"->",
"seek",
"(",
"0",
",",
"SEEK_END",
")",
";",
"$",
"this",
"->",
"write",
"(",
"$",
"data",
")",
";",
"if",
"(",
"$",
"pos",
"!==",
"false",
")",
"{",
"// Rewind so that read() can later read this data.",
"$",
"this",
"->",
"seek",
"(",
"$",
"pos",
")",
";",
"}",
"}"
] | Add data to the archive.
@param string $data Data
@return void | [
"Add",
"data",
"to",
"the",
"archive",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/classes/streams/PlaylistArchiveStream.php#L70-L81 | train |
Rudloff/alltube | classes/LocaleManager.php | LocaleManager.getSupportedLocales | public function getSupportedLocales()
{
$return = [];
$process = new Process(['locale', '-a']);
$process->run();
$installedLocales = explode(PHP_EOL, trim($process->getOutput()));
foreach ($this->supportedLocales as $supportedLocale) {
if (in_array($supportedLocale, $installedLocales)
|| in_array($supportedLocale.'.utf8', $installedLocales)
) {
$return[] = new Locale($supportedLocale);
}
}
return $return;
} | php | public function getSupportedLocales()
{
$return = [];
$process = new Process(['locale', '-a']);
$process->run();
$installedLocales = explode(PHP_EOL, trim($process->getOutput()));
foreach ($this->supportedLocales as $supportedLocale) {
if (in_array($supportedLocale, $installedLocales)
|| in_array($supportedLocale.'.utf8', $installedLocales)
) {
$return[] = new Locale($supportedLocale);
}
}
return $return;
} | [
"public",
"function",
"getSupportedLocales",
"(",
")",
"{",
"$",
"return",
"=",
"[",
"]",
";",
"$",
"process",
"=",
"new",
"Process",
"(",
"[",
"'locale'",
",",
"'-a'",
"]",
")",
";",
"$",
"process",
"->",
"run",
"(",
")",
";",
"$",
"installedLocales",
"=",
"explode",
"(",
"PHP_EOL",
",",
"trim",
"(",
"$",
"process",
"->",
"getOutput",
"(",
")",
")",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"supportedLocales",
"as",
"$",
"supportedLocale",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"supportedLocale",
",",
"$",
"installedLocales",
")",
"||",
"in_array",
"(",
"$",
"supportedLocale",
".",
"'.utf8'",
",",
"$",
"installedLocales",
")",
")",
"{",
"$",
"return",
"[",
"]",
"=",
"new",
"Locale",
"(",
"$",
"supportedLocale",
")",
";",
"}",
"}",
"return",
"$",
"return",
";",
"}"
] | Get a list of supported locales.
@return Locale[] | [
"Get",
"a",
"list",
"of",
"supported",
"locales",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/classes/LocaleManager.php#L57-L72 | train |
Rudloff/alltube | classes/LocaleManager.php | LocaleManager.setLocale | public function setLocale(Locale $locale)
{
putenv('LANG='.$locale);
setlocale(LC_ALL, [$locale.'.utf8', $locale]);
$this->curLocale = $locale;
$this->sessionSegment->set('locale', $locale);
} | php | public function setLocale(Locale $locale)
{
putenv('LANG='.$locale);
setlocale(LC_ALL, [$locale.'.utf8', $locale]);
$this->curLocale = $locale;
$this->sessionSegment->set('locale', $locale);
} | [
"public",
"function",
"setLocale",
"(",
"Locale",
"$",
"locale",
")",
"{",
"putenv",
"(",
"'LANG='",
".",
"$",
"locale",
")",
";",
"setlocale",
"(",
"LC_ALL",
",",
"[",
"$",
"locale",
".",
"'.utf8'",
",",
"$",
"locale",
"]",
")",
";",
"$",
"this",
"->",
"curLocale",
"=",
"$",
"locale",
";",
"$",
"this",
"->",
"sessionSegment",
"->",
"set",
"(",
"'locale'",
",",
"$",
"locale",
")",
";",
"}"
] | Set the current locale.
@param Locale $locale Locale | [
"Set",
"the",
"current",
"locale",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/classes/LocaleManager.php#L89-L95 | train |
Rudloff/alltube | controllers/BaseController.php | BaseController.getFormat | protected function getFormat(Request $request)
{
$format = $request->getQueryParam('format');
if (!isset($format)) {
$format = $this->defaultFormat;
}
return $format;
} | php | protected function getFormat(Request $request)
{
$format = $request->getQueryParam('format');
if (!isset($format)) {
$format = $this->defaultFormat;
}
return $format;
} | [
"protected",
"function",
"getFormat",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"format",
"=",
"$",
"request",
"->",
"getQueryParam",
"(",
"'format'",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"format",
")",
")",
"{",
"$",
"format",
"=",
"$",
"this",
"->",
"defaultFormat",
";",
"}",
"return",
"$",
"format",
";",
"}"
] | Get video format from request parameters or default format if none is specified.
@param Request $request PSR-7 request
@return string format | [
"Get",
"video",
"format",
"from",
"request",
"parameters",
"or",
"default",
"format",
"if",
"none",
"is",
"specified",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/controllers/BaseController.php#L79-L87 | train |
Rudloff/alltube | controllers/BaseController.php | BaseController.getPassword | protected function getPassword(Request $request)
{
$url = $request->getQueryParam('url');
$password = $request->getParam('password');
if (isset($password)) {
$this->sessionSegment->setFlash($url, $password);
} else {
$password = $this->sessionSegment->getFlash($url);
}
return $password;
} | php | protected function getPassword(Request $request)
{
$url = $request->getQueryParam('url');
$password = $request->getParam('password');
if (isset($password)) {
$this->sessionSegment->setFlash($url, $password);
} else {
$password = $this->sessionSegment->getFlash($url);
}
return $password;
} | [
"protected",
"function",
"getPassword",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"url",
"=",
"$",
"request",
"->",
"getQueryParam",
"(",
"'url'",
")",
";",
"$",
"password",
"=",
"$",
"request",
"->",
"getParam",
"(",
"'password'",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"password",
")",
")",
"{",
"$",
"this",
"->",
"sessionSegment",
"->",
"setFlash",
"(",
"$",
"url",
",",
"$",
"password",
")",
";",
"}",
"else",
"{",
"$",
"password",
"=",
"$",
"this",
"->",
"sessionSegment",
"->",
"getFlash",
"(",
"$",
"url",
")",
";",
"}",
"return",
"$",
"password",
";",
"}"
] | Get the password entered for the current video.
@param Request $request PSR-7 request
@return string Password | [
"Get",
"the",
"password",
"entered",
"for",
"the",
"current",
"video",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/controllers/BaseController.php#L96-L108 | train |
Rudloff/alltube | classes/Config.php | Config.validateOptions | private function validateOptions()
{
/*
We don't translate these exceptions because they usually occur before Slim can catch them
so they will go to the logs.
*/
if (!is_file($this->youtubedl)) {
throw new Exception("Can't find youtube-dl at ".$this->youtubedl);
} elseif (!Video::checkCommand([$this->python, '--version'])) {
throw new Exception("Can't find Python at ".$this->python);
}
} | php | private function validateOptions()
{
/*
We don't translate these exceptions because they usually occur before Slim can catch them
so they will go to the logs.
*/
if (!is_file($this->youtubedl)) {
throw new Exception("Can't find youtube-dl at ".$this->youtubedl);
} elseif (!Video::checkCommand([$this->python, '--version'])) {
throw new Exception("Can't find Python at ".$this->python);
}
} | [
"private",
"function",
"validateOptions",
"(",
")",
"{",
"/*\n We don't translate these exceptions because they usually occur before Slim can catch them\n so they will go to the logs.\n */",
"if",
"(",
"!",
"is_file",
"(",
"$",
"this",
"->",
"youtubedl",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"Can't find youtube-dl at \"",
".",
"$",
"this",
"->",
"youtubedl",
")",
";",
"}",
"elseif",
"(",
"!",
"Video",
"::",
"checkCommand",
"(",
"[",
"$",
"this",
"->",
"python",
",",
"'--version'",
"]",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"Can't find Python at \"",
".",
"$",
"this",
"->",
"python",
")",
";",
"}",
"}"
] | Throw an exception if some of the options are invalid.
@throws Exception If youtube-dl is missing
@throws Exception If Python is missing
@return void | [
"Throw",
"an",
"exception",
"if",
"some",
"of",
"the",
"options",
"are",
"invalid",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/classes/Config.php#L148-L159 | train |
Rudloff/alltube | classes/Config.php | Config.applyOptions | private function applyOptions(array $options)
{
foreach ($options as $option => $value) {
if (isset($this->$option) && isset($value)) {
$this->$option = $value;
}
}
} | php | private function applyOptions(array $options)
{
foreach ($options as $option => $value) {
if (isset($this->$option) && isset($value)) {
$this->$option = $value;
}
}
} | [
"private",
"function",
"applyOptions",
"(",
"array",
"$",
"options",
")",
"{",
"foreach",
"(",
"$",
"options",
"as",
"$",
"option",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"$",
"option",
")",
"&&",
"isset",
"(",
"$",
"value",
")",
")",
"{",
"$",
"this",
"->",
"$",
"option",
"=",
"$",
"value",
";",
"}",
"}",
"}"
] | Apply the provided options.
@param array $options Options
@return void | [
"Apply",
"the",
"provided",
"options",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/classes/Config.php#L168-L175 | train |
Rudloff/alltube | classes/Config.php | Config.setFile | public static function setFile($file)
{
if (is_file($file)) {
$options = Yaml::parse(file_get_contents($file));
self::$instance = new self($options);
self::$instance->validateOptions();
} else {
throw new Exception("Can't find config file at ".$file);
}
} | php | public static function setFile($file)
{
if (is_file($file)) {
$options = Yaml::parse(file_get_contents($file));
self::$instance = new self($options);
self::$instance->validateOptions();
} else {
throw new Exception("Can't find config file at ".$file);
}
} | [
"public",
"static",
"function",
"setFile",
"(",
"$",
"file",
")",
"{",
"if",
"(",
"is_file",
"(",
"$",
"file",
")",
")",
"{",
"$",
"options",
"=",
"Yaml",
"::",
"parse",
"(",
"file_get_contents",
"(",
"$",
"file",
")",
")",
";",
"self",
"::",
"$",
"instance",
"=",
"new",
"self",
"(",
"$",
"options",
")",
";",
"self",
"::",
"$",
"instance",
"->",
"validateOptions",
"(",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Exception",
"(",
"\"Can't find config file at \"",
".",
"$",
"file",
")",
";",
"}",
"}"
] | Set options from a YAML file.
@param string $file Path to the YAML file | [
"Set",
"options",
"from",
"a",
"YAML",
"file",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/classes/Config.php#L213-L222 | train |
Rudloff/alltube | classes/Config.php | Config.setOptions | public static function setOptions(array $options, $update = true)
{
if ($update) {
$config = self::getInstance();
$config->applyOptions($options);
$config->validateOptions();
} else {
self::$instance = new self($options);
}
} | php | public static function setOptions(array $options, $update = true)
{
if ($update) {
$config = self::getInstance();
$config->applyOptions($options);
$config->validateOptions();
} else {
self::$instance = new self($options);
}
} | [
"public",
"static",
"function",
"setOptions",
"(",
"array",
"$",
"options",
",",
"$",
"update",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"update",
")",
"{",
"$",
"config",
"=",
"self",
"::",
"getInstance",
"(",
")",
";",
"$",
"config",
"->",
"applyOptions",
"(",
"$",
"options",
")",
";",
"$",
"config",
"->",
"validateOptions",
"(",
")",
";",
"}",
"else",
"{",
"self",
"::",
"$",
"instance",
"=",
"new",
"self",
"(",
"$",
"options",
")",
";",
"}",
"}"
] | Manually set some options.
@param array $options Options (see `config/config.example.yml` for available options)
@param bool $update True to update an existing instance | [
"Manually",
"set",
"some",
"options",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/classes/Config.php#L230-L239 | train |
Rudloff/alltube | controllers/DownloadController.php | DownloadController.download | public function download(Request $request, Response $response)
{
$url = $request->getQueryParam('url');
if (isset($url)) {
$this->video = new Video($url, $this->getFormat($request), $this->getPassword($request));
try {
if ($this->config->convert && $request->getQueryParam('audio')) {
// Audio convert.
return $this->getAudioResponse($request, $response);
} elseif ($this->config->convertAdvanced && !is_null($request->getQueryParam('customConvert'))) {
// Advance convert.
return $this->getConvertedResponse($request, $response);
}
// Regular download.
return $this->getDownloadResponse($request, $response);
} catch (PasswordException $e) {
return $response->withRedirect(
$this->container->get('router')->pathFor('info').'?'.http_build_query($request->getQueryParams())
);
} catch (Exception $e) {
$response->getBody()->write($e->getMessage());
return $response->withHeader('Content-Type', 'text/plain')->withStatus(500);
}
} else {
return $response->withRedirect($this->container->get('router')->pathFor('index'));
}
} | php | public function download(Request $request, Response $response)
{
$url = $request->getQueryParam('url');
if (isset($url)) {
$this->video = new Video($url, $this->getFormat($request), $this->getPassword($request));
try {
if ($this->config->convert && $request->getQueryParam('audio')) {
// Audio convert.
return $this->getAudioResponse($request, $response);
} elseif ($this->config->convertAdvanced && !is_null($request->getQueryParam('customConvert'))) {
// Advance convert.
return $this->getConvertedResponse($request, $response);
}
// Regular download.
return $this->getDownloadResponse($request, $response);
} catch (PasswordException $e) {
return $response->withRedirect(
$this->container->get('router')->pathFor('info').'?'.http_build_query($request->getQueryParams())
);
} catch (Exception $e) {
$response->getBody()->write($e->getMessage());
return $response->withHeader('Content-Type', 'text/plain')->withStatus(500);
}
} else {
return $response->withRedirect($this->container->get('router')->pathFor('index'));
}
} | [
"public",
"function",
"download",
"(",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
")",
"{",
"$",
"url",
"=",
"$",
"request",
"->",
"getQueryParam",
"(",
"'url'",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"url",
")",
")",
"{",
"$",
"this",
"->",
"video",
"=",
"new",
"Video",
"(",
"$",
"url",
",",
"$",
"this",
"->",
"getFormat",
"(",
"$",
"request",
")",
",",
"$",
"this",
"->",
"getPassword",
"(",
"$",
"request",
")",
")",
";",
"try",
"{",
"if",
"(",
"$",
"this",
"->",
"config",
"->",
"convert",
"&&",
"$",
"request",
"->",
"getQueryParam",
"(",
"'audio'",
")",
")",
"{",
"// Audio convert.",
"return",
"$",
"this",
"->",
"getAudioResponse",
"(",
"$",
"request",
",",
"$",
"response",
")",
";",
"}",
"elseif",
"(",
"$",
"this",
"->",
"config",
"->",
"convertAdvanced",
"&&",
"!",
"is_null",
"(",
"$",
"request",
"->",
"getQueryParam",
"(",
"'customConvert'",
")",
")",
")",
"{",
"// Advance convert.",
"return",
"$",
"this",
"->",
"getConvertedResponse",
"(",
"$",
"request",
",",
"$",
"response",
")",
";",
"}",
"// Regular download.",
"return",
"$",
"this",
"->",
"getDownloadResponse",
"(",
"$",
"request",
",",
"$",
"response",
")",
";",
"}",
"catch",
"(",
"PasswordException",
"$",
"e",
")",
"{",
"return",
"$",
"response",
"->",
"withRedirect",
"(",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'router'",
")",
"->",
"pathFor",
"(",
"'info'",
")",
".",
"'?'",
".",
"http_build_query",
"(",
"$",
"request",
"->",
"getQueryParams",
"(",
")",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"$",
"response",
"->",
"getBody",
"(",
")",
"->",
"write",
"(",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
";",
"return",
"$",
"response",
"->",
"withHeader",
"(",
"'Content-Type'",
",",
"'text/plain'",
")",
"->",
"withStatus",
"(",
"500",
")",
";",
"}",
"}",
"else",
"{",
"return",
"$",
"response",
"->",
"withRedirect",
"(",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'router'",
")",
"->",
"pathFor",
"(",
"'index'",
")",
")",
";",
"}",
"}"
] | Redirect to video file.
@param Request $request PSR-7 request
@param Response $response PSR-7 response
@return Response HTTP response | [
"Redirect",
"to",
"video",
"file",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/controllers/DownloadController.php#L32-L62 | train |
Rudloff/alltube | controllers/DownloadController.php | DownloadController.getConvertedAudioResponse | private function getConvertedAudioResponse(Request $request, Response $response)
{
$from = $request->getQueryParam('from');
$to = $request->getQueryParam('to');
$response = $response->withHeader(
'Content-Disposition',
'attachment; filename="'.
$this->video->getFileNameWithExtension('mp3').'"'
);
$response = $response->withHeader('Content-Type', 'audio/mpeg');
if ($request->isGet() || $request->isPost()) {
try {
$process = $this->video->getAudioStream($from, $to);
} catch (Exception $e) {
// Fallback to default format.
$this->video = $this->video->withFormat($this->defaultFormat);
$process = $this->video->getAudioStream($from, $to);
}
$response = $response->withBody(new Stream($process));
}
return $response;
} | php | private function getConvertedAudioResponse(Request $request, Response $response)
{
$from = $request->getQueryParam('from');
$to = $request->getQueryParam('to');
$response = $response->withHeader(
'Content-Disposition',
'attachment; filename="'.
$this->video->getFileNameWithExtension('mp3').'"'
);
$response = $response->withHeader('Content-Type', 'audio/mpeg');
if ($request->isGet() || $request->isPost()) {
try {
$process = $this->video->getAudioStream($from, $to);
} catch (Exception $e) {
// Fallback to default format.
$this->video = $this->video->withFormat($this->defaultFormat);
$process = $this->video->getAudioStream($from, $to);
}
$response = $response->withBody(new Stream($process));
}
return $response;
} | [
"private",
"function",
"getConvertedAudioResponse",
"(",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
")",
"{",
"$",
"from",
"=",
"$",
"request",
"->",
"getQueryParam",
"(",
"'from'",
")",
";",
"$",
"to",
"=",
"$",
"request",
"->",
"getQueryParam",
"(",
"'to'",
")",
";",
"$",
"response",
"=",
"$",
"response",
"->",
"withHeader",
"(",
"'Content-Disposition'",
",",
"'attachment; filename=\"'",
".",
"$",
"this",
"->",
"video",
"->",
"getFileNameWithExtension",
"(",
"'mp3'",
")",
".",
"'\"'",
")",
";",
"$",
"response",
"=",
"$",
"response",
"->",
"withHeader",
"(",
"'Content-Type'",
",",
"'audio/mpeg'",
")",
";",
"if",
"(",
"$",
"request",
"->",
"isGet",
"(",
")",
"||",
"$",
"request",
"->",
"isPost",
"(",
")",
")",
"{",
"try",
"{",
"$",
"process",
"=",
"$",
"this",
"->",
"video",
"->",
"getAudioStream",
"(",
"$",
"from",
",",
"$",
"to",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"// Fallback to default format.",
"$",
"this",
"->",
"video",
"=",
"$",
"this",
"->",
"video",
"->",
"withFormat",
"(",
"$",
"this",
"->",
"defaultFormat",
")",
";",
"$",
"process",
"=",
"$",
"this",
"->",
"video",
"->",
"getAudioStream",
"(",
"$",
"from",
",",
"$",
"to",
")",
";",
"}",
"$",
"response",
"=",
"$",
"response",
"->",
"withBody",
"(",
"new",
"Stream",
"(",
"$",
"process",
")",
")",
";",
"}",
"return",
"$",
"response",
";",
"}"
] | Return a converted MP3 file.
@param Request $request PSR-7 request
@param Response $response PSR-7 response
@return Response HTTP response | [
"Return",
"a",
"converted",
"MP3",
"file",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/controllers/DownloadController.php#L72-L96 | train |
Rudloff/alltube | controllers/DownloadController.php | DownloadController.getAudioResponse | private function getAudioResponse(Request $request, Response $response)
{
try {
// First, we try to get a MP3 file directly.
if (!empty($request->getQueryParam('from')) || !empty($request->getQueryParam('to'))) {
throw new Exception('Force convert when we need to seek.');
}
if ($this->config->stream) {
$this->video = $this->video->withFormat('mp3');
return $this->getStream($request, $response);
} else {
$this->video = $this->video->withFormat('mp3[protocol=https]/mp3[protocol=http]');
$urls = $this->video->getUrl();
return $response->withRedirect($urls[0]);
}
} catch (PasswordException $e) {
$frontController = new FrontController($this->container);
return $frontController->password($request, $response);
} catch (Exception $e) {
// If MP3 is not available, we convert it.
$this->video = $this->video->withFormat($this->defaultFormat);
return $this->getConvertedAudioResponse($request, $response);
}
} | php | private function getAudioResponse(Request $request, Response $response)
{
try {
// First, we try to get a MP3 file directly.
if (!empty($request->getQueryParam('from')) || !empty($request->getQueryParam('to'))) {
throw new Exception('Force convert when we need to seek.');
}
if ($this->config->stream) {
$this->video = $this->video->withFormat('mp3');
return $this->getStream($request, $response);
} else {
$this->video = $this->video->withFormat('mp3[protocol=https]/mp3[protocol=http]');
$urls = $this->video->getUrl();
return $response->withRedirect($urls[0]);
}
} catch (PasswordException $e) {
$frontController = new FrontController($this->container);
return $frontController->password($request, $response);
} catch (Exception $e) {
// If MP3 is not available, we convert it.
$this->video = $this->video->withFormat($this->defaultFormat);
return $this->getConvertedAudioResponse($request, $response);
}
} | [
"private",
"function",
"getAudioResponse",
"(",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
")",
"{",
"try",
"{",
"// First, we try to get a MP3 file directly.",
"if",
"(",
"!",
"empty",
"(",
"$",
"request",
"->",
"getQueryParam",
"(",
"'from'",
")",
")",
"||",
"!",
"empty",
"(",
"$",
"request",
"->",
"getQueryParam",
"(",
"'to'",
")",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Force convert when we need to seek.'",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"config",
"->",
"stream",
")",
"{",
"$",
"this",
"->",
"video",
"=",
"$",
"this",
"->",
"video",
"->",
"withFormat",
"(",
"'mp3'",
")",
";",
"return",
"$",
"this",
"->",
"getStream",
"(",
"$",
"request",
",",
"$",
"response",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"video",
"=",
"$",
"this",
"->",
"video",
"->",
"withFormat",
"(",
"'mp3[protocol=https]/mp3[protocol=http]'",
")",
";",
"$",
"urls",
"=",
"$",
"this",
"->",
"video",
"->",
"getUrl",
"(",
")",
";",
"return",
"$",
"response",
"->",
"withRedirect",
"(",
"$",
"urls",
"[",
"0",
"]",
")",
";",
"}",
"}",
"catch",
"(",
"PasswordException",
"$",
"e",
")",
"{",
"$",
"frontController",
"=",
"new",
"FrontController",
"(",
"$",
"this",
"->",
"container",
")",
";",
"return",
"$",
"frontController",
"->",
"password",
"(",
"$",
"request",
",",
"$",
"response",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"// If MP3 is not available, we convert it.",
"$",
"this",
"->",
"video",
"=",
"$",
"this",
"->",
"video",
"->",
"withFormat",
"(",
"$",
"this",
"->",
"defaultFormat",
")",
";",
"return",
"$",
"this",
"->",
"getConvertedAudioResponse",
"(",
"$",
"request",
",",
"$",
"response",
")",
";",
"}",
"}"
] | Return the MP3 file.
@param Request $request PSR-7 request
@param Response $response PSR-7 response
@return Response HTTP response | [
"Return",
"the",
"MP3",
"file",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/controllers/DownloadController.php#L106-L135 | train |
Rudloff/alltube | controllers/DownloadController.php | DownloadController.getRemuxStream | private function getRemuxStream(Request $request, Response $response)
{
if (!$this->config->remux) {
throw new Exception(_('You need to enable remux mode to merge two formats.'));
}
$stream = $this->video->getRemuxStream();
$response = $response->withHeader('Content-Type', 'video/x-matroska');
if ($request->isGet()) {
$response = $response->withBody(new Stream($stream));
}
return $response->withHeader(
'Content-Disposition',
'attachment; filename="'.$this->video->getFileNameWithExtension('mkv')
);
} | php | private function getRemuxStream(Request $request, Response $response)
{
if (!$this->config->remux) {
throw new Exception(_('You need to enable remux mode to merge two formats.'));
}
$stream = $this->video->getRemuxStream();
$response = $response->withHeader('Content-Type', 'video/x-matroska');
if ($request->isGet()) {
$response = $response->withBody(new Stream($stream));
}
return $response->withHeader(
'Content-Disposition',
'attachment; filename="'.$this->video->getFileNameWithExtension('mkv')
);
} | [
"private",
"function",
"getRemuxStream",
"(",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"config",
"->",
"remux",
")",
"{",
"throw",
"new",
"Exception",
"(",
"_",
"(",
"'You need to enable remux mode to merge two formats.'",
")",
")",
";",
"}",
"$",
"stream",
"=",
"$",
"this",
"->",
"video",
"->",
"getRemuxStream",
"(",
")",
";",
"$",
"response",
"=",
"$",
"response",
"->",
"withHeader",
"(",
"'Content-Type'",
",",
"'video/x-matroska'",
")",
";",
"if",
"(",
"$",
"request",
"->",
"isGet",
"(",
")",
")",
"{",
"$",
"response",
"=",
"$",
"response",
"->",
"withBody",
"(",
"new",
"Stream",
"(",
"$",
"stream",
")",
")",
";",
"}",
"return",
"$",
"response",
"->",
"withHeader",
"(",
"'Content-Disposition'",
",",
"'attachment; filename=\"'",
".",
"$",
"this",
"->",
"video",
"->",
"getFileNameWithExtension",
"(",
"'mkv'",
")",
")",
";",
"}"
] | Get a remuxed stream piped through the server.
@param Response $response PSR-7 response
@param Request $request PSR-7 request
@return Response HTTP response | [
"Get",
"a",
"remuxed",
"stream",
"piped",
"through",
"the",
"server",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/controllers/DownloadController.php#L204-L219 | train |
Rudloff/alltube | controllers/DownloadController.php | DownloadController.getDownloadResponse | private function getDownloadResponse(Request $request, Response $response)
{
try {
$videoUrls = $this->video->getUrl();
} catch (EmptyUrlException $e) {
/*
If this happens it is probably a playlist
so it will either be handled by getStream() or throw an exception anyway.
*/
$videoUrls = [];
}
if (count($videoUrls) > 1) {
return $this->getRemuxStream($request, $response);
} elseif ($this->config->stream && (isset($this->video->entries) || $request->getQueryParam('stream'))) {
return $this->getStream($request, $response);
} else {
if (empty($videoUrls[0])) {
throw new Exception(_("Can't find URL of video."));
}
return $response->withRedirect($videoUrls[0]);
}
} | php | private function getDownloadResponse(Request $request, Response $response)
{
try {
$videoUrls = $this->video->getUrl();
} catch (EmptyUrlException $e) {
/*
If this happens it is probably a playlist
so it will either be handled by getStream() or throw an exception anyway.
*/
$videoUrls = [];
}
if (count($videoUrls) > 1) {
return $this->getRemuxStream($request, $response);
} elseif ($this->config->stream && (isset($this->video->entries) || $request->getQueryParam('stream'))) {
return $this->getStream($request, $response);
} else {
if (empty($videoUrls[0])) {
throw new Exception(_("Can't find URL of video."));
}
return $response->withRedirect($videoUrls[0]);
}
} | [
"private",
"function",
"getDownloadResponse",
"(",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
")",
"{",
"try",
"{",
"$",
"videoUrls",
"=",
"$",
"this",
"->",
"video",
"->",
"getUrl",
"(",
")",
";",
"}",
"catch",
"(",
"EmptyUrlException",
"$",
"e",
")",
"{",
"/*\n If this happens it is probably a playlist\n so it will either be handled by getStream() or throw an exception anyway.\n */",
"$",
"videoUrls",
"=",
"[",
"]",
";",
"}",
"if",
"(",
"count",
"(",
"$",
"videoUrls",
")",
">",
"1",
")",
"{",
"return",
"$",
"this",
"->",
"getRemuxStream",
"(",
"$",
"request",
",",
"$",
"response",
")",
";",
"}",
"elseif",
"(",
"$",
"this",
"->",
"config",
"->",
"stream",
"&&",
"(",
"isset",
"(",
"$",
"this",
"->",
"video",
"->",
"entries",
")",
"||",
"$",
"request",
"->",
"getQueryParam",
"(",
"'stream'",
")",
")",
")",
"{",
"return",
"$",
"this",
"->",
"getStream",
"(",
"$",
"request",
",",
"$",
"response",
")",
";",
"}",
"else",
"{",
"if",
"(",
"empty",
"(",
"$",
"videoUrls",
"[",
"0",
"]",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"_",
"(",
"\"Can't find URL of video.\"",
")",
")",
";",
"}",
"return",
"$",
"response",
"->",
"withRedirect",
"(",
"$",
"videoUrls",
"[",
"0",
"]",
")",
";",
"}",
"}"
] | Get approriate HTTP response to download query.
Depends on whether we want to stream, remux or simply redirect.
@param Response $response PSR-7 response
@param Request $request PSR-7 request
@return Response HTTP response | [
"Get",
"approriate",
"HTTP",
"response",
"to",
"download",
"query",
".",
"Depends",
"on",
"whether",
"we",
"want",
"to",
"stream",
"remux",
"or",
"simply",
"redirect",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/controllers/DownloadController.php#L230-L252 | train |
Rudloff/alltube | controllers/DownloadController.php | DownloadController.getConvertedResponse | private function getConvertedResponse(Request $request, Response $response)
{
$response = $response->withHeader(
'Content-Disposition',
'attachment; filename="'.
$this->video->getFileNameWithExtension($request->getQueryParam('customFormat')).'"'
);
$response = $response->withHeader('Content-Type', 'video/'.$request->getQueryParam('customFormat'));
if ($request->isGet() || $request->isPost()) {
$process = $this->video->getConvertedStream(
$request->getQueryParam('customBitrate'),
$request->getQueryParam('customFormat')
);
$response = $response->withBody(new Stream($process));
}
return $response;
} | php | private function getConvertedResponse(Request $request, Response $response)
{
$response = $response->withHeader(
'Content-Disposition',
'attachment; filename="'.
$this->video->getFileNameWithExtension($request->getQueryParam('customFormat')).'"'
);
$response = $response->withHeader('Content-Type', 'video/'.$request->getQueryParam('customFormat'));
if ($request->isGet() || $request->isPost()) {
$process = $this->video->getConvertedStream(
$request->getQueryParam('customBitrate'),
$request->getQueryParam('customFormat')
);
$response = $response->withBody(new Stream($process));
}
return $response;
} | [
"private",
"function",
"getConvertedResponse",
"(",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
")",
"{",
"$",
"response",
"=",
"$",
"response",
"->",
"withHeader",
"(",
"'Content-Disposition'",
",",
"'attachment; filename=\"'",
".",
"$",
"this",
"->",
"video",
"->",
"getFileNameWithExtension",
"(",
"$",
"request",
"->",
"getQueryParam",
"(",
"'customFormat'",
")",
")",
".",
"'\"'",
")",
";",
"$",
"response",
"=",
"$",
"response",
"->",
"withHeader",
"(",
"'Content-Type'",
",",
"'video/'",
".",
"$",
"request",
"->",
"getQueryParam",
"(",
"'customFormat'",
")",
")",
";",
"if",
"(",
"$",
"request",
"->",
"isGet",
"(",
")",
"||",
"$",
"request",
"->",
"isPost",
"(",
")",
")",
"{",
"$",
"process",
"=",
"$",
"this",
"->",
"video",
"->",
"getConvertedStream",
"(",
"$",
"request",
"->",
"getQueryParam",
"(",
"'customBitrate'",
")",
",",
"$",
"request",
"->",
"getQueryParam",
"(",
"'customFormat'",
")",
")",
";",
"$",
"response",
"=",
"$",
"response",
"->",
"withBody",
"(",
"new",
"Stream",
"(",
"$",
"process",
")",
")",
";",
"}",
"return",
"$",
"response",
";",
"}"
] | Return a converted video file.
@param Request $request PSR-7 request
@param Response $response PSR-7 response
@return Response HTTP response | [
"Return",
"a",
"converted",
"video",
"file",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/controllers/DownloadController.php#L262-L280 | train |
Rudloff/alltube | controllers/FrontController.php | FrontController.index | public function index(Request $request, Response $response)
{
$uri = $request->getUri()->withUserInfo('');
$this->view->render(
$response,
'index.tpl',
[
'config' => $this->config,
'class' => 'index',
'description' => _('Easily download videos from Youtube, Dailymotion, Vimeo and other websites.'),
'domain' => $uri->getScheme().'://'.$uri->getAuthority(),
'canonical' => $this->getCanonicalUrl($request),
'supportedLocales' => $this->localeManager->getSupportedLocales(),
'locale' => $this->localeManager->getLocale(),
]
);
return $response;
} | php | public function index(Request $request, Response $response)
{
$uri = $request->getUri()->withUserInfo('');
$this->view->render(
$response,
'index.tpl',
[
'config' => $this->config,
'class' => 'index',
'description' => _('Easily download videos from Youtube, Dailymotion, Vimeo and other websites.'),
'domain' => $uri->getScheme().'://'.$uri->getAuthority(),
'canonical' => $this->getCanonicalUrl($request),
'supportedLocales' => $this->localeManager->getSupportedLocales(),
'locale' => $this->localeManager->getLocale(),
]
);
return $response;
} | [
"public",
"function",
"index",
"(",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
")",
"{",
"$",
"uri",
"=",
"$",
"request",
"->",
"getUri",
"(",
")",
"->",
"withUserInfo",
"(",
"''",
")",
";",
"$",
"this",
"->",
"view",
"->",
"render",
"(",
"$",
"response",
",",
"'index.tpl'",
",",
"[",
"'config'",
"=>",
"$",
"this",
"->",
"config",
",",
"'class'",
"=>",
"'index'",
",",
"'description'",
"=>",
"_",
"(",
"'Easily download videos from Youtube, Dailymotion, Vimeo and other websites.'",
")",
",",
"'domain'",
"=>",
"$",
"uri",
"->",
"getScheme",
"(",
")",
".",
"'://'",
".",
"$",
"uri",
"->",
"getAuthority",
"(",
")",
",",
"'canonical'",
"=>",
"$",
"this",
"->",
"getCanonicalUrl",
"(",
"$",
"request",
")",
",",
"'supportedLocales'",
"=>",
"$",
"this",
"->",
"localeManager",
"->",
"getSupportedLocales",
"(",
")",
",",
"'locale'",
"=>",
"$",
"this",
"->",
"localeManager",
"->",
"getLocale",
"(",
")",
",",
"]",
")",
";",
"return",
"$",
"response",
";",
"}"
] | Display index page.
@param Request $request PSR-7 request
@param Response $response PSR-7 response
@return Response HTTP response | [
"Display",
"index",
"page",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/controllers/FrontController.php#L60-L78 | train |
Rudloff/alltube | controllers/FrontController.php | FrontController.locale | public function locale(Request $request, Response $response, array $data)
{
$this->localeManager->setLocale(new Locale($data['locale']));
return $response->withRedirect($this->container->get('router')->pathFor('index'));
} | php | public function locale(Request $request, Response $response, array $data)
{
$this->localeManager->setLocale(new Locale($data['locale']));
return $response->withRedirect($this->container->get('router')->pathFor('index'));
} | [
"public",
"function",
"locale",
"(",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
",",
"array",
"$",
"data",
")",
"{",
"$",
"this",
"->",
"localeManager",
"->",
"setLocale",
"(",
"new",
"Locale",
"(",
"$",
"data",
"[",
"'locale'",
"]",
")",
")",
";",
"return",
"$",
"response",
"->",
"withRedirect",
"(",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'router'",
")",
"->",
"pathFor",
"(",
"'index'",
")",
")",
";",
"}"
] | Switch locale.
@param Request $request PSR-7 request
@param Response $response PSR-7 response
@param array $data Query parameters
@return Response | [
"Switch",
"locale",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/controllers/FrontController.php#L89-L94 | train |
Rudloff/alltube | controllers/FrontController.php | FrontController.extractors | public function extractors(Request $request, Response $response)
{
$this->view->render(
$response,
'extractors.tpl',
[
'config' => $this->config,
'extractors' => Video::getExtractors(),
'class' => 'extractors',
'title' => _('Supported websites'),
'description' => _('List of all supported websites from which Alltube Download '.
'can extract video or audio files'),
'canonical' => $this->getCanonicalUrl($request),
'locale' => $this->localeManager->getLocale(),
]
);
return $response;
} | php | public function extractors(Request $request, Response $response)
{
$this->view->render(
$response,
'extractors.tpl',
[
'config' => $this->config,
'extractors' => Video::getExtractors(),
'class' => 'extractors',
'title' => _('Supported websites'),
'description' => _('List of all supported websites from which Alltube Download '.
'can extract video or audio files'),
'canonical' => $this->getCanonicalUrl($request),
'locale' => $this->localeManager->getLocale(),
]
);
return $response;
} | [
"public",
"function",
"extractors",
"(",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
")",
"{",
"$",
"this",
"->",
"view",
"->",
"render",
"(",
"$",
"response",
",",
"'extractors.tpl'",
",",
"[",
"'config'",
"=>",
"$",
"this",
"->",
"config",
",",
"'extractors'",
"=>",
"Video",
"::",
"getExtractors",
"(",
")",
",",
"'class'",
"=>",
"'extractors'",
",",
"'title'",
"=>",
"_",
"(",
"'Supported websites'",
")",
",",
"'description'",
"=>",
"_",
"(",
"'List of all supported websites from which Alltube Download '",
".",
"'can extract video or audio files'",
")",
",",
"'canonical'",
"=>",
"$",
"this",
"->",
"getCanonicalUrl",
"(",
"$",
"request",
")",
",",
"'locale'",
"=>",
"$",
"this",
"->",
"localeManager",
"->",
"getLocale",
"(",
")",
",",
"]",
")",
";",
"return",
"$",
"response",
";",
"}"
] | Display a list of extractors.
@param Request $request PSR-7 request
@param Response $response PSR-7 response
@return Response HTTP response | [
"Display",
"a",
"list",
"of",
"extractors",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/controllers/FrontController.php#L104-L122 | train |
Rudloff/alltube | controllers/FrontController.php | FrontController.password | public function password(Request $request, Response $response)
{
$this->view->render(
$response,
'password.tpl',
[
'config' => $this->config,
'class' => 'password',
'title' => _('Password prompt'),
'description' => _('You need a password in order to download this video with Alltube Download'),
'canonical' => $this->getCanonicalUrl($request),
'locale' => $this->localeManager->getLocale(),
]
);
return $response;
} | php | public function password(Request $request, Response $response)
{
$this->view->render(
$response,
'password.tpl',
[
'config' => $this->config,
'class' => 'password',
'title' => _('Password prompt'),
'description' => _('You need a password in order to download this video with Alltube Download'),
'canonical' => $this->getCanonicalUrl($request),
'locale' => $this->localeManager->getLocale(),
]
);
return $response;
} | [
"public",
"function",
"password",
"(",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
")",
"{",
"$",
"this",
"->",
"view",
"->",
"render",
"(",
"$",
"response",
",",
"'password.tpl'",
",",
"[",
"'config'",
"=>",
"$",
"this",
"->",
"config",
",",
"'class'",
"=>",
"'password'",
",",
"'title'",
"=>",
"_",
"(",
"'Password prompt'",
")",
",",
"'description'",
"=>",
"_",
"(",
"'You need a password in order to download this video with Alltube Download'",
")",
",",
"'canonical'",
"=>",
"$",
"this",
"->",
"getCanonicalUrl",
"(",
"$",
"request",
")",
",",
"'locale'",
"=>",
"$",
"this",
"->",
"localeManager",
"->",
"getLocale",
"(",
")",
",",
"]",
")",
";",
"return",
"$",
"response",
";",
"}"
] | Display a password prompt.
@param Request $request PSR-7 request
@param Response $response PSR-7 response
@return Response HTTP response | [
"Display",
"a",
"password",
"prompt",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/controllers/FrontController.php#L132-L148 | train |
Rudloff/alltube | controllers/FrontController.php | FrontController.getInfoResponse | private function getInfoResponse(Request $request, Response $response)
{
try {
$this->video->getJson();
} catch (PasswordException $e) {
return $this->password($request, $response);
}
if (isset($this->video->entries)) {
$template = 'playlist.tpl';
} else {
$template = 'info.tpl';
}
$title = _('Video download');
$description = _('Download video from ').$this->video->extractor_key;
if (isset($this->video->title)) {
$title = $this->video->title;
$description = _('Download').' "'.$this->video->title.'" '._('from').' '.$this->video->extractor_key;
}
$this->view->render(
$response,
$template,
[
'video' => $this->video,
'class' => 'info',
'title' => $title,
'description' => $description,
'config' => $this->config,
'canonical' => $this->getCanonicalUrl($request),
'locale' => $this->localeManager->getLocale(),
'defaultFormat' => $this->defaultFormat,
]
);
return $response;
} | php | private function getInfoResponse(Request $request, Response $response)
{
try {
$this->video->getJson();
} catch (PasswordException $e) {
return $this->password($request, $response);
}
if (isset($this->video->entries)) {
$template = 'playlist.tpl';
} else {
$template = 'info.tpl';
}
$title = _('Video download');
$description = _('Download video from ').$this->video->extractor_key;
if (isset($this->video->title)) {
$title = $this->video->title;
$description = _('Download').' "'.$this->video->title.'" '._('from').' '.$this->video->extractor_key;
}
$this->view->render(
$response,
$template,
[
'video' => $this->video,
'class' => 'info',
'title' => $title,
'description' => $description,
'config' => $this->config,
'canonical' => $this->getCanonicalUrl($request),
'locale' => $this->localeManager->getLocale(),
'defaultFormat' => $this->defaultFormat,
]
);
return $response;
} | [
"private",
"function",
"getInfoResponse",
"(",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"video",
"->",
"getJson",
"(",
")",
";",
"}",
"catch",
"(",
"PasswordException",
"$",
"e",
")",
"{",
"return",
"$",
"this",
"->",
"password",
"(",
"$",
"request",
",",
"$",
"response",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"video",
"->",
"entries",
")",
")",
"{",
"$",
"template",
"=",
"'playlist.tpl'",
";",
"}",
"else",
"{",
"$",
"template",
"=",
"'info.tpl'",
";",
"}",
"$",
"title",
"=",
"_",
"(",
"'Video download'",
")",
";",
"$",
"description",
"=",
"_",
"(",
"'Download video from '",
")",
".",
"$",
"this",
"->",
"video",
"->",
"extractor_key",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"video",
"->",
"title",
")",
")",
"{",
"$",
"title",
"=",
"$",
"this",
"->",
"video",
"->",
"title",
";",
"$",
"description",
"=",
"_",
"(",
"'Download'",
")",
".",
"' \"'",
".",
"$",
"this",
"->",
"video",
"->",
"title",
".",
"'\" '",
".",
"_",
"(",
"'from'",
")",
".",
"' '",
".",
"$",
"this",
"->",
"video",
"->",
"extractor_key",
";",
"}",
"$",
"this",
"->",
"view",
"->",
"render",
"(",
"$",
"response",
",",
"$",
"template",
",",
"[",
"'video'",
"=>",
"$",
"this",
"->",
"video",
",",
"'class'",
"=>",
"'info'",
",",
"'title'",
"=>",
"$",
"title",
",",
"'description'",
"=>",
"$",
"description",
",",
"'config'",
"=>",
"$",
"this",
"->",
"config",
",",
"'canonical'",
"=>",
"$",
"this",
"->",
"getCanonicalUrl",
"(",
"$",
"request",
")",
",",
"'locale'",
"=>",
"$",
"this",
"->",
"localeManager",
"->",
"getLocale",
"(",
")",
",",
"'defaultFormat'",
"=>",
"$",
"this",
"->",
"defaultFormat",
",",
"]",
")",
";",
"return",
"$",
"response",
";",
"}"
] | Return the video description page.
@param Request $request PSR-7 request
@param Response $response PSR-7 response
@return Response HTTP response | [
"Return",
"the",
"video",
"description",
"page",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/controllers/FrontController.php#L158-L193 | train |
Rudloff/alltube | controllers/FrontController.php | FrontController.info | public function info(Request $request, Response $response)
{
$url = $request->getQueryParam('url') ?: $request->getQueryParam('v');
if (isset($url) && !empty($url)) {
$this->video = new Video($url, $this->getFormat($request), $this->getPassword($request));
if ($this->config->convert && $request->getQueryParam('audio')) {
// We skip the info page and get directly to the download.
return $response->withRedirect(
$this->container->get('router')->pathFor('download').
'?'.http_build_query($request->getQueryParams())
);
} else {
return $this->getInfoResponse($request, $response);
}
} else {
return $response->withRedirect($this->container->get('router')->pathFor('index'));
}
} | php | public function info(Request $request, Response $response)
{
$url = $request->getQueryParam('url') ?: $request->getQueryParam('v');
if (isset($url) && !empty($url)) {
$this->video = new Video($url, $this->getFormat($request), $this->getPassword($request));
if ($this->config->convert && $request->getQueryParam('audio')) {
// We skip the info page and get directly to the download.
return $response->withRedirect(
$this->container->get('router')->pathFor('download').
'?'.http_build_query($request->getQueryParams())
);
} else {
return $this->getInfoResponse($request, $response);
}
} else {
return $response->withRedirect($this->container->get('router')->pathFor('index'));
}
} | [
"public",
"function",
"info",
"(",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
")",
"{",
"$",
"url",
"=",
"$",
"request",
"->",
"getQueryParam",
"(",
"'url'",
")",
"?",
":",
"$",
"request",
"->",
"getQueryParam",
"(",
"'v'",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"url",
")",
"&&",
"!",
"empty",
"(",
"$",
"url",
")",
")",
"{",
"$",
"this",
"->",
"video",
"=",
"new",
"Video",
"(",
"$",
"url",
",",
"$",
"this",
"->",
"getFormat",
"(",
"$",
"request",
")",
",",
"$",
"this",
"->",
"getPassword",
"(",
"$",
"request",
")",
")",
";",
"if",
"(",
"$",
"this",
"->",
"config",
"->",
"convert",
"&&",
"$",
"request",
"->",
"getQueryParam",
"(",
"'audio'",
")",
")",
"{",
"// We skip the info page and get directly to the download.",
"return",
"$",
"response",
"->",
"withRedirect",
"(",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'router'",
")",
"->",
"pathFor",
"(",
"'download'",
")",
".",
"'?'",
".",
"http_build_query",
"(",
"$",
"request",
"->",
"getQueryParams",
"(",
")",
")",
")",
";",
"}",
"else",
"{",
"return",
"$",
"this",
"->",
"getInfoResponse",
"(",
"$",
"request",
",",
"$",
"response",
")",
";",
"}",
"}",
"else",
"{",
"return",
"$",
"response",
"->",
"withRedirect",
"(",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'router'",
")",
"->",
"pathFor",
"(",
"'index'",
")",
")",
";",
"}",
"}"
] | Dislay information about the video.
@param Request $request PSR-7 request
@param Response $response PSR-7 response
@return Response HTTP response | [
"Dislay",
"information",
"about",
"the",
"video",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/controllers/FrontController.php#L203-L222 | train |
Rudloff/alltube | controllers/FrontController.php | FrontController.error | public function error(Request $request, Response $response, Exception $exception)
{
$this->view->render(
$response,
'error.tpl',
[
'config' => $this->config,
'errors' => $exception->getMessage(),
'class' => 'video',
'title' => _('Error'),
'canonical' => $this->getCanonicalUrl($request),
'locale' => $this->localeManager->getLocale(),
]
);
return $response->withStatus(500);
} | php | public function error(Request $request, Response $response, Exception $exception)
{
$this->view->render(
$response,
'error.tpl',
[
'config' => $this->config,
'errors' => $exception->getMessage(),
'class' => 'video',
'title' => _('Error'),
'canonical' => $this->getCanonicalUrl($request),
'locale' => $this->localeManager->getLocale(),
]
);
return $response->withStatus(500);
} | [
"public",
"function",
"error",
"(",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
",",
"Exception",
"$",
"exception",
")",
"{",
"$",
"this",
"->",
"view",
"->",
"render",
"(",
"$",
"response",
",",
"'error.tpl'",
",",
"[",
"'config'",
"=>",
"$",
"this",
"->",
"config",
",",
"'errors'",
"=>",
"$",
"exception",
"->",
"getMessage",
"(",
")",
",",
"'class'",
"=>",
"'video'",
",",
"'title'",
"=>",
"_",
"(",
"'Error'",
")",
",",
"'canonical'",
"=>",
"$",
"this",
"->",
"getCanonicalUrl",
"(",
"$",
"request",
")",
",",
"'locale'",
"=>",
"$",
"this",
"->",
"localeManager",
"->",
"getLocale",
"(",
")",
",",
"]",
")",
";",
"return",
"$",
"response",
"->",
"withStatus",
"(",
"500",
")",
";",
"}"
] | Display an error page.
@param Request $request PSR-7 request
@param Response $response PSR-7 response
@param Exception $exception Error to display
@return Response HTTP response | [
"Display",
"an",
"error",
"page",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/controllers/FrontController.php#L233-L249 | train |
Rudloff/alltube | controllers/FrontController.php | FrontController.getCanonicalUrl | private function getCanonicalUrl(Request $request)
{
$uri = $request->getUri();
$return = 'https://alltubedownload.net/';
$path = $uri->getPath();
if ($path != '/') {
$return .= $path;
}
$query = $uri->getQuery();
if (!empty($query)) {
$return .= '?'.$query;
}
return $return;
} | php | private function getCanonicalUrl(Request $request)
{
$uri = $request->getUri();
$return = 'https://alltubedownload.net/';
$path = $uri->getPath();
if ($path != '/') {
$return .= $path;
}
$query = $uri->getQuery();
if (!empty($query)) {
$return .= '?'.$query;
}
return $return;
} | [
"private",
"function",
"getCanonicalUrl",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"uri",
"=",
"$",
"request",
"->",
"getUri",
"(",
")",
";",
"$",
"return",
"=",
"'https://alltubedownload.net/'",
";",
"$",
"path",
"=",
"$",
"uri",
"->",
"getPath",
"(",
")",
";",
"if",
"(",
"$",
"path",
"!=",
"'/'",
")",
"{",
"$",
"return",
".=",
"$",
"path",
";",
"}",
"$",
"query",
"=",
"$",
"uri",
"->",
"getQuery",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"query",
")",
")",
"{",
"$",
"return",
".=",
"'?'",
".",
"$",
"query",
";",
"}",
"return",
"$",
"return",
";",
"}"
] | Generate the canonical URL of the current page.
@param Request $request PSR-7 Request
@return string URL | [
"Generate",
"the",
"canonical",
"URL",
"of",
"the",
"current",
"page",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/controllers/FrontController.php#L258-L274 | train |
Rudloff/alltube | controllers/JsonController.php | JsonController.json | public function json(Request $request, Response $response)
{
$url = $request->getQueryParam('url');
if (isset($url)) {
try {
$this->video = new Video($url, $this->getFormat($request), $this->getPassword($request));
return $response->withJson($this->video->getJson());
} catch (Exception $e) {
return $response->withJson(['error' => $e->getMessage()])
->withStatus(500);
}
} else {
return $response->withJson(['error' => 'You need to provide the url parameter'])
->withStatus(400);
}
} | php | public function json(Request $request, Response $response)
{
$url = $request->getQueryParam('url');
if (isset($url)) {
try {
$this->video = new Video($url, $this->getFormat($request), $this->getPassword($request));
return $response->withJson($this->video->getJson());
} catch (Exception $e) {
return $response->withJson(['error' => $e->getMessage()])
->withStatus(500);
}
} else {
return $response->withJson(['error' => 'You need to provide the url parameter'])
->withStatus(400);
}
} | [
"public",
"function",
"json",
"(",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
")",
"{",
"$",
"url",
"=",
"$",
"request",
"->",
"getQueryParam",
"(",
"'url'",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"url",
")",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"video",
"=",
"new",
"Video",
"(",
"$",
"url",
",",
"$",
"this",
"->",
"getFormat",
"(",
"$",
"request",
")",
",",
"$",
"this",
"->",
"getPassword",
"(",
"$",
"request",
")",
")",
";",
"return",
"$",
"response",
"->",
"withJson",
"(",
"$",
"this",
"->",
"video",
"->",
"getJson",
"(",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"return",
"$",
"response",
"->",
"withJson",
"(",
"[",
"'error'",
"=>",
"$",
"e",
"->",
"getMessage",
"(",
")",
"]",
")",
"->",
"withStatus",
"(",
"500",
")",
";",
"}",
"}",
"else",
"{",
"return",
"$",
"response",
"->",
"withJson",
"(",
"[",
"'error'",
"=>",
"'You need to provide the url parameter'",
"]",
")",
"->",
"withStatus",
"(",
"400",
")",
";",
"}",
"}"
] | Return the JSON object generated by youtube-dl.
@param Request $request PSR-7 request
@param Response $response PSR-7 response
@return Response HTTP response | [
"Return",
"the",
"JSON",
"object",
"generated",
"by",
"youtube",
"-",
"dl",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/controllers/JsonController.php#L26-L43 | train |
Rudloff/alltube | classes/SessionManager.php | SessionManager.getSession | public static function getSession()
{
if (!isset(self::$session)) {
$session_factory = new SessionFactory();
self::$session = $session_factory->newInstance($_COOKIE);
}
return self::$session;
} | php | public static function getSession()
{
if (!isset(self::$session)) {
$session_factory = new SessionFactory();
self::$session = $session_factory->newInstance($_COOKIE);
}
return self::$session;
} | [
"public",
"static",
"function",
"getSession",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"session",
")",
")",
"{",
"$",
"session_factory",
"=",
"new",
"SessionFactory",
"(",
")",
";",
"self",
"::",
"$",
"session",
"=",
"$",
"session_factory",
"->",
"newInstance",
"(",
"$",
"_COOKIE",
")",
";",
"}",
"return",
"self",
"::",
"$",
"session",
";",
"}"
] | Get the current session.
@return Session | [
"Get",
"the",
"current",
"session",
"."
] | a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a | https://github.com/Rudloff/alltube/blob/a0811c6dc4a7ac6102aede1b439fa8e53ab1ed3a/classes/SessionManager.php#L28-L36 | train |
algolia/algoliasearch-client-php | src/Support/Helpers.php | Helpers.apiPath | public static function apiPath($pathFormat, $args = null, $_ = null)
{
$arguments = array_slice(func_get_args(), 1);
foreach ($arguments as &$arg) {
$arg = urlencode(urldecode($arg));
}
array_unshift($arguments, $pathFormat);
return call_user_func_array('sprintf', $arguments);
} | php | public static function apiPath($pathFormat, $args = null, $_ = null)
{
$arguments = array_slice(func_get_args(), 1);
foreach ($arguments as &$arg) {
$arg = urlencode(urldecode($arg));
}
array_unshift($arguments, $pathFormat);
return call_user_func_array('sprintf', $arguments);
} | [
"public",
"static",
"function",
"apiPath",
"(",
"$",
"pathFormat",
",",
"$",
"args",
"=",
"null",
",",
"$",
"_",
"=",
"null",
")",
"{",
"$",
"arguments",
"=",
"array_slice",
"(",
"func_get_args",
"(",
")",
",",
"1",
")",
";",
"foreach",
"(",
"$",
"arguments",
"as",
"&",
"$",
"arg",
")",
"{",
"$",
"arg",
"=",
"urlencode",
"(",
"urldecode",
"(",
"$",
"arg",
")",
")",
";",
"}",
"array_unshift",
"(",
"$",
"arguments",
",",
"$",
"pathFormat",
")",
";",
"return",
"call_user_func_array",
"(",
"'sprintf'",
",",
"$",
"arguments",
")",
";",
"}"
] | Use this function to generate API path. It will ensure
that all parameters are properly urlencoded.
The function will not double encode if the params are
already urlencoded
Signature is the same `sprintf`.
Examples:
- api_path('1/indexes/%s/search', $indexName)
- api_path('/1/indexes/%s/synonyms/%s', $indexName, $objectID)
@param string $pathFormat
@param mixed $args
@param mixed $_
@return mixed | [
"Use",
"this",
"function",
"to",
"generate",
"API",
"path",
".",
"It",
"will",
"ensure",
"that",
"all",
"parameters",
"are",
"properly",
"urlencoded",
".",
"The",
"function",
"will",
"not",
"double",
"encode",
"if",
"the",
"params",
"are",
"already",
"urlencoded",
"Signature",
"is",
"the",
"same",
"sprintf",
"."
] | 1a058bb0c06542e677505032ee3a1cb42135a8bc | https://github.com/algolia/algoliasearch-client-php/blob/1a058bb0c06542e677505032ee3a1cb42135a8bc/src/Support/Helpers.php#L26-L35 | train |
algolia/algoliasearch-client-php | src/Support/Helpers.php | Helpers.buildQuery | public static function buildQuery(array $args)
{
if (!$args) {
return '';
}
$args = array_map(function ($value) {
if (is_array($value)) {
return json_encode($value);
} elseif (is_bool($value)) {
return $value ? 'true' : 'false';
} else {
return $value;
}
}, $args);
return http_build_query($args);
} | php | public static function buildQuery(array $args)
{
if (!$args) {
return '';
}
$args = array_map(function ($value) {
if (is_array($value)) {
return json_encode($value);
} elseif (is_bool($value)) {
return $value ? 'true' : 'false';
} else {
return $value;
}
}, $args);
return http_build_query($args);
} | [
"public",
"static",
"function",
"buildQuery",
"(",
"array",
"$",
"args",
")",
"{",
"if",
"(",
"!",
"$",
"args",
")",
"{",
"return",
"''",
";",
"}",
"$",
"args",
"=",
"array_map",
"(",
"function",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"return",
"json_encode",
"(",
"$",
"value",
")",
";",
"}",
"elseif",
"(",
"is_bool",
"(",
"$",
"value",
")",
")",
"{",
"return",
"$",
"value",
"?",
"'true'",
":",
"'false'",
";",
"}",
"else",
"{",
"return",
"$",
"value",
";",
"}",
"}",
",",
"$",
"args",
")",
";",
"return",
"http_build_query",
"(",
"$",
"args",
")",
";",
"}"
] | When building a query string, array values must be json_encoded.
This function can be used to turn any array into a Algolia-valid query string.
Do not use a typical implementation where ['key' => ['one', 'two']] is
turned into key[1]=one&key[2]=two. Algolia will not understand key[x].
It should be turned into key=['one','two'] (before being url_encoded).
@param array $args
@return string The urlencoded query string to send to Algolia | [
"When",
"building",
"a",
"query",
"string",
"array",
"values",
"must",
"be",
"json_encoded",
".",
"This",
"function",
"can",
"be",
"used",
"to",
"turn",
"any",
"array",
"into",
"a",
"Algolia",
"-",
"valid",
"query",
"string",
"."
] | 1a058bb0c06542e677505032ee3a1cb42135a8bc | https://github.com/algolia/algoliasearch-client-php/blob/1a058bb0c06542e677505032ee3a1cb42135a8bc/src/Support/Helpers.php#L49-L66 | train |
algolia/algoliasearch-client-php | src/Http/Psr7/Uri.php | Uri.isSameDocumentReference | public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null)
{
if (null !== $base) {
$uri = UriResolver::resolve($base, $uri);
return ($uri->getScheme() === $base->getScheme())
&& ($uri->getAuthority() === $base->getAuthority())
&& ($uri->getPath() === $base->getPath())
&& ($uri->getQuery() === $base->getQuery());
}
return '' === $uri->getScheme() && '' === $uri->getAuthority() && '' === $uri->getPath() && '' === $uri->getQuery();
} | php | public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null)
{
if (null !== $base) {
$uri = UriResolver::resolve($base, $uri);
return ($uri->getScheme() === $base->getScheme())
&& ($uri->getAuthority() === $base->getAuthority())
&& ($uri->getPath() === $base->getPath())
&& ($uri->getQuery() === $base->getQuery());
}
return '' === $uri->getScheme() && '' === $uri->getAuthority() && '' === $uri->getPath() && '' === $uri->getQuery();
} | [
"public",
"static",
"function",
"isSameDocumentReference",
"(",
"UriInterface",
"$",
"uri",
",",
"UriInterface",
"$",
"base",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"!==",
"$",
"base",
")",
"{",
"$",
"uri",
"=",
"UriResolver",
"::",
"resolve",
"(",
"$",
"base",
",",
"$",
"uri",
")",
";",
"return",
"(",
"$",
"uri",
"->",
"getScheme",
"(",
")",
"===",
"$",
"base",
"->",
"getScheme",
"(",
")",
")",
"&&",
"(",
"$",
"uri",
"->",
"getAuthority",
"(",
")",
"===",
"$",
"base",
"->",
"getAuthority",
"(",
")",
")",
"&&",
"(",
"$",
"uri",
"->",
"getPath",
"(",
")",
"===",
"$",
"base",
"->",
"getPath",
"(",
")",
")",
"&&",
"(",
"$",
"uri",
"->",
"getQuery",
"(",
")",
"===",
"$",
"base",
"->",
"getQuery",
"(",
")",
")",
";",
"}",
"return",
"''",
"===",
"$",
"uri",
"->",
"getScheme",
"(",
")",
"&&",
"''",
"===",
"$",
"uri",
"->",
"getAuthority",
"(",
")",
"&&",
"''",
"===",
"$",
"uri",
"->",
"getPath",
"(",
")",
"&&",
"''",
"===",
"$",
"uri",
"->",
"getQuery",
"(",
")",
";",
"}"
] | Whether the URI is a same-document reference.
A same-document reference refers to a URI that is, aside from its fragment
component, identical to the base URI. When no base URI is given, only an empty
URI reference (apart from its fragment) is considered a same-document reference.
@param UriInterface $uri The URI to check
@param UriInterface|null $base An optional base URI to compare against
@return bool
@see https://tools.ietf.org/html/rfc3986#section-4.4 | [
"Whether",
"the",
"URI",
"is",
"a",
"same",
"-",
"document",
"reference",
"."
] | 1a058bb0c06542e677505032ee3a1cb42135a8bc | https://github.com/algolia/algoliasearch-client-php/blob/1a058bb0c06542e677505032ee3a1cb42135a8bc/src/Http/Psr7/Uri.php#L258-L270 | train |
algolia/algoliasearch-client-php | src/RequestOptions/RequestOptions.php | RequestOptions.addDefaultHeader | public function addDefaultHeader($name, $value)
{
if (!isset($this->headers[$name])) {
$this->headers[$name] = $value;
}
return $this;
} | php | public function addDefaultHeader($name, $value)
{
if (!isset($this->headers[$name])) {
$this->headers[$name] = $value;
}
return $this;
} | [
"public",
"function",
"addDefaultHeader",
"(",
"$",
"name",
",",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"headers",
"[",
"$",
"name",
"]",
")",
")",
"{",
"$",
"this",
"->",
"headers",
"[",
"$",
"name",
"]",
"=",
"$",
"value",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Add a new header to the list if there is no value already set.
@param string $name Name of the header
@param string $value Value of the header
@return $this | [
"Add",
"a",
"new",
"header",
"to",
"the",
"list",
"if",
"there",
"is",
"no",
"value",
"already",
"set",
"."
] | 1a058bb0c06542e677505032ee3a1cb42135a8bc | https://github.com/algolia/algoliasearch-client-php/blob/1a058bb0c06542e677505032ee3a1cb42135a8bc/src/RequestOptions/RequestOptions.php#L79-L86 | train |
algolia/algoliasearch-client-php | src/RequestOptions/RequestOptions.php | RequestOptions.addDefaultHeaders | public function addDefaultHeaders($headers)
{
foreach ($headers as $name => $value) {
$this->addDefaultHeader($name, $value);
}
return $this;
} | php | public function addDefaultHeaders($headers)
{
foreach ($headers as $name => $value) {
$this->addDefaultHeader($name, $value);
}
return $this;
} | [
"public",
"function",
"addDefaultHeaders",
"(",
"$",
"headers",
")",
"{",
"foreach",
"(",
"$",
"headers",
"as",
"$",
"name",
"=>",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"addDefaultHeader",
"(",
"$",
"name",
",",
"$",
"value",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Add the headers passed if the value isn't already set.
@param array $headers List of header name/value pairs
@return $this | [
"Add",
"the",
"headers",
"passed",
"if",
"the",
"value",
"isn",
"t",
"already",
"set",
"."
] | 1a058bb0c06542e677505032ee3a1cb42135a8bc | https://github.com/algolia/algoliasearch-client-php/blob/1a058bb0c06542e677505032ee3a1cb42135a8bc/src/RequestOptions/RequestOptions.php#L95-L102 | train |
algolia/algoliasearch-client-php | src/RequestOptions/RequestOptions.php | RequestOptions.addDefaultQueryParameter | public function addDefaultQueryParameter($name, $value)
{
if (!isset($this->query[$name])) {
$this->query[$name] = $value;
}
return $this;
} | php | public function addDefaultQueryParameter($name, $value)
{
if (!isset($this->query[$name])) {
$this->query[$name] = $value;
}
return $this;
} | [
"public",
"function",
"addDefaultQueryParameter",
"(",
"$",
"name",
",",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"query",
"[",
"$",
"name",
"]",
")",
")",
"{",
"$",
"this",
"->",
"query",
"[",
"$",
"name",
"]",
"=",
"$",
"value",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Add a query parameter if it isn't already set.
@param string $name Name of the query parameter
@param string $value Value of the query parameter
@return $this | [
"Add",
"a",
"query",
"parameter",
"if",
"it",
"isn",
"t",
"already",
"set",
"."
] | 1a058bb0c06542e677505032ee3a1cb42135a8bc | https://github.com/algolia/algoliasearch-client-php/blob/1a058bb0c06542e677505032ee3a1cb42135a8bc/src/RequestOptions/RequestOptions.php#L172-L179 | train |
algolia/algoliasearch-client-php | src/RequestOptions/RequestOptions.php | RequestOptions.addDefaultBodyParameter | public function addDefaultBodyParameter($name, $value)
{
if (!isset($this->body[$name])) {
$this->body[$name] = $value;
}
return $this;
} | php | public function addDefaultBodyParameter($name, $value)
{
if (!isset($this->body[$name])) {
$this->body[$name] = $value;
}
return $this;
} | [
"public",
"function",
"addDefaultBodyParameter",
"(",
"$",
"name",
",",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"body",
"[",
"$",
"name",
"]",
")",
")",
"{",
"$",
"this",
"->",
"body",
"[",
"$",
"name",
"]",
"=",
"$",
"value",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Add a body parameter if it isn't already set.
@param string $name Name of the query parameter
@param string $value Value of the query parameter
@return $this | [
"Add",
"a",
"body",
"parameter",
"if",
"it",
"isn",
"t",
"already",
"set",
"."
] | 1a058bb0c06542e677505032ee3a1cb42135a8bc | https://github.com/algolia/algoliasearch-client-php/blob/1a058bb0c06542e677505032ee3a1cb42135a8bc/src/RequestOptions/RequestOptions.php#L258-L265 | train |
guzzle/psr7 | src/UriNormalizer.php | UriNormalizer.normalize | public static function normalize(UriInterface $uri, $flags = self::PRESERVING_NORMALIZATIONS)
{
if ($flags & self::CAPITALIZE_PERCENT_ENCODING) {
$uri = self::capitalizePercentEncoding($uri);
}
if ($flags & self::DECODE_UNRESERVED_CHARACTERS) {
$uri = self::decodeUnreservedCharacters($uri);
}
if ($flags & self::CONVERT_EMPTY_PATH && $uri->getPath() === '' &&
($uri->getScheme() === 'http' || $uri->getScheme() === 'https')
) {
$uri = $uri->withPath('/');
}
if ($flags & self::REMOVE_DEFAULT_HOST && $uri->getScheme() === 'file' && $uri->getHost() === 'localhost') {
$uri = $uri->withHost('');
}
if ($flags & self::REMOVE_DEFAULT_PORT && $uri->getPort() !== null && Uri::isDefaultPort($uri)) {
$uri = $uri->withPort(null);
}
if ($flags & self::REMOVE_DOT_SEGMENTS && !Uri::isRelativePathReference($uri)) {
$uri = $uri->withPath(UriResolver::removeDotSegments($uri->getPath()));
}
if ($flags & self::REMOVE_DUPLICATE_SLASHES) {
$uri = $uri->withPath(preg_replace('#//++#', '/', $uri->getPath()));
}
if ($flags & self::SORT_QUERY_PARAMETERS && $uri->getQuery() !== '') {
$queryKeyValues = explode('&', $uri->getQuery());
sort($queryKeyValues);
$uri = $uri->withQuery(implode('&', $queryKeyValues));
}
return $uri;
} | php | public static function normalize(UriInterface $uri, $flags = self::PRESERVING_NORMALIZATIONS)
{
if ($flags & self::CAPITALIZE_PERCENT_ENCODING) {
$uri = self::capitalizePercentEncoding($uri);
}
if ($flags & self::DECODE_UNRESERVED_CHARACTERS) {
$uri = self::decodeUnreservedCharacters($uri);
}
if ($flags & self::CONVERT_EMPTY_PATH && $uri->getPath() === '' &&
($uri->getScheme() === 'http' || $uri->getScheme() === 'https')
) {
$uri = $uri->withPath('/');
}
if ($flags & self::REMOVE_DEFAULT_HOST && $uri->getScheme() === 'file' && $uri->getHost() === 'localhost') {
$uri = $uri->withHost('');
}
if ($flags & self::REMOVE_DEFAULT_PORT && $uri->getPort() !== null && Uri::isDefaultPort($uri)) {
$uri = $uri->withPort(null);
}
if ($flags & self::REMOVE_DOT_SEGMENTS && !Uri::isRelativePathReference($uri)) {
$uri = $uri->withPath(UriResolver::removeDotSegments($uri->getPath()));
}
if ($flags & self::REMOVE_DUPLICATE_SLASHES) {
$uri = $uri->withPath(preg_replace('#//++#', '/', $uri->getPath()));
}
if ($flags & self::SORT_QUERY_PARAMETERS && $uri->getQuery() !== '') {
$queryKeyValues = explode('&', $uri->getQuery());
sort($queryKeyValues);
$uri = $uri->withQuery(implode('&', $queryKeyValues));
}
return $uri;
} | [
"public",
"static",
"function",
"normalize",
"(",
"UriInterface",
"$",
"uri",
",",
"$",
"flags",
"=",
"self",
"::",
"PRESERVING_NORMALIZATIONS",
")",
"{",
"if",
"(",
"$",
"flags",
"&",
"self",
"::",
"CAPITALIZE_PERCENT_ENCODING",
")",
"{",
"$",
"uri",
"=",
"self",
"::",
"capitalizePercentEncoding",
"(",
"$",
"uri",
")",
";",
"}",
"if",
"(",
"$",
"flags",
"&",
"self",
"::",
"DECODE_UNRESERVED_CHARACTERS",
")",
"{",
"$",
"uri",
"=",
"self",
"::",
"decodeUnreservedCharacters",
"(",
"$",
"uri",
")",
";",
"}",
"if",
"(",
"$",
"flags",
"&",
"self",
"::",
"CONVERT_EMPTY_PATH",
"&&",
"$",
"uri",
"->",
"getPath",
"(",
")",
"===",
"''",
"&&",
"(",
"$",
"uri",
"->",
"getScheme",
"(",
")",
"===",
"'http'",
"||",
"$",
"uri",
"->",
"getScheme",
"(",
")",
"===",
"'https'",
")",
")",
"{",
"$",
"uri",
"=",
"$",
"uri",
"->",
"withPath",
"(",
"'/'",
")",
";",
"}",
"if",
"(",
"$",
"flags",
"&",
"self",
"::",
"REMOVE_DEFAULT_HOST",
"&&",
"$",
"uri",
"->",
"getScheme",
"(",
")",
"===",
"'file'",
"&&",
"$",
"uri",
"->",
"getHost",
"(",
")",
"===",
"'localhost'",
")",
"{",
"$",
"uri",
"=",
"$",
"uri",
"->",
"withHost",
"(",
"''",
")",
";",
"}",
"if",
"(",
"$",
"flags",
"&",
"self",
"::",
"REMOVE_DEFAULT_PORT",
"&&",
"$",
"uri",
"->",
"getPort",
"(",
")",
"!==",
"null",
"&&",
"Uri",
"::",
"isDefaultPort",
"(",
"$",
"uri",
")",
")",
"{",
"$",
"uri",
"=",
"$",
"uri",
"->",
"withPort",
"(",
"null",
")",
";",
"}",
"if",
"(",
"$",
"flags",
"&",
"self",
"::",
"REMOVE_DOT_SEGMENTS",
"&&",
"!",
"Uri",
"::",
"isRelativePathReference",
"(",
"$",
"uri",
")",
")",
"{",
"$",
"uri",
"=",
"$",
"uri",
"->",
"withPath",
"(",
"UriResolver",
"::",
"removeDotSegments",
"(",
"$",
"uri",
"->",
"getPath",
"(",
")",
")",
")",
";",
"}",
"if",
"(",
"$",
"flags",
"&",
"self",
"::",
"REMOVE_DUPLICATE_SLASHES",
")",
"{",
"$",
"uri",
"=",
"$",
"uri",
"->",
"withPath",
"(",
"preg_replace",
"(",
"'#//++#'",
",",
"'/'",
",",
"$",
"uri",
"->",
"getPath",
"(",
")",
")",
")",
";",
"}",
"if",
"(",
"$",
"flags",
"&",
"self",
"::",
"SORT_QUERY_PARAMETERS",
"&&",
"$",
"uri",
"->",
"getQuery",
"(",
")",
"!==",
"''",
")",
"{",
"$",
"queryKeyValues",
"=",
"explode",
"(",
"'&'",
",",
"$",
"uri",
"->",
"getQuery",
"(",
")",
")",
";",
"sort",
"(",
"$",
"queryKeyValues",
")",
";",
"$",
"uri",
"=",
"$",
"uri",
"->",
"withQuery",
"(",
"implode",
"(",
"'&'",
",",
"$",
"queryKeyValues",
")",
")",
";",
"}",
"return",
"$",
"uri",
";",
"}"
] | Returns a normalized URI.
The scheme and host component are already normalized to lowercase per PSR-7 UriInterface.
This methods adds additional normalizations that can be configured with the $flags parameter.
PSR-7 UriInterface cannot distinguish between an empty component and a missing component as
getQuery(), getFragment() etc. always return a string. This means the URIs "/?#" and "/" are
treated equivalent which is not necessarily true according to RFC 3986. But that difference
is highly uncommon in reality. So this potential normalization is implied in PSR-7 as well.
@param UriInterface $uri The URI to normalize
@param int $flags A bitmask of normalizations to apply, see constants
@return UriInterface The normalized URI
@link https://tools.ietf.org/html/rfc3986#section-6.2 | [
"Returns",
"a",
"normalized",
"URI",
"."
] | a346647434953deb5bd599d92922b2d225e25170 | https://github.com/guzzle/psr7/blob/a346647434953deb5bd599d92922b2d225e25170/src/UriNormalizer.php#L119-L158 | train |
guzzle/psr7 | src/UriNormalizer.php | UriNormalizer.isEquivalent | public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, $normalizations = self::PRESERVING_NORMALIZATIONS)
{
return (string) self::normalize($uri1, $normalizations) === (string) self::normalize($uri2, $normalizations);
} | php | public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, $normalizations = self::PRESERVING_NORMALIZATIONS)
{
return (string) self::normalize($uri1, $normalizations) === (string) self::normalize($uri2, $normalizations);
} | [
"public",
"static",
"function",
"isEquivalent",
"(",
"UriInterface",
"$",
"uri1",
",",
"UriInterface",
"$",
"uri2",
",",
"$",
"normalizations",
"=",
"self",
"::",
"PRESERVING_NORMALIZATIONS",
")",
"{",
"return",
"(",
"string",
")",
"self",
"::",
"normalize",
"(",
"$",
"uri1",
",",
"$",
"normalizations",
")",
"===",
"(",
"string",
")",
"self",
"::",
"normalize",
"(",
"$",
"uri2",
",",
"$",
"normalizations",
")",
";",
"}"
] | Whether two URIs can be considered equivalent.
Both URIs are normalized automatically before comparison with the given $normalizations bitmask. The method also
accepts relative URI references and returns true when they are equivalent. This of course assumes they will be
resolved against the same base URI. If this is not the case, determination of equivalence or difference of
relative references does not mean anything.
@param UriInterface $uri1 An URI to compare
@param UriInterface $uri2 An URI to compare
@param int $normalizations A bitmask of normalizations to apply, see constants
@return bool
@link https://tools.ietf.org/html/rfc3986#section-6.1 | [
"Whether",
"two",
"URIs",
"can",
"be",
"considered",
"equivalent",
"."
] | a346647434953deb5bd599d92922b2d225e25170 | https://github.com/guzzle/psr7/blob/a346647434953deb5bd599d92922b2d225e25170/src/UriNormalizer.php#L175-L178 | train |
guzzle/psr7 | src/Uri.php | Uri.withQueryValues | public static function withQueryValues(UriInterface $uri, array $keyValueArray)
{
$result = self::getFilteredQueryString($uri, array_keys($keyValueArray));
foreach ($keyValueArray as $key => $value) {
$result[] = self::generateQueryString($key, $value);
}
return $uri->withQuery(implode('&', $result));
} | php | public static function withQueryValues(UriInterface $uri, array $keyValueArray)
{
$result = self::getFilteredQueryString($uri, array_keys($keyValueArray));
foreach ($keyValueArray as $key => $value) {
$result[] = self::generateQueryString($key, $value);
}
return $uri->withQuery(implode('&', $result));
} | [
"public",
"static",
"function",
"withQueryValues",
"(",
"UriInterface",
"$",
"uri",
",",
"array",
"$",
"keyValueArray",
")",
"{",
"$",
"result",
"=",
"self",
"::",
"getFilteredQueryString",
"(",
"$",
"uri",
",",
"array_keys",
"(",
"$",
"keyValueArray",
")",
")",
";",
"foreach",
"(",
"$",
"keyValueArray",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"result",
"[",
"]",
"=",
"self",
"::",
"generateQueryString",
"(",
"$",
"key",
",",
"$",
"value",
")",
";",
"}",
"return",
"$",
"uri",
"->",
"withQuery",
"(",
"implode",
"(",
"'&'",
",",
"$",
"result",
")",
")",
";",
"}"
] | Creates a new URI with multiple specific query string values.
It has the same behavior as withQueryValue() but for an associative array of key => value.
@param UriInterface $uri URI to use as a base.
@param array $keyValueArray Associative array of key and values
@return UriInterface | [
"Creates",
"a",
"new",
"URI",
"with",
"multiple",
"specific",
"query",
"string",
"values",
"."
] | a346647434953deb5bd599d92922b2d225e25170 | https://github.com/guzzle/psr7/blob/a346647434953deb5bd599d92922b2d225e25170/src/Uri.php#L343-L352 | train |
guzzle/psr7 | src/UriResolver.php | UriResolver.relativize | public static function relativize(UriInterface $base, UriInterface $target)
{
if ($target->getScheme() !== '' &&
($base->getScheme() !== $target->getScheme() || $target->getAuthority() === '' && $base->getAuthority() !== '')
) {
return $target;
}
if (Uri::isRelativePathReference($target)) {
// As the target is already highly relative we return it as-is. It would be possible to resolve
// the target with `$target = self::resolve($base, $target);` and then try make it more relative
// by removing a duplicate query. But let's not do that automatically.
return $target;
}
if ($target->getAuthority() !== '' && $base->getAuthority() !== $target->getAuthority()) {
return $target->withScheme('');
}
// We must remove the path before removing the authority because if the path starts with two slashes, the URI
// would turn invalid. And we also cannot set a relative path before removing the authority, as that is also
// invalid.
$emptyPathUri = $target->withScheme('')->withPath('')->withUserInfo('')->withPort(null)->withHost('');
if ($base->getPath() !== $target->getPath()) {
return $emptyPathUri->withPath(self::getRelativePath($base, $target));
}
if ($base->getQuery() === $target->getQuery()) {
// Only the target fragment is left. And it must be returned even if base and target fragment are the same.
return $emptyPathUri->withQuery('');
}
// If the base URI has a query but the target has none, we cannot return an empty path reference as it would
// inherit the base query component when resolving.
if ($target->getQuery() === '') {
$segments = explode('/', $target->getPath());
$lastSegment = end($segments);
return $emptyPathUri->withPath($lastSegment === '' ? './' : $lastSegment);
}
return $emptyPathUri;
} | php | public static function relativize(UriInterface $base, UriInterface $target)
{
if ($target->getScheme() !== '' &&
($base->getScheme() !== $target->getScheme() || $target->getAuthority() === '' && $base->getAuthority() !== '')
) {
return $target;
}
if (Uri::isRelativePathReference($target)) {
// As the target is already highly relative we return it as-is. It would be possible to resolve
// the target with `$target = self::resolve($base, $target);` and then try make it more relative
// by removing a duplicate query. But let's not do that automatically.
return $target;
}
if ($target->getAuthority() !== '' && $base->getAuthority() !== $target->getAuthority()) {
return $target->withScheme('');
}
// We must remove the path before removing the authority because if the path starts with two slashes, the URI
// would turn invalid. And we also cannot set a relative path before removing the authority, as that is also
// invalid.
$emptyPathUri = $target->withScheme('')->withPath('')->withUserInfo('')->withPort(null)->withHost('');
if ($base->getPath() !== $target->getPath()) {
return $emptyPathUri->withPath(self::getRelativePath($base, $target));
}
if ($base->getQuery() === $target->getQuery()) {
// Only the target fragment is left. And it must be returned even if base and target fragment are the same.
return $emptyPathUri->withQuery('');
}
// If the base URI has a query but the target has none, we cannot return an empty path reference as it would
// inherit the base query component when resolving.
if ($target->getQuery() === '') {
$segments = explode('/', $target->getPath());
$lastSegment = end($segments);
return $emptyPathUri->withPath($lastSegment === '' ? './' : $lastSegment);
}
return $emptyPathUri;
} | [
"public",
"static",
"function",
"relativize",
"(",
"UriInterface",
"$",
"base",
",",
"UriInterface",
"$",
"target",
")",
"{",
"if",
"(",
"$",
"target",
"->",
"getScheme",
"(",
")",
"!==",
"''",
"&&",
"(",
"$",
"base",
"->",
"getScheme",
"(",
")",
"!==",
"$",
"target",
"->",
"getScheme",
"(",
")",
"||",
"$",
"target",
"->",
"getAuthority",
"(",
")",
"===",
"''",
"&&",
"$",
"base",
"->",
"getAuthority",
"(",
")",
"!==",
"''",
")",
")",
"{",
"return",
"$",
"target",
";",
"}",
"if",
"(",
"Uri",
"::",
"isRelativePathReference",
"(",
"$",
"target",
")",
")",
"{",
"// As the target is already highly relative we return it as-is. It would be possible to resolve",
"// the target with `$target = self::resolve($base, $target);` and then try make it more relative",
"// by removing a duplicate query. But let's not do that automatically.",
"return",
"$",
"target",
";",
"}",
"if",
"(",
"$",
"target",
"->",
"getAuthority",
"(",
")",
"!==",
"''",
"&&",
"$",
"base",
"->",
"getAuthority",
"(",
")",
"!==",
"$",
"target",
"->",
"getAuthority",
"(",
")",
")",
"{",
"return",
"$",
"target",
"->",
"withScheme",
"(",
"''",
")",
";",
"}",
"// We must remove the path before removing the authority because if the path starts with two slashes, the URI",
"// would turn invalid. And we also cannot set a relative path before removing the authority, as that is also",
"// invalid.",
"$",
"emptyPathUri",
"=",
"$",
"target",
"->",
"withScheme",
"(",
"''",
")",
"->",
"withPath",
"(",
"''",
")",
"->",
"withUserInfo",
"(",
"''",
")",
"->",
"withPort",
"(",
"null",
")",
"->",
"withHost",
"(",
"''",
")",
";",
"if",
"(",
"$",
"base",
"->",
"getPath",
"(",
")",
"!==",
"$",
"target",
"->",
"getPath",
"(",
")",
")",
"{",
"return",
"$",
"emptyPathUri",
"->",
"withPath",
"(",
"self",
"::",
"getRelativePath",
"(",
"$",
"base",
",",
"$",
"target",
")",
")",
";",
"}",
"if",
"(",
"$",
"base",
"->",
"getQuery",
"(",
")",
"===",
"$",
"target",
"->",
"getQuery",
"(",
")",
")",
"{",
"// Only the target fragment is left. And it must be returned even if base and target fragment are the same.",
"return",
"$",
"emptyPathUri",
"->",
"withQuery",
"(",
"''",
")",
";",
"}",
"// If the base URI has a query but the target has none, we cannot return an empty path reference as it would",
"// inherit the base query component when resolving.",
"if",
"(",
"$",
"target",
"->",
"getQuery",
"(",
")",
"===",
"''",
")",
"{",
"$",
"segments",
"=",
"explode",
"(",
"'/'",
",",
"$",
"target",
"->",
"getPath",
"(",
")",
")",
";",
"$",
"lastSegment",
"=",
"end",
"(",
"$",
"segments",
")",
";",
"return",
"$",
"emptyPathUri",
"->",
"withPath",
"(",
"$",
"lastSegment",
"===",
"''",
"?",
"'./'",
":",
"$",
"lastSegment",
")",
";",
"}",
"return",
"$",
"emptyPathUri",
";",
"}"
] | Returns the target URI as a relative reference from the base URI.
This method is the counterpart to resolve():
(string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target))
One use-case is to use the current request URI as base URI and then generate relative links in your documents
to reduce the document size or offer self-contained downloadable document archives.
$base = new Uri('http://example.com/a/b/');
echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'.
echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'.
echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'.
echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'.
This method also accepts a target that is already relative and will try to relativize it further. Only a
relative-path reference will be returned as-is.
echo UriResolver::relativize($base, new Uri('/a/b/c')); // prints 'c' as well
@param UriInterface $base Base URI
@param UriInterface $target Target URI
@return UriInterface The relative URI reference | [
"Returns",
"the",
"target",
"URI",
"as",
"a",
"relative",
"reference",
"from",
"the",
"base",
"URI",
"."
] | a346647434953deb5bd599d92922b2d225e25170 | https://github.com/guzzle/psr7/blob/a346647434953deb5bd599d92922b2d225e25170/src/UriResolver.php#L137-L180 | train |
apereo/phpCAS | source/CAS/Client.php | CAS_Client._renameSession | private function _renameSession($ticket)
{
phpCAS::traceBegin();
if ($this->getChangeSessionID()) {
if (!empty($this->_user)) {
$old_session = $_SESSION;
phpCAS :: trace("Killing session: ". session_id());
session_destroy();
// set up a new session, of name based on the ticket
$session_id = $this->_sessionIdForTicket($ticket);
phpCAS :: trace("Starting session: ". $session_id);
session_id($session_id);
session_start();
phpCAS :: trace("Restoring old session vars");
$_SESSION = $old_session;
} else {
phpCAS :: trace (
'Session should only be renamed after successfull authentication'
);
}
} else {
phpCAS :: trace(
"Skipping session rename since phpCAS is not handling the session."
);
}
phpCAS::traceEnd();
} | php | private function _renameSession($ticket)
{
phpCAS::traceBegin();
if ($this->getChangeSessionID()) {
if (!empty($this->_user)) {
$old_session = $_SESSION;
phpCAS :: trace("Killing session: ". session_id());
session_destroy();
// set up a new session, of name based on the ticket
$session_id = $this->_sessionIdForTicket($ticket);
phpCAS :: trace("Starting session: ". $session_id);
session_id($session_id);
session_start();
phpCAS :: trace("Restoring old session vars");
$_SESSION = $old_session;
} else {
phpCAS :: trace (
'Session should only be renamed after successfull authentication'
);
}
} else {
phpCAS :: trace(
"Skipping session rename since phpCAS is not handling the session."
);
}
phpCAS::traceEnd();
} | [
"private",
"function",
"_renameSession",
"(",
"$",
"ticket",
")",
"{",
"phpCAS",
"::",
"traceBegin",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"getChangeSessionID",
"(",
")",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"_user",
")",
")",
"{",
"$",
"old_session",
"=",
"$",
"_SESSION",
";",
"phpCAS",
"::",
"trace",
"(",
"\"Killing session: \"",
".",
"session_id",
"(",
")",
")",
";",
"session_destroy",
"(",
")",
";",
"// set up a new session, of name based on the ticket",
"$",
"session_id",
"=",
"$",
"this",
"->",
"_sessionIdForTicket",
"(",
"$",
"ticket",
")",
";",
"phpCAS",
"::",
"trace",
"(",
"\"Starting session: \"",
".",
"$",
"session_id",
")",
";",
"session_id",
"(",
"$",
"session_id",
")",
";",
"session_start",
"(",
")",
";",
"phpCAS",
"::",
"trace",
"(",
"\"Restoring old session vars\"",
")",
";",
"$",
"_SESSION",
"=",
"$",
"old_session",
";",
"}",
"else",
"{",
"phpCAS",
"::",
"trace",
"(",
"'Session should only be renamed after successfull authentication'",
")",
";",
"}",
"}",
"else",
"{",
"phpCAS",
"::",
"trace",
"(",
"\"Skipping session rename since phpCAS is not handling the session.\"",
")",
";",
"}",
"phpCAS",
"::",
"traceEnd",
"(",
")",
";",
"}"
] | Renaming the session
@param string $ticket name of the ticket
@return void | [
"Renaming",
"the",
"session"
] | a5528d23572a02e28ee9eb37608644852a7a7b03 | https://github.com/apereo/phpCAS/blob/a5528d23572a02e28ee9eb37608644852a7a7b03/source/CAS/Client.php#L3655-L3681 | train |
apereo/phpCAS | source/CAS/Client.php | CAS_Client._authError | private function _authError(
$failure,
$cas_url,
$no_response=false,
$bad_response=false,
$cas_response='',
$err_code=-1,
$err_msg=''
) {
phpCAS::traceBegin();
$lang = $this->getLangObj();
$this->printHTMLHeader($lang->getAuthenticationFailed());
printf(
$lang->getYouWereNotAuthenticated(), htmlentities($this->getURL()),
isset($_SERVER['SERVER_ADMIN']) ? $_SERVER['SERVER_ADMIN']:''
);
phpCAS::trace('CAS URL: '.$cas_url);
phpCAS::trace('Authentication failure: '.$failure);
if ( $no_response ) {
phpCAS::trace('Reason: no response from the CAS server');
} else {
if ( $bad_response ) {
phpCAS::trace('Reason: bad response from the CAS server');
} else {
switch ($this->getServerVersion()) {
case CAS_VERSION_1_0:
phpCAS::trace('Reason: CAS error');
break;
case CAS_VERSION_2_0:
case CAS_VERSION_3_0:
if ( $err_code === -1 ) {
phpCAS::trace('Reason: no CAS error');
} else {
phpCAS::trace(
'Reason: ['.$err_code.'] CAS error: '.$err_msg
);
}
break;
}
}
phpCAS::trace('CAS response: '.$cas_response);
}
$this->printHTMLFooter();
phpCAS::traceExit();
throw new CAS_GracefullTerminationException();
} | php | private function _authError(
$failure,
$cas_url,
$no_response=false,
$bad_response=false,
$cas_response='',
$err_code=-1,
$err_msg=''
) {
phpCAS::traceBegin();
$lang = $this->getLangObj();
$this->printHTMLHeader($lang->getAuthenticationFailed());
printf(
$lang->getYouWereNotAuthenticated(), htmlentities($this->getURL()),
isset($_SERVER['SERVER_ADMIN']) ? $_SERVER['SERVER_ADMIN']:''
);
phpCAS::trace('CAS URL: '.$cas_url);
phpCAS::trace('Authentication failure: '.$failure);
if ( $no_response ) {
phpCAS::trace('Reason: no response from the CAS server');
} else {
if ( $bad_response ) {
phpCAS::trace('Reason: bad response from the CAS server');
} else {
switch ($this->getServerVersion()) {
case CAS_VERSION_1_0:
phpCAS::trace('Reason: CAS error');
break;
case CAS_VERSION_2_0:
case CAS_VERSION_3_0:
if ( $err_code === -1 ) {
phpCAS::trace('Reason: no CAS error');
} else {
phpCAS::trace(
'Reason: ['.$err_code.'] CAS error: '.$err_msg
);
}
break;
}
}
phpCAS::trace('CAS response: '.$cas_response);
}
$this->printHTMLFooter();
phpCAS::traceExit();
throw new CAS_GracefullTerminationException();
} | [
"private",
"function",
"_authError",
"(",
"$",
"failure",
",",
"$",
"cas_url",
",",
"$",
"no_response",
"=",
"false",
",",
"$",
"bad_response",
"=",
"false",
",",
"$",
"cas_response",
"=",
"''",
",",
"$",
"err_code",
"=",
"-",
"1",
",",
"$",
"err_msg",
"=",
"''",
")",
"{",
"phpCAS",
"::",
"traceBegin",
"(",
")",
";",
"$",
"lang",
"=",
"$",
"this",
"->",
"getLangObj",
"(",
")",
";",
"$",
"this",
"->",
"printHTMLHeader",
"(",
"$",
"lang",
"->",
"getAuthenticationFailed",
"(",
")",
")",
";",
"printf",
"(",
"$",
"lang",
"->",
"getYouWereNotAuthenticated",
"(",
")",
",",
"htmlentities",
"(",
"$",
"this",
"->",
"getURL",
"(",
")",
")",
",",
"isset",
"(",
"$",
"_SERVER",
"[",
"'SERVER_ADMIN'",
"]",
")",
"?",
"$",
"_SERVER",
"[",
"'SERVER_ADMIN'",
"]",
":",
"''",
")",
";",
"phpCAS",
"::",
"trace",
"(",
"'CAS URL: '",
".",
"$",
"cas_url",
")",
";",
"phpCAS",
"::",
"trace",
"(",
"'Authentication failure: '",
".",
"$",
"failure",
")",
";",
"if",
"(",
"$",
"no_response",
")",
"{",
"phpCAS",
"::",
"trace",
"(",
"'Reason: no response from the CAS server'",
")",
";",
"}",
"else",
"{",
"if",
"(",
"$",
"bad_response",
")",
"{",
"phpCAS",
"::",
"trace",
"(",
"'Reason: bad response from the CAS server'",
")",
";",
"}",
"else",
"{",
"switch",
"(",
"$",
"this",
"->",
"getServerVersion",
"(",
")",
")",
"{",
"case",
"CAS_VERSION_1_0",
":",
"phpCAS",
"::",
"trace",
"(",
"'Reason: CAS error'",
")",
";",
"break",
";",
"case",
"CAS_VERSION_2_0",
":",
"case",
"CAS_VERSION_3_0",
":",
"if",
"(",
"$",
"err_code",
"===",
"-",
"1",
")",
"{",
"phpCAS",
"::",
"trace",
"(",
"'Reason: no CAS error'",
")",
";",
"}",
"else",
"{",
"phpCAS",
"::",
"trace",
"(",
"'Reason: ['",
".",
"$",
"err_code",
".",
"'] CAS error: '",
".",
"$",
"err_msg",
")",
";",
"}",
"break",
";",
"}",
"}",
"phpCAS",
"::",
"trace",
"(",
"'CAS response: '",
".",
"$",
"cas_response",
")",
";",
"}",
"$",
"this",
"->",
"printHTMLFooter",
"(",
")",
";",
"phpCAS",
"::",
"traceExit",
"(",
")",
";",
"throw",
"new",
"CAS_GracefullTerminationException",
"(",
")",
";",
"}"
] | This method is used to print the HTML output when the user was not
authenticated.
@param string $failure the failure that occured
@param string $cas_url the URL the CAS server was asked for
@param bool $no_response the response from the CAS server (other
parameters are ignored if true)
@param bool $bad_response bad response from the CAS server ($err_code
and $err_msg ignored if true)
@param string $cas_response the response of the CAS server
@param int $err_code the error code given by the CAS server
@param string $err_msg the error message given by the CAS server
@return void | [
"This",
"method",
"is",
"used",
"to",
"print",
"the",
"HTML",
"output",
"when",
"the",
"user",
"was",
"not",
"authenticated",
"."
] | a5528d23572a02e28ee9eb37608644852a7a7b03 | https://github.com/apereo/phpCAS/blob/a5528d23572a02e28ee9eb37608644852a7a7b03/source/CAS/Client.php#L3738-L3783 | train |
apereo/phpCAS | source/CAS.php | phpCAS.getSupportedProtocols | public static function getSupportedProtocols()
{
$supportedProtocols = array();
$supportedProtocols[CAS_VERSION_1_0] = 'CAS 1.0';
$supportedProtocols[CAS_VERSION_2_0] = 'CAS 2.0';
$supportedProtocols[CAS_VERSION_3_0] = 'CAS 3.0';
$supportedProtocols[SAML_VERSION_1_1] = 'SAML 1.1';
return $supportedProtocols;
} | php | public static function getSupportedProtocols()
{
$supportedProtocols = array();
$supportedProtocols[CAS_VERSION_1_0] = 'CAS 1.0';
$supportedProtocols[CAS_VERSION_2_0] = 'CAS 2.0';
$supportedProtocols[CAS_VERSION_3_0] = 'CAS 3.0';
$supportedProtocols[SAML_VERSION_1_1] = 'SAML 1.1';
return $supportedProtocols;
} | [
"public",
"static",
"function",
"getSupportedProtocols",
"(",
")",
"{",
"$",
"supportedProtocols",
"=",
"array",
"(",
")",
";",
"$",
"supportedProtocols",
"[",
"CAS_VERSION_1_0",
"]",
"=",
"'CAS 1.0'",
";",
"$",
"supportedProtocols",
"[",
"CAS_VERSION_2_0",
"]",
"=",
"'CAS 2.0'",
";",
"$",
"supportedProtocols",
"[",
"CAS_VERSION_3_0",
"]",
"=",
"'CAS 3.0'",
";",
"$",
"supportedProtocols",
"[",
"SAML_VERSION_1_1",
"]",
"=",
"'SAML 1.1'",
";",
"return",
"$",
"supportedProtocols",
";",
"}"
] | This method returns supported protocols.
@return array an array of all supported protocols. Use internal protocol name as array key. | [
"This",
"method",
"returns",
"supported",
"protocols",
"."
] | a5528d23572a02e28ee9eb37608644852a7a7b03 | https://github.com/apereo/phpCAS/blob/a5528d23572a02e28ee9eb37608644852a7a7b03/source/CAS.php#L730-L739 | train |
Gregwar/Captcha | src/Gregwar/Captcha/ImageFileHandler.php | ImageFileHandler.saveAsFile | public function saveAsFile($contents)
{
$this->createFolderIfMissing();
$filename = md5(uniqid()) . '.jpg';
$filePath = $this->webPath . '/' . $this->imageFolder . '/' . $filename;
imagejpeg($contents, $filePath, 15);
return '/' . $this->imageFolder . '/' . $filename;
} | php | public function saveAsFile($contents)
{
$this->createFolderIfMissing();
$filename = md5(uniqid()) . '.jpg';
$filePath = $this->webPath . '/' . $this->imageFolder . '/' . $filename;
imagejpeg($contents, $filePath, 15);
return '/' . $this->imageFolder . '/' . $filename;
} | [
"public",
"function",
"saveAsFile",
"(",
"$",
"contents",
")",
"{",
"$",
"this",
"->",
"createFolderIfMissing",
"(",
")",
";",
"$",
"filename",
"=",
"md5",
"(",
"uniqid",
"(",
")",
")",
".",
"'.jpg'",
";",
"$",
"filePath",
"=",
"$",
"this",
"->",
"webPath",
".",
"'/'",
".",
"$",
"this",
"->",
"imageFolder",
".",
"'/'",
".",
"$",
"filename",
";",
"imagejpeg",
"(",
"$",
"contents",
",",
"$",
"filePath",
",",
"15",
")",
";",
"return",
"'/'",
".",
"$",
"this",
"->",
"imageFolder",
".",
"'/'",
".",
"$",
"filename",
";",
"}"
] | Saves the provided image content as a file
@param string $contents
@return string | [
"Saves",
"the",
"provided",
"image",
"content",
"as",
"a",
"file"
] | cf953dd79748406e0292cea8c565399681e4d345 | https://github.com/Gregwar/Captcha/blob/cf953dd79748406e0292cea8c565399681e4d345/src/Gregwar/Captcha/ImageFileHandler.php#L60-L69 | train |
Gregwar/Captcha | src/Gregwar/Captcha/ImageFileHandler.php | ImageFileHandler.collectGarbage | public function collectGarbage()
{
if (!mt_rand(1, $this->gcFreq) == 1) {
return false;
}
$this->createFolderIfMissing();
$finder = new Finder();
$criteria = sprintf('<= now - %s minutes', $this->expiration);
$finder->in($this->webPath . '/' . $this->imageFolder)
->date($criteria);
foreach ($finder->files() as $file) {
unlink($file->getPathname());
}
return true;
} | php | public function collectGarbage()
{
if (!mt_rand(1, $this->gcFreq) == 1) {
return false;
}
$this->createFolderIfMissing();
$finder = new Finder();
$criteria = sprintf('<= now - %s minutes', $this->expiration);
$finder->in($this->webPath . '/' . $this->imageFolder)
->date($criteria);
foreach ($finder->files() as $file) {
unlink($file->getPathname());
}
return true;
} | [
"public",
"function",
"collectGarbage",
"(",
")",
"{",
"if",
"(",
"!",
"mt_rand",
"(",
"1",
",",
"$",
"this",
"->",
"gcFreq",
")",
"==",
"1",
")",
"{",
"return",
"false",
";",
"}",
"$",
"this",
"->",
"createFolderIfMissing",
"(",
")",
";",
"$",
"finder",
"=",
"new",
"Finder",
"(",
")",
";",
"$",
"criteria",
"=",
"sprintf",
"(",
"'<= now - %s minutes'",
",",
"$",
"this",
"->",
"expiration",
")",
";",
"$",
"finder",
"->",
"in",
"(",
"$",
"this",
"->",
"webPath",
".",
"'/'",
".",
"$",
"this",
"->",
"imageFolder",
")",
"->",
"date",
"(",
"$",
"criteria",
")",
";",
"foreach",
"(",
"$",
"finder",
"->",
"files",
"(",
")",
"as",
"$",
"file",
")",
"{",
"unlink",
"(",
"$",
"file",
"->",
"getPathname",
"(",
")",
")",
";",
"}",
"return",
"true",
";",
"}"
] | Randomly runs garbage collection on the image directory
@return bool | [
"Randomly",
"runs",
"garbage",
"collection",
"on",
"the",
"image",
"directory"
] | cf953dd79748406e0292cea8c565399681e4d345 | https://github.com/Gregwar/Captcha/blob/cf953dd79748406e0292cea8c565399681e4d345/src/Gregwar/Captcha/ImageFileHandler.php#L76-L94 | train |
Gregwar/Captcha | src/Gregwar/Captcha/ImageFileHandler.php | ImageFileHandler.createFolderIfMissing | protected function createFolderIfMissing()
{
if (!file_exists($this->webPath . '/' . $this->imageFolder)) {
mkdir($this->webPath . '/' . $this->imageFolder, 0755);
}
} | php | protected function createFolderIfMissing()
{
if (!file_exists($this->webPath . '/' . $this->imageFolder)) {
mkdir($this->webPath . '/' . $this->imageFolder, 0755);
}
} | [
"protected",
"function",
"createFolderIfMissing",
"(",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"this",
"->",
"webPath",
".",
"'/'",
".",
"$",
"this",
"->",
"imageFolder",
")",
")",
"{",
"mkdir",
"(",
"$",
"this",
"->",
"webPath",
".",
"'/'",
".",
"$",
"this",
"->",
"imageFolder",
",",
"0755",
")",
";",
"}",
"}"
] | Creates the folder if it doesn't exist | [
"Creates",
"the",
"folder",
"if",
"it",
"doesn",
"t",
"exist"
] | cf953dd79748406e0292cea8c565399681e4d345 | https://github.com/Gregwar/Captcha/blob/cf953dd79748406e0292cea8c565399681e4d345/src/Gregwar/Captcha/ImageFileHandler.php#L99-L104 | train |
Gregwar/Captcha | src/Gregwar/Captcha/PhraseBuilder.php | PhraseBuilder.build | public function build($length = null, $charset = null)
{
if ($length !== null) {
$this->length = $length;
}
if ($charset !== null) {
$this->charset = $charset;
}
$phrase = '';
$chars = str_split($this->charset);
for ($i = 0; $i < $this->length; $i++) {
$phrase .= $chars[array_rand($chars)];
}
return $phrase;
} | php | public function build($length = null, $charset = null)
{
if ($length !== null) {
$this->length = $length;
}
if ($charset !== null) {
$this->charset = $charset;
}
$phrase = '';
$chars = str_split($this->charset);
for ($i = 0; $i < $this->length; $i++) {
$phrase .= $chars[array_rand($chars)];
}
return $phrase;
} | [
"public",
"function",
"build",
"(",
"$",
"length",
"=",
"null",
",",
"$",
"charset",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"length",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"length",
"=",
"$",
"length",
";",
"}",
"if",
"(",
"$",
"charset",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"charset",
"=",
"$",
"charset",
";",
"}",
"$",
"phrase",
"=",
"''",
";",
"$",
"chars",
"=",
"str_split",
"(",
"$",
"this",
"->",
"charset",
")",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"this",
"->",
"length",
";",
"$",
"i",
"++",
")",
"{",
"$",
"phrase",
".=",
"$",
"chars",
"[",
"array_rand",
"(",
"$",
"chars",
")",
"]",
";",
"}",
"return",
"$",
"phrase",
";",
"}"
] | Generates random phrase of given length with given charset | [
"Generates",
"random",
"phrase",
"of",
"given",
"length",
"with",
"given",
"charset"
] | cf953dd79748406e0292cea8c565399681e4d345 | https://github.com/Gregwar/Captcha/blob/cf953dd79748406e0292cea8c565399681e4d345/src/Gregwar/Captcha/PhraseBuilder.php#L33-L50 | train |
Gregwar/Captcha | src/Gregwar/Captcha/CaptchaBuilder.php | CaptchaBuilder.setTextColor | public function setTextColor($r, $g, $b)
{
$this->textColor = array($r, $g, $b);
return $this;
} | php | public function setTextColor($r, $g, $b)
{
$this->textColor = array($r, $g, $b);
return $this;
} | [
"public",
"function",
"setTextColor",
"(",
"$",
"r",
",",
"$",
"g",
",",
"$",
"b",
")",
"{",
"$",
"this",
"->",
"textColor",
"=",
"array",
"(",
"$",
"r",
",",
"$",
"g",
",",
"$",
"b",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Sets the text color to use | [
"Sets",
"the",
"text",
"color",
"to",
"use"
] | cf953dd79748406e0292cea8c565399681e4d345 | https://github.com/Gregwar/Captcha/blob/cf953dd79748406e0292cea8c565399681e4d345/src/Gregwar/Captcha/CaptchaBuilder.php#L215-L220 | train |
Gregwar/Captcha | src/Gregwar/Captcha/CaptchaBuilder.php | CaptchaBuilder.setBackgroundColor | public function setBackgroundColor($r, $g, $b)
{
$this->backgroundColor = array($r, $g, $b);
return $this;
} | php | public function setBackgroundColor($r, $g, $b)
{
$this->backgroundColor = array($r, $g, $b);
return $this;
} | [
"public",
"function",
"setBackgroundColor",
"(",
"$",
"r",
",",
"$",
"g",
",",
"$",
"b",
")",
"{",
"$",
"this",
"->",
"backgroundColor",
"=",
"array",
"(",
"$",
"r",
",",
"$",
"g",
",",
"$",
"b",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Sets the background color to use | [
"Sets",
"the",
"background",
"color",
"to",
"use"
] | cf953dd79748406e0292cea8c565399681e4d345 | https://github.com/Gregwar/Captcha/blob/cf953dd79748406e0292cea8c565399681e4d345/src/Gregwar/Captcha/CaptchaBuilder.php#L225-L230 | train |
Gregwar/Captcha | src/Gregwar/Captcha/CaptchaBuilder.php | CaptchaBuilder.postEffect | protected function postEffect($image)
{
if (!function_exists('imagefilter')) {
return;
}
if ($this->backgroundColor != null || $this->textColor != null) {
return;
}
// Negate ?
if ($this->rand(0, 1) == 0) {
imagefilter($image, IMG_FILTER_NEGATE);
}
// Edge ?
if ($this->rand(0, 10) == 0) {
imagefilter($image, IMG_FILTER_EDGEDETECT);
}
// Contrast
imagefilter($image, IMG_FILTER_CONTRAST, $this->rand(-50, 10));
// Colorize
if ($this->rand(0, 5) == 0) {
imagefilter($image, IMG_FILTER_COLORIZE, $this->rand(-80, 50), $this->rand(-80, 50), $this->rand(-80, 50));
}
} | php | protected function postEffect($image)
{
if (!function_exists('imagefilter')) {
return;
}
if ($this->backgroundColor != null || $this->textColor != null) {
return;
}
// Negate ?
if ($this->rand(0, 1) == 0) {
imagefilter($image, IMG_FILTER_NEGATE);
}
// Edge ?
if ($this->rand(0, 10) == 0) {
imagefilter($image, IMG_FILTER_EDGEDETECT);
}
// Contrast
imagefilter($image, IMG_FILTER_CONTRAST, $this->rand(-50, 10));
// Colorize
if ($this->rand(0, 5) == 0) {
imagefilter($image, IMG_FILTER_COLORIZE, $this->rand(-80, 50), $this->rand(-80, 50), $this->rand(-80, 50));
}
} | [
"protected",
"function",
"postEffect",
"(",
"$",
"image",
")",
"{",
"if",
"(",
"!",
"function_exists",
"(",
"'imagefilter'",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"backgroundColor",
"!=",
"null",
"||",
"$",
"this",
"->",
"textColor",
"!=",
"null",
")",
"{",
"return",
";",
"}",
"// Negate ?",
"if",
"(",
"$",
"this",
"->",
"rand",
"(",
"0",
",",
"1",
")",
"==",
"0",
")",
"{",
"imagefilter",
"(",
"$",
"image",
",",
"IMG_FILTER_NEGATE",
")",
";",
"}",
"// Edge ?",
"if",
"(",
"$",
"this",
"->",
"rand",
"(",
"0",
",",
"10",
")",
"==",
"0",
")",
"{",
"imagefilter",
"(",
"$",
"image",
",",
"IMG_FILTER_EDGEDETECT",
")",
";",
"}",
"// Contrast",
"imagefilter",
"(",
"$",
"image",
",",
"IMG_FILTER_CONTRAST",
",",
"$",
"this",
"->",
"rand",
"(",
"-",
"50",
",",
"10",
")",
")",
";",
"// Colorize",
"if",
"(",
"$",
"this",
"->",
"rand",
"(",
"0",
",",
"5",
")",
"==",
"0",
")",
"{",
"imagefilter",
"(",
"$",
"image",
",",
"IMG_FILTER_COLORIZE",
",",
"$",
"this",
"->",
"rand",
"(",
"-",
"80",
",",
"50",
")",
",",
"$",
"this",
"->",
"rand",
"(",
"-",
"80",
",",
"50",
")",
",",
"$",
"this",
"->",
"rand",
"(",
"-",
"80",
",",
"50",
")",
")",
";",
"}",
"}"
] | Apply some post effects | [
"Apply",
"some",
"post",
"effects"
] | cf953dd79748406e0292cea8c565399681e4d345 | https://github.com/Gregwar/Captcha/blob/cf953dd79748406e0292cea8c565399681e4d345/src/Gregwar/Captcha/CaptchaBuilder.php#L282-L309 | train |
Gregwar/Captcha | src/Gregwar/Captcha/CaptchaBuilder.php | CaptchaBuilder.writePhrase | protected function writePhrase($image, $phrase, $font, $width, $height)
{
$length = mb_strlen($phrase);
if ($length === 0) {
return \imagecolorallocate($image, 0, 0, 0);
}
// Gets the text size and start position
$size = $width / $length - $this->rand(0, 3) - 1;
$box = \imagettfbbox($size, 0, $font, $phrase);
$textWidth = $box[2] - $box[0];
$textHeight = $box[1] - $box[7];
$x = ($width - $textWidth) / 2;
$y = ($height - $textHeight) / 2 + $size;
if (!$this->textColor) {
$textColor = array($this->rand(0, 150), $this->rand(0, 150), $this->rand(0, 150));
} else {
$textColor = $this->textColor;
}
$col = \imagecolorallocate($image, $textColor[0], $textColor[1], $textColor[2]);
// Write the letters one by one, with random angle
for ($i=0; $i<$length; $i++) {
$symbol = mb_substr($phrase, $i, 1);
$box = \imagettfbbox($size, 0, $font, $symbol);
$w = $box[2] - $box[0];
$angle = $this->rand(-$this->maxAngle, $this->maxAngle);
$offset = $this->rand(-$this->maxOffset, $this->maxOffset);
\imagettftext($image, $size, $angle, $x, $y + $offset, $col, $font, $symbol);
$x += $w;
}
return $col;
} | php | protected function writePhrase($image, $phrase, $font, $width, $height)
{
$length = mb_strlen($phrase);
if ($length === 0) {
return \imagecolorallocate($image, 0, 0, 0);
}
// Gets the text size and start position
$size = $width / $length - $this->rand(0, 3) - 1;
$box = \imagettfbbox($size, 0, $font, $phrase);
$textWidth = $box[2] - $box[0];
$textHeight = $box[1] - $box[7];
$x = ($width - $textWidth) / 2;
$y = ($height - $textHeight) / 2 + $size;
if (!$this->textColor) {
$textColor = array($this->rand(0, 150), $this->rand(0, 150), $this->rand(0, 150));
} else {
$textColor = $this->textColor;
}
$col = \imagecolorallocate($image, $textColor[0], $textColor[1], $textColor[2]);
// Write the letters one by one, with random angle
for ($i=0; $i<$length; $i++) {
$symbol = mb_substr($phrase, $i, 1);
$box = \imagettfbbox($size, 0, $font, $symbol);
$w = $box[2] - $box[0];
$angle = $this->rand(-$this->maxAngle, $this->maxAngle);
$offset = $this->rand(-$this->maxOffset, $this->maxOffset);
\imagettftext($image, $size, $angle, $x, $y + $offset, $col, $font, $symbol);
$x += $w;
}
return $col;
} | [
"protected",
"function",
"writePhrase",
"(",
"$",
"image",
",",
"$",
"phrase",
",",
"$",
"font",
",",
"$",
"width",
",",
"$",
"height",
")",
"{",
"$",
"length",
"=",
"mb_strlen",
"(",
"$",
"phrase",
")",
";",
"if",
"(",
"$",
"length",
"===",
"0",
")",
"{",
"return",
"\\",
"imagecolorallocate",
"(",
"$",
"image",
",",
"0",
",",
"0",
",",
"0",
")",
";",
"}",
"// Gets the text size and start position",
"$",
"size",
"=",
"$",
"width",
"/",
"$",
"length",
"-",
"$",
"this",
"->",
"rand",
"(",
"0",
",",
"3",
")",
"-",
"1",
";",
"$",
"box",
"=",
"\\",
"imagettfbbox",
"(",
"$",
"size",
",",
"0",
",",
"$",
"font",
",",
"$",
"phrase",
")",
";",
"$",
"textWidth",
"=",
"$",
"box",
"[",
"2",
"]",
"-",
"$",
"box",
"[",
"0",
"]",
";",
"$",
"textHeight",
"=",
"$",
"box",
"[",
"1",
"]",
"-",
"$",
"box",
"[",
"7",
"]",
";",
"$",
"x",
"=",
"(",
"$",
"width",
"-",
"$",
"textWidth",
")",
"/",
"2",
";",
"$",
"y",
"=",
"(",
"$",
"height",
"-",
"$",
"textHeight",
")",
"/",
"2",
"+",
"$",
"size",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"textColor",
")",
"{",
"$",
"textColor",
"=",
"array",
"(",
"$",
"this",
"->",
"rand",
"(",
"0",
",",
"150",
")",
",",
"$",
"this",
"->",
"rand",
"(",
"0",
",",
"150",
")",
",",
"$",
"this",
"->",
"rand",
"(",
"0",
",",
"150",
")",
")",
";",
"}",
"else",
"{",
"$",
"textColor",
"=",
"$",
"this",
"->",
"textColor",
";",
"}",
"$",
"col",
"=",
"\\",
"imagecolorallocate",
"(",
"$",
"image",
",",
"$",
"textColor",
"[",
"0",
"]",
",",
"$",
"textColor",
"[",
"1",
"]",
",",
"$",
"textColor",
"[",
"2",
"]",
")",
";",
"// Write the letters one by one, with random angle",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"length",
";",
"$",
"i",
"++",
")",
"{",
"$",
"symbol",
"=",
"mb_substr",
"(",
"$",
"phrase",
",",
"$",
"i",
",",
"1",
")",
";",
"$",
"box",
"=",
"\\",
"imagettfbbox",
"(",
"$",
"size",
",",
"0",
",",
"$",
"font",
",",
"$",
"symbol",
")",
";",
"$",
"w",
"=",
"$",
"box",
"[",
"2",
"]",
"-",
"$",
"box",
"[",
"0",
"]",
";",
"$",
"angle",
"=",
"$",
"this",
"->",
"rand",
"(",
"-",
"$",
"this",
"->",
"maxAngle",
",",
"$",
"this",
"->",
"maxAngle",
")",
";",
"$",
"offset",
"=",
"$",
"this",
"->",
"rand",
"(",
"-",
"$",
"this",
"->",
"maxOffset",
",",
"$",
"this",
"->",
"maxOffset",
")",
";",
"\\",
"imagettftext",
"(",
"$",
"image",
",",
"$",
"size",
",",
"$",
"angle",
",",
"$",
"x",
",",
"$",
"y",
"+",
"$",
"offset",
",",
"$",
"col",
",",
"$",
"font",
",",
"$",
"symbol",
")",
";",
"$",
"x",
"+=",
"$",
"w",
";",
"}",
"return",
"$",
"col",
";",
"}"
] | Writes the phrase on the image | [
"Writes",
"the",
"phrase",
"on",
"the",
"image"
] | cf953dd79748406e0292cea8c565399681e4d345 | https://github.com/Gregwar/Captcha/blob/cf953dd79748406e0292cea8c565399681e4d345/src/Gregwar/Captcha/CaptchaBuilder.php#L314-L348 | train |
Gregwar/Captcha | src/Gregwar/Captcha/CaptchaBuilder.php | CaptchaBuilder.isOCRReadable | public function isOCRReadable()
{
if (!is_dir($this->tempDir)) {
@mkdir($this->tempDir, 0755, true);
}
$tempj = $this->tempDir . uniqid('captcha', true) . '.jpg';
$tempp = $this->tempDir . uniqid('captcha', true) . '.pgm';
$this->save($tempj);
shell_exec("convert $tempj $tempp");
$value = trim(strtolower(shell_exec("ocrad $tempp")));
@unlink($tempj);
@unlink($tempp);
return $this->testPhrase($value);
} | php | public function isOCRReadable()
{
if (!is_dir($this->tempDir)) {
@mkdir($this->tempDir, 0755, true);
}
$tempj = $this->tempDir . uniqid('captcha', true) . '.jpg';
$tempp = $this->tempDir . uniqid('captcha', true) . '.pgm';
$this->save($tempj);
shell_exec("convert $tempj $tempp");
$value = trim(strtolower(shell_exec("ocrad $tempp")));
@unlink($tempj);
@unlink($tempp);
return $this->testPhrase($value);
} | [
"public",
"function",
"isOCRReadable",
"(",
")",
"{",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"this",
"->",
"tempDir",
")",
")",
"{",
"@",
"mkdir",
"(",
"$",
"this",
"->",
"tempDir",
",",
"0755",
",",
"true",
")",
";",
"}",
"$",
"tempj",
"=",
"$",
"this",
"->",
"tempDir",
".",
"uniqid",
"(",
"'captcha'",
",",
"true",
")",
".",
"'.jpg'",
";",
"$",
"tempp",
"=",
"$",
"this",
"->",
"tempDir",
".",
"uniqid",
"(",
"'captcha'",
",",
"true",
")",
".",
"'.pgm'",
";",
"$",
"this",
"->",
"save",
"(",
"$",
"tempj",
")",
";",
"shell_exec",
"(",
"\"convert $tempj $tempp\"",
")",
";",
"$",
"value",
"=",
"trim",
"(",
"strtolower",
"(",
"shell_exec",
"(",
"\"ocrad $tempp\"",
")",
")",
")",
";",
"@",
"unlink",
"(",
"$",
"tempj",
")",
";",
"@",
"unlink",
"(",
"$",
"tempp",
")",
";",
"return",
"$",
"this",
"->",
"testPhrase",
"(",
"$",
"value",
")",
";",
"}"
] | Try to read the code against an OCR | [
"Try",
"to",
"read",
"the",
"code",
"against",
"an",
"OCR"
] | cf953dd79748406e0292cea8c565399681e4d345 | https://github.com/Gregwar/Captcha/blob/cf953dd79748406e0292cea8c565399681e4d345/src/Gregwar/Captcha/CaptchaBuilder.php#L353-L370 | train |
Gregwar/Captcha | src/Gregwar/Captcha/CaptchaBuilder.php | CaptchaBuilder.buildAgainstOCR | public function buildAgainstOCR($width = 150, $height = 40, $font = null, $fingerprint = null)
{
do {
$this->build($width, $height, $font, $fingerprint);
} while ($this->isOCRReadable());
} | php | public function buildAgainstOCR($width = 150, $height = 40, $font = null, $fingerprint = null)
{
do {
$this->build($width, $height, $font, $fingerprint);
} while ($this->isOCRReadable());
} | [
"public",
"function",
"buildAgainstOCR",
"(",
"$",
"width",
"=",
"150",
",",
"$",
"height",
"=",
"40",
",",
"$",
"font",
"=",
"null",
",",
"$",
"fingerprint",
"=",
"null",
")",
"{",
"do",
"{",
"$",
"this",
"->",
"build",
"(",
"$",
"width",
",",
"$",
"height",
",",
"$",
"font",
",",
"$",
"fingerprint",
")",
";",
"}",
"while",
"(",
"$",
"this",
"->",
"isOCRReadable",
"(",
")",
")",
";",
"}"
] | Builds while the code is readable against an OCR | [
"Builds",
"while",
"the",
"code",
"is",
"readable",
"against",
"an",
"OCR"
] | cf953dd79748406e0292cea8c565399681e4d345 | https://github.com/Gregwar/Captcha/blob/cf953dd79748406e0292cea8c565399681e4d345/src/Gregwar/Captcha/CaptchaBuilder.php#L375-L380 | train |
Gregwar/Captcha | src/Gregwar/Captcha/CaptchaBuilder.php | CaptchaBuilder.distort | public function distort($image, $width, $height, $bg)
{
$contents = imagecreatetruecolor($width, $height);
$X = $this->rand(0, $width);
$Y = $this->rand(0, $height);
$phase = $this->rand(0, 10);
$scale = 1.1 + $this->rand(0, 10000) / 30000;
for ($x = 0; $x < $width; $x++) {
for ($y = 0; $y < $height; $y++) {
$Vx = $x - $X;
$Vy = $y - $Y;
$Vn = sqrt($Vx * $Vx + $Vy * $Vy);
if ($Vn != 0) {
$Vn2 = $Vn + 4 * sin($Vn / 30);
$nX = $X + ($Vx * $Vn2 / $Vn);
$nY = $Y + ($Vy * $Vn2 / $Vn);
} else {
$nX = $X;
$nY = $Y;
}
$nY = $nY + $scale * sin($phase + $nX * 0.2);
if ($this->interpolation) {
$p = $this->interpolate(
$nX - floor($nX),
$nY - floor($nY),
$this->getCol($image, floor($nX), floor($nY), $bg),
$this->getCol($image, ceil($nX), floor($nY), $bg),
$this->getCol($image, floor($nX), ceil($nY), $bg),
$this->getCol($image, ceil($nX), ceil($nY), $bg)
);
} else {
$p = $this->getCol($image, round($nX), round($nY), $bg);
}
if ($p == 0) {
$p = $bg;
}
imagesetpixel($contents, $x, $y, $p);
}
}
return $contents;
} | php | public function distort($image, $width, $height, $bg)
{
$contents = imagecreatetruecolor($width, $height);
$X = $this->rand(0, $width);
$Y = $this->rand(0, $height);
$phase = $this->rand(0, 10);
$scale = 1.1 + $this->rand(0, 10000) / 30000;
for ($x = 0; $x < $width; $x++) {
for ($y = 0; $y < $height; $y++) {
$Vx = $x - $X;
$Vy = $y - $Y;
$Vn = sqrt($Vx * $Vx + $Vy * $Vy);
if ($Vn != 0) {
$Vn2 = $Vn + 4 * sin($Vn / 30);
$nX = $X + ($Vx * $Vn2 / $Vn);
$nY = $Y + ($Vy * $Vn2 / $Vn);
} else {
$nX = $X;
$nY = $Y;
}
$nY = $nY + $scale * sin($phase + $nX * 0.2);
if ($this->interpolation) {
$p = $this->interpolate(
$nX - floor($nX),
$nY - floor($nY),
$this->getCol($image, floor($nX), floor($nY), $bg),
$this->getCol($image, ceil($nX), floor($nY), $bg),
$this->getCol($image, floor($nX), ceil($nY), $bg),
$this->getCol($image, ceil($nX), ceil($nY), $bg)
);
} else {
$p = $this->getCol($image, round($nX), round($nY), $bg);
}
if ($p == 0) {
$p = $bg;
}
imagesetpixel($contents, $x, $y, $p);
}
}
return $contents;
} | [
"public",
"function",
"distort",
"(",
"$",
"image",
",",
"$",
"width",
",",
"$",
"height",
",",
"$",
"bg",
")",
"{",
"$",
"contents",
"=",
"imagecreatetruecolor",
"(",
"$",
"width",
",",
"$",
"height",
")",
";",
"$",
"X",
"=",
"$",
"this",
"->",
"rand",
"(",
"0",
",",
"$",
"width",
")",
";",
"$",
"Y",
"=",
"$",
"this",
"->",
"rand",
"(",
"0",
",",
"$",
"height",
")",
";",
"$",
"phase",
"=",
"$",
"this",
"->",
"rand",
"(",
"0",
",",
"10",
")",
";",
"$",
"scale",
"=",
"1.1",
"+",
"$",
"this",
"->",
"rand",
"(",
"0",
",",
"10000",
")",
"/",
"30000",
";",
"for",
"(",
"$",
"x",
"=",
"0",
";",
"$",
"x",
"<",
"$",
"width",
";",
"$",
"x",
"++",
")",
"{",
"for",
"(",
"$",
"y",
"=",
"0",
";",
"$",
"y",
"<",
"$",
"height",
";",
"$",
"y",
"++",
")",
"{",
"$",
"Vx",
"=",
"$",
"x",
"-",
"$",
"X",
";",
"$",
"Vy",
"=",
"$",
"y",
"-",
"$",
"Y",
";",
"$",
"Vn",
"=",
"sqrt",
"(",
"$",
"Vx",
"*",
"$",
"Vx",
"+",
"$",
"Vy",
"*",
"$",
"Vy",
")",
";",
"if",
"(",
"$",
"Vn",
"!=",
"0",
")",
"{",
"$",
"Vn2",
"=",
"$",
"Vn",
"+",
"4",
"*",
"sin",
"(",
"$",
"Vn",
"/",
"30",
")",
";",
"$",
"nX",
"=",
"$",
"X",
"+",
"(",
"$",
"Vx",
"*",
"$",
"Vn2",
"/",
"$",
"Vn",
")",
";",
"$",
"nY",
"=",
"$",
"Y",
"+",
"(",
"$",
"Vy",
"*",
"$",
"Vn2",
"/",
"$",
"Vn",
")",
";",
"}",
"else",
"{",
"$",
"nX",
"=",
"$",
"X",
";",
"$",
"nY",
"=",
"$",
"Y",
";",
"}",
"$",
"nY",
"=",
"$",
"nY",
"+",
"$",
"scale",
"*",
"sin",
"(",
"$",
"phase",
"+",
"$",
"nX",
"*",
"0.2",
")",
";",
"if",
"(",
"$",
"this",
"->",
"interpolation",
")",
"{",
"$",
"p",
"=",
"$",
"this",
"->",
"interpolate",
"(",
"$",
"nX",
"-",
"floor",
"(",
"$",
"nX",
")",
",",
"$",
"nY",
"-",
"floor",
"(",
"$",
"nY",
")",
",",
"$",
"this",
"->",
"getCol",
"(",
"$",
"image",
",",
"floor",
"(",
"$",
"nX",
")",
",",
"floor",
"(",
"$",
"nY",
")",
",",
"$",
"bg",
")",
",",
"$",
"this",
"->",
"getCol",
"(",
"$",
"image",
",",
"ceil",
"(",
"$",
"nX",
")",
",",
"floor",
"(",
"$",
"nY",
")",
",",
"$",
"bg",
")",
",",
"$",
"this",
"->",
"getCol",
"(",
"$",
"image",
",",
"floor",
"(",
"$",
"nX",
")",
",",
"ceil",
"(",
"$",
"nY",
")",
",",
"$",
"bg",
")",
",",
"$",
"this",
"->",
"getCol",
"(",
"$",
"image",
",",
"ceil",
"(",
"$",
"nX",
")",
",",
"ceil",
"(",
"$",
"nY",
")",
",",
"$",
"bg",
")",
")",
";",
"}",
"else",
"{",
"$",
"p",
"=",
"$",
"this",
"->",
"getCol",
"(",
"$",
"image",
",",
"round",
"(",
"$",
"nX",
")",
",",
"round",
"(",
"$",
"nY",
")",
",",
"$",
"bg",
")",
";",
"}",
"if",
"(",
"$",
"p",
"==",
"0",
")",
"{",
"$",
"p",
"=",
"$",
"bg",
";",
"}",
"imagesetpixel",
"(",
"$",
"contents",
",",
"$",
"x",
",",
"$",
"y",
",",
"$",
"p",
")",
";",
"}",
"}",
"return",
"$",
"contents",
";",
"}"
] | Distorts the image | [
"Distorts",
"the",
"image"
] | cf953dd79748406e0292cea8c565399681e4d345 | https://github.com/Gregwar/Captcha/blob/cf953dd79748406e0292cea8c565399681e4d345/src/Gregwar/Captcha/CaptchaBuilder.php#L474-L519 | train |
Gregwar/Captcha | src/Gregwar/Captcha/CaptchaBuilder.php | CaptchaBuilder.rand | protected function rand($min, $max)
{
if (!is_array($this->fingerprint)) {
$this->fingerprint = array();
}
if ($this->useFingerprint) {
$value = current($this->fingerprint);
next($this->fingerprint);
} else {
$value = mt_rand($min, $max);
$this->fingerprint[] = $value;
}
return $value;
} | php | protected function rand($min, $max)
{
if (!is_array($this->fingerprint)) {
$this->fingerprint = array();
}
if ($this->useFingerprint) {
$value = current($this->fingerprint);
next($this->fingerprint);
} else {
$value = mt_rand($min, $max);
$this->fingerprint[] = $value;
}
return $value;
} | [
"protected",
"function",
"rand",
"(",
"$",
"min",
",",
"$",
"max",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"this",
"->",
"fingerprint",
")",
")",
"{",
"$",
"this",
"->",
"fingerprint",
"=",
"array",
"(",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"useFingerprint",
")",
"{",
"$",
"value",
"=",
"current",
"(",
"$",
"this",
"->",
"fingerprint",
")",
";",
"next",
"(",
"$",
"this",
"->",
"fingerprint",
")",
";",
"}",
"else",
"{",
"$",
"value",
"=",
"mt_rand",
"(",
"$",
"min",
",",
"$",
"max",
")",
";",
"$",
"this",
"->",
"fingerprint",
"[",
"]",
"=",
"$",
"value",
";",
"}",
"return",
"$",
"value",
";",
"}"
] | Returns a random number or the next number in the
fingerprint | [
"Returns",
"a",
"random",
"number",
"or",
"the",
"next",
"number",
"in",
"the",
"fingerprint"
] | cf953dd79748406e0292cea8c565399681e4d345 | https://github.com/Gregwar/Captcha/blob/cf953dd79748406e0292cea8c565399681e4d345/src/Gregwar/Captcha/CaptchaBuilder.php#L576-L591 | train |
Gregwar/Captcha | src/Gregwar/Captcha/CaptchaBuilder.php | CaptchaBuilder.validateBackgroundImage | protected function validateBackgroundImage($backgroundImage)
{
// check if file exists
if (!file_exists($backgroundImage)) {
$backgroundImageExploded = explode('/', $backgroundImage);
$imageFileName = count($backgroundImageExploded) > 1? $backgroundImageExploded[count($backgroundImageExploded)-1] : $backgroundImage;
throw new Exception('Invalid background image: ' . $imageFileName);
}
// check image type
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
$imageType = finfo_file($finfo, $backgroundImage);
finfo_close($finfo);
if (!in_array($imageType, $this->allowedBackgroundImageTypes)) {
throw new Exception('Invalid background image type! Allowed types are: ' . join(', ', $this->allowedBackgroundImageTypes));
}
return $imageType;
} | php | protected function validateBackgroundImage($backgroundImage)
{
// check if file exists
if (!file_exists($backgroundImage)) {
$backgroundImageExploded = explode('/', $backgroundImage);
$imageFileName = count($backgroundImageExploded) > 1? $backgroundImageExploded[count($backgroundImageExploded)-1] : $backgroundImage;
throw new Exception('Invalid background image: ' . $imageFileName);
}
// check image type
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
$imageType = finfo_file($finfo, $backgroundImage);
finfo_close($finfo);
if (!in_array($imageType, $this->allowedBackgroundImageTypes)) {
throw new Exception('Invalid background image type! Allowed types are: ' . join(', ', $this->allowedBackgroundImageTypes));
}
return $imageType;
} | [
"protected",
"function",
"validateBackgroundImage",
"(",
"$",
"backgroundImage",
")",
"{",
"// check if file exists",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"backgroundImage",
")",
")",
"{",
"$",
"backgroundImageExploded",
"=",
"explode",
"(",
"'/'",
",",
"$",
"backgroundImage",
")",
";",
"$",
"imageFileName",
"=",
"count",
"(",
"$",
"backgroundImageExploded",
")",
">",
"1",
"?",
"$",
"backgroundImageExploded",
"[",
"count",
"(",
"$",
"backgroundImageExploded",
")",
"-",
"1",
"]",
":",
"$",
"backgroundImage",
";",
"throw",
"new",
"Exception",
"(",
"'Invalid background image: '",
".",
"$",
"imageFileName",
")",
";",
"}",
"// check image type",
"$",
"finfo",
"=",
"finfo_open",
"(",
"FILEINFO_MIME_TYPE",
")",
";",
"// return mime type ala mimetype extension",
"$",
"imageType",
"=",
"finfo_file",
"(",
"$",
"finfo",
",",
"$",
"backgroundImage",
")",
";",
"finfo_close",
"(",
"$",
"finfo",
")",
";",
"if",
"(",
"!",
"in_array",
"(",
"$",
"imageType",
",",
"$",
"this",
"->",
"allowedBackgroundImageTypes",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Invalid background image type! Allowed types are: '",
".",
"join",
"(",
"', '",
",",
"$",
"this",
"->",
"allowedBackgroundImageTypes",
")",
")",
";",
"}",
"return",
"$",
"imageType",
";",
"}"
] | Validate the background image path. Return the image type if valid
@param string $backgroundImage
@return string
@throws Exception | [
"Validate",
"the",
"background",
"image",
"path",
".",
"Return",
"the",
"image",
"type",
"if",
"valid"
] | cf953dd79748406e0292cea8c565399681e4d345 | https://github.com/Gregwar/Captcha/blob/cf953dd79748406e0292cea8c565399681e4d345/src/Gregwar/Captcha/CaptchaBuilder.php#L667-L687 | train |
Gregwar/Captcha | src/Gregwar/Captcha/CaptchaBuilder.php | CaptchaBuilder.createBackgroundImageFromType | protected function createBackgroundImageFromType($backgroundImage, $imageType)
{
switch ($imageType) {
case 'image/jpeg':
$image = imagecreatefromjpeg($backgroundImage);
break;
case 'image/png':
$image = imagecreatefrompng($backgroundImage);
break;
case 'image/gif':
$image = imagecreatefromgif($backgroundImage);
break;
default:
throw new Exception('Not supported file type for background image!');
break;
}
return $image;
} | php | protected function createBackgroundImageFromType($backgroundImage, $imageType)
{
switch ($imageType) {
case 'image/jpeg':
$image = imagecreatefromjpeg($backgroundImage);
break;
case 'image/png':
$image = imagecreatefrompng($backgroundImage);
break;
case 'image/gif':
$image = imagecreatefromgif($backgroundImage);
break;
default:
throw new Exception('Not supported file type for background image!');
break;
}
return $image;
} | [
"protected",
"function",
"createBackgroundImageFromType",
"(",
"$",
"backgroundImage",
",",
"$",
"imageType",
")",
"{",
"switch",
"(",
"$",
"imageType",
")",
"{",
"case",
"'image/jpeg'",
":",
"$",
"image",
"=",
"imagecreatefromjpeg",
"(",
"$",
"backgroundImage",
")",
";",
"break",
";",
"case",
"'image/png'",
":",
"$",
"image",
"=",
"imagecreatefrompng",
"(",
"$",
"backgroundImage",
")",
";",
"break",
";",
"case",
"'image/gif'",
":",
"$",
"image",
"=",
"imagecreatefromgif",
"(",
"$",
"backgroundImage",
")",
";",
"break",
";",
"default",
":",
"throw",
"new",
"Exception",
"(",
"'Not supported file type for background image!'",
")",
";",
"break",
";",
"}",
"return",
"$",
"image",
";",
"}"
] | Create background image from type
@param string $backgroundImage
@param string $imageType
@return resource
@throws Exception | [
"Create",
"background",
"image",
"from",
"type"
] | cf953dd79748406e0292cea8c565399681e4d345 | https://github.com/Gregwar/Captcha/blob/cf953dd79748406e0292cea8c565399681e4d345/src/Gregwar/Captcha/CaptchaBuilder.php#L697-L716 | train |
KnpLabs/KnpMenuBundle | src/Provider/BuilderAliasProvider.php | BuilderAliasProvider.getBuilder | protected function getBuilder($bundleName, $className)
{
$name = sprintf('%s:%s', $bundleName, $className);
if (!isset($this->builders[$name])) {
$class = null;
$logs = [];
$bundles = [];
$allBundles = $this->kernel->getBundle($bundleName, false);
// In Symfony 4, bundle inheritance is gone, so there is no way to get an array anymore.
if (!is_array($allBundles)) {
$allBundles = [$allBundles];
}
foreach ($allBundles as $bundle) {
$try = $bundle->getNamespace().'\\Menu\\'.$className;
if (class_exists($try)) {
$class = $try;
break;
}
$logs[] = sprintf('Class "%s" does not exist for menu builder "%s".', $try, $name);
$bundles[] = $bundle->getName();
}
if (null === $class) {
if (1 === count($logs)) {
throw new \InvalidArgumentException($logs[0]);
}
throw new \InvalidArgumentException(sprintf('Unable to find menu builder "%s" in bundles %s.', $name, implode(', ', $bundles)));
}
$builder = new $class();
if ($builder instanceof ContainerAwareInterface) {
$builder->setContainer($this->container);
}
$this->builders[$name] = $builder;
}
return $this->builders[$name];
} | php | protected function getBuilder($bundleName, $className)
{
$name = sprintf('%s:%s', $bundleName, $className);
if (!isset($this->builders[$name])) {
$class = null;
$logs = [];
$bundles = [];
$allBundles = $this->kernel->getBundle($bundleName, false);
// In Symfony 4, bundle inheritance is gone, so there is no way to get an array anymore.
if (!is_array($allBundles)) {
$allBundles = [$allBundles];
}
foreach ($allBundles as $bundle) {
$try = $bundle->getNamespace().'\\Menu\\'.$className;
if (class_exists($try)) {
$class = $try;
break;
}
$logs[] = sprintf('Class "%s" does not exist for menu builder "%s".', $try, $name);
$bundles[] = $bundle->getName();
}
if (null === $class) {
if (1 === count($logs)) {
throw new \InvalidArgumentException($logs[0]);
}
throw new \InvalidArgumentException(sprintf('Unable to find menu builder "%s" in bundles %s.', $name, implode(', ', $bundles)));
}
$builder = new $class();
if ($builder instanceof ContainerAwareInterface) {
$builder->setContainer($this->container);
}
$this->builders[$name] = $builder;
}
return $this->builders[$name];
} | [
"protected",
"function",
"getBuilder",
"(",
"$",
"bundleName",
",",
"$",
"className",
")",
"{",
"$",
"name",
"=",
"sprintf",
"(",
"'%s:%s'",
",",
"$",
"bundleName",
",",
"$",
"className",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"builders",
"[",
"$",
"name",
"]",
")",
")",
"{",
"$",
"class",
"=",
"null",
";",
"$",
"logs",
"=",
"[",
"]",
";",
"$",
"bundles",
"=",
"[",
"]",
";",
"$",
"allBundles",
"=",
"$",
"this",
"->",
"kernel",
"->",
"getBundle",
"(",
"$",
"bundleName",
",",
"false",
")",
";",
"// In Symfony 4, bundle inheritance is gone, so there is no way to get an array anymore.",
"if",
"(",
"!",
"is_array",
"(",
"$",
"allBundles",
")",
")",
"{",
"$",
"allBundles",
"=",
"[",
"$",
"allBundles",
"]",
";",
"}",
"foreach",
"(",
"$",
"allBundles",
"as",
"$",
"bundle",
")",
"{",
"$",
"try",
"=",
"$",
"bundle",
"->",
"getNamespace",
"(",
")",
".",
"'\\\\Menu\\\\'",
".",
"$",
"className",
";",
"if",
"(",
"class_exists",
"(",
"$",
"try",
")",
")",
"{",
"$",
"class",
"=",
"$",
"try",
";",
"break",
";",
"}",
"$",
"logs",
"[",
"]",
"=",
"sprintf",
"(",
"'Class \"%s\" does not exist for menu builder \"%s\".'",
",",
"$",
"try",
",",
"$",
"name",
")",
";",
"$",
"bundles",
"[",
"]",
"=",
"$",
"bundle",
"->",
"getName",
"(",
")",
";",
"}",
"if",
"(",
"null",
"===",
"$",
"class",
")",
"{",
"if",
"(",
"1",
"===",
"count",
"(",
"$",
"logs",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"$",
"logs",
"[",
"0",
"]",
")",
";",
"}",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Unable to find menu builder \"%s\" in bundles %s.'",
",",
"$",
"name",
",",
"implode",
"(",
"', '",
",",
"$",
"bundles",
")",
")",
")",
";",
"}",
"$",
"builder",
"=",
"new",
"$",
"class",
"(",
")",
";",
"if",
"(",
"$",
"builder",
"instanceof",
"ContainerAwareInterface",
")",
"{",
"$",
"builder",
"->",
"setContainer",
"(",
"$",
"this",
"->",
"container",
")",
";",
"}",
"$",
"this",
"->",
"builders",
"[",
"$",
"name",
"]",
"=",
"$",
"builder",
";",
"}",
"return",
"$",
"this",
"->",
"builders",
"[",
"$",
"name",
"]",
";",
"}"
] | Creates and returns the builder that lives in the given bundle
The convention is to look in the Menu namespace of the bundle for
this class, to instantiate it with no arguments, and to inject the
container if the class is ContainerAware.
@param string $bundleName
@param string $className The class name of the builder
@return object
@throws \InvalidArgumentException If the class does not exist | [
"Creates",
"and",
"returns",
"the",
"builder",
"that",
"lives",
"in",
"the",
"given",
"bundle"
] | 1cb5ebae9e1892347eda155dc25e0bea57137b9e | https://github.com/KnpLabs/KnpMenuBundle/blob/1cb5ebae9e1892347eda155dc25e0bea57137b9e/src/Provider/BuilderAliasProvider.php#L95-L139 | train |
KnpLabs/KnpMenuBundle | src/Templating/Helper/MenuHelper.php | MenuHelper.get | public function get($menu, array $path = [], array $options = [])
{
return $this->helper->get($menu, $path, $options);
} | php | public function get($menu, array $path = [], array $options = [])
{
return $this->helper->get($menu, $path, $options);
} | [
"public",
"function",
"get",
"(",
"$",
"menu",
",",
"array",
"$",
"path",
"=",
"[",
"]",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"helper",
"->",
"get",
"(",
"$",
"menu",
",",
"$",
"path",
",",
"$",
"options",
")",
";",
"}"
] | Retrieves an item following a path in the tree.
@param \Knp\Menu\ItemInterface|string $menu
@param array $path
@param array $options
@return \Knp\Menu\ItemInterface | [
"Retrieves",
"an",
"item",
"following",
"a",
"path",
"in",
"the",
"tree",
"."
] | 1cb5ebae9e1892347eda155dc25e0bea57137b9e | https://github.com/KnpLabs/KnpMenuBundle/blob/1cb5ebae9e1892347eda155dc25e0bea57137b9e/src/Templating/Helper/MenuHelper.php#L36-L39 | train |
KnpLabs/KnpMenuBundle | src/Templating/Helper/MenuHelper.php | MenuHelper.isAncestor | public function isAncestor(ItemInterface $item, $depth = null)
{
return $this->matcher->isAncestor($item, $depth);
} | php | public function isAncestor(ItemInterface $item, $depth = null)
{
return $this->matcher->isAncestor($item, $depth);
} | [
"public",
"function",
"isAncestor",
"(",
"ItemInterface",
"$",
"item",
",",
"$",
"depth",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"matcher",
"->",
"isAncestor",
"(",
"$",
"item",
",",
"$",
"depth",
")",
";",
"}"
] | Checks whether an item is the ancestor of a current item.
@param ItemInterface $item
@param integer $depth The max depth to look for the item
@return boolean | [
"Checks",
"whether",
"an",
"item",
"is",
"the",
"ancestor",
"of",
"a",
"current",
"item",
"."
] | 1cb5ebae9e1892347eda155dc25e0bea57137b9e | https://github.com/KnpLabs/KnpMenuBundle/blob/1cb5ebae9e1892347eda155dc25e0bea57137b9e/src/Templating/Helper/MenuHelper.php#L103-L106 | train |
KnpLabs/KnpMenuBundle | src/DependencyInjection/KnpMenuExtension.php | KnpMenuExtension.load | public function load(array $configs, ContainerBuilder $container)
{
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('menu.xml');
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
foreach ($config['providers'] as $builder => $enabled) {
if ($enabled) {
$container->getDefinition(sprintf('knp_menu.menu_provider.%s', $builder))->addTag('knp_menu.provider');
}
}
if (isset($config['twig'])) {
$loader->load('twig.xml');
$container->setParameter('knp_menu.renderer.twig.template', $config['twig']['template']);
}
if ($config['templating']) {
$loader->load('templating.xml');
}
$container->setParameter('knp_menu.default_renderer', $config['default_renderer']);
// Register autoconfiguration rules for Symfony DI 3.3+
if (method_exists($container, 'registerForAutoconfiguration')) {
$container->registerForAutoconfiguration(VoterInterface::class)
->addTag('knp_menu.voter');
}
} | php | public function load(array $configs, ContainerBuilder $container)
{
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('menu.xml');
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
foreach ($config['providers'] as $builder => $enabled) {
if ($enabled) {
$container->getDefinition(sprintf('knp_menu.menu_provider.%s', $builder))->addTag('knp_menu.provider');
}
}
if (isset($config['twig'])) {
$loader->load('twig.xml');
$container->setParameter('knp_menu.renderer.twig.template', $config['twig']['template']);
}
if ($config['templating']) {
$loader->load('templating.xml');
}
$container->setParameter('knp_menu.default_renderer', $config['default_renderer']);
// Register autoconfiguration rules for Symfony DI 3.3+
if (method_exists($container, 'registerForAutoconfiguration')) {
$container->registerForAutoconfiguration(VoterInterface::class)
->addTag('knp_menu.voter');
}
} | [
"public",
"function",
"load",
"(",
"array",
"$",
"configs",
",",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"loader",
"=",
"new",
"XmlFileLoader",
"(",
"$",
"container",
",",
"new",
"FileLocator",
"(",
"__DIR__",
".",
"'/../Resources/config'",
")",
")",
";",
"$",
"loader",
"->",
"load",
"(",
"'menu.xml'",
")",
";",
"$",
"configuration",
"=",
"new",
"Configuration",
"(",
")",
";",
"$",
"config",
"=",
"$",
"this",
"->",
"processConfiguration",
"(",
"$",
"configuration",
",",
"$",
"configs",
")",
";",
"foreach",
"(",
"$",
"config",
"[",
"'providers'",
"]",
"as",
"$",
"builder",
"=>",
"$",
"enabled",
")",
"{",
"if",
"(",
"$",
"enabled",
")",
"{",
"$",
"container",
"->",
"getDefinition",
"(",
"sprintf",
"(",
"'knp_menu.menu_provider.%s'",
",",
"$",
"builder",
")",
")",
"->",
"addTag",
"(",
"'knp_menu.provider'",
")",
";",
"}",
"}",
"if",
"(",
"isset",
"(",
"$",
"config",
"[",
"'twig'",
"]",
")",
")",
"{",
"$",
"loader",
"->",
"load",
"(",
"'twig.xml'",
")",
";",
"$",
"container",
"->",
"setParameter",
"(",
"'knp_menu.renderer.twig.template'",
",",
"$",
"config",
"[",
"'twig'",
"]",
"[",
"'template'",
"]",
")",
";",
"}",
"if",
"(",
"$",
"config",
"[",
"'templating'",
"]",
")",
"{",
"$",
"loader",
"->",
"load",
"(",
"'templating.xml'",
")",
";",
"}",
"$",
"container",
"->",
"setParameter",
"(",
"'knp_menu.default_renderer'",
",",
"$",
"config",
"[",
"'default_renderer'",
"]",
")",
";",
"// Register autoconfiguration rules for Symfony DI 3.3+",
"if",
"(",
"method_exists",
"(",
"$",
"container",
",",
"'registerForAutoconfiguration'",
")",
")",
"{",
"$",
"container",
"->",
"registerForAutoconfiguration",
"(",
"VoterInterface",
"::",
"class",
")",
"->",
"addTag",
"(",
"'knp_menu.voter'",
")",
";",
"}",
"}"
] | Handles the knp_menu configuration.
@param array $configs The configurations being loaded
@param ContainerBuilder $container | [
"Handles",
"the",
"knp_menu",
"configuration",
"."
] | 1cb5ebae9e1892347eda155dc25e0bea57137b9e | https://github.com/KnpLabs/KnpMenuBundle/blob/1cb5ebae9e1892347eda155dc25e0bea57137b9e/src/DependencyInjection/KnpMenuExtension.php#L21-L50 | train |
mpociot/teamwork | src/Mpociot/Teamwork/Traits/TeamworkTeamTrait.php | TeamworkTeamTrait.owner | public function owner()
{
$userModel = Config::get( 'teamwork.user_model' );
$userKeyName = ( new $userModel() )->getKeyName();
return $this->hasOne(Config::get('teamwork.user_model'), $userKeyName, "owner_id");
} | php | public function owner()
{
$userModel = Config::get( 'teamwork.user_model' );
$userKeyName = ( new $userModel() )->getKeyName();
return $this->hasOne(Config::get('teamwork.user_model'), $userKeyName, "owner_id");
} | [
"public",
"function",
"owner",
"(",
")",
"{",
"$",
"userModel",
"=",
"Config",
"::",
"get",
"(",
"'teamwork.user_model'",
")",
";",
"$",
"userKeyName",
"=",
"(",
"new",
"$",
"userModel",
"(",
")",
")",
"->",
"getKeyName",
"(",
")",
";",
"return",
"$",
"this",
"->",
"hasOne",
"(",
"Config",
"::",
"get",
"(",
"'teamwork.user_model'",
")",
",",
"$",
"userKeyName",
",",
"\"owner_id\"",
")",
";",
"}"
] | Has-One relation with the user model.
This indicates the owner of the team
@return \Illuminate\Database\Eloquent\Relations\HasOne | [
"Has",
"-",
"One",
"relation",
"with",
"the",
"user",
"model",
".",
"This",
"indicates",
"the",
"owner",
"of",
"the",
"team"
] | 4de34f53c44757030ed54dde5f69fe48b7a207e1 | https://github.com/mpociot/teamwork/blob/4de34f53c44757030ed54dde5f69fe48b7a207e1/src/Mpociot/Teamwork/Traits/TeamworkTeamTrait.php#L41-L46 | train |
mpociot/teamwork | src/Mpociot/Teamwork/Traits/TeamworkTeamTrait.php | TeamworkTeamTrait.hasUser | public function hasUser( Model $user )
{
return $this->users()->where( $user->getKeyName(), "=", $user->getKey() )->first() ? true : false;
} | php | public function hasUser( Model $user )
{
return $this->users()->where( $user->getKeyName(), "=", $user->getKey() )->first() ? true : false;
} | [
"public",
"function",
"hasUser",
"(",
"Model",
"$",
"user",
")",
"{",
"return",
"$",
"this",
"->",
"users",
"(",
")",
"->",
"where",
"(",
"$",
"user",
"->",
"getKeyName",
"(",
")",
",",
"\"=\"",
",",
"$",
"user",
"->",
"getKey",
"(",
")",
")",
"->",
"first",
"(",
")",
"?",
"true",
":",
"false",
";",
"}"
] | Helper function to determine if a user is part
of this team
@param Model $user
@return bool | [
"Helper",
"function",
"to",
"determine",
"if",
"a",
"user",
"is",
"part",
"of",
"this",
"team"
] | 4de34f53c44757030ed54dde5f69fe48b7a207e1 | https://github.com/mpociot/teamwork/blob/4de34f53c44757030ed54dde5f69fe48b7a207e1/src/Mpociot/Teamwork/Traits/TeamworkTeamTrait.php#L55-L58 | train |
mpociot/teamwork | src/Mpociot/Teamwork/Teamwork.php | Teamwork.inviteToTeam | public function inviteToTeam( $user, $team = null, callable $success = null )
{
if ( is_null( $team ) )
{
$team = $this->user()->current_team_id;
} elseif( is_object( $team ) )
{
$team = $team->getKey();
}elseif( is_array( $team ) )
{
$team = $team["id"];
}
if( is_object( $user ) && isset($user->email) )
{
$email = $user->email;
} elseif( is_string($user) ) {
$email = $user;
} else {
throw new \Exception('The provided object has no "email" attribute and is not a string.');
}
$invite = $this->app->make(Config::get('teamwork.invite_model'));
$invite->user_id = $this->user()->getKey();
$invite->team_id = $team;
$invite->type = 'invite';
$invite->email = $email;
$invite->accept_token = md5( uniqid( microtime() ) );
$invite->deny_token = md5( uniqid( microtime() ) );
$invite->save();
if ( !is_null( $success ) )
{
event(new UserInvitedToTeam($invite));
return $success( $invite );
}
} | php | public function inviteToTeam( $user, $team = null, callable $success = null )
{
if ( is_null( $team ) )
{
$team = $this->user()->current_team_id;
} elseif( is_object( $team ) )
{
$team = $team->getKey();
}elseif( is_array( $team ) )
{
$team = $team["id"];
}
if( is_object( $user ) && isset($user->email) )
{
$email = $user->email;
} elseif( is_string($user) ) {
$email = $user;
} else {
throw new \Exception('The provided object has no "email" attribute and is not a string.');
}
$invite = $this->app->make(Config::get('teamwork.invite_model'));
$invite->user_id = $this->user()->getKey();
$invite->team_id = $team;
$invite->type = 'invite';
$invite->email = $email;
$invite->accept_token = md5( uniqid( microtime() ) );
$invite->deny_token = md5( uniqid( microtime() ) );
$invite->save();
if ( !is_null( $success ) )
{
event(new UserInvitedToTeam($invite));
return $success( $invite );
}
} | [
"public",
"function",
"inviteToTeam",
"(",
"$",
"user",
",",
"$",
"team",
"=",
"null",
",",
"callable",
"$",
"success",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"team",
")",
")",
"{",
"$",
"team",
"=",
"$",
"this",
"->",
"user",
"(",
")",
"->",
"current_team_id",
";",
"}",
"elseif",
"(",
"is_object",
"(",
"$",
"team",
")",
")",
"{",
"$",
"team",
"=",
"$",
"team",
"->",
"getKey",
"(",
")",
";",
"}",
"elseif",
"(",
"is_array",
"(",
"$",
"team",
")",
")",
"{",
"$",
"team",
"=",
"$",
"team",
"[",
"\"id\"",
"]",
";",
"}",
"if",
"(",
"is_object",
"(",
"$",
"user",
")",
"&&",
"isset",
"(",
"$",
"user",
"->",
"email",
")",
")",
"{",
"$",
"email",
"=",
"$",
"user",
"->",
"email",
";",
"}",
"elseif",
"(",
"is_string",
"(",
"$",
"user",
")",
")",
"{",
"$",
"email",
"=",
"$",
"user",
";",
"}",
"else",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'The provided object has no \"email\" attribute and is not a string.'",
")",
";",
"}",
"$",
"invite",
"=",
"$",
"this",
"->",
"app",
"->",
"make",
"(",
"Config",
"::",
"get",
"(",
"'teamwork.invite_model'",
")",
")",
";",
"$",
"invite",
"->",
"user_id",
"=",
"$",
"this",
"->",
"user",
"(",
")",
"->",
"getKey",
"(",
")",
";",
"$",
"invite",
"->",
"team_id",
"=",
"$",
"team",
";",
"$",
"invite",
"->",
"type",
"=",
"'invite'",
";",
"$",
"invite",
"->",
"email",
"=",
"$",
"email",
";",
"$",
"invite",
"->",
"accept_token",
"=",
"md5",
"(",
"uniqid",
"(",
"microtime",
"(",
")",
")",
")",
";",
"$",
"invite",
"->",
"deny_token",
"=",
"md5",
"(",
"uniqid",
"(",
"microtime",
"(",
")",
")",
")",
";",
"$",
"invite",
"->",
"save",
"(",
")",
";",
"if",
"(",
"!",
"is_null",
"(",
"$",
"success",
")",
")",
"{",
"event",
"(",
"new",
"UserInvitedToTeam",
"(",
"$",
"invite",
")",
")",
";",
"return",
"$",
"success",
"(",
"$",
"invite",
")",
";",
"}",
"}"
] | Invite an email adress to a team.
Either provide a email address or an object with an email property.
If no team is given, the current_team_id will be used instead.
@param string|User $user
@param null|Team $team
@param callable $success
@throws \Exception | [
"Invite",
"an",
"email",
"adress",
"to",
"a",
"team",
".",
"Either",
"provide",
"a",
"email",
"address",
"or",
"an",
"object",
"with",
"an",
"email",
"property",
"."
] | 4de34f53c44757030ed54dde5f69fe48b7a207e1 | https://github.com/mpociot/teamwork/blob/4de34f53c44757030ed54dde5f69fe48b7a207e1/src/Mpociot/Teamwork/Teamwork.php#L51-L87 | train |
mpociot/teamwork | src/Mpociot/Teamwork/Teamwork.php | Teamwork.hasPendingInvite | public function hasPendingInvite( $email, $team )
{
if( is_object( $team ) )
{
$team = $team->getKey();
}
if( is_array( $team ) )
{
$team = $team["id"];
}
return $this->app->make(Config::get('teamwork.invite_model'))->where('email', "=", $email)->where('team_id', "=", $team )->first() ? true : false;
} | php | public function hasPendingInvite( $email, $team )
{
if( is_object( $team ) )
{
$team = $team->getKey();
}
if( is_array( $team ) )
{
$team = $team["id"];
}
return $this->app->make(Config::get('teamwork.invite_model'))->where('email', "=", $email)->where('team_id', "=", $team )->first() ? true : false;
} | [
"public",
"function",
"hasPendingInvite",
"(",
"$",
"email",
",",
"$",
"team",
")",
"{",
"if",
"(",
"is_object",
"(",
"$",
"team",
")",
")",
"{",
"$",
"team",
"=",
"$",
"team",
"->",
"getKey",
"(",
")",
";",
"}",
"if",
"(",
"is_array",
"(",
"$",
"team",
")",
")",
"{",
"$",
"team",
"=",
"$",
"team",
"[",
"\"id\"",
"]",
";",
"}",
"return",
"$",
"this",
"->",
"app",
"->",
"make",
"(",
"Config",
"::",
"get",
"(",
"'teamwork.invite_model'",
")",
")",
"->",
"where",
"(",
"'email'",
",",
"\"=\"",
",",
"$",
"email",
")",
"->",
"where",
"(",
"'team_id'",
",",
"\"=\"",
",",
"$",
"team",
")",
"->",
"first",
"(",
")",
"?",
"true",
":",
"false",
";",
"}"
] | Checks if the given email address has a pending invite for the
provided Team
@param $email
@param Team|array|integer $team
@return bool | [
"Checks",
"if",
"the",
"given",
"email",
"address",
"has",
"a",
"pending",
"invite",
"for",
"the",
"provided",
"Team"
] | 4de34f53c44757030ed54dde5f69fe48b7a207e1 | https://github.com/mpociot/teamwork/blob/4de34f53c44757030ed54dde5f69fe48b7a207e1/src/Mpociot/Teamwork/Teamwork.php#L96-L107 | train |
mpociot/teamwork | src/Mpociot/Teamwork/Traits/UserHasTeams.php | UserHasTeams.isOwnerOfTeam | public function isOwnerOfTeam( $team )
{
$team_id = $this->retrieveTeamId( $team );
return ( $this->teams()
->where('owner_id', $this->getKey())
->where('team_id', $team_id)->first()
) ? true : false;
} | php | public function isOwnerOfTeam( $team )
{
$team_id = $this->retrieveTeamId( $team );
return ( $this->teams()
->where('owner_id', $this->getKey())
->where('team_id', $team_id)->first()
) ? true : false;
} | [
"public",
"function",
"isOwnerOfTeam",
"(",
"$",
"team",
")",
"{",
"$",
"team_id",
"=",
"$",
"this",
"->",
"retrieveTeamId",
"(",
"$",
"team",
")",
";",
"return",
"(",
"$",
"this",
"->",
"teams",
"(",
")",
"->",
"where",
"(",
"'owner_id'",
",",
"$",
"this",
"->",
"getKey",
"(",
")",
")",
"->",
"where",
"(",
"'team_id'",
",",
"$",
"team_id",
")",
"->",
"first",
"(",
")",
")",
"?",
"true",
":",
"false",
";",
"}"
] | Returns if the user owns the given team
@param mixed $team
@return bool | [
"Returns",
"if",
"the",
"user",
"owns",
"the",
"given",
"team"
] | 4de34f53c44757030ed54dde5f69fe48b7a207e1 | https://github.com/mpociot/teamwork/blob/4de34f53c44757030ed54dde5f69fe48b7a207e1/src/Mpociot/Teamwork/Traits/UserHasTeams.php#L120-L127 | train |
mpociot/teamwork | src/Mpociot/Teamwork/Traits/UserHasTeams.php | UserHasTeams.switchTeam | public function switchTeam( $team )
{
if( $team !== 0 && $team !== null )
{
$team = $this->retrieveTeamId( $team );
$teamModel = Config::get( 'teamwork.team_model' );
$teamObject = ( new $teamModel() )->find( $team );
if( !$teamObject )
{
$exception = new ModelNotFoundException();
$exception->setModel( $teamModel );
throw $exception;
}
if( !$teamObject->users->contains( $this->getKey() ) )
{
$exception = new UserNotInTeamException();
$exception->setTeam( $teamObject->name );
throw $exception;
}
}
$this->current_team_id = $team;
$this->save();
if( $this->relationLoaded('currentTeam') ) {
$this->load('currentTeam');
}
return $this;
} | php | public function switchTeam( $team )
{
if( $team !== 0 && $team !== null )
{
$team = $this->retrieveTeamId( $team );
$teamModel = Config::get( 'teamwork.team_model' );
$teamObject = ( new $teamModel() )->find( $team );
if( !$teamObject )
{
$exception = new ModelNotFoundException();
$exception->setModel( $teamModel );
throw $exception;
}
if( !$teamObject->users->contains( $this->getKey() ) )
{
$exception = new UserNotInTeamException();
$exception->setTeam( $teamObject->name );
throw $exception;
}
}
$this->current_team_id = $team;
$this->save();
if( $this->relationLoaded('currentTeam') ) {
$this->load('currentTeam');
}
return $this;
} | [
"public",
"function",
"switchTeam",
"(",
"$",
"team",
")",
"{",
"if",
"(",
"$",
"team",
"!==",
"0",
"&&",
"$",
"team",
"!==",
"null",
")",
"{",
"$",
"team",
"=",
"$",
"this",
"->",
"retrieveTeamId",
"(",
"$",
"team",
")",
";",
"$",
"teamModel",
"=",
"Config",
"::",
"get",
"(",
"'teamwork.team_model'",
")",
";",
"$",
"teamObject",
"=",
"(",
"new",
"$",
"teamModel",
"(",
")",
")",
"->",
"find",
"(",
"$",
"team",
")",
";",
"if",
"(",
"!",
"$",
"teamObject",
")",
"{",
"$",
"exception",
"=",
"new",
"ModelNotFoundException",
"(",
")",
";",
"$",
"exception",
"->",
"setModel",
"(",
"$",
"teamModel",
")",
";",
"throw",
"$",
"exception",
";",
"}",
"if",
"(",
"!",
"$",
"teamObject",
"->",
"users",
"->",
"contains",
"(",
"$",
"this",
"->",
"getKey",
"(",
")",
")",
")",
"{",
"$",
"exception",
"=",
"new",
"UserNotInTeamException",
"(",
")",
";",
"$",
"exception",
"->",
"setTeam",
"(",
"$",
"teamObject",
"->",
"name",
")",
";",
"throw",
"$",
"exception",
";",
"}",
"}",
"$",
"this",
"->",
"current_team_id",
"=",
"$",
"team",
";",
"$",
"this",
"->",
"save",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"relationLoaded",
"(",
"'currentTeam'",
")",
")",
"{",
"$",
"this",
"->",
"load",
"(",
"'currentTeam'",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Switch the current team of the user
@param object|array|integer $team
@return $this
@throws ModelNotFoundException
@throws UserNotInTeamException | [
"Switch",
"the",
"current",
"team",
"of",
"the",
"user"
] | 4de34f53c44757030ed54dde5f69fe48b7a207e1 | https://github.com/mpociot/teamwork/blob/4de34f53c44757030ed54dde5f69fe48b7a207e1/src/Mpociot/Teamwork/Traits/UserHasTeams.php#L242-L270 | train |
mpociot/teamwork | src/Mpociot/Teamwork/Traits/UsedByTeams.php | UsedByTeams.bootUsedByTeams | protected static function bootUsedByTeams()
{
static::addGlobalScope('team', function (Builder $builder) {
static::teamGuard();
$builder->where($builder->getQuery()->from . '.team_id', auth()->user()->currentTeam->getKey());
});
static::saving(function (Model $model) {
static::teamGuard();
if (!isset($model->team_id)) {
$model->team_id = auth()->user()->currentTeam->getKey();
}
});
} | php | protected static function bootUsedByTeams()
{
static::addGlobalScope('team', function (Builder $builder) {
static::teamGuard();
$builder->where($builder->getQuery()->from . '.team_id', auth()->user()->currentTeam->getKey());
});
static::saving(function (Model $model) {
static::teamGuard();
if (!isset($model->team_id)) {
$model->team_id = auth()->user()->currentTeam->getKey();
}
});
} | [
"protected",
"static",
"function",
"bootUsedByTeams",
"(",
")",
"{",
"static",
"::",
"addGlobalScope",
"(",
"'team'",
",",
"function",
"(",
"Builder",
"$",
"builder",
")",
"{",
"static",
"::",
"teamGuard",
"(",
")",
";",
"$",
"builder",
"->",
"where",
"(",
"$",
"builder",
"->",
"getQuery",
"(",
")",
"->",
"from",
".",
"'.team_id'",
",",
"auth",
"(",
")",
"->",
"user",
"(",
")",
"->",
"currentTeam",
"->",
"getKey",
"(",
")",
")",
";",
"}",
")",
";",
"static",
"::",
"saving",
"(",
"function",
"(",
"Model",
"$",
"model",
")",
"{",
"static",
"::",
"teamGuard",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"model",
"->",
"team_id",
")",
")",
"{",
"$",
"model",
"->",
"team_id",
"=",
"auth",
"(",
")",
"->",
"user",
"(",
")",
"->",
"currentTeam",
"->",
"getKey",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Boot the global scope | [
"Boot",
"the",
"global",
"scope"
] | 4de34f53c44757030ed54dde5f69fe48b7a207e1 | https://github.com/mpociot/teamwork/blob/4de34f53c44757030ed54dde5f69fe48b7a207e1/src/Mpociot/Teamwork/Traits/UsedByTeams.php#L24-L39 | train |
picocms/Pico | lib/PicoTwigExtension.php | PicoTwigExtension.getFilters | public function getFilters()
{
return array(
'markdown' => new Twig_SimpleFilter('markdown', array($this, 'markdownFilter')),
'map' => new Twig_SimpleFilter('map', array($this, 'mapFilter')),
'sort_by' => new Twig_SimpleFilter('sort_by', array($this, 'sortByFilter')),
'link' => new Twig_SimpleFilter('link', array($this->pico, 'getPageUrl'))
);
} | php | public function getFilters()
{
return array(
'markdown' => new Twig_SimpleFilter('markdown', array($this, 'markdownFilter')),
'map' => new Twig_SimpleFilter('map', array($this, 'mapFilter')),
'sort_by' => new Twig_SimpleFilter('sort_by', array($this, 'sortByFilter')),
'link' => new Twig_SimpleFilter('link', array($this->pico, 'getPageUrl'))
);
} | [
"public",
"function",
"getFilters",
"(",
")",
"{",
"return",
"array",
"(",
"'markdown'",
"=>",
"new",
"Twig_SimpleFilter",
"(",
"'markdown'",
",",
"array",
"(",
"$",
"this",
",",
"'markdownFilter'",
")",
")",
",",
"'map'",
"=>",
"new",
"Twig_SimpleFilter",
"(",
"'map'",
",",
"array",
"(",
"$",
"this",
",",
"'mapFilter'",
")",
")",
",",
"'sort_by'",
"=>",
"new",
"Twig_SimpleFilter",
"(",
"'sort_by'",
",",
"array",
"(",
"$",
"this",
",",
"'sortByFilter'",
")",
")",
",",
"'link'",
"=>",
"new",
"Twig_SimpleFilter",
"(",
"'link'",
",",
"array",
"(",
"$",
"this",
"->",
"pico",
",",
"'getPageUrl'",
")",
")",
")",
";",
"}"
] | Returns a list of Pico-specific Twig filters
@see Twig_ExtensionInterface::getFilters()
@return Twig_SimpleFilter[] array of Pico's Twig filters | [
"Returns",
"a",
"list",
"of",
"Pico",
"-",
"specific",
"Twig",
"filters"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/PicoTwigExtension.php#L72-L80 | train |
picocms/Pico | lib/PicoTwigExtension.php | PicoTwigExtension.markdownFilter | public function markdownFilter($markdown, array $meta = array())
{
$markdown = $this->getPico()->substituteFileContent($markdown, $meta);
return $this->getPico()->parseFileContent($markdown);
} | php | public function markdownFilter($markdown, array $meta = array())
{
$markdown = $this->getPico()->substituteFileContent($markdown, $meta);
return $this->getPico()->parseFileContent($markdown);
} | [
"public",
"function",
"markdownFilter",
"(",
"$",
"markdown",
",",
"array",
"$",
"meta",
"=",
"array",
"(",
")",
")",
"{",
"$",
"markdown",
"=",
"$",
"this",
"->",
"getPico",
"(",
")",
"->",
"substituteFileContent",
"(",
"$",
"markdown",
",",
"$",
"meta",
")",
";",
"return",
"$",
"this",
"->",
"getPico",
"(",
")",
"->",
"parseFileContent",
"(",
"$",
"markdown",
")",
";",
"}"
] | Parses a markdown string to HTML
This method is registered as the Twig `markdown` filter. You can use it
to e.g. parse a meta variable (`{{ meta.description|markdown }}`).
Don't use it to parse the contents of a page, use the `content` filter
instead, what ensures the proper preparation of the contents.
@see Pico::substituteFileContent()
@see Pico::parseFileContent()
@param string $markdown markdown to parse
@param array $meta meta data to use for %meta.*% replacement
@return string parsed HTML | [
"Parses",
"a",
"markdown",
"string",
"to",
"HTML"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/PicoTwigExtension.php#L113-L117 | train |
picocms/Pico | lib/PicoTwigExtension.php | PicoTwigExtension.mapFilter | public function mapFilter($var, $mapKeyPath)
{
if (!is_array($var) && (!is_object($var) || !($var instanceof Traversable))) {
throw new Twig_Error_Runtime(sprintf(
'The map filter only works with arrays or "Traversable", got "%s"',
is_object($var) ? get_class($var) : gettype($var)
));
}
$result = array();
foreach ($var as $key => $value) {
$mapValue = $this->getKeyOfVar($value, $mapKeyPath);
$result[$key] = ($mapValue !== null) ? $mapValue : $value;
}
return $result;
} | php | public function mapFilter($var, $mapKeyPath)
{
if (!is_array($var) && (!is_object($var) || !($var instanceof Traversable))) {
throw new Twig_Error_Runtime(sprintf(
'The map filter only works with arrays or "Traversable", got "%s"',
is_object($var) ? get_class($var) : gettype($var)
));
}
$result = array();
foreach ($var as $key => $value) {
$mapValue = $this->getKeyOfVar($value, $mapKeyPath);
$result[$key] = ($mapValue !== null) ? $mapValue : $value;
}
return $result;
} | [
"public",
"function",
"mapFilter",
"(",
"$",
"var",
",",
"$",
"mapKeyPath",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"var",
")",
"&&",
"(",
"!",
"is_object",
"(",
"$",
"var",
")",
"||",
"!",
"(",
"$",
"var",
"instanceof",
"Traversable",
")",
")",
")",
"{",
"throw",
"new",
"Twig_Error_Runtime",
"(",
"sprintf",
"(",
"'The map filter only works with arrays or \"Traversable\", got \"%s\"'",
",",
"is_object",
"(",
"$",
"var",
")",
"?",
"get_class",
"(",
"$",
"var",
")",
":",
"gettype",
"(",
"$",
"var",
")",
")",
")",
";",
"}",
"$",
"result",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"var",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"mapValue",
"=",
"$",
"this",
"->",
"getKeyOfVar",
"(",
"$",
"value",
",",
"$",
"mapKeyPath",
")",
";",
"$",
"result",
"[",
"$",
"key",
"]",
"=",
"(",
"$",
"mapValue",
"!==",
"null",
")",
"?",
"$",
"mapValue",
":",
"$",
"value",
";",
"}",
"return",
"$",
"result",
";",
"}"
] | Returns a array with the values of the given key or key path
This method is registered as the Twig `map` filter. You can use this
filter to e.g. get all page titles (`{{ pages|map("title") }}`).
@param array|Traversable $var variable to map
@param mixed $mapKeyPath key to map; either a scalar or a
array interpreted as key path (i.e. ['foo', 'bar'] will return all
$item['foo']['bar'] values)
@return array mapped values | [
"Returns",
"a",
"array",
"with",
"the",
"values",
"of",
"the",
"given",
"key",
"or",
"key",
"path"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/PicoTwigExtension.php#L132-L147 | train |
picocms/Pico | lib/PicoTwigExtension.php | PicoTwigExtension.sortByFilter | public function sortByFilter($var, $sortKeyPath, $fallback = 'bottom')
{
if (is_object($var) && ($var instanceof Traversable)) {
$var = iterator_to_array($var, true);
} elseif (!is_array($var)) {
throw new Twig_Error_Runtime(sprintf(
'The sort_by filter only works with arrays or "Traversable", got "%s"',
is_object($var) ? get_class($var) : gettype($var)
));
}
if (($fallback !== 'top') && ($fallback !== 'bottom') && ($fallback !== 'keep') && ($fallback !== "remove")) {
throw new Twig_Error_Runtime(
'The sort_by filter only supports the "top", "bottom", "keep" and "remove" fallbacks'
);
}
$twigExtension = $this;
$varKeys = array_keys($var);
$removeItems = array();
uksort($var, function ($a, $b) use ($twigExtension, $var, $varKeys, $sortKeyPath, $fallback, &$removeItems) {
$aSortValue = $twigExtension->getKeyOfVar($var[$a], $sortKeyPath);
$aSortValueNull = ($aSortValue === null);
$bSortValue = $twigExtension->getKeyOfVar($var[$b], $sortKeyPath);
$bSortValueNull = ($bSortValue === null);
if (($fallback === 'remove') && ($aSortValueNull || $bSortValueNull)) {
if ($aSortValueNull) {
$removeItems[$a] = $var[$a];
}
if ($bSortValueNull) {
$removeItems[$b] = $var[$b];
}
return ($aSortValueNull - $bSortValueNull);
} elseif ($aSortValueNull xor $bSortValueNull) {
if ($fallback === 'top') {
return ($aSortValueNull - $bSortValueNull) * -1;
} elseif ($fallback === 'bottom') {
return ($aSortValueNull - $bSortValueNull);
}
} elseif (!$aSortValueNull && !$bSortValueNull) {
if ($aSortValue != $bSortValue) {
return ($aSortValue > $bSortValue) ? 1 : -1;
}
}
// never assume equality; fallback to original order
$aIndex = array_search($a, $varKeys);
$bIndex = array_search($b, $varKeys);
return ($aIndex > $bIndex) ? 1 : -1;
});
if ($removeItems) {
$var = array_diff_key($var, $removeItems);
}
return $var;
} | php | public function sortByFilter($var, $sortKeyPath, $fallback = 'bottom')
{
if (is_object($var) && ($var instanceof Traversable)) {
$var = iterator_to_array($var, true);
} elseif (!is_array($var)) {
throw new Twig_Error_Runtime(sprintf(
'The sort_by filter only works with arrays or "Traversable", got "%s"',
is_object($var) ? get_class($var) : gettype($var)
));
}
if (($fallback !== 'top') && ($fallback !== 'bottom') && ($fallback !== 'keep') && ($fallback !== "remove")) {
throw new Twig_Error_Runtime(
'The sort_by filter only supports the "top", "bottom", "keep" and "remove" fallbacks'
);
}
$twigExtension = $this;
$varKeys = array_keys($var);
$removeItems = array();
uksort($var, function ($a, $b) use ($twigExtension, $var, $varKeys, $sortKeyPath, $fallback, &$removeItems) {
$aSortValue = $twigExtension->getKeyOfVar($var[$a], $sortKeyPath);
$aSortValueNull = ($aSortValue === null);
$bSortValue = $twigExtension->getKeyOfVar($var[$b], $sortKeyPath);
$bSortValueNull = ($bSortValue === null);
if (($fallback === 'remove') && ($aSortValueNull || $bSortValueNull)) {
if ($aSortValueNull) {
$removeItems[$a] = $var[$a];
}
if ($bSortValueNull) {
$removeItems[$b] = $var[$b];
}
return ($aSortValueNull - $bSortValueNull);
} elseif ($aSortValueNull xor $bSortValueNull) {
if ($fallback === 'top') {
return ($aSortValueNull - $bSortValueNull) * -1;
} elseif ($fallback === 'bottom') {
return ($aSortValueNull - $bSortValueNull);
}
} elseif (!$aSortValueNull && !$bSortValueNull) {
if ($aSortValue != $bSortValue) {
return ($aSortValue > $bSortValue) ? 1 : -1;
}
}
// never assume equality; fallback to original order
$aIndex = array_search($a, $varKeys);
$bIndex = array_search($b, $varKeys);
return ($aIndex > $bIndex) ? 1 : -1;
});
if ($removeItems) {
$var = array_diff_key($var, $removeItems);
}
return $var;
} | [
"public",
"function",
"sortByFilter",
"(",
"$",
"var",
",",
"$",
"sortKeyPath",
",",
"$",
"fallback",
"=",
"'bottom'",
")",
"{",
"if",
"(",
"is_object",
"(",
"$",
"var",
")",
"&&",
"(",
"$",
"var",
"instanceof",
"Traversable",
")",
")",
"{",
"$",
"var",
"=",
"iterator_to_array",
"(",
"$",
"var",
",",
"true",
")",
";",
"}",
"elseif",
"(",
"!",
"is_array",
"(",
"$",
"var",
")",
")",
"{",
"throw",
"new",
"Twig_Error_Runtime",
"(",
"sprintf",
"(",
"'The sort_by filter only works with arrays or \"Traversable\", got \"%s\"'",
",",
"is_object",
"(",
"$",
"var",
")",
"?",
"get_class",
"(",
"$",
"var",
")",
":",
"gettype",
"(",
"$",
"var",
")",
")",
")",
";",
"}",
"if",
"(",
"(",
"$",
"fallback",
"!==",
"'top'",
")",
"&&",
"(",
"$",
"fallback",
"!==",
"'bottom'",
")",
"&&",
"(",
"$",
"fallback",
"!==",
"'keep'",
")",
"&&",
"(",
"$",
"fallback",
"!==",
"\"remove\"",
")",
")",
"{",
"throw",
"new",
"Twig_Error_Runtime",
"(",
"'The sort_by filter only supports the \"top\", \"bottom\", \"keep\" and \"remove\" fallbacks'",
")",
";",
"}",
"$",
"twigExtension",
"=",
"$",
"this",
";",
"$",
"varKeys",
"=",
"array_keys",
"(",
"$",
"var",
")",
";",
"$",
"removeItems",
"=",
"array",
"(",
")",
";",
"uksort",
"(",
"$",
"var",
",",
"function",
"(",
"$",
"a",
",",
"$",
"b",
")",
"use",
"(",
"$",
"twigExtension",
",",
"$",
"var",
",",
"$",
"varKeys",
",",
"$",
"sortKeyPath",
",",
"$",
"fallback",
",",
"&",
"$",
"removeItems",
")",
"{",
"$",
"aSortValue",
"=",
"$",
"twigExtension",
"->",
"getKeyOfVar",
"(",
"$",
"var",
"[",
"$",
"a",
"]",
",",
"$",
"sortKeyPath",
")",
";",
"$",
"aSortValueNull",
"=",
"(",
"$",
"aSortValue",
"===",
"null",
")",
";",
"$",
"bSortValue",
"=",
"$",
"twigExtension",
"->",
"getKeyOfVar",
"(",
"$",
"var",
"[",
"$",
"b",
"]",
",",
"$",
"sortKeyPath",
")",
";",
"$",
"bSortValueNull",
"=",
"(",
"$",
"bSortValue",
"===",
"null",
")",
";",
"if",
"(",
"(",
"$",
"fallback",
"===",
"'remove'",
")",
"&&",
"(",
"$",
"aSortValueNull",
"||",
"$",
"bSortValueNull",
")",
")",
"{",
"if",
"(",
"$",
"aSortValueNull",
")",
"{",
"$",
"removeItems",
"[",
"$",
"a",
"]",
"=",
"$",
"var",
"[",
"$",
"a",
"]",
";",
"}",
"if",
"(",
"$",
"bSortValueNull",
")",
"{",
"$",
"removeItems",
"[",
"$",
"b",
"]",
"=",
"$",
"var",
"[",
"$",
"b",
"]",
";",
"}",
"return",
"(",
"$",
"aSortValueNull",
"-",
"$",
"bSortValueNull",
")",
";",
"}",
"elseif",
"(",
"$",
"aSortValueNull",
"xor",
"$",
"bSortValueNull",
")",
"{",
"if",
"(",
"$",
"fallback",
"===",
"'top'",
")",
"{",
"return",
"(",
"$",
"aSortValueNull",
"-",
"$",
"bSortValueNull",
")",
"*",
"-",
"1",
";",
"}",
"elseif",
"(",
"$",
"fallback",
"===",
"'bottom'",
")",
"{",
"return",
"(",
"$",
"aSortValueNull",
"-",
"$",
"bSortValueNull",
")",
";",
"}",
"}",
"elseif",
"(",
"!",
"$",
"aSortValueNull",
"&&",
"!",
"$",
"bSortValueNull",
")",
"{",
"if",
"(",
"$",
"aSortValue",
"!=",
"$",
"bSortValue",
")",
"{",
"return",
"(",
"$",
"aSortValue",
">",
"$",
"bSortValue",
")",
"?",
"1",
":",
"-",
"1",
";",
"}",
"}",
"// never assume equality; fallback to original order",
"$",
"aIndex",
"=",
"array_search",
"(",
"$",
"a",
",",
"$",
"varKeys",
")",
";",
"$",
"bIndex",
"=",
"array_search",
"(",
"$",
"b",
",",
"$",
"varKeys",
")",
";",
"return",
"(",
"$",
"aIndex",
">",
"$",
"bIndex",
")",
"?",
"1",
":",
"-",
"1",
";",
"}",
")",
";",
"if",
"(",
"$",
"removeItems",
")",
"{",
"$",
"var",
"=",
"array_diff_key",
"(",
"$",
"var",
",",
"$",
"removeItems",
")",
";",
"}",
"return",
"$",
"var",
";",
"}"
] | Sorts an array by one of its keys or a arbitrary deep sub-key
This method is registered as the Twig `sort_by` filter. You can use this
filter to e.g. sort the pages array by a arbitrary meta value. Calling
`{{ pages|sort_by([ "meta", "nav" ]) }}` returns all pages sorted by the
meta value `nav`. The sorting algorithm will never assume equality of
two values, it will then fall back to the original order. The result is
always sorted in ascending order, apply Twigs `reverse` filter to
achieve a descending order.
@param array|Traversable $var variable to sort
@param mixed $sortKeyPath key to use for sorting; either
a scalar or a array interpreted as key path (i.e. ['foo', 'bar']
will sort $var by $item['foo']['bar'])
@param string $fallback specify what to do with items
which don't contain the specified sort key; use "bottom" (default)
to move these items to the end of the sorted array, "top" to rank
them first, "keep" to keep the original order, or "remove" to remove
these items
@return array sorted array | [
"Sorts",
"an",
"array",
"by",
"one",
"of",
"its",
"keys",
"or",
"a",
"arbitrary",
"deep",
"sub",
"-",
"key"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/PicoTwigExtension.php#L172-L229 | train |
picocms/Pico | lib/PicoTwigExtension.php | PicoTwigExtension.getKeyOfVar | public static function getKeyOfVar($var, $keyPath)
{
if (!$keyPath) {
return null;
} elseif (!is_array($keyPath)) {
$keyPath = array($keyPath);
}
foreach ($keyPath as $key) {
if (is_object($var)) {
if ($var instanceof ArrayAccess) {
// use ArrayAccess, see below
} elseif ($var instanceof Traversable) {
$var = iterator_to_array($var);
} elseif (isset($var->{$key})) {
$var = $var->{$key};
continue;
} elseif (is_callable(array($var, 'get' . ucfirst($key)))) {
try {
$var = call_user_func(array($var, 'get' . ucfirst($key)));
continue;
} catch (BadMethodCallException $e) {
return null;
}
} else {
return null;
}
} elseif (!is_array($var)) {
return null;
}
if (isset($var[$key])) {
$var = $var[$key];
continue;
}
return null;
}
return $var;
} | php | public static function getKeyOfVar($var, $keyPath)
{
if (!$keyPath) {
return null;
} elseif (!is_array($keyPath)) {
$keyPath = array($keyPath);
}
foreach ($keyPath as $key) {
if (is_object($var)) {
if ($var instanceof ArrayAccess) {
// use ArrayAccess, see below
} elseif ($var instanceof Traversable) {
$var = iterator_to_array($var);
} elseif (isset($var->{$key})) {
$var = $var->{$key};
continue;
} elseif (is_callable(array($var, 'get' . ucfirst($key)))) {
try {
$var = call_user_func(array($var, 'get' . ucfirst($key)));
continue;
} catch (BadMethodCallException $e) {
return null;
}
} else {
return null;
}
} elseif (!is_array($var)) {
return null;
}
if (isset($var[$key])) {
$var = $var[$key];
continue;
}
return null;
}
return $var;
} | [
"public",
"static",
"function",
"getKeyOfVar",
"(",
"$",
"var",
",",
"$",
"keyPath",
")",
"{",
"if",
"(",
"!",
"$",
"keyPath",
")",
"{",
"return",
"null",
";",
"}",
"elseif",
"(",
"!",
"is_array",
"(",
"$",
"keyPath",
")",
")",
"{",
"$",
"keyPath",
"=",
"array",
"(",
"$",
"keyPath",
")",
";",
"}",
"foreach",
"(",
"$",
"keyPath",
"as",
"$",
"key",
")",
"{",
"if",
"(",
"is_object",
"(",
"$",
"var",
")",
")",
"{",
"if",
"(",
"$",
"var",
"instanceof",
"ArrayAccess",
")",
"{",
"// use ArrayAccess, see below",
"}",
"elseif",
"(",
"$",
"var",
"instanceof",
"Traversable",
")",
"{",
"$",
"var",
"=",
"iterator_to_array",
"(",
"$",
"var",
")",
";",
"}",
"elseif",
"(",
"isset",
"(",
"$",
"var",
"->",
"{",
"$",
"key",
"}",
")",
")",
"{",
"$",
"var",
"=",
"$",
"var",
"->",
"{",
"$",
"key",
"}",
";",
"continue",
";",
"}",
"elseif",
"(",
"is_callable",
"(",
"array",
"(",
"$",
"var",
",",
"'get'",
".",
"ucfirst",
"(",
"$",
"key",
")",
")",
")",
")",
"{",
"try",
"{",
"$",
"var",
"=",
"call_user_func",
"(",
"array",
"(",
"$",
"var",
",",
"'get'",
".",
"ucfirst",
"(",
"$",
"key",
")",
")",
")",
";",
"continue",
";",
"}",
"catch",
"(",
"BadMethodCallException",
"$",
"e",
")",
"{",
"return",
"null",
";",
"}",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}",
"elseif",
"(",
"!",
"is_array",
"(",
"$",
"var",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"var",
"[",
"$",
"key",
"]",
")",
")",
"{",
"$",
"var",
"=",
"$",
"var",
"[",
"$",
"key",
"]",
";",
"continue",
";",
"}",
"return",
"null",
";",
"}",
"return",
"$",
"var",
";",
"}"
] | Returns the value of a variable item specified by a scalar key or a
arbitrary deep sub-key using a key path
@param array|Traversable|ArrayAccess|object $var base variable
@param mixed $keyPath scalar key or a
array interpreted as key path (when passing e.g. ['foo', 'bar'],
the method will return $var['foo']['bar']) specifying the value
@return mixed the requested value or NULL when the given key or key path
didn't match | [
"Returns",
"the",
"value",
"of",
"a",
"variable",
"item",
"specified",
"by",
"a",
"scalar",
"key",
"or",
"a",
"arbitrary",
"deep",
"sub",
"-",
"key",
"using",
"a",
"key",
"path"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/PicoTwigExtension.php#L243-L283 | train |
picocms/Pico | lib/AbstractPicoPlugin.php | AbstractPicoPlugin.getPluginConfig | public function getPluginConfig($configName = null, $default = null)
{
$pluginConfig = $this->getConfig(get_called_class(), array());
if ($configName === null) {
return $pluginConfig;
}
return isset($pluginConfig[$configName]) ? $pluginConfig[$configName] : $default;
} | php | public function getPluginConfig($configName = null, $default = null)
{
$pluginConfig = $this->getConfig(get_called_class(), array());
if ($configName === null) {
return $pluginConfig;
}
return isset($pluginConfig[$configName]) ? $pluginConfig[$configName] : $default;
} | [
"public",
"function",
"getPluginConfig",
"(",
"$",
"configName",
"=",
"null",
",",
"$",
"default",
"=",
"null",
")",
"{",
"$",
"pluginConfig",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"get_called_class",
"(",
")",
",",
"array",
"(",
")",
")",
";",
"if",
"(",
"$",
"configName",
"===",
"null",
")",
"{",
"return",
"$",
"pluginConfig",
";",
"}",
"return",
"isset",
"(",
"$",
"pluginConfig",
"[",
"$",
"configName",
"]",
")",
"?",
"$",
"pluginConfig",
"[",
"$",
"configName",
"]",
":",
"$",
"default",
";",
"}"
] | Returns either the value of the specified plugin config variable or
the config array
@param string $configName optional name of a config variable
@param mixed $default optional default value to return when the
named config variable doesn't exist
@return mixed if no name of a config variable has been supplied, the
plugin's config array is returned; otherwise it returns either the
value of the named config variable, or, if the named config variable
doesn't exist, the provided default value or NULL | [
"Returns",
"either",
"the",
"value",
"of",
"the",
"specified",
"plugin",
"config",
"variable",
"or",
"the",
"config",
"array"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/AbstractPicoPlugin.php#L175-L184 | train |
picocms/Pico | lib/AbstractPicoPlugin.php | AbstractPicoPlugin.checkDependencies | protected function checkDependencies($recursive)
{
foreach ($this->getDependencies() as $pluginName) {
try {
$plugin = $this->getPlugin($pluginName);
} catch (RuntimeException $e) {
throw new RuntimeException(
"Unable to enable plugin '" . get_called_class() . "': "
. "Required plugin '" . $pluginName . "' not found"
);
}
// plugins which don't implement PicoPluginInterface are always enabled
if (($plugin instanceof PicoPluginInterface) && !$plugin->isEnabled()) {
if ($recursive) {
if (!$plugin->isStatusChanged()) {
$plugin->setEnabled(true, true, true);
} else {
throw new RuntimeException(
"Unable to enable plugin '" . get_called_class() . "': "
. "Required plugin '" . $pluginName . "' was disabled manually"
);
}
} else {
throw new RuntimeException(
"Unable to enable plugin '" . get_called_class() . "': "
. "Required plugin '" . $pluginName . "' is disabled"
);
}
}
}
} | php | protected function checkDependencies($recursive)
{
foreach ($this->getDependencies() as $pluginName) {
try {
$plugin = $this->getPlugin($pluginName);
} catch (RuntimeException $e) {
throw new RuntimeException(
"Unable to enable plugin '" . get_called_class() . "': "
. "Required plugin '" . $pluginName . "' not found"
);
}
// plugins which don't implement PicoPluginInterface are always enabled
if (($plugin instanceof PicoPluginInterface) && !$plugin->isEnabled()) {
if ($recursive) {
if (!$plugin->isStatusChanged()) {
$plugin->setEnabled(true, true, true);
} else {
throw new RuntimeException(
"Unable to enable plugin '" . get_called_class() . "': "
. "Required plugin '" . $pluginName . "' was disabled manually"
);
}
} else {
throw new RuntimeException(
"Unable to enable plugin '" . get_called_class() . "': "
. "Required plugin '" . $pluginName . "' is disabled"
);
}
}
}
} | [
"protected",
"function",
"checkDependencies",
"(",
"$",
"recursive",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getDependencies",
"(",
")",
"as",
"$",
"pluginName",
")",
"{",
"try",
"{",
"$",
"plugin",
"=",
"$",
"this",
"->",
"getPlugin",
"(",
"$",
"pluginName",
")",
";",
"}",
"catch",
"(",
"RuntimeException",
"$",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Unable to enable plugin '\"",
".",
"get_called_class",
"(",
")",
".",
"\"': \"",
".",
"\"Required plugin '\"",
".",
"$",
"pluginName",
".",
"\"' not found\"",
")",
";",
"}",
"// plugins which don't implement PicoPluginInterface are always enabled",
"if",
"(",
"(",
"$",
"plugin",
"instanceof",
"PicoPluginInterface",
")",
"&&",
"!",
"$",
"plugin",
"->",
"isEnabled",
"(",
")",
")",
"{",
"if",
"(",
"$",
"recursive",
")",
"{",
"if",
"(",
"!",
"$",
"plugin",
"->",
"isStatusChanged",
"(",
")",
")",
"{",
"$",
"plugin",
"->",
"setEnabled",
"(",
"true",
",",
"true",
",",
"true",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Unable to enable plugin '\"",
".",
"get_called_class",
"(",
")",
".",
"\"': \"",
".",
"\"Required plugin '\"",
".",
"$",
"pluginName",
".",
"\"' was disabled manually\"",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Unable to enable plugin '\"",
".",
"get_called_class",
"(",
")",
".",
"\"': \"",
".",
"\"Required plugin '\"",
".",
"$",
"pluginName",
".",
"\"' is disabled\"",
")",
";",
"}",
"}",
"}",
"}"
] | Enables all plugins which this plugin depends on
@see PicoPluginInterface::getDependencies()
@param bool $recursive enable required plugins automatically
@return void
@throws RuntimeException thrown when a dependency fails | [
"Enables",
"all",
"plugins",
"which",
"this",
"plugin",
"depends",
"on"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/AbstractPicoPlugin.php#L219-L250 | train |
picocms/Pico | lib/AbstractPicoPlugin.php | AbstractPicoPlugin.checkDependants | protected function checkDependants($recursive)
{
$dependants = $this->getDependants();
if ($dependants) {
if ($recursive) {
foreach ($this->getDependants() as $pluginName => $plugin) {
if ($plugin->isEnabled()) {
if (!$plugin->isStatusChanged()) {
$plugin->setEnabled(false, true, true);
} else {
throw new RuntimeException(
"Unable to disable plugin '" . get_called_class() . "': "
. "Required by manually enabled plugin '" . $pluginName . "'"
);
}
}
}
} else {
$dependantsList = 'plugin' . ((count($dependants) > 1) ? 's' : '') . ' '
. "'" . implode("', '", array_keys($dependants)) . "'";
throw new RuntimeException(
"Unable to disable plugin '" . get_called_class() . "': "
. "Required by " . $dependantsList
);
}
}
} | php | protected function checkDependants($recursive)
{
$dependants = $this->getDependants();
if ($dependants) {
if ($recursive) {
foreach ($this->getDependants() as $pluginName => $plugin) {
if ($plugin->isEnabled()) {
if (!$plugin->isStatusChanged()) {
$plugin->setEnabled(false, true, true);
} else {
throw new RuntimeException(
"Unable to disable plugin '" . get_called_class() . "': "
. "Required by manually enabled plugin '" . $pluginName . "'"
);
}
}
}
} else {
$dependantsList = 'plugin' . ((count($dependants) > 1) ? 's' : '') . ' '
. "'" . implode("', '", array_keys($dependants)) . "'";
throw new RuntimeException(
"Unable to disable plugin '" . get_called_class() . "': "
. "Required by " . $dependantsList
);
}
}
} | [
"protected",
"function",
"checkDependants",
"(",
"$",
"recursive",
")",
"{",
"$",
"dependants",
"=",
"$",
"this",
"->",
"getDependants",
"(",
")",
";",
"if",
"(",
"$",
"dependants",
")",
"{",
"if",
"(",
"$",
"recursive",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getDependants",
"(",
")",
"as",
"$",
"pluginName",
"=>",
"$",
"plugin",
")",
"{",
"if",
"(",
"$",
"plugin",
"->",
"isEnabled",
"(",
")",
")",
"{",
"if",
"(",
"!",
"$",
"plugin",
"->",
"isStatusChanged",
"(",
")",
")",
"{",
"$",
"plugin",
"->",
"setEnabled",
"(",
"false",
",",
"true",
",",
"true",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Unable to disable plugin '\"",
".",
"get_called_class",
"(",
")",
".",
"\"': \"",
".",
"\"Required by manually enabled plugin '\"",
".",
"$",
"pluginName",
".",
"\"'\"",
")",
";",
"}",
"}",
"}",
"}",
"else",
"{",
"$",
"dependantsList",
"=",
"'plugin'",
".",
"(",
"(",
"count",
"(",
"$",
"dependants",
")",
">",
"1",
")",
"?",
"'s'",
":",
"''",
")",
".",
"' '",
".",
"\"'\"",
".",
"implode",
"(",
"\"', '\"",
",",
"array_keys",
"(",
"$",
"dependants",
")",
")",
".",
"\"'\"",
";",
"throw",
"new",
"RuntimeException",
"(",
"\"Unable to disable plugin '\"",
".",
"get_called_class",
"(",
")",
".",
"\"': \"",
".",
"\"Required by \"",
".",
"$",
"dependantsList",
")",
";",
"}",
"}",
"}"
] | Disables all plugins which depend on this plugin
@see PicoPluginInterface::getDependants()
@param bool $recursive disabled dependant plugins automatically
@return void
@throws RuntimeException thrown when a dependency fails | [
"Disables",
"all",
"plugins",
"which",
"depend",
"on",
"this",
"plugin"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/AbstractPicoPlugin.php#L271-L297 | train |
picocms/Pico | lib/AbstractPicoPlugin.php | AbstractPicoPlugin.checkCompatibility | protected function checkCompatibility()
{
if ($this->nativePlugin === null) {
$picoClassName = get_class($this->pico);
$picoApiVersion = defined($picoClassName . '::API_VERSION') ? $picoClassName::API_VERSION : 1;
$pluginApiVersion = defined('static::API_VERSION') ? static::API_VERSION : 1;
$this->nativePlugin = ($pluginApiVersion === $picoApiVersion);
if (!$this->nativePlugin && ($pluginApiVersion > $picoApiVersion)) {
throw new RuntimeException(
"Unable to enable plugin '" . get_called_class() . "': The plugin's API (version "
. $pluginApiVersion . ") isn't compatible with Pico's API (version " . $picoApiVersion . ")"
);
}
}
} | php | protected function checkCompatibility()
{
if ($this->nativePlugin === null) {
$picoClassName = get_class($this->pico);
$picoApiVersion = defined($picoClassName . '::API_VERSION') ? $picoClassName::API_VERSION : 1;
$pluginApiVersion = defined('static::API_VERSION') ? static::API_VERSION : 1;
$this->nativePlugin = ($pluginApiVersion === $picoApiVersion);
if (!$this->nativePlugin && ($pluginApiVersion > $picoApiVersion)) {
throw new RuntimeException(
"Unable to enable plugin '" . get_called_class() . "': The plugin's API (version "
. $pluginApiVersion . ") isn't compatible with Pico's API (version " . $picoApiVersion . ")"
);
}
}
} | [
"protected",
"function",
"checkCompatibility",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"nativePlugin",
"===",
"null",
")",
"{",
"$",
"picoClassName",
"=",
"get_class",
"(",
"$",
"this",
"->",
"pico",
")",
";",
"$",
"picoApiVersion",
"=",
"defined",
"(",
"$",
"picoClassName",
".",
"'::API_VERSION'",
")",
"?",
"$",
"picoClassName",
"::",
"API_VERSION",
":",
"1",
";",
"$",
"pluginApiVersion",
"=",
"defined",
"(",
"'static::API_VERSION'",
")",
"?",
"static",
"::",
"API_VERSION",
":",
"1",
";",
"$",
"this",
"->",
"nativePlugin",
"=",
"(",
"$",
"pluginApiVersion",
"===",
"$",
"picoApiVersion",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"nativePlugin",
"&&",
"(",
"$",
"pluginApiVersion",
">",
"$",
"picoApiVersion",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Unable to enable plugin '\"",
".",
"get_called_class",
"(",
")",
".",
"\"': The plugin's API (version \"",
".",
"$",
"pluginApiVersion",
".",
"\") isn't compatible with Pico's API (version \"",
".",
"$",
"picoApiVersion",
".",
"\")\"",
")",
";",
"}",
"}",
"}"
] | Checks compatibility with Pico's API version
Pico automatically adds a dependency to {@see PicoDeprecated} when the
plugin's API is older than Pico's API. {@see PicoDeprecated} furthermore
throws a exception when it can't provide compatibility in such cases.
However, we still have to decide whether this plugin is compatible to
newer API versions, what requires some special (version specific)
precaution and is therefore usually not the case.
@return void
@throws RuntimeException thrown when the plugin's and Pico's API aren't
compatible | [
"Checks",
"compatibility",
"with",
"Pico",
"s",
"API",
"version"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/AbstractPicoPlugin.php#L335-L351 | train |
picocms/Pico | lib/Pico.php | Pico.loadPlugin | public function loadPlugin($plugin)
{
if (!is_object($plugin)) {
$className = (string) $plugin;
if (class_exists($className)) {
$plugin = new $className($this);
} else {
throw new RuntimeException("Unable to load plugin '" . $className . "': Class not found");
}
}
$className = get_class($plugin);
if (!($plugin instanceof PicoPluginInterface)) {
throw new RuntimeException(
"Unable to load plugin '" . $className . "': "
. "Manually loaded plugins must implement 'PicoPluginInterface'"
);
}
$this->plugins[$className] = $plugin;
if (defined($className . '::API_VERSION') && ($className::API_VERSION >= static::API_VERSION)) {
$this->nativePlugins[$className] = $plugin;
}
// trigger onPluginManuallyLoaded event
// the event is also triggered on the newly loaded plugin, allowing you to distinguish manual and auto loading
$this->triggerEvent('onPluginManuallyLoaded', array($plugin));
return $plugin;
} | php | public function loadPlugin($plugin)
{
if (!is_object($plugin)) {
$className = (string) $plugin;
if (class_exists($className)) {
$plugin = new $className($this);
} else {
throw new RuntimeException("Unable to load plugin '" . $className . "': Class not found");
}
}
$className = get_class($plugin);
if (!($plugin instanceof PicoPluginInterface)) {
throw new RuntimeException(
"Unable to load plugin '" . $className . "': "
. "Manually loaded plugins must implement 'PicoPluginInterface'"
);
}
$this->plugins[$className] = $plugin;
if (defined($className . '::API_VERSION') && ($className::API_VERSION >= static::API_VERSION)) {
$this->nativePlugins[$className] = $plugin;
}
// trigger onPluginManuallyLoaded event
// the event is also triggered on the newly loaded plugin, allowing you to distinguish manual and auto loading
$this->triggerEvent('onPluginManuallyLoaded', array($plugin));
return $plugin;
} | [
"public",
"function",
"loadPlugin",
"(",
"$",
"plugin",
")",
"{",
"if",
"(",
"!",
"is_object",
"(",
"$",
"plugin",
")",
")",
"{",
"$",
"className",
"=",
"(",
"string",
")",
"$",
"plugin",
";",
"if",
"(",
"class_exists",
"(",
"$",
"className",
")",
")",
"{",
"$",
"plugin",
"=",
"new",
"$",
"className",
"(",
"$",
"this",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Unable to load plugin '\"",
".",
"$",
"className",
".",
"\"': Class not found\"",
")",
";",
"}",
"}",
"$",
"className",
"=",
"get_class",
"(",
"$",
"plugin",
")",
";",
"if",
"(",
"!",
"(",
"$",
"plugin",
"instanceof",
"PicoPluginInterface",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Unable to load plugin '\"",
".",
"$",
"className",
".",
"\"': \"",
".",
"\"Manually loaded plugins must implement 'PicoPluginInterface'\"",
")",
";",
"}",
"$",
"this",
"->",
"plugins",
"[",
"$",
"className",
"]",
"=",
"$",
"plugin",
";",
"if",
"(",
"defined",
"(",
"$",
"className",
".",
"'::API_VERSION'",
")",
"&&",
"(",
"$",
"className",
"::",
"API_VERSION",
">=",
"static",
"::",
"API_VERSION",
")",
")",
"{",
"$",
"this",
"->",
"nativePlugins",
"[",
"$",
"className",
"]",
"=",
"$",
"plugin",
";",
"}",
"// trigger onPluginManuallyLoaded event",
"// the event is also triggered on the newly loaded plugin, allowing you to distinguish manual and auto loading",
"$",
"this",
"->",
"triggerEvent",
"(",
"'onPluginManuallyLoaded'",
",",
"array",
"(",
"$",
"plugin",
")",
")",
";",
"return",
"$",
"plugin",
";",
"}"
] | Manually loads a plugin
Manually loaded plugins MUST implement {@see PicoPluginInterface}. They
are simply appended to the plugins array without any additional checks,
so you might get unexpected results, depending on *when* you're loading
a plugin. You SHOULD NOT load plugins after a event has been triggered
by Pico. In-depth knowledge of Pico's inner workings is strongly advised
otherwise, and you MUST NOT rely on {@see PicoDeprecated} to maintain
backward compatibility in such cases.
If you e.g. load a plugin after the `onPluginsLoaded` event, Pico
doesn't guarantee the plugin's order ({@see Pico::sortPlugins()}).
Already triggered events won't get triggered on the manually loaded
plugin. Thus you SHOULD load plugins either before {@see Pico::run()}
is called, or via the constructor of another plugin (i.e. the plugin's
`__construct()` method; plugins are instanced in
{@see Pico::loadPlugins()}).
This method triggers the `onPluginManuallyLoaded` event.
@see Pico::loadPlugins()
@see Pico::getPlugin()
@see Pico::getPlugins()
@param PicoPluginInterface|string $plugin either the class name of a
plugin to instantiate or a plugin instance
@return PicoPluginInterface instance of the loaded plugin
@throws RuntimeException thrown when a plugin couldn't be loaded | [
"Manually",
"loads",
"a",
"plugin"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/Pico.php#L708-L739 | train |
picocms/Pico | lib/Pico.php | Pico.sortPlugins | protected function sortPlugins()
{
$plugins = $this->plugins;
$nativePlugins = $this->nativePlugins;
$sortedPlugins = array();
$sortedNativePlugins = array();
$visitedPlugins = array();
$visitPlugin = function ($plugin) use (
$plugins,
$nativePlugins,
&$sortedPlugins,
&$sortedNativePlugins,
&$visitedPlugins,
&$visitPlugin
) {
$pluginName = get_class($plugin);
// skip already visited plugins and ignore circular dependencies
if (!isset($visitedPlugins[$pluginName])) {
$visitedPlugins[$pluginName] = true;
$dependencies = array();
if ($plugin instanceof PicoPluginInterface) {
$dependencies = $plugin->getDependencies();
}
if (!isset($nativePlugins[$pluginName])) {
$dependencies[] = 'PicoDeprecated';
}
foreach ($dependencies as $dependency) {
// ignore missing dependencies
// this is only a problem when the user tries to enable this plugin
if (isset($plugins[$dependency])) {
$visitPlugin($plugins[$dependency]);
}
}
$sortedPlugins[$pluginName] = $plugin;
if (isset($nativePlugins[$pluginName])) {
$sortedNativePlugins[$pluginName] = $plugin;
}
}
};
if (isset($this->plugins['PicoDeprecated'])) {
$visitPlugin($this->plugins['PicoDeprecated']);
}
foreach ($this->plugins as $plugin) {
$visitPlugin($plugin);
}
$this->plugins = $sortedPlugins;
$this->nativePlugins = $sortedNativePlugins;
} | php | protected function sortPlugins()
{
$plugins = $this->plugins;
$nativePlugins = $this->nativePlugins;
$sortedPlugins = array();
$sortedNativePlugins = array();
$visitedPlugins = array();
$visitPlugin = function ($plugin) use (
$plugins,
$nativePlugins,
&$sortedPlugins,
&$sortedNativePlugins,
&$visitedPlugins,
&$visitPlugin
) {
$pluginName = get_class($plugin);
// skip already visited plugins and ignore circular dependencies
if (!isset($visitedPlugins[$pluginName])) {
$visitedPlugins[$pluginName] = true;
$dependencies = array();
if ($plugin instanceof PicoPluginInterface) {
$dependencies = $plugin->getDependencies();
}
if (!isset($nativePlugins[$pluginName])) {
$dependencies[] = 'PicoDeprecated';
}
foreach ($dependencies as $dependency) {
// ignore missing dependencies
// this is only a problem when the user tries to enable this plugin
if (isset($plugins[$dependency])) {
$visitPlugin($plugins[$dependency]);
}
}
$sortedPlugins[$pluginName] = $plugin;
if (isset($nativePlugins[$pluginName])) {
$sortedNativePlugins[$pluginName] = $plugin;
}
}
};
if (isset($this->plugins['PicoDeprecated'])) {
$visitPlugin($this->plugins['PicoDeprecated']);
}
foreach ($this->plugins as $plugin) {
$visitPlugin($plugin);
}
$this->plugins = $sortedPlugins;
$this->nativePlugins = $sortedNativePlugins;
} | [
"protected",
"function",
"sortPlugins",
"(",
")",
"{",
"$",
"plugins",
"=",
"$",
"this",
"->",
"plugins",
";",
"$",
"nativePlugins",
"=",
"$",
"this",
"->",
"nativePlugins",
";",
"$",
"sortedPlugins",
"=",
"array",
"(",
")",
";",
"$",
"sortedNativePlugins",
"=",
"array",
"(",
")",
";",
"$",
"visitedPlugins",
"=",
"array",
"(",
")",
";",
"$",
"visitPlugin",
"=",
"function",
"(",
"$",
"plugin",
")",
"use",
"(",
"$",
"plugins",
",",
"$",
"nativePlugins",
",",
"&",
"$",
"sortedPlugins",
",",
"&",
"$",
"sortedNativePlugins",
",",
"&",
"$",
"visitedPlugins",
",",
"&",
"$",
"visitPlugin",
")",
"{",
"$",
"pluginName",
"=",
"get_class",
"(",
"$",
"plugin",
")",
";",
"// skip already visited plugins and ignore circular dependencies",
"if",
"(",
"!",
"isset",
"(",
"$",
"visitedPlugins",
"[",
"$",
"pluginName",
"]",
")",
")",
"{",
"$",
"visitedPlugins",
"[",
"$",
"pluginName",
"]",
"=",
"true",
";",
"$",
"dependencies",
"=",
"array",
"(",
")",
";",
"if",
"(",
"$",
"plugin",
"instanceof",
"PicoPluginInterface",
")",
"{",
"$",
"dependencies",
"=",
"$",
"plugin",
"->",
"getDependencies",
"(",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"nativePlugins",
"[",
"$",
"pluginName",
"]",
")",
")",
"{",
"$",
"dependencies",
"[",
"]",
"=",
"'PicoDeprecated'",
";",
"}",
"foreach",
"(",
"$",
"dependencies",
"as",
"$",
"dependency",
")",
"{",
"// ignore missing dependencies",
"// this is only a problem when the user tries to enable this plugin",
"if",
"(",
"isset",
"(",
"$",
"plugins",
"[",
"$",
"dependency",
"]",
")",
")",
"{",
"$",
"visitPlugin",
"(",
"$",
"plugins",
"[",
"$",
"dependency",
"]",
")",
";",
"}",
"}",
"$",
"sortedPlugins",
"[",
"$",
"pluginName",
"]",
"=",
"$",
"plugin",
";",
"if",
"(",
"isset",
"(",
"$",
"nativePlugins",
"[",
"$",
"pluginName",
"]",
")",
")",
"{",
"$",
"sortedNativePlugins",
"[",
"$",
"pluginName",
"]",
"=",
"$",
"plugin",
";",
"}",
"}",
"}",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"plugins",
"[",
"'PicoDeprecated'",
"]",
")",
")",
"{",
"$",
"visitPlugin",
"(",
"$",
"this",
"->",
"plugins",
"[",
"'PicoDeprecated'",
"]",
")",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"plugins",
"as",
"$",
"plugin",
")",
"{",
"$",
"visitPlugin",
"(",
"$",
"plugin",
")",
";",
"}",
"$",
"this",
"->",
"plugins",
"=",
"$",
"sortedPlugins",
";",
"$",
"this",
"->",
"nativePlugins",
"=",
"$",
"sortedNativePlugins",
";",
"}"
] | Sorts all loaded plugins using a plugin dependency topology
Execution order matters: if plugin A depends on plugin B, it usually
means that plugin B does stuff which plugin A requires. However, Pico
loads plugins in alphabetical order, so events might get fired on
plugin A before plugin B.
Hence plugins need to be sorted. Pico sorts plugins using a dependency
topology, this means that it moves all plugins, on which a plugin
depends, in front of that plugin. The order isn't touched apart from
that, so they are still sorted alphabetically, as long as this doesn't
interfere with the dependency topology. Circular dependencies are being
ignored; their behavior is undefiend. Missing dependencies are being
ignored until you try to enable the dependant plugin.
This method bases on Marc J. Schmidt's Topological Sort library in
version 1.1.0, licensed under the MIT license. It uses the `ArraySort`
implementation (class `\MJS\TopSort\Implementations\ArraySort`).
@see Pico::loadPlugins()
@see Pico::getPlugins()
@see https://github.com/marcj/topsort.php
Marc J. Schmidt's Topological Sort / Dependency resolver in PHP
@see https://github.com/marcj/topsort.php/blob/1.1.0/src/Implementations/ArraySort.php
\MJS\TopSort\Implementations\ArraySort class
@return void | [
"Sorts",
"all",
"loaded",
"plugins",
"using",
"a",
"plugin",
"dependency",
"topology"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/Pico.php#L770-L825 | train |
picocms/Pico | lib/Pico.php | Pico.getPlugin | public function getPlugin($pluginName)
{
if (isset($this->plugins[$pluginName])) {
return $this->plugins[$pluginName];
}
throw new RuntimeException("Missing plugin '" . $pluginName . "'");
} | php | public function getPlugin($pluginName)
{
if (isset($this->plugins[$pluginName])) {
return $this->plugins[$pluginName];
}
throw new RuntimeException("Missing plugin '" . $pluginName . "'");
} | [
"public",
"function",
"getPlugin",
"(",
"$",
"pluginName",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"plugins",
"[",
"$",
"pluginName",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"plugins",
"[",
"$",
"pluginName",
"]",
";",
"}",
"throw",
"new",
"RuntimeException",
"(",
"\"Missing plugin '\"",
".",
"$",
"pluginName",
".",
"\"'\"",
")",
";",
"}"
] | Returns the instance of a named plugin
Plugins SHOULD implement {@see PicoPluginInterface}, but you MUST NOT
rely on it. For more information see {@see PicoPluginInterface}.
@see Pico::loadPlugins()
@see Pico::getPlugins()
@param string $pluginName name of the plugin
@return object instance of the plugin
@throws RuntimeException thrown when the plugin wasn't found | [
"Returns",
"the",
"instance",
"of",
"a",
"named",
"plugin"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/Pico.php#L842-L849 | train |
picocms/Pico | lib/Pico.php | Pico.getConfig | public function getConfig($configName = null, $default = null)
{
if ($configName !== null) {
return isset($this->config[$configName]) ? $this->config[$configName] : $default;
} else {
return $this->config;
}
} | php | public function getConfig($configName = null, $default = null)
{
if ($configName !== null) {
return isset($this->config[$configName]) ? $this->config[$configName] : $default;
} else {
return $this->config;
}
} | [
"public",
"function",
"getConfig",
"(",
"$",
"configName",
"=",
"null",
",",
"$",
"default",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"configName",
"!==",
"null",
")",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"config",
"[",
"$",
"configName",
"]",
")",
"?",
"$",
"this",
"->",
"config",
"[",
"$",
"configName",
"]",
":",
"$",
"default",
";",
"}",
"else",
"{",
"return",
"$",
"this",
"->",
"config",
";",
"}",
"}"
] | Returns either the value of the specified config variable or
the config array
@see Pico::setConfig()
@see Pico::loadConfig()
@param string $configName optional name of a config variable
@param mixed $default optional default value to return when the
named config variable doesn't exist
@return mixed if no name of a config variable has been supplied, the
config array is returned; otherwise it returns either the value of
the named config variable, or, if the named config variable doesn't
exist, the provided default value or NULL | [
"Returns",
"either",
"the",
"value",
"of",
"the",
"specified",
"config",
"variable",
"or",
"the",
"config",
"array"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/Pico.php#L1019-L1026 | train |
picocms/Pico | lib/Pico.php | Pico.evaluateRequestUrl | protected function evaluateRequestUrl()
{
// use QUERY_STRING; e.g. /pico/?sub/page
$pathComponent = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';
if ($pathComponent) {
$pathComponent = strstr($pathComponent, '&', true) ?: $pathComponent;
if (strpos($pathComponent, '=') === false) {
$this->requestUrl = trim(rawurldecode($pathComponent), '/');
}
}
// use REQUEST_URI (requires URL rewriting); e.g. /pico/sub/page
if (($this->requestUrl === null) && $this->isUrlRewritingEnabled()) {
$scriptName = isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : '/index.php';
$basePath = dirname($scriptName);
$basePath = !in_array($basePath, array('.', '/', '\\'), true) ? $basePath . '/' : '/';
$basePathLength = strlen($basePath);
$requestUri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
if ($requestUri && (substr($requestUri, 0, $basePathLength) === $basePath)) {
$requestUri = substr($requestUri, $basePathLength);
if ($requestUri && (($queryStringPos = strpos($requestUri, '?')) !== false)) {
$requestUri = substr($requestUri, 0, $queryStringPos);
}
if ($requestUri && ($requestUri !== basename($scriptName))) {
$this->requestUrl = rtrim(rawurldecode($requestUri), '/');
}
}
}
if ($this->requestUrl === null) {
$this->requestUrl = '';
}
} | php | protected function evaluateRequestUrl()
{
// use QUERY_STRING; e.g. /pico/?sub/page
$pathComponent = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';
if ($pathComponent) {
$pathComponent = strstr($pathComponent, '&', true) ?: $pathComponent;
if (strpos($pathComponent, '=') === false) {
$this->requestUrl = trim(rawurldecode($pathComponent), '/');
}
}
// use REQUEST_URI (requires URL rewriting); e.g. /pico/sub/page
if (($this->requestUrl === null) && $this->isUrlRewritingEnabled()) {
$scriptName = isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : '/index.php';
$basePath = dirname($scriptName);
$basePath = !in_array($basePath, array('.', '/', '\\'), true) ? $basePath . '/' : '/';
$basePathLength = strlen($basePath);
$requestUri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
if ($requestUri && (substr($requestUri, 0, $basePathLength) === $basePath)) {
$requestUri = substr($requestUri, $basePathLength);
if ($requestUri && (($queryStringPos = strpos($requestUri, '?')) !== false)) {
$requestUri = substr($requestUri, 0, $queryStringPos);
}
if ($requestUri && ($requestUri !== basename($scriptName))) {
$this->requestUrl = rtrim(rawurldecode($requestUri), '/');
}
}
}
if ($this->requestUrl === null) {
$this->requestUrl = '';
}
} | [
"protected",
"function",
"evaluateRequestUrl",
"(",
")",
"{",
"// use QUERY_STRING; e.g. /pico/?sub/page",
"$",
"pathComponent",
"=",
"isset",
"(",
"$",
"_SERVER",
"[",
"'QUERY_STRING'",
"]",
")",
"?",
"$",
"_SERVER",
"[",
"'QUERY_STRING'",
"]",
":",
"''",
";",
"if",
"(",
"$",
"pathComponent",
")",
"{",
"$",
"pathComponent",
"=",
"strstr",
"(",
"$",
"pathComponent",
",",
"'&'",
",",
"true",
")",
"?",
":",
"$",
"pathComponent",
";",
"if",
"(",
"strpos",
"(",
"$",
"pathComponent",
",",
"'='",
")",
"===",
"false",
")",
"{",
"$",
"this",
"->",
"requestUrl",
"=",
"trim",
"(",
"rawurldecode",
"(",
"$",
"pathComponent",
")",
",",
"'/'",
")",
";",
"}",
"}",
"// use REQUEST_URI (requires URL rewriting); e.g. /pico/sub/page",
"if",
"(",
"(",
"$",
"this",
"->",
"requestUrl",
"===",
"null",
")",
"&&",
"$",
"this",
"->",
"isUrlRewritingEnabled",
"(",
")",
")",
"{",
"$",
"scriptName",
"=",
"isset",
"(",
"$",
"_SERVER",
"[",
"'SCRIPT_NAME'",
"]",
")",
"?",
"$",
"_SERVER",
"[",
"'SCRIPT_NAME'",
"]",
":",
"'/index.php'",
";",
"$",
"basePath",
"=",
"dirname",
"(",
"$",
"scriptName",
")",
";",
"$",
"basePath",
"=",
"!",
"in_array",
"(",
"$",
"basePath",
",",
"array",
"(",
"'.'",
",",
"'/'",
",",
"'\\\\'",
")",
",",
"true",
")",
"?",
"$",
"basePath",
".",
"'/'",
":",
"'/'",
";",
"$",
"basePathLength",
"=",
"strlen",
"(",
"$",
"basePath",
")",
";",
"$",
"requestUri",
"=",
"isset",
"(",
"$",
"_SERVER",
"[",
"'REQUEST_URI'",
"]",
")",
"?",
"$",
"_SERVER",
"[",
"'REQUEST_URI'",
"]",
":",
"''",
";",
"if",
"(",
"$",
"requestUri",
"&&",
"(",
"substr",
"(",
"$",
"requestUri",
",",
"0",
",",
"$",
"basePathLength",
")",
"===",
"$",
"basePath",
")",
")",
"{",
"$",
"requestUri",
"=",
"substr",
"(",
"$",
"requestUri",
",",
"$",
"basePathLength",
")",
";",
"if",
"(",
"$",
"requestUri",
"&&",
"(",
"(",
"$",
"queryStringPos",
"=",
"strpos",
"(",
"$",
"requestUri",
",",
"'?'",
")",
")",
"!==",
"false",
")",
")",
"{",
"$",
"requestUri",
"=",
"substr",
"(",
"$",
"requestUri",
",",
"0",
",",
"$",
"queryStringPos",
")",
";",
"}",
"if",
"(",
"$",
"requestUri",
"&&",
"(",
"$",
"requestUri",
"!==",
"basename",
"(",
"$",
"scriptName",
")",
")",
")",
"{",
"$",
"this",
"->",
"requestUrl",
"=",
"rtrim",
"(",
"rawurldecode",
"(",
"$",
"requestUri",
")",
",",
"'/'",
")",
";",
"}",
"}",
"}",
"if",
"(",
"$",
"this",
"->",
"requestUrl",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"requestUrl",
"=",
"''",
";",
"}",
"}"
] | Evaluates the requested URL
Pico uses the `QUERY_STRING` routing method (e.g. `/pico/?sub/page`)
to support SEO-like URLs out-of-the-box with any webserver. You can
still setup URL rewriting to basically remove the `?` from URLs.
However, URL rewriting requires some special configuration of your
webserver, but this should be "basic work" for any webmaster...
With Pico 1.0 you had to setup URL rewriting (e.g. using `mod_rewrite`
on Apache) in a way that rewritten URLs follow the `QUERY_STRING`
principles. Starting with version 2.0, Pico additionally supports the
`REQUEST_URI` routing method, what allows you to simply rewrite all
requests to just `index.php`. Pico then reads the requested page from
the `REQUEST_URI` environment variable provided by the webserver.
Please note that `QUERY_STRING` takes precedence over `REQUEST_URI`.
Pico 0.9 and older required Apache with `mod_rewrite` enabled, thus old
plugins, templates and contents may require you to enable URL rewriting
to work. If you're upgrading from Pico 0.9, you will probably have to
update your rewriting rules.
We recommend you to use the `link` filter in templates to create
internal links, e.g. `{{ "sub/page"|link }}` is equivalent to
`{{ base_url }}/sub/page` and `{{ base_url }}?sub/page`, depending on
enabled URL rewriting. In content files you can use the `%base_url%`
variable; e.g. `%base_url%?sub/page` will be replaced accordingly.
Heads up! Pico always interprets the first parameter as name of the
requested page (provided that the parameter has no value). According to
that you MUST NOT call Pico with a parameter without value as first
parameter (e.g. http://example.com/pico/?someBooleanParam), otherwise
Pico interprets `someBooleanParam` as name of the requested page. Use
`/pico/?someBooleanParam=` or `/pico/?index&someBooleanParam` instead.
@see Pico::getRequestUrl()
@return void | [
"Evaluates",
"the",
"requested",
"URL"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/Pico.php#L1067-L1101 | train |
picocms/Pico | lib/Pico.php | Pico.resolveFilePath | public function resolveFilePath($requestUrl)
{
$contentDir = $this->getConfig('content_dir');
$contentExt = $this->getConfig('content_ext');
if (!$requestUrl) {
return $contentDir . 'index' . $contentExt;
} else {
// prevent content_dir breakouts
$requestUrl = str_replace('\\', '/', $requestUrl);
$requestUrlParts = explode('/', $requestUrl);
$requestFileParts = array();
foreach ($requestUrlParts as $requestUrlPart) {
if (($requestUrlPart === '') || ($requestUrlPart === '.')) {
continue;
} elseif ($requestUrlPart === '..') {
array_pop($requestFileParts);
continue;
}
$requestFileParts[] = $requestUrlPart;
}
if (!$requestFileParts) {
return $contentDir . 'index' . $contentExt;
}
// discover the content file to serve
// Note: $requestFileParts neither contains a trailing nor a leading slash
$requestFile = $contentDir . implode('/', $requestFileParts);
if (is_dir($requestFile)) {
// if no index file is found, try a accordingly named file in the previous dir
// if this file doesn't exist either, show the 404 page, but assume the index
// file as being requested (maintains backward compatibility to Pico < 1.0)
$indexFile = $requestFile . '/index' . $contentExt;
if (file_exists($indexFile) || !file_exists($requestFile . $contentExt)) {
return $indexFile;
}
}
return $requestFile . $contentExt;
}
} | php | public function resolveFilePath($requestUrl)
{
$contentDir = $this->getConfig('content_dir');
$contentExt = $this->getConfig('content_ext');
if (!$requestUrl) {
return $contentDir . 'index' . $contentExt;
} else {
// prevent content_dir breakouts
$requestUrl = str_replace('\\', '/', $requestUrl);
$requestUrlParts = explode('/', $requestUrl);
$requestFileParts = array();
foreach ($requestUrlParts as $requestUrlPart) {
if (($requestUrlPart === '') || ($requestUrlPart === '.')) {
continue;
} elseif ($requestUrlPart === '..') {
array_pop($requestFileParts);
continue;
}
$requestFileParts[] = $requestUrlPart;
}
if (!$requestFileParts) {
return $contentDir . 'index' . $contentExt;
}
// discover the content file to serve
// Note: $requestFileParts neither contains a trailing nor a leading slash
$requestFile = $contentDir . implode('/', $requestFileParts);
if (is_dir($requestFile)) {
// if no index file is found, try a accordingly named file in the previous dir
// if this file doesn't exist either, show the 404 page, but assume the index
// file as being requested (maintains backward compatibility to Pico < 1.0)
$indexFile = $requestFile . '/index' . $contentExt;
if (file_exists($indexFile) || !file_exists($requestFile . $contentExt)) {
return $indexFile;
}
}
return $requestFile . $contentExt;
}
} | [
"public",
"function",
"resolveFilePath",
"(",
"$",
"requestUrl",
")",
"{",
"$",
"contentDir",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'content_dir'",
")",
";",
"$",
"contentExt",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'content_ext'",
")",
";",
"if",
"(",
"!",
"$",
"requestUrl",
")",
"{",
"return",
"$",
"contentDir",
".",
"'index'",
".",
"$",
"contentExt",
";",
"}",
"else",
"{",
"// prevent content_dir breakouts",
"$",
"requestUrl",
"=",
"str_replace",
"(",
"'\\\\'",
",",
"'/'",
",",
"$",
"requestUrl",
")",
";",
"$",
"requestUrlParts",
"=",
"explode",
"(",
"'/'",
",",
"$",
"requestUrl",
")",
";",
"$",
"requestFileParts",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"requestUrlParts",
"as",
"$",
"requestUrlPart",
")",
"{",
"if",
"(",
"(",
"$",
"requestUrlPart",
"===",
"''",
")",
"||",
"(",
"$",
"requestUrlPart",
"===",
"'.'",
")",
")",
"{",
"continue",
";",
"}",
"elseif",
"(",
"$",
"requestUrlPart",
"===",
"'..'",
")",
"{",
"array_pop",
"(",
"$",
"requestFileParts",
")",
";",
"continue",
";",
"}",
"$",
"requestFileParts",
"[",
"]",
"=",
"$",
"requestUrlPart",
";",
"}",
"if",
"(",
"!",
"$",
"requestFileParts",
")",
"{",
"return",
"$",
"contentDir",
".",
"'index'",
".",
"$",
"contentExt",
";",
"}",
"// discover the content file to serve",
"// Note: $requestFileParts neither contains a trailing nor a leading slash",
"$",
"requestFile",
"=",
"$",
"contentDir",
".",
"implode",
"(",
"'/'",
",",
"$",
"requestFileParts",
")",
";",
"if",
"(",
"is_dir",
"(",
"$",
"requestFile",
")",
")",
"{",
"// if no index file is found, try a accordingly named file in the previous dir",
"// if this file doesn't exist either, show the 404 page, but assume the index",
"// file as being requested (maintains backward compatibility to Pico < 1.0)",
"$",
"indexFile",
"=",
"$",
"requestFile",
".",
"'/index'",
".",
"$",
"contentExt",
";",
"if",
"(",
"file_exists",
"(",
"$",
"indexFile",
")",
"||",
"!",
"file_exists",
"(",
"$",
"requestFile",
".",
"$",
"contentExt",
")",
")",
"{",
"return",
"$",
"indexFile",
";",
"}",
"}",
"return",
"$",
"requestFile",
".",
"$",
"contentExt",
";",
"}",
"}"
] | Resolves a given file path to its corresponding content file
This method also prevents `content_dir` breakouts using malicious
request URLs. We don't use `realpath()`, because we neither want to
check for file existance, nor prohibit symlinks which intentionally
point to somewhere outside the `content_dir` folder. It is STRONGLY
RECOMMENDED to use PHP's `open_basedir` feature - always, not just
with Pico!
@see Pico::getRequestFile()
@param string $requestUrl path name (likely from a URL) to resolve
@return string path to the resolved content file | [
"Resolves",
"a",
"given",
"file",
"path",
"to",
"its",
"corresponding",
"content",
"file"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/Pico.php#L1131-L1173 | train |
picocms/Pico | lib/Pico.php | Pico.load404Content | public function load404Content($file)
{
$contentDir = $this->getConfig('content_dir');
$contentDirLength = strlen($contentDir);
$contentExt = $this->getConfig('content_ext');
if (substr($file, 0, $contentDirLength) === $contentDir) {
$errorFileDir = substr($file, $contentDirLength);
while ($errorFileDir !== '.') {
$errorFileDir = dirname($errorFileDir);
$errorFile = $errorFileDir . '/404' . $contentExt;
if (file_exists($contentDir . $errorFile)) {
return $this->loadFileContent($contentDir . $errorFile);
}
}
} elseif (file_exists($contentDir . '404' . $contentExt)) {
// provided that the requested file is not in the regular
// content directory, fallback to Pico's global `404.md`
return $this->loadFileContent($contentDir . '404' . $contentExt);
}
// fallback to built-in error message
$rawErrorContent = "---\n"
. "Title: Error 404\n"
. "Robots: noindex,nofollow\n"
. "---\n\n"
. "# Error 404\n\n"
. "Woops. Looks like this page doesn't exist.\n";
return $rawErrorContent;
} | php | public function load404Content($file)
{
$contentDir = $this->getConfig('content_dir');
$contentDirLength = strlen($contentDir);
$contentExt = $this->getConfig('content_ext');
if (substr($file, 0, $contentDirLength) === $contentDir) {
$errorFileDir = substr($file, $contentDirLength);
while ($errorFileDir !== '.') {
$errorFileDir = dirname($errorFileDir);
$errorFile = $errorFileDir . '/404' . $contentExt;
if (file_exists($contentDir . $errorFile)) {
return $this->loadFileContent($contentDir . $errorFile);
}
}
} elseif (file_exists($contentDir . '404' . $contentExt)) {
// provided that the requested file is not in the regular
// content directory, fallback to Pico's global `404.md`
return $this->loadFileContent($contentDir . '404' . $contentExt);
}
// fallback to built-in error message
$rawErrorContent = "---\n"
. "Title: Error 404\n"
. "Robots: noindex,nofollow\n"
. "---\n\n"
. "# Error 404\n\n"
. "Woops. Looks like this page doesn't exist.\n";
return $rawErrorContent;
} | [
"public",
"function",
"load404Content",
"(",
"$",
"file",
")",
"{",
"$",
"contentDir",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'content_dir'",
")",
";",
"$",
"contentDirLength",
"=",
"strlen",
"(",
"$",
"contentDir",
")",
";",
"$",
"contentExt",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'content_ext'",
")",
";",
"if",
"(",
"substr",
"(",
"$",
"file",
",",
"0",
",",
"$",
"contentDirLength",
")",
"===",
"$",
"contentDir",
")",
"{",
"$",
"errorFileDir",
"=",
"substr",
"(",
"$",
"file",
",",
"$",
"contentDirLength",
")",
";",
"while",
"(",
"$",
"errorFileDir",
"!==",
"'.'",
")",
"{",
"$",
"errorFileDir",
"=",
"dirname",
"(",
"$",
"errorFileDir",
")",
";",
"$",
"errorFile",
"=",
"$",
"errorFileDir",
".",
"'/404'",
".",
"$",
"contentExt",
";",
"if",
"(",
"file_exists",
"(",
"$",
"contentDir",
".",
"$",
"errorFile",
")",
")",
"{",
"return",
"$",
"this",
"->",
"loadFileContent",
"(",
"$",
"contentDir",
".",
"$",
"errorFile",
")",
";",
"}",
"}",
"}",
"elseif",
"(",
"file_exists",
"(",
"$",
"contentDir",
".",
"'404'",
".",
"$",
"contentExt",
")",
")",
"{",
"// provided that the requested file is not in the regular",
"// content directory, fallback to Pico's global `404.md`",
"return",
"$",
"this",
"->",
"loadFileContent",
"(",
"$",
"contentDir",
".",
"'404'",
".",
"$",
"contentExt",
")",
";",
"}",
"// fallback to built-in error message",
"$",
"rawErrorContent",
"=",
"\"---\\n\"",
".",
"\"Title: Error 404\\n\"",
".",
"\"Robots: noindex,nofollow\\n\"",
".",
"\"---\\n\\n\"",
".",
"\"# Error 404\\n\\n\"",
".",
"\"Woops. Looks like this page doesn't exist.\\n\"",
";",
"return",
"$",
"rawErrorContent",
";",
"}"
] | Returns the raw contents of the first found 404 file when traversing
up from the directory the requested file is in
If no suitable `404.md` is found, fallback to a built-in error message.
@see Pico::getRawContent()
@param string $file path to requested (but not existing) file
@return string raw contents of the 404 file | [
"Returns",
"the",
"raw",
"contents",
"of",
"the",
"first",
"found",
"404",
"file",
"when",
"traversing",
"up",
"from",
"the",
"directory",
"the",
"requested",
"file",
"is",
"in"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/Pico.php#L1213-L1244 | train |
picocms/Pico | lib/Pico.php | Pico.getMetaHeaders | public function getMetaHeaders()
{
if ($this->metaHeaders === null) {
$this->metaHeaders = array(
'Title' => 'title',
'Description' => 'description',
'Author' => 'author',
'Date' => 'date',
'Formatted Date' => 'date_formatted',
'Time' => 'time',
'Robots' => 'robots',
'Template' => 'template',
'Hidden' => 'hidden'
);
$this->triggerEvent('onMetaHeaders', array(&$this->metaHeaders));
}
return $this->metaHeaders;
} | php | public function getMetaHeaders()
{
if ($this->metaHeaders === null) {
$this->metaHeaders = array(
'Title' => 'title',
'Description' => 'description',
'Author' => 'author',
'Date' => 'date',
'Formatted Date' => 'date_formatted',
'Time' => 'time',
'Robots' => 'robots',
'Template' => 'template',
'Hidden' => 'hidden'
);
$this->triggerEvent('onMetaHeaders', array(&$this->metaHeaders));
}
return $this->metaHeaders;
} | [
"public",
"function",
"getMetaHeaders",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"metaHeaders",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"metaHeaders",
"=",
"array",
"(",
"'Title'",
"=>",
"'title'",
",",
"'Description'",
"=>",
"'description'",
",",
"'Author'",
"=>",
"'author'",
",",
"'Date'",
"=>",
"'date'",
",",
"'Formatted Date'",
"=>",
"'date_formatted'",
",",
"'Time'",
"=>",
"'time'",
",",
"'Robots'",
"=>",
"'robots'",
",",
"'Template'",
"=>",
"'template'",
",",
"'Hidden'",
"=>",
"'hidden'",
")",
";",
"$",
"this",
"->",
"triggerEvent",
"(",
"'onMetaHeaders'",
",",
"array",
"(",
"&",
"$",
"this",
"->",
"metaHeaders",
")",
")",
";",
"}",
"return",
"$",
"this",
"->",
"metaHeaders",
";",
"}"
] | Returns known meta headers
This method triggers the `onMetaHeaders` event when the known meta
headers weren't assembled yet.
@return string[] known meta headers; the array key specifies the YAML
key to search for, the array value is later used to access the
found value | [
"Returns",
"known",
"meta",
"headers"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/Pico.php#L1281-L1300 | train |
picocms/Pico | lib/Pico.php | Pico.getYamlParser | public function getYamlParser()
{
if ($this->yamlParser === null) {
$this->yamlParser = new \Symfony\Component\Yaml\Parser();
$this->triggerEvent('onYamlParserRegistered', array(&$this->yamlParser));
}
return $this->yamlParser;
} | php | public function getYamlParser()
{
if ($this->yamlParser === null) {
$this->yamlParser = new \Symfony\Component\Yaml\Parser();
$this->triggerEvent('onYamlParserRegistered', array(&$this->yamlParser));
}
return $this->yamlParser;
} | [
"public",
"function",
"getYamlParser",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"yamlParser",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"yamlParser",
"=",
"new",
"\\",
"Symfony",
"\\",
"Component",
"\\",
"Yaml",
"\\",
"Parser",
"(",
")",
";",
"$",
"this",
"->",
"triggerEvent",
"(",
"'onYamlParserRegistered'",
",",
"array",
"(",
"&",
"$",
"this",
"->",
"yamlParser",
")",
")",
";",
"}",
"return",
"$",
"this",
"->",
"yamlParser",
";",
"}"
] | Returns the Symfony YAML parser
This method triggers the `onYamlParserRegistered` event when the Symfony
YAML parser wasn't initiated yet.
@return \Symfony\Component\Yaml\Parser Symfony YAML parser | [
"Returns",
"the",
"Symfony",
"YAML",
"parser"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/Pico.php#L1310-L1318 | train |
picocms/Pico | lib/Pico.php | Pico.parseFileMeta | public function parseFileMeta($rawContent, array $headers)
{
$meta = array();
$pattern = "/^(\/(\*)|---)[[:blank:]]*(?:\r)?\n"
. "(?:(.*?)(?:\r)?\n)?(?(2)\*\/|---)[[:blank:]]*(?:(?:\r)?\n|$)/s";
if (preg_match($pattern, $rawContent, $rawMetaMatches) && isset($rawMetaMatches[3])) {
$meta = $this->getYamlParser()->parse($rawMetaMatches[3]) ?: array();
$meta = is_array($meta) ? $meta : array('title' => $meta);
foreach ($headers as $name => $key) {
if (isset($meta[$name])) {
// rename field (e.g. remove whitespaces)
if ($key != $name) {
$meta[$key] = $meta[$name];
unset($meta[$name]);
}
} elseif (!isset($meta[$key])) {
// guarantee array key existance
$meta[$key] = '';
}
}
if (!empty($meta['date']) || !empty($meta['time'])) {
// workaround for issue #336
// Symfony YAML interprets ISO-8601 datetime strings and returns timestamps instead of the string
// this behavior conforms to the YAML standard, i.e. this is no bug of Symfony YAML
if (is_int($meta['date'])) {
$meta['time'] = $meta['date'];
$meta['date'] = '';
}
if (empty($meta['time'])) {
$meta['time'] = strtotime($meta['date']) ?: '';
} elseif (empty($meta['date'])) {
$rawDateFormat = (date('H:i:s', $meta['time']) === '00:00:00') ? 'Y-m-d' : 'Y-m-d H:i:s';
$meta['date'] = date($rawDateFormat, $meta['time']);
}
} else {
$meta['date'] = $meta['time'] = '';
}
if (empty($meta['date_formatted'])) {
$dateFormat = $this->getConfig('date_format');
$meta['date_formatted'] = $meta['time'] ? utf8_encode(strftime($dateFormat, $meta['time'])) : '';
}
} else {
// guarantee array key existance
$meta = array_fill_keys($headers, '');
}
return $meta;
} | php | public function parseFileMeta($rawContent, array $headers)
{
$meta = array();
$pattern = "/^(\/(\*)|---)[[:blank:]]*(?:\r)?\n"
. "(?:(.*?)(?:\r)?\n)?(?(2)\*\/|---)[[:blank:]]*(?:(?:\r)?\n|$)/s";
if (preg_match($pattern, $rawContent, $rawMetaMatches) && isset($rawMetaMatches[3])) {
$meta = $this->getYamlParser()->parse($rawMetaMatches[3]) ?: array();
$meta = is_array($meta) ? $meta : array('title' => $meta);
foreach ($headers as $name => $key) {
if (isset($meta[$name])) {
// rename field (e.g. remove whitespaces)
if ($key != $name) {
$meta[$key] = $meta[$name];
unset($meta[$name]);
}
} elseif (!isset($meta[$key])) {
// guarantee array key existance
$meta[$key] = '';
}
}
if (!empty($meta['date']) || !empty($meta['time'])) {
// workaround for issue #336
// Symfony YAML interprets ISO-8601 datetime strings and returns timestamps instead of the string
// this behavior conforms to the YAML standard, i.e. this is no bug of Symfony YAML
if (is_int($meta['date'])) {
$meta['time'] = $meta['date'];
$meta['date'] = '';
}
if (empty($meta['time'])) {
$meta['time'] = strtotime($meta['date']) ?: '';
} elseif (empty($meta['date'])) {
$rawDateFormat = (date('H:i:s', $meta['time']) === '00:00:00') ? 'Y-m-d' : 'Y-m-d H:i:s';
$meta['date'] = date($rawDateFormat, $meta['time']);
}
} else {
$meta['date'] = $meta['time'] = '';
}
if (empty($meta['date_formatted'])) {
$dateFormat = $this->getConfig('date_format');
$meta['date_formatted'] = $meta['time'] ? utf8_encode(strftime($dateFormat, $meta['time'])) : '';
}
} else {
// guarantee array key existance
$meta = array_fill_keys($headers, '');
}
return $meta;
} | [
"public",
"function",
"parseFileMeta",
"(",
"$",
"rawContent",
",",
"array",
"$",
"headers",
")",
"{",
"$",
"meta",
"=",
"array",
"(",
")",
";",
"$",
"pattern",
"=",
"\"/^(\\/(\\*)|---)[[:blank:]]*(?:\\r)?\\n\"",
".",
"\"(?:(.*?)(?:\\r)?\\n)?(?(2)\\*\\/|---)[[:blank:]]*(?:(?:\\r)?\\n|$)/s\"",
";",
"if",
"(",
"preg_match",
"(",
"$",
"pattern",
",",
"$",
"rawContent",
",",
"$",
"rawMetaMatches",
")",
"&&",
"isset",
"(",
"$",
"rawMetaMatches",
"[",
"3",
"]",
")",
")",
"{",
"$",
"meta",
"=",
"$",
"this",
"->",
"getYamlParser",
"(",
")",
"->",
"parse",
"(",
"$",
"rawMetaMatches",
"[",
"3",
"]",
")",
"?",
":",
"array",
"(",
")",
";",
"$",
"meta",
"=",
"is_array",
"(",
"$",
"meta",
")",
"?",
"$",
"meta",
":",
"array",
"(",
"'title'",
"=>",
"$",
"meta",
")",
";",
"foreach",
"(",
"$",
"headers",
"as",
"$",
"name",
"=>",
"$",
"key",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"meta",
"[",
"$",
"name",
"]",
")",
")",
"{",
"// rename field (e.g. remove whitespaces)",
"if",
"(",
"$",
"key",
"!=",
"$",
"name",
")",
"{",
"$",
"meta",
"[",
"$",
"key",
"]",
"=",
"$",
"meta",
"[",
"$",
"name",
"]",
";",
"unset",
"(",
"$",
"meta",
"[",
"$",
"name",
"]",
")",
";",
"}",
"}",
"elseif",
"(",
"!",
"isset",
"(",
"$",
"meta",
"[",
"$",
"key",
"]",
")",
")",
"{",
"// guarantee array key existance",
"$",
"meta",
"[",
"$",
"key",
"]",
"=",
"''",
";",
"}",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"meta",
"[",
"'date'",
"]",
")",
"||",
"!",
"empty",
"(",
"$",
"meta",
"[",
"'time'",
"]",
")",
")",
"{",
"// workaround for issue #336",
"// Symfony YAML interprets ISO-8601 datetime strings and returns timestamps instead of the string",
"// this behavior conforms to the YAML standard, i.e. this is no bug of Symfony YAML",
"if",
"(",
"is_int",
"(",
"$",
"meta",
"[",
"'date'",
"]",
")",
")",
"{",
"$",
"meta",
"[",
"'time'",
"]",
"=",
"$",
"meta",
"[",
"'date'",
"]",
";",
"$",
"meta",
"[",
"'date'",
"]",
"=",
"''",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"meta",
"[",
"'time'",
"]",
")",
")",
"{",
"$",
"meta",
"[",
"'time'",
"]",
"=",
"strtotime",
"(",
"$",
"meta",
"[",
"'date'",
"]",
")",
"?",
":",
"''",
";",
"}",
"elseif",
"(",
"empty",
"(",
"$",
"meta",
"[",
"'date'",
"]",
")",
")",
"{",
"$",
"rawDateFormat",
"=",
"(",
"date",
"(",
"'H:i:s'",
",",
"$",
"meta",
"[",
"'time'",
"]",
")",
"===",
"'00:00:00'",
")",
"?",
"'Y-m-d'",
":",
"'Y-m-d H:i:s'",
";",
"$",
"meta",
"[",
"'date'",
"]",
"=",
"date",
"(",
"$",
"rawDateFormat",
",",
"$",
"meta",
"[",
"'time'",
"]",
")",
";",
"}",
"}",
"else",
"{",
"$",
"meta",
"[",
"'date'",
"]",
"=",
"$",
"meta",
"[",
"'time'",
"]",
"=",
"''",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"meta",
"[",
"'date_formatted'",
"]",
")",
")",
"{",
"$",
"dateFormat",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'date_format'",
")",
";",
"$",
"meta",
"[",
"'date_formatted'",
"]",
"=",
"$",
"meta",
"[",
"'time'",
"]",
"?",
"utf8_encode",
"(",
"strftime",
"(",
"$",
"dateFormat",
",",
"$",
"meta",
"[",
"'time'",
"]",
")",
")",
":",
"''",
";",
"}",
"}",
"else",
"{",
"// guarantee array key existance",
"$",
"meta",
"=",
"array_fill_keys",
"(",
"$",
"headers",
",",
"''",
")",
";",
"}",
"return",
"$",
"meta",
";",
"}"
] | Parses the file meta from raw file contents
Meta data MUST start on the first line of the file, either opened and
closed by `---` or C-style block comments (deprecated). The headers are
parsed by the YAML component of the Symfony project. If you're a plugin
developer, you MUST register new headers during the `onMetaHeaders`
event first. The implicit availability of headers is for users and
pure (!) theme developers ONLY.
@see Pico::getFileMeta()
@param string $rawContent the raw file contents
@param string[] $headers known meta headers
@return array parsed meta data
@throws \Symfony\Component\Yaml\Exception\ParseException thrown when the
meta data is invalid | [
"Parses",
"the",
"file",
"meta",
"from",
"raw",
"file",
"contents"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/Pico.php#L1340-L1391 | train |
picocms/Pico | lib/Pico.php | Pico.getParsedown | public function getParsedown()
{
if ($this->parsedown === null) {
$className = $this->config['content_config']['extra'] ? 'ParsedownExtra' : 'Parsedown';
$this->parsedown = new $className();
$this->parsedown->setBreaksEnabled((bool) $this->config['content_config']['breaks']);
$this->parsedown->setMarkupEscaped((bool) $this->config['content_config']['escape']);
$this->parsedown->setUrlsLinked((bool) $this->config['content_config']['auto_urls']);
$this->triggerEvent('onParsedownRegistered', array(&$this->parsedown));
}
return $this->parsedown;
} | php | public function getParsedown()
{
if ($this->parsedown === null) {
$className = $this->config['content_config']['extra'] ? 'ParsedownExtra' : 'Parsedown';
$this->parsedown = new $className();
$this->parsedown->setBreaksEnabled((bool) $this->config['content_config']['breaks']);
$this->parsedown->setMarkupEscaped((bool) $this->config['content_config']['escape']);
$this->parsedown->setUrlsLinked((bool) $this->config['content_config']['auto_urls']);
$this->triggerEvent('onParsedownRegistered', array(&$this->parsedown));
}
return $this->parsedown;
} | [
"public",
"function",
"getParsedown",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"parsedown",
"===",
"null",
")",
"{",
"$",
"className",
"=",
"$",
"this",
"->",
"config",
"[",
"'content_config'",
"]",
"[",
"'extra'",
"]",
"?",
"'ParsedownExtra'",
":",
"'Parsedown'",
";",
"$",
"this",
"->",
"parsedown",
"=",
"new",
"$",
"className",
"(",
")",
";",
"$",
"this",
"->",
"parsedown",
"->",
"setBreaksEnabled",
"(",
"(",
"bool",
")",
"$",
"this",
"->",
"config",
"[",
"'content_config'",
"]",
"[",
"'breaks'",
"]",
")",
";",
"$",
"this",
"->",
"parsedown",
"->",
"setMarkupEscaped",
"(",
"(",
"bool",
")",
"$",
"this",
"->",
"config",
"[",
"'content_config'",
"]",
"[",
"'escape'",
"]",
")",
";",
"$",
"this",
"->",
"parsedown",
"->",
"setUrlsLinked",
"(",
"(",
"bool",
")",
"$",
"this",
"->",
"config",
"[",
"'content_config'",
"]",
"[",
"'auto_urls'",
"]",
")",
";",
"$",
"this",
"->",
"triggerEvent",
"(",
"'onParsedownRegistered'",
",",
"array",
"(",
"&",
"$",
"this",
"->",
"parsedown",
")",
")",
";",
"}",
"return",
"$",
"this",
"->",
"parsedown",
";",
"}"
] | Returns the Parsedown markdown parser
This method triggers the `onParsedownRegistered` event when the
Parsedown markdown parser wasn't initiated yet.
@return Parsedown Parsedown markdown parser | [
"Returns",
"the",
"Parsedown",
"markdown",
"parser"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/Pico.php#L1413-L1427 | train |
picocms/Pico | lib/Pico.php | Pico.prepareFileContent | public function prepareFileContent($rawContent, array $meta = array())
{
// remove meta header
$metaHeaderPattern = "/^(\/(\*)|---)[[:blank:]]*(?:\r)?\n"
. "(?:(.*?)(?:\r)?\n)?(?(2)\*\/|---)[[:blank:]]*(?:(?:\r)?\n|$)/s";
$markdown = preg_replace($metaHeaderPattern, '', $rawContent, 1);
// replace placeholders
$markdown = $this->substituteFileContent($markdown, $meta);
return $markdown;
} | php | public function prepareFileContent($rawContent, array $meta = array())
{
// remove meta header
$metaHeaderPattern = "/^(\/(\*)|---)[[:blank:]]*(?:\r)?\n"
. "(?:(.*?)(?:\r)?\n)?(?(2)\*\/|---)[[:blank:]]*(?:(?:\r)?\n|$)/s";
$markdown = preg_replace($metaHeaderPattern, '', $rawContent, 1);
// replace placeholders
$markdown = $this->substituteFileContent($markdown, $meta);
return $markdown;
} | [
"public",
"function",
"prepareFileContent",
"(",
"$",
"rawContent",
",",
"array",
"$",
"meta",
"=",
"array",
"(",
")",
")",
"{",
"// remove meta header",
"$",
"metaHeaderPattern",
"=",
"\"/^(\\/(\\*)|---)[[:blank:]]*(?:\\r)?\\n\"",
".",
"\"(?:(.*?)(?:\\r)?\\n)?(?(2)\\*\\/|---)[[:blank:]]*(?:(?:\\r)?\\n|$)/s\"",
";",
"$",
"markdown",
"=",
"preg_replace",
"(",
"$",
"metaHeaderPattern",
",",
"''",
",",
"$",
"rawContent",
",",
"1",
")",
";",
"// replace placeholders",
"$",
"markdown",
"=",
"$",
"this",
"->",
"substituteFileContent",
"(",
"$",
"markdown",
",",
"$",
"meta",
")",
";",
"return",
"$",
"markdown",
";",
"}"
] | Applies some static preparations to the raw contents of a page
This method removes the meta header and replaces `%...%` placeholders
by calling the {@see Pico::substituteFileContent()} method.
@see Pico::substituteFileContent()
@see Pico::parseFileContent()
@see Pico::getFileContent()
@param string $rawContent raw contents of a page
@param array $meta meta data to use for %meta.*% replacement
@return string prepared Markdown contents | [
"Applies",
"some",
"static",
"preparations",
"to",
"the",
"raw",
"contents",
"of",
"a",
"page"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/Pico.php#L1444-L1455 | train |
picocms/Pico | lib/Pico.php | Pico.substituteFileContent | public function substituteFileContent($markdown, array $meta = array())
{
$variables = array();
// replace %version%
$variables['%version%'] = static::VERSION;
// replace %site_title%
$variables['%site_title%'] = $this->getConfig('site_title');
// replace %base_url%
if ($this->isUrlRewritingEnabled()) {
// always use `%base_url%?sub/page` syntax for internal links
// we'll replace the links accordingly, depending on enabled rewriting
$variables['%base_url%?'] = $this->getBaseUrl();
} else {
// actually not necessary, but makes the URL look a little nicer
$variables['%base_url%?'] = $this->getBaseUrl() . '?';
}
$variables['%base_url%'] = rtrim($this->getBaseUrl(), '/');
// replace %theme_url%
$variables['%theme_url%'] = $this->getBaseThemeUrl() . $this->getConfig('theme');
// replace %meta.*%
if ($meta) {
foreach ($meta as $metaKey => $metaValue) {
if (is_scalar($metaValue) || ($metaValue === null)) {
$variables['%meta.' . $metaKey . '%'] = (string) $metaValue;
}
}
}
return str_replace(array_keys($variables), $variables, $markdown);
} | php | public function substituteFileContent($markdown, array $meta = array())
{
$variables = array();
// replace %version%
$variables['%version%'] = static::VERSION;
// replace %site_title%
$variables['%site_title%'] = $this->getConfig('site_title');
// replace %base_url%
if ($this->isUrlRewritingEnabled()) {
// always use `%base_url%?sub/page` syntax for internal links
// we'll replace the links accordingly, depending on enabled rewriting
$variables['%base_url%?'] = $this->getBaseUrl();
} else {
// actually not necessary, but makes the URL look a little nicer
$variables['%base_url%?'] = $this->getBaseUrl() . '?';
}
$variables['%base_url%'] = rtrim($this->getBaseUrl(), '/');
// replace %theme_url%
$variables['%theme_url%'] = $this->getBaseThemeUrl() . $this->getConfig('theme');
// replace %meta.*%
if ($meta) {
foreach ($meta as $metaKey => $metaValue) {
if (is_scalar($metaValue) || ($metaValue === null)) {
$variables['%meta.' . $metaKey . '%'] = (string) $metaValue;
}
}
}
return str_replace(array_keys($variables), $variables, $markdown);
} | [
"public",
"function",
"substituteFileContent",
"(",
"$",
"markdown",
",",
"array",
"$",
"meta",
"=",
"array",
"(",
")",
")",
"{",
"$",
"variables",
"=",
"array",
"(",
")",
";",
"// replace %version%",
"$",
"variables",
"[",
"'%version%'",
"]",
"=",
"static",
"::",
"VERSION",
";",
"// replace %site_title%",
"$",
"variables",
"[",
"'%site_title%'",
"]",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'site_title'",
")",
";",
"// replace %base_url%",
"if",
"(",
"$",
"this",
"->",
"isUrlRewritingEnabled",
"(",
")",
")",
"{",
"// always use `%base_url%?sub/page` syntax for internal links",
"// we'll replace the links accordingly, depending on enabled rewriting",
"$",
"variables",
"[",
"'%base_url%?'",
"]",
"=",
"$",
"this",
"->",
"getBaseUrl",
"(",
")",
";",
"}",
"else",
"{",
"// actually not necessary, but makes the URL look a little nicer",
"$",
"variables",
"[",
"'%base_url%?'",
"]",
"=",
"$",
"this",
"->",
"getBaseUrl",
"(",
")",
".",
"'?'",
";",
"}",
"$",
"variables",
"[",
"'%base_url%'",
"]",
"=",
"rtrim",
"(",
"$",
"this",
"->",
"getBaseUrl",
"(",
")",
",",
"'/'",
")",
";",
"// replace %theme_url%",
"$",
"variables",
"[",
"'%theme_url%'",
"]",
"=",
"$",
"this",
"->",
"getBaseThemeUrl",
"(",
")",
".",
"$",
"this",
"->",
"getConfig",
"(",
"'theme'",
")",
";",
"// replace %meta.*%",
"if",
"(",
"$",
"meta",
")",
"{",
"foreach",
"(",
"$",
"meta",
"as",
"$",
"metaKey",
"=>",
"$",
"metaValue",
")",
"{",
"if",
"(",
"is_scalar",
"(",
"$",
"metaValue",
")",
"||",
"(",
"$",
"metaValue",
"===",
"null",
")",
")",
"{",
"$",
"variables",
"[",
"'%meta.'",
".",
"$",
"metaKey",
".",
"'%'",
"]",
"=",
"(",
"string",
")",
"$",
"metaValue",
";",
"}",
"}",
"}",
"return",
"str_replace",
"(",
"array_keys",
"(",
"$",
"variables",
")",
",",
"$",
"variables",
",",
"$",
"markdown",
")",
";",
"}"
] | Replaces all %...% placeholders in a page's contents
@param string $markdown Markdown contents of a page
@param array $meta meta data to use for %meta.*% replacement
@return string substituted Markdown contents | [
"Replaces",
"all",
"%",
"...",
"%",
"placeholders",
"in",
"a",
"page",
"s",
"contents"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/Pico.php#L1465-L1499 | train |
picocms/Pico | lib/Pico.php | Pico.readPages | protected function readPages()
{
$contentDir = $this->getConfig('content_dir');
$contentExt = $this->getConfig('content_ext');
$this->pages = array();
$files = $this->getFiles($contentDir, $contentExt, self::SORT_NONE);
foreach ($files as $i => $file) {
// skip 404 page
if (basename($file) === '404' . $contentExt) {
unset($files[$i]);
continue;
}
$id = substr($file, strlen($contentDir), -strlen($contentExt));
// trigger onSinglePageLoading event
// skip inaccessible pages (e.g. drop "sub.md" if "sub/index.md" exists) by default
$conflictFile = $contentDir . $id . '/index' . $contentExt;
$skipFile = in_array($conflictFile, $files, true) ?: null;
$this->triggerEvent('onSinglePageLoading', array($id, &$skipFile));
if ($skipFile) {
continue;
}
$url = $this->getPageUrl($id);
if ($file !== $this->requestFile) {
$rawContent = $this->loadFileContent($file);
// trigger onSinglePageContent event
$this->triggerEvent('onSinglePageContent', array($id, &$rawContent));
$headers = $this->getMetaHeaders();
try {
$meta = $this->parseFileMeta($rawContent, $headers);
} catch (\Symfony\Component\Yaml\Exception\ParseException $e) {
$meta = $this->parseFileMeta('', $headers);
$meta['YAML_ParseError'] = $e->getMessage();
}
} else {
$rawContent = &$this->rawContent;
$meta = &$this->meta;
}
// build page data
// title, description, author and date are assumed to be pretty basic data
// everything else is accessible through $page['meta']
$page = array(
'id' => $id,
'url' => $url,
'title' => &$meta['title'],
'description' => &$meta['description'],
'author' => &$meta['author'],
'time' => &$meta['time'],
'date' => &$meta['date'],
'date_formatted' => &$meta['date_formatted'],
'hidden' => (preg_match('/(?:^|\/)_/', $id) || $meta['hidden']),
'raw_content' => &$rawContent,
'meta' => &$meta
);
if ($file === $this->requestFile) {
$page['content'] = &$this->content;
}
unset($rawContent, $meta);
// trigger onSinglePageLoaded event
$this->triggerEvent('onSinglePageLoaded', array(&$page));
if ($page !== null) {
$this->pages[$id] = $page;
}
}
} | php | protected function readPages()
{
$contentDir = $this->getConfig('content_dir');
$contentExt = $this->getConfig('content_ext');
$this->pages = array();
$files = $this->getFiles($contentDir, $contentExt, self::SORT_NONE);
foreach ($files as $i => $file) {
// skip 404 page
if (basename($file) === '404' . $contentExt) {
unset($files[$i]);
continue;
}
$id = substr($file, strlen($contentDir), -strlen($contentExt));
// trigger onSinglePageLoading event
// skip inaccessible pages (e.g. drop "sub.md" if "sub/index.md" exists) by default
$conflictFile = $contentDir . $id . '/index' . $contentExt;
$skipFile = in_array($conflictFile, $files, true) ?: null;
$this->triggerEvent('onSinglePageLoading', array($id, &$skipFile));
if ($skipFile) {
continue;
}
$url = $this->getPageUrl($id);
if ($file !== $this->requestFile) {
$rawContent = $this->loadFileContent($file);
// trigger onSinglePageContent event
$this->triggerEvent('onSinglePageContent', array($id, &$rawContent));
$headers = $this->getMetaHeaders();
try {
$meta = $this->parseFileMeta($rawContent, $headers);
} catch (\Symfony\Component\Yaml\Exception\ParseException $e) {
$meta = $this->parseFileMeta('', $headers);
$meta['YAML_ParseError'] = $e->getMessage();
}
} else {
$rawContent = &$this->rawContent;
$meta = &$this->meta;
}
// build page data
// title, description, author and date are assumed to be pretty basic data
// everything else is accessible through $page['meta']
$page = array(
'id' => $id,
'url' => $url,
'title' => &$meta['title'],
'description' => &$meta['description'],
'author' => &$meta['author'],
'time' => &$meta['time'],
'date' => &$meta['date'],
'date_formatted' => &$meta['date_formatted'],
'hidden' => (preg_match('/(?:^|\/)_/', $id) || $meta['hidden']),
'raw_content' => &$rawContent,
'meta' => &$meta
);
if ($file === $this->requestFile) {
$page['content'] = &$this->content;
}
unset($rawContent, $meta);
// trigger onSinglePageLoaded event
$this->triggerEvent('onSinglePageLoaded', array(&$page));
if ($page !== null) {
$this->pages[$id] = $page;
}
}
} | [
"protected",
"function",
"readPages",
"(",
")",
"{",
"$",
"contentDir",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'content_dir'",
")",
";",
"$",
"contentExt",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'content_ext'",
")",
";",
"$",
"this",
"->",
"pages",
"=",
"array",
"(",
")",
";",
"$",
"files",
"=",
"$",
"this",
"->",
"getFiles",
"(",
"$",
"contentDir",
",",
"$",
"contentExt",
",",
"self",
"::",
"SORT_NONE",
")",
";",
"foreach",
"(",
"$",
"files",
"as",
"$",
"i",
"=>",
"$",
"file",
")",
"{",
"// skip 404 page",
"if",
"(",
"basename",
"(",
"$",
"file",
")",
"===",
"'404'",
".",
"$",
"contentExt",
")",
"{",
"unset",
"(",
"$",
"files",
"[",
"$",
"i",
"]",
")",
";",
"continue",
";",
"}",
"$",
"id",
"=",
"substr",
"(",
"$",
"file",
",",
"strlen",
"(",
"$",
"contentDir",
")",
",",
"-",
"strlen",
"(",
"$",
"contentExt",
")",
")",
";",
"// trigger onSinglePageLoading event",
"// skip inaccessible pages (e.g. drop \"sub.md\" if \"sub/index.md\" exists) by default",
"$",
"conflictFile",
"=",
"$",
"contentDir",
".",
"$",
"id",
".",
"'/index'",
".",
"$",
"contentExt",
";",
"$",
"skipFile",
"=",
"in_array",
"(",
"$",
"conflictFile",
",",
"$",
"files",
",",
"true",
")",
"?",
":",
"null",
";",
"$",
"this",
"->",
"triggerEvent",
"(",
"'onSinglePageLoading'",
",",
"array",
"(",
"$",
"id",
",",
"&",
"$",
"skipFile",
")",
")",
";",
"if",
"(",
"$",
"skipFile",
")",
"{",
"continue",
";",
"}",
"$",
"url",
"=",
"$",
"this",
"->",
"getPageUrl",
"(",
"$",
"id",
")",
";",
"if",
"(",
"$",
"file",
"!==",
"$",
"this",
"->",
"requestFile",
")",
"{",
"$",
"rawContent",
"=",
"$",
"this",
"->",
"loadFileContent",
"(",
"$",
"file",
")",
";",
"// trigger onSinglePageContent event",
"$",
"this",
"->",
"triggerEvent",
"(",
"'onSinglePageContent'",
",",
"array",
"(",
"$",
"id",
",",
"&",
"$",
"rawContent",
")",
")",
";",
"$",
"headers",
"=",
"$",
"this",
"->",
"getMetaHeaders",
"(",
")",
";",
"try",
"{",
"$",
"meta",
"=",
"$",
"this",
"->",
"parseFileMeta",
"(",
"$",
"rawContent",
",",
"$",
"headers",
")",
";",
"}",
"catch",
"(",
"\\",
"Symfony",
"\\",
"Component",
"\\",
"Yaml",
"\\",
"Exception",
"\\",
"ParseException",
"$",
"e",
")",
"{",
"$",
"meta",
"=",
"$",
"this",
"->",
"parseFileMeta",
"(",
"''",
",",
"$",
"headers",
")",
";",
"$",
"meta",
"[",
"'YAML_ParseError'",
"]",
"=",
"$",
"e",
"->",
"getMessage",
"(",
")",
";",
"}",
"}",
"else",
"{",
"$",
"rawContent",
"=",
"&",
"$",
"this",
"->",
"rawContent",
";",
"$",
"meta",
"=",
"&",
"$",
"this",
"->",
"meta",
";",
"}",
"// build page data",
"// title, description, author and date are assumed to be pretty basic data",
"// everything else is accessible through $page['meta']",
"$",
"page",
"=",
"array",
"(",
"'id'",
"=>",
"$",
"id",
",",
"'url'",
"=>",
"$",
"url",
",",
"'title'",
"=>",
"&",
"$",
"meta",
"[",
"'title'",
"]",
",",
"'description'",
"=>",
"&",
"$",
"meta",
"[",
"'description'",
"]",
",",
"'author'",
"=>",
"&",
"$",
"meta",
"[",
"'author'",
"]",
",",
"'time'",
"=>",
"&",
"$",
"meta",
"[",
"'time'",
"]",
",",
"'date'",
"=>",
"&",
"$",
"meta",
"[",
"'date'",
"]",
",",
"'date_formatted'",
"=>",
"&",
"$",
"meta",
"[",
"'date_formatted'",
"]",
",",
"'hidden'",
"=>",
"(",
"preg_match",
"(",
"'/(?:^|\\/)_/'",
",",
"$",
"id",
")",
"||",
"$",
"meta",
"[",
"'hidden'",
"]",
")",
",",
"'raw_content'",
"=>",
"&",
"$",
"rawContent",
",",
"'meta'",
"=>",
"&",
"$",
"meta",
")",
";",
"if",
"(",
"$",
"file",
"===",
"$",
"this",
"->",
"requestFile",
")",
"{",
"$",
"page",
"[",
"'content'",
"]",
"=",
"&",
"$",
"this",
"->",
"content",
";",
"}",
"unset",
"(",
"$",
"rawContent",
",",
"$",
"meta",
")",
";",
"// trigger onSinglePageLoaded event",
"$",
"this",
"->",
"triggerEvent",
"(",
"'onSinglePageLoaded'",
",",
"array",
"(",
"&",
"$",
"page",
")",
")",
";",
"if",
"(",
"$",
"page",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"pages",
"[",
"$",
"id",
"]",
"=",
"$",
"page",
";",
"}",
"}",
"}"
] | Reads the data of all pages known to Pico
The page data will be an array containing the following values:
| Array key | Type | Description |
| -------------- | ------- | ---------------------------------------- |
| id | string | relative path to the content file |
| url | string | URL to the page |
| title | string | title of the page (YAML header) |
| description | string | description of the page (YAML header) |
| author | string | author of the page (YAML header) |
| time | int | timestamp derived from the Date header |
| date | string | date of the page (YAML header) |
| date_formatted | string | formatted date of the page |
| hidden | bool | this page shouldn't be visible |
| raw_content | string | raw, not yet parsed contents of the page |
| meta | string[] | parsed meta data of the page |
| previous_page | &array[] | reference to the previous page |
| next_page | &array[] | reference to the next page |
| tree_node | &array[] | reference to the page's tree node |
Please note that the `previous_page` and `next_page` keys don't
exist until the `onCurrentPageDiscovered` event is triggered
({@see Pico::discoverPageSiblings()}). The `tree_node` key doesn't
exit until the `onPageTreeBuilt` event is triggered
({@see Pico::buildPageTree()}).
@see Pico::sortPages()
@see Pico::discoverPageSiblings()
@see Pico::getPages()
@return void | [
"Reads",
"the",
"data",
"of",
"all",
"pages",
"known",
"to",
"Pico"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/Pico.php#L1565-L1640 | train |
picocms/Pico | lib/Pico.php | Pico.discoverPageSiblings | protected function discoverPageSiblings()
{
if (($this->getConfig('order_by') === 'date') && ($this->getConfig('order') === 'desc')) {
$precedingPageKey = 'next_page';
$succeedingPageKey = 'previous_page';
} else {
$precedingPageKey = 'previous_page';
$succeedingPageKey = 'next_page';
}
$precedingPageId = null;
foreach ($this->pages as $id => &$pageData) {
$pageData[$precedingPageKey] = null;
$pageData[$succeedingPageKey] = null;
if (!empty($pageData['hidden'])) {
continue;
}
if ($precedingPageId !== null) {
$precedingPageData = &$this->pages[$precedingPageId];
$pageData[$precedingPageKey] = &$precedingPageData;
$precedingPageData[$succeedingPageKey] = &$pageData;
}
$precedingPageId = $id;
}
} | php | protected function discoverPageSiblings()
{
if (($this->getConfig('order_by') === 'date') && ($this->getConfig('order') === 'desc')) {
$precedingPageKey = 'next_page';
$succeedingPageKey = 'previous_page';
} else {
$precedingPageKey = 'previous_page';
$succeedingPageKey = 'next_page';
}
$precedingPageId = null;
foreach ($this->pages as $id => &$pageData) {
$pageData[$precedingPageKey] = null;
$pageData[$succeedingPageKey] = null;
if (!empty($pageData['hidden'])) {
continue;
}
if ($precedingPageId !== null) {
$precedingPageData = &$this->pages[$precedingPageId];
$pageData[$precedingPageKey] = &$precedingPageData;
$precedingPageData[$succeedingPageKey] = &$pageData;
}
$precedingPageId = $id;
}
} | [
"protected",
"function",
"discoverPageSiblings",
"(",
")",
"{",
"if",
"(",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'order_by'",
")",
"===",
"'date'",
")",
"&&",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'order'",
")",
"===",
"'desc'",
")",
")",
"{",
"$",
"precedingPageKey",
"=",
"'next_page'",
";",
"$",
"succeedingPageKey",
"=",
"'previous_page'",
";",
"}",
"else",
"{",
"$",
"precedingPageKey",
"=",
"'previous_page'",
";",
"$",
"succeedingPageKey",
"=",
"'next_page'",
";",
"}",
"$",
"precedingPageId",
"=",
"null",
";",
"foreach",
"(",
"$",
"this",
"->",
"pages",
"as",
"$",
"id",
"=>",
"&",
"$",
"pageData",
")",
"{",
"$",
"pageData",
"[",
"$",
"precedingPageKey",
"]",
"=",
"null",
";",
"$",
"pageData",
"[",
"$",
"succeedingPageKey",
"]",
"=",
"null",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"pageData",
"[",
"'hidden'",
"]",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"$",
"precedingPageId",
"!==",
"null",
")",
"{",
"$",
"precedingPageData",
"=",
"&",
"$",
"this",
"->",
"pages",
"[",
"$",
"precedingPageId",
"]",
";",
"$",
"pageData",
"[",
"$",
"precedingPageKey",
"]",
"=",
"&",
"$",
"precedingPageData",
";",
"$",
"precedingPageData",
"[",
"$",
"succeedingPageKey",
"]",
"=",
"&",
"$",
"pageData",
";",
"}",
"$",
"precedingPageId",
"=",
"$",
"id",
";",
"}",
"}"
] | Walks through the list of all known pages and discovers the previous and
next page respectively
@see Pico::readPages()
@see Pico::getPages()
@return void | [
"Walks",
"through",
"the",
"list",
"of",
"all",
"known",
"pages",
"and",
"discovers",
"the",
"previous",
"and",
"next",
"page",
"respectively"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/Pico.php#L1731-L1758 | train |
picocms/Pico | lib/Pico.php | Pico.discoverCurrentPage | protected function discoverCurrentPage()
{
$currentPageId = $this->getPageId($this->requestFile);
if ($currentPageId && isset($this->pages[$currentPageId])) {
$this->currentPage = &$this->pages[$currentPageId];
$this->previousPage = &$this->pages[$currentPageId]['previous_page'];
$this->nextPage = &$this->pages[$currentPageId]['next_page'];
}
} | php | protected function discoverCurrentPage()
{
$currentPageId = $this->getPageId($this->requestFile);
if ($currentPageId && isset($this->pages[$currentPageId])) {
$this->currentPage = &$this->pages[$currentPageId];
$this->previousPage = &$this->pages[$currentPageId]['previous_page'];
$this->nextPage = &$this->pages[$currentPageId]['next_page'];
}
} | [
"protected",
"function",
"discoverCurrentPage",
"(",
")",
"{",
"$",
"currentPageId",
"=",
"$",
"this",
"->",
"getPageId",
"(",
"$",
"this",
"->",
"requestFile",
")",
";",
"if",
"(",
"$",
"currentPageId",
"&&",
"isset",
"(",
"$",
"this",
"->",
"pages",
"[",
"$",
"currentPageId",
"]",
")",
")",
"{",
"$",
"this",
"->",
"currentPage",
"=",
"&",
"$",
"this",
"->",
"pages",
"[",
"$",
"currentPageId",
"]",
";",
"$",
"this",
"->",
"previousPage",
"=",
"&",
"$",
"this",
"->",
"pages",
"[",
"$",
"currentPageId",
"]",
"[",
"'previous_page'",
"]",
";",
"$",
"this",
"->",
"nextPage",
"=",
"&",
"$",
"this",
"->",
"pages",
"[",
"$",
"currentPageId",
"]",
"[",
"'next_page'",
"]",
";",
"}",
"}"
] | Discovers the page data of the requested page as well as the previous
and next page relative to it
@see Pico::getCurrentPage()
@see Pico::getPreviousPage()
@see Pico::getNextPage()
@return void | [
"Discovers",
"the",
"page",
"data",
"of",
"the",
"requested",
"page",
"as",
"well",
"as",
"the",
"previous",
"and",
"next",
"page",
"relative",
"to",
"it"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/Pico.php#L1782-L1790 | train |
picocms/Pico | lib/Pico.php | Pico.buildPageTree | protected function buildPageTree()
{
$this->pageTree = array();
foreach ($this->pages as $id => &$pageData) {
// main index page
if ($id === 'index') {
$this->pageTree['']['/']['id'] = '/';
$this->pageTree['']['/']['page'] = &$pageData;
$pageData['tree_node'] = &$this->pageTree['']['/'];
continue;
}
// get a page's node and branch
$basename = basename($id);
$branch = dirname($id);
$isIndexPage = ($basename === 'index');
if ($isIndexPage) {
$basename = basename($branch);
$branch = dirname($branch);
}
$branch = ($branch !== '.') ? $branch : '/';
$node = ($branch !== '/') ? $branch . '/' . $basename : $basename;
// skip inaccessible pages (e.g. drop "sub.md" if "sub/index.md" exists)
if (isset($this->pageTree[$branch][$node]['page']) && !$isIndexPage) {
continue;
}
// add node to page tree
$isNewBranch = !isset($this->pageTree[$branch]);
$this->pageTree[$branch][$node]['id'] = $node;
$this->pageTree[$branch][$node]['page'] = &$pageData;
$pageData['tree_node'] = &$this->pageTree[$branch][$node];
// add parent nodes to page tree, if necessary
while ($isNewBranch && $branch) {
$parentNode = $branch;
$parentBranch = ($branch !== '/') ? dirname($parentNode) : '';
$parentBranch = ($parentBranch !== '.') ? $parentBranch : '/';
$isNewBranch = !isset($this->pageTree[$parentBranch]);
$this->pageTree[$parentBranch][$parentNode]['id'] = $parentNode;
$this->pageTree[$parentBranch][$parentNode]['children'] = &$this->pageTree[$branch];
$branch = $parentBranch;
}
}
} | php | protected function buildPageTree()
{
$this->pageTree = array();
foreach ($this->pages as $id => &$pageData) {
// main index page
if ($id === 'index') {
$this->pageTree['']['/']['id'] = '/';
$this->pageTree['']['/']['page'] = &$pageData;
$pageData['tree_node'] = &$this->pageTree['']['/'];
continue;
}
// get a page's node and branch
$basename = basename($id);
$branch = dirname($id);
$isIndexPage = ($basename === 'index');
if ($isIndexPage) {
$basename = basename($branch);
$branch = dirname($branch);
}
$branch = ($branch !== '.') ? $branch : '/';
$node = ($branch !== '/') ? $branch . '/' . $basename : $basename;
// skip inaccessible pages (e.g. drop "sub.md" if "sub/index.md" exists)
if (isset($this->pageTree[$branch][$node]['page']) && !$isIndexPage) {
continue;
}
// add node to page tree
$isNewBranch = !isset($this->pageTree[$branch]);
$this->pageTree[$branch][$node]['id'] = $node;
$this->pageTree[$branch][$node]['page'] = &$pageData;
$pageData['tree_node'] = &$this->pageTree[$branch][$node];
// add parent nodes to page tree, if necessary
while ($isNewBranch && $branch) {
$parentNode = $branch;
$parentBranch = ($branch !== '/') ? dirname($parentNode) : '';
$parentBranch = ($parentBranch !== '.') ? $parentBranch : '/';
$isNewBranch = !isset($this->pageTree[$parentBranch]);
$this->pageTree[$parentBranch][$parentNode]['id'] = $parentNode;
$this->pageTree[$parentBranch][$parentNode]['children'] = &$this->pageTree[$branch];
$branch = $parentBranch;
}
}
} | [
"protected",
"function",
"buildPageTree",
"(",
")",
"{",
"$",
"this",
"->",
"pageTree",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"pages",
"as",
"$",
"id",
"=>",
"&",
"$",
"pageData",
")",
"{",
"// main index page",
"if",
"(",
"$",
"id",
"===",
"'index'",
")",
"{",
"$",
"this",
"->",
"pageTree",
"[",
"''",
"]",
"[",
"'/'",
"]",
"[",
"'id'",
"]",
"=",
"'/'",
";",
"$",
"this",
"->",
"pageTree",
"[",
"''",
"]",
"[",
"'/'",
"]",
"[",
"'page'",
"]",
"=",
"&",
"$",
"pageData",
";",
"$",
"pageData",
"[",
"'tree_node'",
"]",
"=",
"&",
"$",
"this",
"->",
"pageTree",
"[",
"''",
"]",
"[",
"'/'",
"]",
";",
"continue",
";",
"}",
"// get a page's node and branch",
"$",
"basename",
"=",
"basename",
"(",
"$",
"id",
")",
";",
"$",
"branch",
"=",
"dirname",
"(",
"$",
"id",
")",
";",
"$",
"isIndexPage",
"=",
"(",
"$",
"basename",
"===",
"'index'",
")",
";",
"if",
"(",
"$",
"isIndexPage",
")",
"{",
"$",
"basename",
"=",
"basename",
"(",
"$",
"branch",
")",
";",
"$",
"branch",
"=",
"dirname",
"(",
"$",
"branch",
")",
";",
"}",
"$",
"branch",
"=",
"(",
"$",
"branch",
"!==",
"'.'",
")",
"?",
"$",
"branch",
":",
"'/'",
";",
"$",
"node",
"=",
"(",
"$",
"branch",
"!==",
"'/'",
")",
"?",
"$",
"branch",
".",
"'/'",
".",
"$",
"basename",
":",
"$",
"basename",
";",
"// skip inaccessible pages (e.g. drop \"sub.md\" if \"sub/index.md\" exists)",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"pageTree",
"[",
"$",
"branch",
"]",
"[",
"$",
"node",
"]",
"[",
"'page'",
"]",
")",
"&&",
"!",
"$",
"isIndexPage",
")",
"{",
"continue",
";",
"}",
"// add node to page tree",
"$",
"isNewBranch",
"=",
"!",
"isset",
"(",
"$",
"this",
"->",
"pageTree",
"[",
"$",
"branch",
"]",
")",
";",
"$",
"this",
"->",
"pageTree",
"[",
"$",
"branch",
"]",
"[",
"$",
"node",
"]",
"[",
"'id'",
"]",
"=",
"$",
"node",
";",
"$",
"this",
"->",
"pageTree",
"[",
"$",
"branch",
"]",
"[",
"$",
"node",
"]",
"[",
"'page'",
"]",
"=",
"&",
"$",
"pageData",
";",
"$",
"pageData",
"[",
"'tree_node'",
"]",
"=",
"&",
"$",
"this",
"->",
"pageTree",
"[",
"$",
"branch",
"]",
"[",
"$",
"node",
"]",
";",
"// add parent nodes to page tree, if necessary",
"while",
"(",
"$",
"isNewBranch",
"&&",
"$",
"branch",
")",
"{",
"$",
"parentNode",
"=",
"$",
"branch",
";",
"$",
"parentBranch",
"=",
"(",
"$",
"branch",
"!==",
"'/'",
")",
"?",
"dirname",
"(",
"$",
"parentNode",
")",
":",
"''",
";",
"$",
"parentBranch",
"=",
"(",
"$",
"parentBranch",
"!==",
"'.'",
")",
"?",
"$",
"parentBranch",
":",
"'/'",
";",
"$",
"isNewBranch",
"=",
"!",
"isset",
"(",
"$",
"this",
"->",
"pageTree",
"[",
"$",
"parentBranch",
"]",
")",
";",
"$",
"this",
"->",
"pageTree",
"[",
"$",
"parentBranch",
"]",
"[",
"$",
"parentNode",
"]",
"[",
"'id'",
"]",
"=",
"$",
"parentNode",
";",
"$",
"this",
"->",
"pageTree",
"[",
"$",
"parentBranch",
"]",
"[",
"$",
"parentNode",
"]",
"[",
"'children'",
"]",
"=",
"&",
"$",
"this",
"->",
"pageTree",
"[",
"$",
"branch",
"]",
";",
"$",
"branch",
"=",
"$",
"parentBranch",
";",
"}",
"}",
"}"
] | Builds a tree structure containing all known pages
Pico's page tree is a list of all the tree's branches (no matter the
depth). Thus, by iterating a array element, you get the nodes of a given
branch. All leaf nodes do represent a page, but inner nodes may or may
not represent a page (e.g. if there's a `sub/page.md`, but neither a
`sub/index.md` nor a `sub.md`, the inner node `sub`, that is the parent
of the `sub/page` node, represents no page itself).
A page's file path describes its node's path in the tree (e.g. the page
`sub/page.md` is represented by the `sub/page` node, thus a child of the
`sub` node and a element of the `sub` branch). However, the index page
of a folder (e.g. `sub/index.md`), is *not* a node of the `sub` branch,
but rather of the `/` branch. The page's node is not `sub/index`, but
`sub`. If two pages are described by the same node (e.g. if both a
`sub/index.md` and a `sub.md` exist), the index page takes precedence.
Pico's main index page (i.e. `index.md`) is represented by the tree's
root node `/` and a special case: it is the only node of the `` (i.e.
the empty string) branch.
A node is represented by an array with the keys `id`, `page` and
`children`. The `id` key contains a string with the node's name. If the
node represents a page, the `page` key is a reference to the page's
data array. If the node is a inner node, the `children` key is a
reference to its matching branch (i.e. a list of the node's children).
The order of a node's children matches the order in Pico's pages array.
If you want to walk the whole page tree, start with the tree's root node
at `$pageTree[""]["/"]`, or rather, use `$pages["index"]["tree_node"]`.
The root node's `children` key is a reference to the `/` branch at
`$pageTree["/"]`, that is a list of the root node's direct child nodes
and their siblings.
You MUST NOT iterate the page tree itself (i.e. the list of the tree's
branches), its order is undefined and the array will be replaced by a
non-iterable data structure with Pico 3.0.
@see Pico::getPageTree()
@return void | [
"Builds",
"a",
"tree",
"structure",
"containing",
"all",
"known",
"pages"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/Pico.php#L1870-L1920 | train |
picocms/Pico | lib/Pico.php | Pico.getTwig | public function getTwig()
{
if ($this->twig === null) {
$twigConfig = $this->getConfig('twig_config');
$twigLoader = new Twig_Loader_Filesystem($this->getThemesDir() . $this->getConfig('theme'));
$this->twig = new Twig_Environment($twigLoader, $twigConfig);
$this->twig->addExtension(new PicoTwigExtension($this));
if (!empty($twigConfig['debug'])) {
$this->twig->addExtension(new Twig_Extension_Debug());
}
// register content filter
// we pass the $pages array by reference to prevent multiple parser runs for the same page
// this is the reason why we can't register this filter as part of PicoTwigExtension
$pico = $this;
$pages = &$this->pages;
$this->twig->addFilter(new Twig_SimpleFilter('content', function ($page) use ($pico, &$pages) {
if (isset($pages[$page])) {
$pageData = &$pages[$page];
if (!isset($pageData['content'])) {
$pageData['content'] = $pico->prepareFileContent($pageData['raw_content'], $pageData['meta']);
$pageData['content'] = $pico->parseFileContent($pageData['content']);
}
return $pageData['content'];
}
return null;
}));
// trigger onTwigRegistration event
$this->triggerEvent('onTwigRegistered', array(&$this->twig));
}
return $this->twig;
} | php | public function getTwig()
{
if ($this->twig === null) {
$twigConfig = $this->getConfig('twig_config');
$twigLoader = new Twig_Loader_Filesystem($this->getThemesDir() . $this->getConfig('theme'));
$this->twig = new Twig_Environment($twigLoader, $twigConfig);
$this->twig->addExtension(new PicoTwigExtension($this));
if (!empty($twigConfig['debug'])) {
$this->twig->addExtension(new Twig_Extension_Debug());
}
// register content filter
// we pass the $pages array by reference to prevent multiple parser runs for the same page
// this is the reason why we can't register this filter as part of PicoTwigExtension
$pico = $this;
$pages = &$this->pages;
$this->twig->addFilter(new Twig_SimpleFilter('content', function ($page) use ($pico, &$pages) {
if (isset($pages[$page])) {
$pageData = &$pages[$page];
if (!isset($pageData['content'])) {
$pageData['content'] = $pico->prepareFileContent($pageData['raw_content'], $pageData['meta']);
$pageData['content'] = $pico->parseFileContent($pageData['content']);
}
return $pageData['content'];
}
return null;
}));
// trigger onTwigRegistration event
$this->triggerEvent('onTwigRegistered', array(&$this->twig));
}
return $this->twig;
} | [
"public",
"function",
"getTwig",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"twig",
"===",
"null",
")",
"{",
"$",
"twigConfig",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'twig_config'",
")",
";",
"$",
"twigLoader",
"=",
"new",
"Twig_Loader_Filesystem",
"(",
"$",
"this",
"->",
"getThemesDir",
"(",
")",
".",
"$",
"this",
"->",
"getConfig",
"(",
"'theme'",
")",
")",
";",
"$",
"this",
"->",
"twig",
"=",
"new",
"Twig_Environment",
"(",
"$",
"twigLoader",
",",
"$",
"twigConfig",
")",
";",
"$",
"this",
"->",
"twig",
"->",
"addExtension",
"(",
"new",
"PicoTwigExtension",
"(",
"$",
"this",
")",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"twigConfig",
"[",
"'debug'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"twig",
"->",
"addExtension",
"(",
"new",
"Twig_Extension_Debug",
"(",
")",
")",
";",
"}",
"// register content filter",
"// we pass the $pages array by reference to prevent multiple parser runs for the same page",
"// this is the reason why we can't register this filter as part of PicoTwigExtension",
"$",
"pico",
"=",
"$",
"this",
";",
"$",
"pages",
"=",
"&",
"$",
"this",
"->",
"pages",
";",
"$",
"this",
"->",
"twig",
"->",
"addFilter",
"(",
"new",
"Twig_SimpleFilter",
"(",
"'content'",
",",
"function",
"(",
"$",
"page",
")",
"use",
"(",
"$",
"pico",
",",
"&",
"$",
"pages",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"pages",
"[",
"$",
"page",
"]",
")",
")",
"{",
"$",
"pageData",
"=",
"&",
"$",
"pages",
"[",
"$",
"page",
"]",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"pageData",
"[",
"'content'",
"]",
")",
")",
"{",
"$",
"pageData",
"[",
"'content'",
"]",
"=",
"$",
"pico",
"->",
"prepareFileContent",
"(",
"$",
"pageData",
"[",
"'raw_content'",
"]",
",",
"$",
"pageData",
"[",
"'meta'",
"]",
")",
";",
"$",
"pageData",
"[",
"'content'",
"]",
"=",
"$",
"pico",
"->",
"parseFileContent",
"(",
"$",
"pageData",
"[",
"'content'",
"]",
")",
";",
"}",
"return",
"$",
"pageData",
"[",
"'content'",
"]",
";",
"}",
"return",
"null",
";",
"}",
")",
")",
";",
"// trigger onTwigRegistration event",
"$",
"this",
"->",
"triggerEvent",
"(",
"'onTwigRegistered'",
",",
"array",
"(",
"&",
"$",
"this",
"->",
"twig",
")",
")",
";",
"}",
"return",
"$",
"this",
"->",
"twig",
";",
"}"
] | Returns the Twig template engine
This method triggers the `onTwigRegistered` event when the Twig template
engine wasn't initiated yet. When initiating Twig, this method also
registers Pico's core Twig filter `content` as well as Pico's
{@see PicoTwigExtension} Twig extension.
@see Pico::getTwig()
@see http://twig.sensiolabs.org/ Twig website
@see https://github.com/twigphp/Twig Twig on GitHub
@return Twig_Environment|null Twig template engine | [
"Returns",
"the",
"Twig",
"template",
"engine"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/Pico.php#L1948-L1983 | train |
picocms/Pico | lib/Pico.php | Pico.getTwigVariables | protected function getTwigVariables()
{
return array(
'config' => $this->getConfig(),
'base_dir' => rtrim($this->getRootDir(), '/'),
'base_url' => rtrim($this->getBaseUrl(), '/'),
'theme_dir' => $this->getThemesDir() . $this->getConfig('theme'),
'theme_url' => $this->getBaseThemeUrl() . $this->getConfig('theme'),
'site_title' => $this->getConfig('site_title'),
'meta' => $this->meta,
'content' => $this->content,
'pages' => $this->pages,
'prev_page' => $this->previousPage,
'current_page' => $this->currentPage,
'next_page' => $this->nextPage,
'version' => static::VERSION
);
} | php | protected function getTwigVariables()
{
return array(
'config' => $this->getConfig(),
'base_dir' => rtrim($this->getRootDir(), '/'),
'base_url' => rtrim($this->getBaseUrl(), '/'),
'theme_dir' => $this->getThemesDir() . $this->getConfig('theme'),
'theme_url' => $this->getBaseThemeUrl() . $this->getConfig('theme'),
'site_title' => $this->getConfig('site_title'),
'meta' => $this->meta,
'content' => $this->content,
'pages' => $this->pages,
'prev_page' => $this->previousPage,
'current_page' => $this->currentPage,
'next_page' => $this->nextPage,
'version' => static::VERSION
);
} | [
"protected",
"function",
"getTwigVariables",
"(",
")",
"{",
"return",
"array",
"(",
"'config'",
"=>",
"$",
"this",
"->",
"getConfig",
"(",
")",
",",
"'base_dir'",
"=>",
"rtrim",
"(",
"$",
"this",
"->",
"getRootDir",
"(",
")",
",",
"'/'",
")",
",",
"'base_url'",
"=>",
"rtrim",
"(",
"$",
"this",
"->",
"getBaseUrl",
"(",
")",
",",
"'/'",
")",
",",
"'theme_dir'",
"=>",
"$",
"this",
"->",
"getThemesDir",
"(",
")",
".",
"$",
"this",
"->",
"getConfig",
"(",
"'theme'",
")",
",",
"'theme_url'",
"=>",
"$",
"this",
"->",
"getBaseThemeUrl",
"(",
")",
".",
"$",
"this",
"->",
"getConfig",
"(",
"'theme'",
")",
",",
"'site_title'",
"=>",
"$",
"this",
"->",
"getConfig",
"(",
"'site_title'",
")",
",",
"'meta'",
"=>",
"$",
"this",
"->",
"meta",
",",
"'content'",
"=>",
"$",
"this",
"->",
"content",
",",
"'pages'",
"=>",
"$",
"this",
"->",
"pages",
",",
"'prev_page'",
"=>",
"$",
"this",
"->",
"previousPage",
",",
"'current_page'",
"=>",
"$",
"this",
"->",
"currentPage",
",",
"'next_page'",
"=>",
"$",
"this",
"->",
"nextPage",
",",
"'version'",
"=>",
"static",
"::",
"VERSION",
")",
";",
"}"
] | Returns the variables passed to the template
URLs and paths (namely `base_dir`, `base_url`, `theme_dir` and
`theme_url`) don't add a trailing slash for historic reasons.
@return array template variables | [
"Returns",
"the",
"variables",
"passed",
"to",
"the",
"template"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/Pico.php#L1993-L2010 | train |
picocms/Pico | lib/Pico.php | Pico.getBaseUrl | public function getBaseUrl()
{
$baseUrl = $this->getConfig('base_url');
if ($baseUrl) {
return $baseUrl;
}
$host = 'localhost';
if (!empty($_SERVER['HTTP_X_FORWARDED_HOST'])) {
$host = $_SERVER['HTTP_X_FORWARDED_HOST'];
} elseif (!empty($_SERVER['HTTP_HOST'])) {
$host = $_SERVER['HTTP_HOST'];
} elseif (!empty($_SERVER['SERVER_NAME'])) {
$host = $_SERVER['SERVER_NAME'];
}
$port = 80;
if (!empty($_SERVER['HTTP_X_FORWARDED_PORT'])) {
$port = (int) $_SERVER['HTTP_X_FORWARDED_PORT'];
} elseif (!empty($_SERVER['SERVER_PORT'])) {
$port = (int) $_SERVER['SERVER_PORT'];
}
$hostPortPosition = ($host[0] === '[') ? strpos($host, ':', strrpos($host, ']') ?: 0) : strrpos($host, ':');
if ($hostPortPosition !== false) {
$port = (int) substr($host, $hostPortPosition + 1);
$host = substr($host, 0, $hostPortPosition);
}
$protocol = 'http';
if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
$secureProxyHeader = strtolower(current(explode(',', $_SERVER['HTTP_X_FORWARDED_PROTO'])));
$protocol = in_array($secureProxyHeader, array('https', 'on', 'ssl', '1'), true) ? 'https' : 'http';
} elseif (!empty($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] !== 'off')) {
$protocol = 'https';
} elseif ($port === 443) {
$protocol = 'https';
}
$basePath = isset($_SERVER['SCRIPT_NAME']) ? dirname($_SERVER['SCRIPT_NAME']) : '/';
$basePath = !in_array($basePath, array('.', '/', '\\'), true) ? $basePath . '/' : '/';
if ((($protocol === 'http') && ($port !== 80)) || (($protocol === 'https') && ($port !== 443))) {
$host = $host . ':' . $port;
}
$this->config['base_url'] = $protocol . "://" . $host . $basePath;
return $this->config['base_url'];
} | php | public function getBaseUrl()
{
$baseUrl = $this->getConfig('base_url');
if ($baseUrl) {
return $baseUrl;
}
$host = 'localhost';
if (!empty($_SERVER['HTTP_X_FORWARDED_HOST'])) {
$host = $_SERVER['HTTP_X_FORWARDED_HOST'];
} elseif (!empty($_SERVER['HTTP_HOST'])) {
$host = $_SERVER['HTTP_HOST'];
} elseif (!empty($_SERVER['SERVER_NAME'])) {
$host = $_SERVER['SERVER_NAME'];
}
$port = 80;
if (!empty($_SERVER['HTTP_X_FORWARDED_PORT'])) {
$port = (int) $_SERVER['HTTP_X_FORWARDED_PORT'];
} elseif (!empty($_SERVER['SERVER_PORT'])) {
$port = (int) $_SERVER['SERVER_PORT'];
}
$hostPortPosition = ($host[0] === '[') ? strpos($host, ':', strrpos($host, ']') ?: 0) : strrpos($host, ':');
if ($hostPortPosition !== false) {
$port = (int) substr($host, $hostPortPosition + 1);
$host = substr($host, 0, $hostPortPosition);
}
$protocol = 'http';
if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
$secureProxyHeader = strtolower(current(explode(',', $_SERVER['HTTP_X_FORWARDED_PROTO'])));
$protocol = in_array($secureProxyHeader, array('https', 'on', 'ssl', '1'), true) ? 'https' : 'http';
} elseif (!empty($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] !== 'off')) {
$protocol = 'https';
} elseif ($port === 443) {
$protocol = 'https';
}
$basePath = isset($_SERVER['SCRIPT_NAME']) ? dirname($_SERVER['SCRIPT_NAME']) : '/';
$basePath = !in_array($basePath, array('.', '/', '\\'), true) ? $basePath . '/' : '/';
if ((($protocol === 'http') && ($port !== 80)) || (($protocol === 'https') && ($port !== 443))) {
$host = $host . ':' . $port;
}
$this->config['base_url'] = $protocol . "://" . $host . $basePath;
return $this->config['base_url'];
} | [
"public",
"function",
"getBaseUrl",
"(",
")",
"{",
"$",
"baseUrl",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'base_url'",
")",
";",
"if",
"(",
"$",
"baseUrl",
")",
"{",
"return",
"$",
"baseUrl",
";",
"}",
"$",
"host",
"=",
"'localhost'",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"_SERVER",
"[",
"'HTTP_X_FORWARDED_HOST'",
"]",
")",
")",
"{",
"$",
"host",
"=",
"$",
"_SERVER",
"[",
"'HTTP_X_FORWARDED_HOST'",
"]",
";",
"}",
"elseif",
"(",
"!",
"empty",
"(",
"$",
"_SERVER",
"[",
"'HTTP_HOST'",
"]",
")",
")",
"{",
"$",
"host",
"=",
"$",
"_SERVER",
"[",
"'HTTP_HOST'",
"]",
";",
"}",
"elseif",
"(",
"!",
"empty",
"(",
"$",
"_SERVER",
"[",
"'SERVER_NAME'",
"]",
")",
")",
"{",
"$",
"host",
"=",
"$",
"_SERVER",
"[",
"'SERVER_NAME'",
"]",
";",
"}",
"$",
"port",
"=",
"80",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"_SERVER",
"[",
"'HTTP_X_FORWARDED_PORT'",
"]",
")",
")",
"{",
"$",
"port",
"=",
"(",
"int",
")",
"$",
"_SERVER",
"[",
"'HTTP_X_FORWARDED_PORT'",
"]",
";",
"}",
"elseif",
"(",
"!",
"empty",
"(",
"$",
"_SERVER",
"[",
"'SERVER_PORT'",
"]",
")",
")",
"{",
"$",
"port",
"=",
"(",
"int",
")",
"$",
"_SERVER",
"[",
"'SERVER_PORT'",
"]",
";",
"}",
"$",
"hostPortPosition",
"=",
"(",
"$",
"host",
"[",
"0",
"]",
"===",
"'['",
")",
"?",
"strpos",
"(",
"$",
"host",
",",
"':'",
",",
"strrpos",
"(",
"$",
"host",
",",
"']'",
")",
"?",
":",
"0",
")",
":",
"strrpos",
"(",
"$",
"host",
",",
"':'",
")",
";",
"if",
"(",
"$",
"hostPortPosition",
"!==",
"false",
")",
"{",
"$",
"port",
"=",
"(",
"int",
")",
"substr",
"(",
"$",
"host",
",",
"$",
"hostPortPosition",
"+",
"1",
")",
";",
"$",
"host",
"=",
"substr",
"(",
"$",
"host",
",",
"0",
",",
"$",
"hostPortPosition",
")",
";",
"}",
"$",
"protocol",
"=",
"'http'",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"_SERVER",
"[",
"'HTTP_X_FORWARDED_PROTO'",
"]",
")",
")",
"{",
"$",
"secureProxyHeader",
"=",
"strtolower",
"(",
"current",
"(",
"explode",
"(",
"','",
",",
"$",
"_SERVER",
"[",
"'HTTP_X_FORWARDED_PROTO'",
"]",
")",
")",
")",
";",
"$",
"protocol",
"=",
"in_array",
"(",
"$",
"secureProxyHeader",
",",
"array",
"(",
"'https'",
",",
"'on'",
",",
"'ssl'",
",",
"'1'",
")",
",",
"true",
")",
"?",
"'https'",
":",
"'http'",
";",
"}",
"elseif",
"(",
"!",
"empty",
"(",
"$",
"_SERVER",
"[",
"'HTTPS'",
"]",
")",
"&&",
"(",
"$",
"_SERVER",
"[",
"'HTTPS'",
"]",
"!==",
"'off'",
")",
")",
"{",
"$",
"protocol",
"=",
"'https'",
";",
"}",
"elseif",
"(",
"$",
"port",
"===",
"443",
")",
"{",
"$",
"protocol",
"=",
"'https'",
";",
"}",
"$",
"basePath",
"=",
"isset",
"(",
"$",
"_SERVER",
"[",
"'SCRIPT_NAME'",
"]",
")",
"?",
"dirname",
"(",
"$",
"_SERVER",
"[",
"'SCRIPT_NAME'",
"]",
")",
":",
"'/'",
";",
"$",
"basePath",
"=",
"!",
"in_array",
"(",
"$",
"basePath",
",",
"array",
"(",
"'.'",
",",
"'/'",
",",
"'\\\\'",
")",
",",
"true",
")",
"?",
"$",
"basePath",
".",
"'/'",
":",
"'/'",
";",
"if",
"(",
"(",
"(",
"$",
"protocol",
"===",
"'http'",
")",
"&&",
"(",
"$",
"port",
"!==",
"80",
")",
")",
"||",
"(",
"(",
"$",
"protocol",
"===",
"'https'",
")",
"&&",
"(",
"$",
"port",
"!==",
"443",
")",
")",
")",
"{",
"$",
"host",
"=",
"$",
"host",
".",
"':'",
".",
"$",
"port",
";",
"}",
"$",
"this",
"->",
"config",
"[",
"'base_url'",
"]",
"=",
"$",
"protocol",
".",
"\"://\"",
".",
"$",
"host",
".",
"$",
"basePath",
";",
"return",
"$",
"this",
"->",
"config",
"[",
"'base_url'",
"]",
";",
"}"
] | Returns the base URL of this Pico instance
Security Notice: You MUST configure Pico's base URL explicitly when
using the base URL in contexts that are potentially vulnerable to
HTTP Host Header Injection attacks (e.g. when generating emails).
@return string the base url | [
"Returns",
"the",
"base",
"URL",
"of",
"this",
"Pico",
"instance"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/Pico.php#L2032-L2080 | train |
picocms/Pico | lib/Pico.php | Pico.isUrlRewritingEnabled | public function isUrlRewritingEnabled()
{
$urlRewritingEnabled = $this->getConfig('rewrite_url');
if ($urlRewritingEnabled !== null) {
return $urlRewritingEnabled;
}
if (isset($_SERVER['PICO_URL_REWRITING'])) {
$this->config['rewrite_url'] = (bool) $_SERVER['PICO_URL_REWRITING'];
} elseif (isset($_SERVER['REDIRECT_PICO_URL_REWRITING'])) {
$this->config['rewrite_url'] = (bool) $_SERVER['REDIRECT_PICO_URL_REWRITING'];
} else {
$this->config['rewrite_url'] = false;
}
return $this->config['rewrite_url'];
} | php | public function isUrlRewritingEnabled()
{
$urlRewritingEnabled = $this->getConfig('rewrite_url');
if ($urlRewritingEnabled !== null) {
return $urlRewritingEnabled;
}
if (isset($_SERVER['PICO_URL_REWRITING'])) {
$this->config['rewrite_url'] = (bool) $_SERVER['PICO_URL_REWRITING'];
} elseif (isset($_SERVER['REDIRECT_PICO_URL_REWRITING'])) {
$this->config['rewrite_url'] = (bool) $_SERVER['REDIRECT_PICO_URL_REWRITING'];
} else {
$this->config['rewrite_url'] = false;
}
return $this->config['rewrite_url'];
} | [
"public",
"function",
"isUrlRewritingEnabled",
"(",
")",
"{",
"$",
"urlRewritingEnabled",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'rewrite_url'",
")",
";",
"if",
"(",
"$",
"urlRewritingEnabled",
"!==",
"null",
")",
"{",
"return",
"$",
"urlRewritingEnabled",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"_SERVER",
"[",
"'PICO_URL_REWRITING'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"config",
"[",
"'rewrite_url'",
"]",
"=",
"(",
"bool",
")",
"$",
"_SERVER",
"[",
"'PICO_URL_REWRITING'",
"]",
";",
"}",
"elseif",
"(",
"isset",
"(",
"$",
"_SERVER",
"[",
"'REDIRECT_PICO_URL_REWRITING'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"config",
"[",
"'rewrite_url'",
"]",
"=",
"(",
"bool",
")",
"$",
"_SERVER",
"[",
"'REDIRECT_PICO_URL_REWRITING'",
"]",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"config",
"[",
"'rewrite_url'",
"]",
"=",
"false",
";",
"}",
"return",
"$",
"this",
"->",
"config",
"[",
"'rewrite_url'",
"]",
";",
"}"
] | Returns TRUE if URL rewriting is enabled
@return bool TRUE if URL rewriting is enabled, FALSE otherwise | [
"Returns",
"TRUE",
"if",
"URL",
"rewriting",
"is",
"enabled"
] | 2cf60e25af993961827e1bf9f54ec1aad7698b09 | https://github.com/picocms/Pico/blob/2cf60e25af993961827e1bf9f54ec1aad7698b09/lib/Pico.php#L2087-L2103 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.