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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
grrr-amsterdam/garp3 | application/modules/g/views/helpers/Vimeo.php | G_View_Helper_Vimeo.render | public function render($vimeo, array $options = array()) {
$this->_setDefaultAttribs($options);
$_attribs = $options['attribs'];
$_attribs['width'] = $options['width'];
$_attribs['height'] = $options['height'];
unset($options['width']);
unset($options['height']);
unset($options['attribs']);
$playerUrl = $this->getPlayerUrl($vimeo, $options);
$_attribs['frameborder'] = 0;
$_attribs['src'] = $playerUrl;
$html = '<iframe' . $this->_htmlAttribs($_attribs) . '></iframe>';
return $html;
} | php | public function render($vimeo, array $options = array()) {
$this->_setDefaultAttribs($options);
$_attribs = $options['attribs'];
$_attribs['width'] = $options['width'];
$_attribs['height'] = $options['height'];
unset($options['width']);
unset($options['height']);
unset($options['attribs']);
$playerUrl = $this->getPlayerUrl($vimeo, $options);
$_attribs['frameborder'] = 0;
$_attribs['src'] = $playerUrl;
$html = '<iframe' . $this->_htmlAttribs($_attribs) . '></iframe>';
return $html;
} | [
"public",
"function",
"render",
"(",
"$",
"vimeo",
",",
"array",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"$",
"this",
"->",
"_setDefaultAttribs",
"(",
"$",
"options",
")",
";",
"$",
"_attribs",
"=",
"$",
"options",
"[",
"'attribs'",
"]",
";... | Render a Vimeo object tag.
@param Garp_Db_Table_Row $vimeo A record from the `vimeo_videos` table (or `media` view)
@param array $options Various rendering options
@return mixed | [
"Render",
"a",
"Vimeo",
"object",
"tag",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/Vimeo.php#L34-L51 | train |
grrr-amsterdam/garp3 | application/modules/g/views/helpers/Vimeo.php | G_View_Helper_Vimeo._setDefaultAttribs | protected function _setDefaultAttribs(&$options) {
$options = $options instanceof Garp_Util_Configuration ?
$options : new Garp_Util_Configuration($options);
$options
->setDefault('height', isset($options['width']) ? round($options['width']*0.55) : 264)
->setDefault('width', 480)
->setDefault('attribs', array());
} | php | protected function _setDefaultAttribs(&$options) {
$options = $options instanceof Garp_Util_Configuration ?
$options : new Garp_Util_Configuration($options);
$options
->setDefault('height', isset($options['width']) ? round($options['width']*0.55) : 264)
->setDefault('width', 480)
->setDefault('attribs', array());
} | [
"protected",
"function",
"_setDefaultAttribs",
"(",
"&",
"$",
"options",
")",
"{",
"$",
"options",
"=",
"$",
"options",
"instanceof",
"Garp_Util_Configuration",
"?",
"$",
"options",
":",
"new",
"Garp_Util_Configuration",
"(",
"$",
"options",
")",
";",
"$",
"op... | Normalize some configuration values.
@param array $options
@return array Modified options | [
"Normalize",
"some",
"configuration",
"values",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/Vimeo.php#L68-L75 | train |
grrr-amsterdam/garp3 | application/modules/g/views/helpers/Vimeo.php | G_View_Helper_Vimeo._setDefaultQueryParams | protected function _setDefaultQueryParams(&$options) {
$options = $options instanceof Garp_Util_Configuration
? $options : new Garp_Util_Configuration($options);
$options
->setDefault('portrait', 0)
->setDefault('title', 0)
->setDefault('byline', 0);
} | php | protected function _setDefaultQueryParams(&$options) {
$options = $options instanceof Garp_Util_Configuration
? $options : new Garp_Util_Configuration($options);
$options
->setDefault('portrait', 0)
->setDefault('title', 0)
->setDefault('byline', 0);
} | [
"protected",
"function",
"_setDefaultQueryParams",
"(",
"&",
"$",
"options",
")",
"{",
"$",
"options",
"=",
"$",
"options",
"instanceof",
"Garp_Util_Configuration",
"?",
"$",
"options",
":",
"new",
"Garp_Util_Configuration",
"(",
"$",
"options",
")",
";",
"$",
... | Normalize some query parameters
@param array $options
@return void
@see https://developers.google.com/youtube/player_parameters | [
"Normalize",
"some",
"query",
"parameters"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/Vimeo.php#L84-L91 | train |
grrr-amsterdam/garp3 | application/modules/g/views/helpers/Video.php | G_View_Helper_Video.getPlayerUrl | public function getPlayerUrl($video, $options = array()) {
$helper = $this->_getSpecializedHelper($video);
return $helper->getPlayerUrl($video, $options);
} | php | public function getPlayerUrl($video, $options = array()) {
$helper = $this->_getSpecializedHelper($video);
return $helper->getPlayerUrl($video, $options);
} | [
"public",
"function",
"getPlayerUrl",
"(",
"$",
"video",
",",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"$",
"helper",
"=",
"$",
"this",
"->",
"_getSpecializedHelper",
"(",
"$",
"video",
")",
";",
"return",
"$",
"helper",
"->",
"getPlayerUrl",
... | Get only a player URL. Some sensible default parameters will be applied.
@param Garp_Db_Table_Row $video A record from a video table
@param array $options Various rendering options
@return string | [
"Get",
"only",
"a",
"player",
"URL",
".",
"Some",
"sensible",
"default",
"parameters",
"will",
"be",
"applied",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/Video.php#L57-L60 | train |
grrr-amsterdam/garp3 | application/modules/g/views/helpers/Video.php | G_View_Helper_Video.isVimeo | public function isVimeo($video) {
$playerurl = (is_string($video) ? $video :
(isset($video['player']) ? $video['player'] : $video));
return preg_match('~player\.vimeo\.com~i', $playerurl);
} | php | public function isVimeo($video) {
$playerurl = (is_string($video) ? $video :
(isset($video['player']) ? $video['player'] : $video));
return preg_match('~player\.vimeo\.com~i', $playerurl);
} | [
"public",
"function",
"isVimeo",
"(",
"$",
"video",
")",
"{",
"$",
"playerurl",
"=",
"(",
"is_string",
"(",
"$",
"video",
")",
"?",
"$",
"video",
":",
"(",
"isset",
"(",
"$",
"video",
"[",
"'player'",
"]",
")",
"?",
"$",
"video",
"[",
"'player'",
... | Check if video is Vimeo
@param Garp_Db_Table_Row|string|array $video
@return bool | [
"Check",
"if",
"video",
"is",
"Vimeo"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/Video.php#L68-L72 | train |
grrr-amsterdam/garp3 | application/modules/g/views/helpers/Video.php | G_View_Helper_Video.isYoutube | public function isYoutube($video) {
$playerurl = (is_string($video) ? $video :
(isset($video['player']) ? $video['player'] : ''));
return preg_match('~youtube\.com~i', $playerurl);
} | php | public function isYoutube($video) {
$playerurl = (is_string($video) ? $video :
(isset($video['player']) ? $video['player'] : ''));
return preg_match('~youtube\.com~i', $playerurl);
} | [
"public",
"function",
"isYoutube",
"(",
"$",
"video",
")",
"{",
"$",
"playerurl",
"=",
"(",
"is_string",
"(",
"$",
"video",
")",
"?",
"$",
"video",
":",
"(",
"isset",
"(",
"$",
"video",
"[",
"'player'",
"]",
")",
"?",
"$",
"video",
"[",
"'player'",... | Check if video is Youtube
@param Garp_Db_Table_Row|string|array $video
@return bool | [
"Check",
"if",
"video",
"is",
"Youtube"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/Video.php#L80-L84 | train |
grrr-amsterdam/garp3 | application/modules/g/views/helpers/Video.php | G_View_Helper_Video._getSpecializedHelper | protected function _getSpecializedHelper($video) {
if ($this->isVimeo($video)) {
return $this->view->vimeo();
} elseif ($this->isYoutube($video)) {
return $this->view->youTube();
}
throw new Exception('Unsupported media type detected: ' . $video);
} | php | protected function _getSpecializedHelper($video) {
if ($this->isVimeo($video)) {
return $this->view->vimeo();
} elseif ($this->isYoutube($video)) {
return $this->view->youTube();
}
throw new Exception('Unsupported media type detected: ' . $video);
} | [
"protected",
"function",
"_getSpecializedHelper",
"(",
"$",
"video",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isVimeo",
"(",
"$",
"video",
")",
")",
"{",
"return",
"$",
"this",
"->",
"view",
"->",
"vimeo",
"(",
")",
";",
"}",
"elseif",
"(",
"$",
"t... | Return either the Vimeo or YouTube helper
@param Garp_Db_Table_Row|string|array $video
@return Zend_View_Helper_Abstract | [
"Return",
"either",
"the",
"Vimeo",
"or",
"YouTube",
"helper"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/Video.php#L92-L99 | train |
grrr-amsterdam/garp3 | library/Garp/Service/Slack/Config.php | Garp_Service_Slack_Config.getParams | public function getParams(array $overrides = null) {
$params = array(
'token' => $this->_token,
'channel' => $this->_channel,
'icon_emoji' => $this->_icon_emoji,
'username' => $this->_username
);
if ($overrides) {
$params = array_merge($params, $overrides);
}
return $params;
} | php | public function getParams(array $overrides = null) {
$params = array(
'token' => $this->_token,
'channel' => $this->_channel,
'icon_emoji' => $this->_icon_emoji,
'username' => $this->_username
);
if ($overrides) {
$params = array_merge($params, $overrides);
}
return $params;
} | [
"public",
"function",
"getParams",
"(",
"array",
"$",
"overrides",
"=",
"null",
")",
"{",
"$",
"params",
"=",
"array",
"(",
"'token'",
"=>",
"$",
"this",
"->",
"_token",
",",
"'channel'",
"=>",
"$",
"this",
"->",
"_channel",
",",
"'icon_emoji'",
"=>",
... | Returns the app-wide configuration parameters.
@param Array $overrides Optional values to pragmatically
override the app-wide configuration. | [
"Returns",
"the",
"app",
"-",
"wide",
"configuration",
"parameters",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Service/Slack/Config.php#L52-L65 | train |
grrr-amsterdam/garp3 | application/modules/g/views/helpers/GoogleStaticMap.php | G_View_Helper_GoogleStaticMap.getMarkersAsString | public function getMarkersAsString($options){
$markers = '';
foreach ($options['markers'] as $marker) {
$markers .= $marker['lat'] . ',' . $marker['lng'] . '|';
}
return $markers ? substr($markers, 0, -1) : '';
} | php | public function getMarkersAsString($options){
$markers = '';
foreach ($options['markers'] as $marker) {
$markers .= $marker['lat'] . ',' . $marker['lng'] . '|';
}
return $markers ? substr($markers, 0, -1) : '';
} | [
"public",
"function",
"getMarkersAsString",
"(",
"$",
"options",
")",
"{",
"$",
"markers",
"=",
"''",
";",
"foreach",
"(",
"$",
"options",
"[",
"'markers'",
"]",
"as",
"$",
"marker",
")",
"{",
"$",
"markers",
".=",
"$",
"marker",
"[",
"'lat'",
"]",
"... | Walks through markers' array
@param array $options
@return string
@todo: implement other marker options | [
"Walks",
"through",
"markers",
"array"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/GoogleStaticMap.php#L47-L55 | train |
grrr-amsterdam/garp3 | application/modules/g/views/helpers/GoogleStaticMap.php | G_View_Helper_GoogleStaticMap.render | public function render($options = array()) {
$options = array_merge($this->_defaults, $options);
$markers = $this->getMarkersAsString($options);
$img = '';
$img .= '<img src="http://maps.google.com/maps/api/staticmap';
$img .= '?center=' . $options['location']['lat'] . ',' . $options['location']['lng'];
$img .= '&zoom=' . $options['zoomLevel'];
$img .= '&size=' . $options['width'] . 'x' . $options['height'];
$img .= '&maptype=' . $options['mapType'];
$img .= ($markers ? '&markers=' . $markers : '');
$img .= '&sensor=' . ($options['sensor'] ? 'true' : 'false') . '" ';
$img .= 'width="' . $options['width'] . '" height="' . $options['height'] . '" alt="';
$img .= $options['altText'] . '" class="g-googlemap" />';
$this->view->script()->src(
'https://www.google.com/maps/api/js?sensor=' . ($options['sensor'] ? 'true' : 'false')
);
return $img;
} | php | public function render($options = array()) {
$options = array_merge($this->_defaults, $options);
$markers = $this->getMarkersAsString($options);
$img = '';
$img .= '<img src="http://maps.google.com/maps/api/staticmap';
$img .= '?center=' . $options['location']['lat'] . ',' . $options['location']['lng'];
$img .= '&zoom=' . $options['zoomLevel'];
$img .= '&size=' . $options['width'] . 'x' . $options['height'];
$img .= '&maptype=' . $options['mapType'];
$img .= ($markers ? '&markers=' . $markers : '');
$img .= '&sensor=' . ($options['sensor'] ? 'true' : 'false') . '" ';
$img .= 'width="' . $options['width'] . '" height="' . $options['height'] . '" alt="';
$img .= $options['altText'] . '" class="g-googlemap" />';
$this->view->script()->src(
'https://www.google.com/maps/api/js?sensor=' . ($options['sensor'] ? 'true' : 'false')
);
return $img;
} | [
"public",
"function",
"render",
"(",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"$",
"options",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"_defaults",
",",
"$",
"options",
")",
";",
"$",
"markers",
"=",
"$",
"this",
"->",
"getMarkersAsString",... | Render the map
@param array $options
@return string | [
"Render",
"the",
"map"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/GoogleStaticMap.php#L63-L82 | train |
grrr-amsterdam/garp3 | library/Garp/Mail/Transport/AmazonSes.php | Garp_Mail_Transport_AmazonSes._sendMail | public function _sendMail()
{
$date = gmdate('D, d M Y H:i:s O');
//Send the request
$client = new Zend_Http_Client($this->_host);
$client->setMethod(Zend_Http_Client::POST);
$client->setHeaders(array(
'Date' => $date,
'X-Amzn-Authorization' => $this->_buildAuthKey($date)
));
$client->setEncType('application/x-www-form-urlencoded');
//Build the parameters
$params = array(
'Action' => 'SendRawEmail',
'Source' => $this->_mail->getFrom(),
'RawMessage.Data' => base64_encode(sprintf("%s\n%s\n", $this->header, $this->body))
);
$recipients = explode(',', $this->recipients);
while(list($index, $recipient) = each($recipients)){
$params[sprintf('Destination.ToAddresses.member.%d', $index + 1)] = $recipient;
}
$client->resetParameters();
$client->setParameterPost($params);
$response = $client->request(Zend_Http_Client::POST);
if($response->getStatus() != 200){
throw new Exception($response->getBody());
}
} | php | public function _sendMail()
{
$date = gmdate('D, d M Y H:i:s O');
//Send the request
$client = new Zend_Http_Client($this->_host);
$client->setMethod(Zend_Http_Client::POST);
$client->setHeaders(array(
'Date' => $date,
'X-Amzn-Authorization' => $this->_buildAuthKey($date)
));
$client->setEncType('application/x-www-form-urlencoded');
//Build the parameters
$params = array(
'Action' => 'SendRawEmail',
'Source' => $this->_mail->getFrom(),
'RawMessage.Data' => base64_encode(sprintf("%s\n%s\n", $this->header, $this->body))
);
$recipients = explode(',', $this->recipients);
while(list($index, $recipient) = each($recipients)){
$params[sprintf('Destination.ToAddresses.member.%d', $index + 1)] = $recipient;
}
$client->resetParameters();
$client->setParameterPost($params);
$response = $client->request(Zend_Http_Client::POST);
if($response->getStatus() != 200){
throw new Exception($response->getBody());
}
} | [
"public",
"function",
"_sendMail",
"(",
")",
"{",
"$",
"date",
"=",
"gmdate",
"(",
"'D, d M Y H:i:s O'",
")",
";",
"//Send the request",
"$",
"client",
"=",
"new",
"Zend_Http_Client",
"(",
"$",
"this",
"->",
"_host",
")",
";",
"$",
"client",
"->",
"setMeth... | Send an email using the amazon webservice api
@return void | [
"Send",
"an",
"email",
"using",
"the",
"amazon",
"webservice",
"api"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Mail/Transport/AmazonSes.php#L88-L120 | train |
grrr-amsterdam/garp3 | library/Garp/Mail/Transport/AmazonSes.php | Garp_Mail_Transport_AmazonSes._buildAuthKey | private function _buildAuthKey($date){
return sprintf('AWS3-HTTPS AWSAccessKeyId=%s,Algorithm=HmacSHA256,Signature=%s', $this->_accessKey, base64_encode(hash_hmac('sha256', $date, $this->_privateKey, TRUE)));
} | php | private function _buildAuthKey($date){
return sprintf('AWS3-HTTPS AWSAccessKeyId=%s,Algorithm=HmacSHA256,Signature=%s', $this->_accessKey, base64_encode(hash_hmac('sha256', $date, $this->_privateKey, TRUE)));
} | [
"private",
"function",
"_buildAuthKey",
"(",
"$",
"date",
")",
"{",
"return",
"sprintf",
"(",
"'AWS3-HTTPS AWSAccessKeyId=%s,Algorithm=HmacSHA256,Signature=%s'",
",",
"$",
"this",
"->",
"_accessKey",
",",
"base64_encode",
"(",
"hash_hmac",
"(",
"'sha256'",
",",
"$",
... | Returns header string containing encoded authentication key
@param date $date
@return string | [
"Returns",
"header",
"string",
"containing",
"encoded",
"authentication",
"key"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Mail/Transport/AmazonSes.php#L156-L158 | train |
grrr-amsterdam/garp3 | library/Garp/Cli/Command/Spawn.php | Garp_Cli_Command_Spawn._spawn | protected function _spawn() {
$filter = $this->getFilter();
$dbShouldSpawn = $filter->shouldSpawnDb();
$jsShouldSpawn = $filter->shouldSpawnJs();
$phpShouldSpawn = $filter->shouldSpawnPhp();
$someFilesShouldSpawn = $jsShouldSpawn || $phpShouldSpawn;
if ($someFilesShouldSpawn) {
$this->_spawnFiles();
}
if ($this->getFeedback()->isInteractive()) {
Garp_Cli::lineOut("\n");
}
if ($dbShouldSpawn) {
$this->_spawnDb();
};
} | php | protected function _spawn() {
$filter = $this->getFilter();
$dbShouldSpawn = $filter->shouldSpawnDb();
$jsShouldSpawn = $filter->shouldSpawnJs();
$phpShouldSpawn = $filter->shouldSpawnPhp();
$someFilesShouldSpawn = $jsShouldSpawn || $phpShouldSpawn;
if ($someFilesShouldSpawn) {
$this->_spawnFiles();
}
if ($this->getFeedback()->isInteractive()) {
Garp_Cli::lineOut("\n");
}
if ($dbShouldSpawn) {
$this->_spawnDb();
};
} | [
"protected",
"function",
"_spawn",
"(",
")",
"{",
"$",
"filter",
"=",
"$",
"this",
"->",
"getFilter",
"(",
")",
";",
"$",
"dbShouldSpawn",
"=",
"$",
"filter",
"->",
"shouldSpawnDb",
"(",
")",
";",
"$",
"jsShouldSpawn",
"=",
"$",
"filter",
"->",
"should... | Spawn JS and PHP files and the database structure.
@return void | [
"Spawn",
"JS",
"and",
"PHP",
"files",
"and",
"the",
"database",
"structure",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cli/Command/Spawn.php#L127-L146 | train |
grrr-amsterdam/garp3 | library/Garp/Cli/Command/Spawn.php | Garp_Cli_Command_Spawn._isHelpRequested | protected function _isHelpRequested($args) {
if (array_key_exists('help', $args)) {
return true;
}
if (!$this->_isFirstArgumentGiven($args)) {
return false;
}
$helpWasAsked = strcasecmp($args[0], 'help') === 0;
return $helpWasAsked;
} | php | protected function _isHelpRequested($args) {
if (array_key_exists('help', $args)) {
return true;
}
if (!$this->_isFirstArgumentGiven($args)) {
return false;
}
$helpWasAsked = strcasecmp($args[0], 'help') === 0;
return $helpWasAsked;
} | [
"protected",
"function",
"_isHelpRequested",
"(",
"$",
"args",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"'help'",
",",
"$",
"args",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"_isFirstArgumentGiven",
"(",
"$",
"a... | Detects whether the CLI user was asking for help.
@param array $args
@return bool | [
"Detects",
"whether",
"the",
"CLI",
"user",
"was",
"asking",
"for",
"help",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cli/Command/Spawn.php#L249-L260 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/HtmlFilterable.php | Garp_Model_Behavior_HtmlFilterable.filter | public function filter($string, HTMLPurifier_Config $config) {
if (!$string) {
return $string;
}
$config->finalize();
$purifier = new HTMLPurifier($config);
$string = $purifier->purify($string);
return $string;
} | php | public function filter($string, HTMLPurifier_Config $config) {
if (!$string) {
return $string;
}
$config->finalize();
$purifier = new HTMLPurifier($config);
$string = $purifier->purify($string);
return $string;
} | [
"public",
"function",
"filter",
"(",
"$",
"string",
",",
"HTMLPurifier_Config",
"$",
"config",
")",
"{",
"if",
"(",
"!",
"$",
"string",
")",
"{",
"return",
"$",
"string",
";",
"}",
"$",
"config",
"->",
"finalize",
"(",
")",
";",
"$",
"purifier",
"=",... | Filter unwanted HTML out of a string
@param String $string The string
@param HTMLPurifier_Config $config
@return String The filtered string | [
"Filter",
"unwanted",
"HTML",
"out",
"of",
"a",
"string"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/HtmlFilterable.php#L49-L57 | train |
grrr-amsterdam/garp3 | library/Garp/Cli/Command/Aws.php | Garp_Cli_Command_Aws._exec | protected function _exec($group, $subCmd, $args) {
$keys = array_keys($args);
$cmd = "aws $group $subCmd";
foreach ($keys as $key) {
$cmd .= is_numeric($key) ? ' ' : " --{$key}";
$cmd .= true === $args[$key] ? '' : ' ' . $args[$key];
}
$cmd .= " --profile {$this->_profile}";
return passthru($cmd);
} | php | protected function _exec($group, $subCmd, $args) {
$keys = array_keys($args);
$cmd = "aws $group $subCmd";
foreach ($keys as $key) {
$cmd .= is_numeric($key) ? ' ' : " --{$key}";
$cmd .= true === $args[$key] ? '' : ' ' . $args[$key];
}
$cmd .= " --profile {$this->_profile}";
return passthru($cmd);
} | [
"protected",
"function",
"_exec",
"(",
"$",
"group",
",",
"$",
"subCmd",
",",
"$",
"args",
")",
"{",
"$",
"keys",
"=",
"array_keys",
"(",
"$",
"args",
")",
";",
"$",
"cmd",
"=",
"\"aws $group $subCmd\"",
";",
"foreach",
"(",
"$",
"keys",
"as",
"$",
... | Execute awscmd function
@param str $group For instance s3, or ec2
@param str $subCmd For instance 'ls' or 'cp'
@param array $args Further commandline arguments
@return bool | [
"Execute",
"awscmd",
"function"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cli/Command/Aws.php#L96-L106 | train |
grrr-amsterdam/garp3 | library/Garp/Cli/Command/Aws.php | Garp_Cli_Command_Aws._setProfile | protected function _setProfile() {
$projectName = basename(dirname(realpath(APPLICATION_PATH)));
$profileName = $projectName . '_' . APPLICATION_ENV;
$this->_profile = $profileName;
} | php | protected function _setProfile() {
$projectName = basename(dirname(realpath(APPLICATION_PATH)));
$profileName = $projectName . '_' . APPLICATION_ENV;
$this->_profile = $profileName;
} | [
"protected",
"function",
"_setProfile",
"(",
")",
"{",
"$",
"projectName",
"=",
"basename",
"(",
"dirname",
"(",
"realpath",
"(",
"APPLICATION_PATH",
")",
")",
")",
";",
"$",
"profileName",
"=",
"$",
"projectName",
".",
"'_'",
".",
"APPLICATION_ENV",
";",
... | Set the current profile
@return void | [
"Set",
"the",
"current",
"profile"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cli/Command/Aws.php#L113-L118 | train |
grrr-amsterdam/garp3 | library/Garp/Cli/Command/Aws.php | Garp_Cli_Command_Aws._profileExists | protected function _profileExists() {
$homeDir = trim(`echo \$HOME`);
$config = file_get_contents($homeDir . DIRECTORY_SEPARATOR . self::AWS_CONFIG_LOCATION);
return strpos($config, "[profile {$this->_profile}]") !== false;
} | php | protected function _profileExists() {
$homeDir = trim(`echo \$HOME`);
$config = file_get_contents($homeDir . DIRECTORY_SEPARATOR . self::AWS_CONFIG_LOCATION);
return strpos($config, "[profile {$this->_profile}]") !== false;
} | [
"protected",
"function",
"_profileExists",
"(",
")",
"{",
"$",
"homeDir",
"=",
"trim",
"(",
"`echo \\$HOME`",
")",
";",
"$",
"config",
"=",
"file_get_contents",
"(",
"$",
"homeDir",
".",
"DIRECTORY_SEPARATOR",
".",
"self",
"::",
"AWS_CONFIG_LOCATION",
")",
";"... | Check if the current profile exists
@return bool | [
"Check",
"if",
"the",
"current",
"profile",
"exists"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cli/Command/Aws.php#L125-L129 | train |
grrr-amsterdam/garp3 | library/Garp/Cli/Command/Aws.php | Garp_Cli_Command_Aws._createProfile | protected function _createProfile() {
$config = Zend_Registry::get('config');
$confStr = "[profile {$this->_profile}]\n";
$confStr .= "aws_access_key_id = {$config->cdn->s3->apikey}\n";
$confStr .= "aws_secret_access_key = {$config->cdn->s3->secret}\n";
$confStr .= "output = json\n";
$confStr .= "region = eu-west-1\n\n";
$homeDir = trim(`echo \$HOME`);
file_put_contents(
$homeDir . DIRECTORY_SEPARATOR . self::AWS_CONFIG_LOCATION,
$confStr, FILE_APPEND
);
} | php | protected function _createProfile() {
$config = Zend_Registry::get('config');
$confStr = "[profile {$this->_profile}]\n";
$confStr .= "aws_access_key_id = {$config->cdn->s3->apikey}\n";
$confStr .= "aws_secret_access_key = {$config->cdn->s3->secret}\n";
$confStr .= "output = json\n";
$confStr .= "region = eu-west-1\n\n";
$homeDir = trim(`echo \$HOME`);
file_put_contents(
$homeDir . DIRECTORY_SEPARATOR . self::AWS_CONFIG_LOCATION,
$confStr, FILE_APPEND
);
} | [
"protected",
"function",
"_createProfile",
"(",
")",
"{",
"$",
"config",
"=",
"Zend_Registry",
"::",
"get",
"(",
"'config'",
")",
";",
"$",
"confStr",
"=",
"\"[profile {$this->_profile}]\\n\"",
";",
"$",
"confStr",
".=",
"\"aws_access_key_id = {$config->cdn->s3->apike... | Create the currently used profile
@return void | [
"Create",
"the",
"currently",
"used",
"profile"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cli/Command/Aws.php#L136-L150 | train |
grrr-amsterdam/garp3 | library/Garp/Cli/Command/Aws.php | Garp_Cli_Command_Aws._usesAmazon | protected function _usesAmazon() {
$config = Zend_Registry::get('config');
return !empty($config->cdn->s3->apikey) && !empty($config->cdn->s3->secret);
} | php | protected function _usesAmazon() {
$config = Zend_Registry::get('config');
return !empty($config->cdn->s3->apikey) && !empty($config->cdn->s3->secret);
} | [
"protected",
"function",
"_usesAmazon",
"(",
")",
"{",
"$",
"config",
"=",
"Zend_Registry",
"::",
"get",
"(",
"'config'",
")",
";",
"return",
"!",
"empty",
"(",
"$",
"config",
"->",
"cdn",
"->",
"s3",
"->",
"apikey",
")",
"&&",
"!",
"empty",
"(",
"$"... | Check wether environment actually uses Amazon
@return bool | [
"Check",
"wether",
"environment",
"actually",
"uses",
"Amazon"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cli/Command/Aws.php#L157-L160 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/ContentController.php | G_ContentController.init | public function init() {
// Do not cache CMS pages. This prevents a common situation where people logout, return to
// the CMS, and see the interface but none of the content feeds load. Only after a browser
// refresh they'll get bounced to the login page.
$this->_helper->cache->setNoCacheHeaders($this->getResponse());
$config = Zend_Registry::get('config');
$this->_setCmsClosedMessage();
if (!$config->cms || !$config->cms->ipfilter || !count($config->cms->ipfilter->toArray())) {
return true;
}
$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
if ($ip === '127.0.0.1') {
// i mean come on
return true;
}
if (!in_array($ip, $config->cms->ipfilter->toArray())) {
$authVars = Garp_Auth::getInstance()->getConfigValues();
$this->_helper->flashMessenger(__($authVars['noPermissionMsg']));
$this->_helper->redirector->gotoRoute(array(), $authVars['login']['route']);
return false;
}
} | php | public function init() {
// Do not cache CMS pages. This prevents a common situation where people logout, return to
// the CMS, and see the interface but none of the content feeds load. Only after a browser
// refresh they'll get bounced to the login page.
$this->_helper->cache->setNoCacheHeaders($this->getResponse());
$config = Zend_Registry::get('config');
$this->_setCmsClosedMessage();
if (!$config->cms || !$config->cms->ipfilter || !count($config->cms->ipfilter->toArray())) {
return true;
}
$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
if ($ip === '127.0.0.1') {
// i mean come on
return true;
}
if (!in_array($ip, $config->cms->ipfilter->toArray())) {
$authVars = Garp_Auth::getInstance()->getConfigValues();
$this->_helper->flashMessenger(__($authVars['noPermissionMsg']));
$this->_helper->redirector->gotoRoute(array(), $authVars['login']['route']);
return false;
}
} | [
"public",
"function",
"init",
"(",
")",
"{",
"// Do not cache CMS pages. This prevents a common situation where people logout, return to",
"// the CMS, and see the interface but none of the content feeds load. Only after a browser",
"// refresh they'll get bounced to the login page.",
"$",
"this... | Called before all actions
@return Void | [
"Called",
"before",
"all",
"actions"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/ContentController.php#L23-L45 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/ContentController.php | G_ContentController.cookiesAction | public function cookiesAction() {
$config = Zend_Registry::get('config');
$viewBasePath = $config->resources->view->basePath ?:
APPLICATION_PATH . '/modules/default/views';
$this->_helper->layout->setLayoutPath($viewBasePath . '/layouts/');
$this->view->title = 'Cookies';
} | php | public function cookiesAction() {
$config = Zend_Registry::get('config');
$viewBasePath = $config->resources->view->basePath ?:
APPLICATION_PATH . '/modules/default/views';
$this->_helper->layout->setLayoutPath($viewBasePath . '/layouts/');
$this->view->title = 'Cookies';
} | [
"public",
"function",
"cookiesAction",
"(",
")",
"{",
"$",
"config",
"=",
"Zend_Registry",
"::",
"get",
"(",
"'config'",
")",
";",
"$",
"viewBasePath",
"=",
"$",
"config",
"->",
"resources",
"->",
"view",
"->",
"basePath",
"?",
":",
"APPLICATION_PATH",
"."... | Display some information about cookies
@return Void | [
"Display",
"some",
"information",
"about",
"cookies"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/ContentController.php#L88-L95 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/ContentController.php | G_ContentController.apiAction | public function apiAction() {
/**
* Prepare the server. Zend_Json_Server cannot work with batched requests natively,
* so that's taken care of customly here. Therefore, autoEmitResponse is set to false
* so the server doesn't print the response directly.
*/
$server = new Zend_Json_Server();
$server->setClass('Garp_Content_Manager_Proxy');
$server->setAutoEmitResponse(false);
if ($this->getRequest()->isPost()) {
$post = $this->_getJsonRpcRequest();
$batch = false;
$responses = array();
$requests = Zend_Json::decode($post, Zend_Json::TYPE_ARRAY);
/**
* Check if this was a batch request. In that case the array is a plain array of
* arrays. If not, there will be a 'jsonrpc' key in the root of the array.
*/
$batch = !array_key_exists('jsonrpc', $requests);
if (!$batch) {
$requests = array($requests);
}
foreach ($requests as $i => $request) {
$request = $this->_reformJsonRpcRequest($request);
$requestJson = Zend_Json::encode($request);
$requestObj = new Zend_Json_Server_Request();
$requestObj->loadJson($requestJson);
$server->setRequest($requestObj);
/**
* Note; response gets returned by reference, resulting in a $responses array
* containing all the same items.
* That's why clone is used here.
*/
$response = clone $server->handle();
$responses[] = $response;
}
$response = $batch ? '[' . implode(',', $responses) . ']' : $responses[0];
} else {
$response = $server->getServiceMap();
}
$this->_helper->layout->setLayout('json');
// filter out escaped slashes, because they're annoying and not necessary.
$response = str_replace('\/', '/', $response);
$this->view->response = $response;
} | php | public function apiAction() {
/**
* Prepare the server. Zend_Json_Server cannot work with batched requests natively,
* so that's taken care of customly here. Therefore, autoEmitResponse is set to false
* so the server doesn't print the response directly.
*/
$server = new Zend_Json_Server();
$server->setClass('Garp_Content_Manager_Proxy');
$server->setAutoEmitResponse(false);
if ($this->getRequest()->isPost()) {
$post = $this->_getJsonRpcRequest();
$batch = false;
$responses = array();
$requests = Zend_Json::decode($post, Zend_Json::TYPE_ARRAY);
/**
* Check if this was a batch request. In that case the array is a plain array of
* arrays. If not, there will be a 'jsonrpc' key in the root of the array.
*/
$batch = !array_key_exists('jsonrpc', $requests);
if (!$batch) {
$requests = array($requests);
}
foreach ($requests as $i => $request) {
$request = $this->_reformJsonRpcRequest($request);
$requestJson = Zend_Json::encode($request);
$requestObj = new Zend_Json_Server_Request();
$requestObj->loadJson($requestJson);
$server->setRequest($requestObj);
/**
* Note; response gets returned by reference, resulting in a $responses array
* containing all the same items.
* That's why clone is used here.
*/
$response = clone $server->handle();
$responses[] = $response;
}
$response = $batch ? '[' . implode(',', $responses) . ']' : $responses[0];
} else {
$response = $server->getServiceMap();
}
$this->_helper->layout->setLayout('json');
// filter out escaped slashes, because they're annoying and not necessary.
$response = str_replace('\/', '/', $response);
$this->view->response = $response;
} | [
"public",
"function",
"apiAction",
"(",
")",
"{",
"/**\n * Prepare the server. Zend_Json_Server cannot work with batched requests natively,\n * so that's taken care of customly here. Therefore, autoEmitResponse is set to false\n * so the server doesn't print the response directly... | JSON-RPC entrance.
@return Void | [
"JSON",
"-",
"RPC",
"entrance",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/ContentController.php#L134-L179 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/ContentController.php | G_ContentController.downloadAction | public function downloadAction() {
$ini = Zend_Registry::get('config');
$downloadType = $this->getRequest()->getParam('downloadType') ?: Garp_File::TYPE_DOCUMENTS;
$uploadOrStatic = $this->getRequest()->getParam('uploadOrStatic') ?: 'upload';
$file = $this->getRequest()->getParam('file');
if (!$file) {
throw new Zend_Controller_Action_Exception('Geen bestandsnaam opgegeven.', 404);
}
try {
$fileHandler = new Garp_File($downloadType, $uploadOrStatic);
$url = $fileHandler->getUrl($file);
$this->_downloadFile($url);
} catch (Garp_File_Exception_InvalidType $e) {
// Just throw a 404, since the error is basically just a wrong URL.
throw new Zend_Controller_Action_Exception($e->getMessage(), 404);
}
} | php | public function downloadAction() {
$ini = Zend_Registry::get('config');
$downloadType = $this->getRequest()->getParam('downloadType') ?: Garp_File::TYPE_DOCUMENTS;
$uploadOrStatic = $this->getRequest()->getParam('uploadOrStatic') ?: 'upload';
$file = $this->getRequest()->getParam('file');
if (!$file) {
throw new Zend_Controller_Action_Exception('Geen bestandsnaam opgegeven.', 404);
}
try {
$fileHandler = new Garp_File($downloadType, $uploadOrStatic);
$url = $fileHandler->getUrl($file);
$this->_downloadFile($url);
} catch (Garp_File_Exception_InvalidType $e) {
// Just throw a 404, since the error is basically just a wrong URL.
throw new Zend_Controller_Action_Exception($e->getMessage(), 404);
}
} | [
"public",
"function",
"downloadAction",
"(",
")",
"{",
"$",
"ini",
"=",
"Zend_Registry",
"::",
"get",
"(",
"'config'",
")",
";",
"$",
"downloadType",
"=",
"$",
"this",
"->",
"getRequest",
"(",
")",
"->",
"getParam",
"(",
"'downloadType'",
")",
"?",
":",
... | Download an uploaded file
@return Void | [
"Download",
"an",
"uploaded",
"file"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/ContentController.php#L270-L288 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/ContentController.php | G_ContentController.importAction | public function importAction() {
$memLim = ini_get('memory_limit');
ini_set('memory_limit', '2G');
set_time_limit(0); // No time limit
$params = new Garp_Util_Configuration($this->getRequest()->getParams());
$params->obligate('datafile')
->obligate('model')
->setDefault('firstRow', 0)
->setDefault('ignoreErrors', false);
$importer = Garp_Content_Import_Factory::getImporter($params['datafile']);
$success = false;
if (isset($params['mapping'])) {
$mapping = Zend_Json::decode($params['mapping']);
$className = Garp_Content_Api::modelAliasToClass($params['model']);
$model = new $className();
$model->setCmsContext(true);
$response = array();
try {
$success = !!$importer->save(
$model, $mapping, array(
'firstRow' => $params['firstRow'],
'ignoreErrors' => $params['ignoreErrors'],
)
);
} catch (Exception $e) {
$response['message'] = $e->getMessage();
}
if ($success) {
// cleanup input file
$gf = new Garp_File();
$gf->remove($params['datafile']);
}
$response['success'] = $success;
$this->view->response = $response;
} else {
$std = new stdClass();
$std->success = true;
$std->data = $importer->getSampleData();
$this->view->response = $std;
}
ini_set('memory_limit', $memLim);
$this->_helper->layout->setLayout('json');
$this->renderScript('content/call.phtml');
} | php | public function importAction() {
$memLim = ini_get('memory_limit');
ini_set('memory_limit', '2G');
set_time_limit(0); // No time limit
$params = new Garp_Util_Configuration($this->getRequest()->getParams());
$params->obligate('datafile')
->obligate('model')
->setDefault('firstRow', 0)
->setDefault('ignoreErrors', false);
$importer = Garp_Content_Import_Factory::getImporter($params['datafile']);
$success = false;
if (isset($params['mapping'])) {
$mapping = Zend_Json::decode($params['mapping']);
$className = Garp_Content_Api::modelAliasToClass($params['model']);
$model = new $className();
$model->setCmsContext(true);
$response = array();
try {
$success = !!$importer->save(
$model, $mapping, array(
'firstRow' => $params['firstRow'],
'ignoreErrors' => $params['ignoreErrors'],
)
);
} catch (Exception $e) {
$response['message'] = $e->getMessage();
}
if ($success) {
// cleanup input file
$gf = new Garp_File();
$gf->remove($params['datafile']);
}
$response['success'] = $success;
$this->view->response = $response;
} else {
$std = new stdClass();
$std->success = true;
$std->data = $importer->getSampleData();
$this->view->response = $std;
}
ini_set('memory_limit', $memLim);
$this->_helper->layout->setLayout('json');
$this->renderScript('content/call.phtml');
} | [
"public",
"function",
"importAction",
"(",
")",
"{",
"$",
"memLim",
"=",
"ini_get",
"(",
"'memory_limit'",
")",
";",
"ini_set",
"(",
"'memory_limit'",
",",
"'2G'",
")",
";",
"set_time_limit",
"(",
"0",
")",
";",
"// No time limit",
"$",
"params",
"=",
"new... | Import content from various formats.
This action has two states;
- first a datafile is uploaded. The user is presented with a mapping interface
where they have to map columns in the datafile to columns in the database.
- then this URL is called again with the selected mapping, and the columns are
mapped and inserted into the database.
@return Void | [
"Import",
"content",
"from",
"various",
"formats",
".",
"This",
"action",
"has",
"two",
"states",
";",
"-",
"first",
"a",
"datafile",
"is",
"uploaded",
".",
"The",
"user",
"is",
"presented",
"with",
"a",
"mapping",
"interface",
"where",
"they",
"have",
"to... | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/ContentController.php#L379-L426 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/ContentController.php | G_ContentController.exportAction | public function exportAction() {
$mem = new Garp_Util_Memory();
$mem->useHighMemory();
$params = new Garp_Util_Configuration($this->getRequest()->getParams());
// make sure some required parameters are in place
$params->obligate('exporttype')
->obligate('model')
->obligate('selection')
->setDefault('fields', Zend_Db_Select::SQL_WILDCARD);
// fetch exporter
$exporter = Garp_Content_Export_Factory::getExporter($params['exporttype']);
$bytes = $exporter->getOutput($params);
$filename = $exporter->getFilename($params);
$download = Zend_Controller_Action_HelperBroker::getStaticHelper('download');
$download->force($bytes, $filename, $this->_response);
$this->_helper->viewRenderer->setNoRender();
} | php | public function exportAction() {
$mem = new Garp_Util_Memory();
$mem->useHighMemory();
$params = new Garp_Util_Configuration($this->getRequest()->getParams());
// make sure some required parameters are in place
$params->obligate('exporttype')
->obligate('model')
->obligate('selection')
->setDefault('fields', Zend_Db_Select::SQL_WILDCARD);
// fetch exporter
$exporter = Garp_Content_Export_Factory::getExporter($params['exporttype']);
$bytes = $exporter->getOutput($params);
$filename = $exporter->getFilename($params);
$download = Zend_Controller_Action_HelperBroker::getStaticHelper('download');
$download->force($bytes, $filename, $this->_response);
$this->_helper->viewRenderer->setNoRender();
} | [
"public",
"function",
"exportAction",
"(",
")",
"{",
"$",
"mem",
"=",
"new",
"Garp_Util_Memory",
"(",
")",
";",
"$",
"mem",
"->",
"useHighMemory",
"(",
")",
";",
"$",
"params",
"=",
"new",
"Garp_Util_Configuration",
"(",
"$",
"this",
"->",
"getRequest",
... | Export content in various formats
@return Void | [
"Export",
"content",
"in",
"various",
"formats"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/ContentController.php#L433-L452 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/ContentController.php | G_ContentController.clearcacheAction | public function clearcacheAction() {
$request = $this->getRequest();
$tags = array();
if ($request->getParam('tags')) {
$tags = explode(',', $request->getParam('tags'));
}
$createClusterJob = is_null($request->getParam('createClusterJob')) ? 1 :
$request->getParam('createClusterJob');
$this->view->title = 'Clear that cache';
Garp_Cache_Manager::purge($tags, $createClusterJob);
} | php | public function clearcacheAction() {
$request = $this->getRequest();
$tags = array();
if ($request->getParam('tags')) {
$tags = explode(',', $request->getParam('tags'));
}
$createClusterJob = is_null($request->getParam('createClusterJob')) ? 1 :
$request->getParam('createClusterJob');
$this->view->title = 'Clear that cache';
Garp_Cache_Manager::purge($tags, $createClusterJob);
} | [
"public",
"function",
"clearcacheAction",
"(",
")",
"{",
"$",
"request",
"=",
"$",
"this",
"->",
"getRequest",
"(",
")",
";",
"$",
"tags",
"=",
"array",
"(",
")",
";",
"if",
"(",
"$",
"request",
"->",
"getParam",
"(",
"'tags'",
")",
")",
"{",
"$",
... | Clear all cache system wide.
Static Cache is tagged, so a comma-separated list of tags may be given to
only clear cache tagged with those tags.
Memcache is not tagged.
@return Void | [
"Clear",
"all",
"cache",
"system",
"wide",
".",
"Static",
"Cache",
"is",
"tagged",
"so",
"a",
"comma",
"-",
"separated",
"list",
"of",
"tags",
"may",
"be",
"given",
"to",
"only",
"clear",
"cache",
"tagged",
"with",
"those",
"tags",
".",
"Memcache",
"is",... | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/ContentController.php#L462-L473 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/ContentController.php | G_ContentController._getJsonRpcRequest | protected function _getJsonRpcRequest() {
if ($this->getRequest()->getPost('request')) {
return $this->getRequest()->getPost('request');
}
return $request = $this->getRequest()->getRawBody();
} | php | protected function _getJsonRpcRequest() {
if ($this->getRequest()->getPost('request')) {
return $this->getRequest()->getPost('request');
}
return $request = $this->getRequest()->getRawBody();
} | [
"protected",
"function",
"_getJsonRpcRequest",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"getRequest",
"(",
")",
"->",
"getPost",
"(",
"'request'",
")",
")",
"{",
"return",
"$",
"this",
"->",
"getRequest",
"(",
")",
"->",
"getPost",
"(",
"'request'",
... | Retrieve POSTed JSON-RPC request
@return String | [
"Retrieve",
"POSTed",
"JSON",
"-",
"RPC",
"request"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/ContentController.php#L542-L547 | train |
grrr-amsterdam/garp3 | library/Garp/Content/Upload/Mediator.php | Garp_Content_Upload_Mediator.fetchDiff | public function fetchDiff() {
$progress = Garp_Cli_Ui_ProgressBar::getInstance();
$diffList = new Garp_Content_Upload_FileList();
$sourceList = $this->_source->fetchFileList();
$targetList = $this->_target->fetchFileList();
$progress->display("Looking for new files");
$newFiles = $this->_findNewFiles($sourceList, $targetList);
$progress->display("Looking for conflicting files");
$conflictingFiles = $this->_findConflictingFiles($sourceList, $targetList);
$diffList->addEntries($newFiles);
$diffList->addEntries($conflictingFiles);
return $diffList;
} | php | public function fetchDiff() {
$progress = Garp_Cli_Ui_ProgressBar::getInstance();
$diffList = new Garp_Content_Upload_FileList();
$sourceList = $this->_source->fetchFileList();
$targetList = $this->_target->fetchFileList();
$progress->display("Looking for new files");
$newFiles = $this->_findNewFiles($sourceList, $targetList);
$progress->display("Looking for conflicting files");
$conflictingFiles = $this->_findConflictingFiles($sourceList, $targetList);
$diffList->addEntries($newFiles);
$diffList->addEntries($conflictingFiles);
return $diffList;
} | [
"public",
"function",
"fetchDiff",
"(",
")",
"{",
"$",
"progress",
"=",
"Garp_Cli_Ui_ProgressBar",
"::",
"getInstance",
"(",
")",
";",
"$",
"diffList",
"=",
"new",
"Garp_Content_Upload_FileList",
"(",
")",
";",
"$",
"sourceList",
"=",
"$",
"this",
"->",
"_so... | Finds out which files should be transferred.
@return Garp_Content_Upload_FileList List of file paths that should be transferred from source to target. | [
"Finds",
"out",
"which",
"files",
"should",
"be",
"transferred",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Content/Upload/Mediator.php#L54-L71 | train |
grrr-amsterdam/garp3 | library/Garp/I18n/ModelFactory.php | Garp_I18n_ModelFactory.getModel | public function getModel($model) {
$this->_normalizeModel($model);
$langSuffix = ucfirst(strtolower($this->_language));
// Sanity check: is the model already localized?
if ($this->_modelIsLocalized($model)) {
throw new Garp_I18n_ModelFactory_Exception_ModelAlreadyLocalized(
"Looks like model $model is already internationalized."
);
}
$modelName = $model.$langSuffix;
$model = new $modelName();
return $model;
} | php | public function getModel($model) {
$this->_normalizeModel($model);
$langSuffix = ucfirst(strtolower($this->_language));
// Sanity check: is the model already localized?
if ($this->_modelIsLocalized($model)) {
throw new Garp_I18n_ModelFactory_Exception_ModelAlreadyLocalized(
"Looks like model $model is already internationalized."
);
}
$modelName = $model.$langSuffix;
$model = new $modelName();
return $model;
} | [
"public",
"function",
"getModel",
"(",
"$",
"model",
")",
"{",
"$",
"this",
"->",
"_normalizeModel",
"(",
"$",
"model",
")",
";",
"$",
"langSuffix",
"=",
"ucfirst",
"(",
"strtolower",
"(",
"$",
"this",
"->",
"_language",
")",
")",
";",
"// Sanity check: ... | Load the model
@param Garp_Model_Db|String $model The original model, based on a table.
@return Garp_Model_Db | [
"Load",
"the",
"model"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/I18n/ModelFactory.php#L38-L50 | train |
grrr-amsterdam/garp3 | library/Garp/I18n/ModelFactory.php | Garp_I18n_ModelFactory.getBindingModel | public function getBindingModel($bindingModel) {
$this->_normalizeModel($bindingModel);
$bindingModel = new $bindingModel();
$referenceMap = $bindingModel->getReferenceMapNormalized();
foreach ($referenceMap as $rule => $reference) {
// Check here wether we need to internationalize the refTableClass
$refModel = new $reference['refTableClass'];
if ($refModel->getObserver('Translatable')) {
try {
$refModel = $this->getModel($reference['refTableClass']);
} catch (Garp_I18n_ModelFactory_Exception_ModelAlreadyLocalized $e) {
continue;
}
}
$refTableClass = get_class($refModel);
$bindingModel->addReference(
$rule,
$reference['columns'],
$refTableClass,
$reference['refColumns']
);
}
return $bindingModel;
} | php | public function getBindingModel($bindingModel) {
$this->_normalizeModel($bindingModel);
$bindingModel = new $bindingModel();
$referenceMap = $bindingModel->getReferenceMapNormalized();
foreach ($referenceMap as $rule => $reference) {
// Check here wether we need to internationalize the refTableClass
$refModel = new $reference['refTableClass'];
if ($refModel->getObserver('Translatable')) {
try {
$refModel = $this->getModel($reference['refTableClass']);
} catch (Garp_I18n_ModelFactory_Exception_ModelAlreadyLocalized $e) {
continue;
}
}
$refTableClass = get_class($refModel);
$bindingModel->addReference(
$rule,
$reference['columns'],
$refTableClass,
$reference['refColumns']
);
}
return $bindingModel;
} | [
"public",
"function",
"getBindingModel",
"(",
"$",
"bindingModel",
")",
"{",
"$",
"this",
"->",
"_normalizeModel",
"(",
"$",
"bindingModel",
")",
";",
"$",
"bindingModel",
"=",
"new",
"$",
"bindingModel",
"(",
")",
";",
"$",
"referenceMap",
"=",
"$",
"bind... | Retrieve an internationalized bindingModel. Its referenceMap
will be tweaked to reflect the changes given as the second parameter.
@param Garp_Model_Db|String $model The original model, based on a table.
@return Garp_Model_Db | [
"Retrieve",
"an",
"internationalized",
"bindingModel",
".",
"Its",
"referenceMap",
"will",
"be",
"tweaked",
"to",
"reflect",
"the",
"changes",
"given",
"as",
"the",
"second",
"parameter",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/I18n/ModelFactory.php#L58-L82 | train |
grrr-amsterdam/garp3 | library/Garp/I18n/ModelFactory.php | Garp_I18n_ModelFactory._normalizeModel | protected function _normalizeModel(&$model) {
if ($model instanceof Garp_Model_Db) {
$model = get_class($model);
}
$model = strpos($model, 'Model_') !== false ? $model : 'Model_' . $model;
} | php | protected function _normalizeModel(&$model) {
if ($model instanceof Garp_Model_Db) {
$model = get_class($model);
}
$model = strpos($model, 'Model_') !== false ? $model : 'Model_' . $model;
} | [
"protected",
"function",
"_normalizeModel",
"(",
"&",
"$",
"model",
")",
"{",
"if",
"(",
"$",
"model",
"instanceof",
"Garp_Model_Db",
")",
"{",
"$",
"model",
"=",
"get_class",
"(",
"$",
"model",
")",
";",
"}",
"$",
"model",
"=",
"strpos",
"(",
"$",
"... | Go from a modelname to a model object
@param Mixed $model
@return Garp_Model_Db | [
"Go",
"from",
"a",
"modelname",
"to",
"a",
"model",
"object"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/I18n/ModelFactory.php#L107-L112 | train |
grrr-amsterdam/garp3 | library/Garp/Spawn/MySql/View/Joint.php | Garp_Spawn_MySql_View_Joint._getRecordLabelSqlForModel | protected function _getRecordLabelSqlForModel($tableAlias, $modelName) {
$model = $this->_getModelFromModelName($modelName);
$tableName = $this->_getOtherTableName($modelName);
$recordLabelFieldDefs = $this->_getRecordLabelFieldDefinitions($tableAlias, $model);
$labelColumnsListSql = implode(', ', $recordLabelFieldDefs);
$glue = $this->_modelHasFirstAndLastNameListFields($model) ? ' ' : ', ';
$sql = "CONVERT(CONCAT_WS('{$glue}', " . $labelColumnsListSql . ') USING utf8)';
return $sql;
} | php | protected function _getRecordLabelSqlForModel($tableAlias, $modelName) {
$model = $this->_getModelFromModelName($modelName);
$tableName = $this->_getOtherTableName($modelName);
$recordLabelFieldDefs = $this->_getRecordLabelFieldDefinitions($tableAlias, $model);
$labelColumnsListSql = implode(', ', $recordLabelFieldDefs);
$glue = $this->_modelHasFirstAndLastNameListFields($model) ? ' ' : ', ';
$sql = "CONVERT(CONCAT_WS('{$glue}', " . $labelColumnsListSql . ') USING utf8)';
return $sql;
} | [
"protected",
"function",
"_getRecordLabelSqlForModel",
"(",
"$",
"tableAlias",
",",
"$",
"modelName",
")",
"{",
"$",
"model",
"=",
"$",
"this",
"->",
"_getModelFromModelName",
"(",
"$",
"modelName",
")",
";",
"$",
"tableName",
"=",
"$",
"this",
"->",
"_getOt... | Compose the method to fetch composite columns as a string in a MySql query
to use as a label to identify the record. These have to be columns in the provided table,
to be able to be used flexibly in another query.
@param string $tableAlias
@param string $modelName
@return string | [
"Compose",
"the",
"method",
"to",
"fetch",
"composite",
"columns",
"as",
"a",
"string",
"in",
"a",
"MySql",
"query",
"to",
"use",
"as",
"a",
"label",
"to",
"identify",
"the",
"record",
".",
"These",
"have",
"to",
"be",
"columns",
"in",
"the",
"provided",... | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Spawn/MySql/View/Joint.php#L203-L214 | train |
grrr-amsterdam/garp3 | library/Garp/Util/FullName.php | Garp_Util_FullName._getFullName | protected function _getFullName($person) {
if (array_key_exists('first_name', $person)
&& array_key_exists('last_name_prefix', $person)
&& array_key_exists('last_name', $person)
) {
$first = $person['first_name'];
$middle = $person['last_name_prefix'] ? ' ' . $person['last_name_prefix'] : '';
$last = $person['last_name'] ? ' ' . $person['last_name'] : '';
return $first . $middle . $last;
} elseif (array_key_exists('name', $person)) {
return $person['name'];
} else {
throw new Exception(
'This model does not have a first name, last name prefix ' .
'and last name. Nor does it have a singular name field.'
);
}
} | php | protected function _getFullName($person) {
if (array_key_exists('first_name', $person)
&& array_key_exists('last_name_prefix', $person)
&& array_key_exists('last_name', $person)
) {
$first = $person['first_name'];
$middle = $person['last_name_prefix'] ? ' ' . $person['last_name_prefix'] : '';
$last = $person['last_name'] ? ' ' . $person['last_name'] : '';
return $first . $middle . $last;
} elseif (array_key_exists('name', $person)) {
return $person['name'];
} else {
throw new Exception(
'This model does not have a first name, last name prefix ' .
'and last name. Nor does it have a singular name field.'
);
}
} | [
"protected",
"function",
"_getFullName",
"(",
"$",
"person",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"'first_name'",
",",
"$",
"person",
")",
"&&",
"array_key_exists",
"(",
"'last_name_prefix'",
",",
"$",
"person",
")",
"&&",
"array_key_exists",
"(",
"'l... | Create full name
@param Garp_Db_Table_Row|StdClass|array $person
@return string | [
"Create",
"full",
"name"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Util/FullName.php#L41-L58 | train |
grrr-amsterdam/garp3 | library/Garp/Spawn/Behavior/Set.php | Garp_Spawn_Behavior_Set._addWeighableBehavior | protected function _addWeighableBehavior() {
$model = $this->getModel();
$weighableRels = $model->relations->getRelations('weighable', true);
if (!$weighableRels) {
return;
}
$weighableConfig = array();
foreach ($weighableRels as $relName => $rel) {
$weightColumn = Garp_Spawn_Util::camelcased2underscored($relName) . '_weight';
$weighableConfig[$relName] = array(
'foreignKeyColumn' => $rel->column,
'weightColumn' => $weightColumn
);
}
$this->_add('relation', 'Weighable', $weighableConfig);
} | php | protected function _addWeighableBehavior() {
$model = $this->getModel();
$weighableRels = $model->relations->getRelations('weighable', true);
if (!$weighableRels) {
return;
}
$weighableConfig = array();
foreach ($weighableRels as $relName => $rel) {
$weightColumn = Garp_Spawn_Util::camelcased2underscored($relName) . '_weight';
$weighableConfig[$relName] = array(
'foreignKeyColumn' => $rel->column,
'weightColumn' => $weightColumn
);
}
$this->_add('relation', 'Weighable', $weighableConfig);
} | [
"protected",
"function",
"_addWeighableBehavior",
"(",
")",
"{",
"$",
"model",
"=",
"$",
"this",
"->",
"getModel",
"(",
")",
";",
"$",
"weighableRels",
"=",
"$",
"model",
"->",
"relations",
"->",
"getRelations",
"(",
"'weighable'",
",",
"true",
")",
";",
... | Adds the weighable behavior, for user defined sorting of related objects.
Can only be initialized after the relations for this model are set.
@return void | [
"Adds",
"the",
"weighable",
"behavior",
"for",
"user",
"defined",
"sorting",
"of",
"related",
"objects",
".",
"Can",
"only",
"be",
"initialized",
"after",
"the",
"relations",
"for",
"this",
"model",
"are",
"set",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Spawn/Behavior/Set.php#L160-L179 | train |
PhpGt/WebEngine | src/Lifecycle.php | Lifecycle.start | public function start():void {
$server = new ServerInfo($_SERVER);
$cwd = dirname($server->getDocumentRoot());
chdir($cwd);
$config = ConfigFactory::createForProject(
$cwd,
implode(DIRECTORY_SEPARATOR, [
dirname(__DIR__),
"config.default.ini",
])
);
$input = new Input($_GET, $_POST, $_FILES);
$cookie = new CookieHandler($_COOKIE);
$sessionHandler = SessionSetup::attachHandler(
$config->get("session.handler")
);
$sessionConfig = $config->getSection("session");
$sessionId = $cookie[$sessionConfig["name"]];
$sessionHandler = new Session(
$sessionHandler,
$sessionConfig,
$sessionId
);
$databaseSettings = new Settings(
$config->get("database.query_directory"),
$config->get("database.driver"),
$config->get("database.schema"),
$config->get("database.host"),
$config->get("database.port"),
$config->get("database.username"),
$config->get("database.password")
);
$database = new Database($databaseSettings);
$this->protectGlobals();
$this->attachAutoloaders(
$server->getDocumentRoot(),
$config->getSection("app")
);
$request = $this->createServerRequest(
$server,
$input,
$cookie
);
$router = $this->createRouter(
$request,
$server->getDocumentRoot()
);
$csrfProtection = new SessionTokenStore(
$sessionHandler->getStore(
"gt.csrf",
true
)
);
$csrfProtection->processAndVerify(
$input->getAll(Input::DATA_BODY)
);
$dispatcher = $this->createDispatcher(
$config,
$server,
$input,
$cookie,
$sessionHandler,
$database,
$router,
$csrfProtection
);
$response = $this->process($request, $dispatcher);
$this->finish($response);
} | php | public function start():void {
$server = new ServerInfo($_SERVER);
$cwd = dirname($server->getDocumentRoot());
chdir($cwd);
$config = ConfigFactory::createForProject(
$cwd,
implode(DIRECTORY_SEPARATOR, [
dirname(__DIR__),
"config.default.ini",
])
);
$input = new Input($_GET, $_POST, $_FILES);
$cookie = new CookieHandler($_COOKIE);
$sessionHandler = SessionSetup::attachHandler(
$config->get("session.handler")
);
$sessionConfig = $config->getSection("session");
$sessionId = $cookie[$sessionConfig["name"]];
$sessionHandler = new Session(
$sessionHandler,
$sessionConfig,
$sessionId
);
$databaseSettings = new Settings(
$config->get("database.query_directory"),
$config->get("database.driver"),
$config->get("database.schema"),
$config->get("database.host"),
$config->get("database.port"),
$config->get("database.username"),
$config->get("database.password")
);
$database = new Database($databaseSettings);
$this->protectGlobals();
$this->attachAutoloaders(
$server->getDocumentRoot(),
$config->getSection("app")
);
$request = $this->createServerRequest(
$server,
$input,
$cookie
);
$router = $this->createRouter(
$request,
$server->getDocumentRoot()
);
$csrfProtection = new SessionTokenStore(
$sessionHandler->getStore(
"gt.csrf",
true
)
);
$csrfProtection->processAndVerify(
$input->getAll(Input::DATA_BODY)
);
$dispatcher = $this->createDispatcher(
$config,
$server,
$input,
$cookie,
$sessionHandler,
$database,
$router,
$csrfProtection
);
$response = $this->process($request, $dispatcher);
$this->finish($response);
} | [
"public",
"function",
"start",
"(",
")",
":",
"void",
"{",
"$",
"server",
"=",
"new",
"ServerInfo",
"(",
"$",
"_SERVER",
")",
";",
"$",
"cwd",
"=",
"dirname",
"(",
"$",
"server",
"->",
"getDocumentRoot",
"(",
")",
")",
";",
"chdir",
"(",
"$",
"cwd"... | The start of the application's lifecycle. This function breaks the lifecycle down
into its different functions, in order. | [
"The",
"start",
"of",
"the",
"application",
"s",
"lifecycle",
".",
"This",
"function",
"breaks",
"the",
"lifecycle",
"down",
"into",
"its",
"different",
"functions",
"in",
"order",
"."
] | 2dc4010349c3c07a695b28e25ec0a8a44cb93ea2 | https://github.com/PhpGt/WebEngine/blob/2dc4010349c3c07a695b28e25ec0a8a44cb93ea2/src/Lifecycle.php#L45-L124 | train |
PhpGt/WebEngine | src/Lifecycle.php | Lifecycle.protectGlobals | public function protectGlobals() {
// TODO: Merge whitelist from config
$whitelist = [
"_COOKIE" => ["XDEBUG_SESSION"],
];
$globalsAfterRemoval = Protection::removeGlobals(
$GLOBALS,
$whitelist
);
Protection::overrideInternals(
$globalsAfterRemoval,
$_ENV,
$_SERVER,
$_GET,
$_POST,
$_FILES,
$_COOKIE,
$_SESSION
);
} | php | public function protectGlobals() {
// TODO: Merge whitelist from config
$whitelist = [
"_COOKIE" => ["XDEBUG_SESSION"],
];
$globalsAfterRemoval = Protection::removeGlobals(
$GLOBALS,
$whitelist
);
Protection::overrideInternals(
$globalsAfterRemoval,
$_ENV,
$_SERVER,
$_GET,
$_POST,
$_FILES,
$_COOKIE,
$_SESSION
);
} | [
"public",
"function",
"protectGlobals",
"(",
")",
"{",
"// TODO: Merge whitelist from config",
"$",
"whitelist",
"=",
"[",
"\"_COOKIE\"",
"=>",
"[",
"\"XDEBUG_SESSION\"",
"]",
",",
"]",
";",
"$",
"globalsAfterRemoval",
"=",
"Protection",
"::",
"removeGlobals",
"(",
... | By default, PHP passes all sensitive user information around in global variables,
available for reading and modification in any code, including third party libraries.
All global variables are replaced with objects that alert the developer of their
protection and encapsulation through GlobalStub objects.
@see https://php.gt/globals | [
"By",
"default",
"PHP",
"passes",
"all",
"sensitive",
"user",
"information",
"around",
"in",
"global",
"variables",
"available",
"for",
"reading",
"and",
"modification",
"in",
"any",
"code",
"including",
"third",
"party",
"libraries",
"."
] | 2dc4010349c3c07a695b28e25ec0a8a44cb93ea2 | https://github.com/PhpGt/WebEngine/blob/2dc4010349c3c07a695b28e25ec0a8a44cb93ea2/src/Lifecycle.php#L135-L154 | train |
grrr-amsterdam/garp3 | library/Garp/Content/Import/Excel.php | Garp_Content_Import_Excel._getReader | protected function _getReader() {
/**
* Note: this is now autoloaded by Composer
*/
//require APPLICATION_PATH.'/../garp/library/Garp/3rdParty/PHPExcel/Classes/PHPExcel.php';
$inputFileType = PHPExcel_IOFactory::identify($this->_importFile);
// HTML is never correct. Just default to Excel2007
// @todo Fix this. It should be able to determine the filetype correctly.
if ($inputFileType === 'HTML') {
$inputFileType = 'Excel2007';
}
$reader = PHPExcel_IOFactory::createReader($inputFileType);
// we are only interested in cell values (not formatting etc.), so set readDataOnly to true
// $reader->setReadDataOnly(true);
$phpexcel = $reader->load($this->_importFile);
return $phpexcel;
} | php | protected function _getReader() {
/**
* Note: this is now autoloaded by Composer
*/
//require APPLICATION_PATH.'/../garp/library/Garp/3rdParty/PHPExcel/Classes/PHPExcel.php';
$inputFileType = PHPExcel_IOFactory::identify($this->_importFile);
// HTML is never correct. Just default to Excel2007
// @todo Fix this. It should be able to determine the filetype correctly.
if ($inputFileType === 'HTML') {
$inputFileType = 'Excel2007';
}
$reader = PHPExcel_IOFactory::createReader($inputFileType);
// we are only interested in cell values (not formatting etc.), so set readDataOnly to true
// $reader->setReadDataOnly(true);
$phpexcel = $reader->load($this->_importFile);
return $phpexcel;
} | [
"protected",
"function",
"_getReader",
"(",
")",
"{",
"/**\n * Note: this is now autoloaded by Composer\n */",
"//require APPLICATION_PATH.'/../garp/library/Garp/3rdParty/PHPExcel/Classes/PHPExcel.php';",
"$",
"inputFileType",
"=",
"PHPExcel_IOFactory",
"::",
"identify",
... | Return an Excel reader
@return PHPExcel | [
"Return",
"an",
"Excel",
"reader"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Content/Import/Excel.php#L113-L131 | train |
grrr-amsterdam/garp3 | library/Garp/DateTime.php | Garp_DateTime.format_local | public function format_local($format) {
// Configure the timezone to account for timezone and/or daylight savings time
$timezone = new DateTimeZone(date_default_timezone_get());
$this->setTimezone($timezone);
$timestamp = $this->getTimestamp();
return strftime($format, $timestamp);
} | php | public function format_local($format) {
// Configure the timezone to account for timezone and/or daylight savings time
$timezone = new DateTimeZone(date_default_timezone_get());
$this->setTimezone($timezone);
$timestamp = $this->getTimestamp();
return strftime($format, $timestamp);
} | [
"public",
"function",
"format_local",
"(",
"$",
"format",
")",
"{",
"// Configure the timezone to account for timezone and/or daylight savings time",
"$",
"timezone",
"=",
"new",
"DateTimeZone",
"(",
"date_default_timezone_get",
"(",
")",
")",
";",
"$",
"this",
"->",
"s... | Support for localized formatting.
@param String $format
@return String | [
"Support",
"for",
"localized",
"formatting",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/DateTime.php#L19-L26 | train |
grrr-amsterdam/garp3 | library/Garp/DateTime.php | Garp_DateTime.formatFromConfig | public static function formatFromConfig($type, $date) {
$ini = Zend_Registry::get('config');
$format = $ini->date->format->$type;
if (strpos($format, '%') !== false) {
return strftime($format, strtotime($date));
} else {
return date($format, strtotime($date));
}
} | php | public static function formatFromConfig($type, $date) {
$ini = Zend_Registry::get('config');
$format = $ini->date->format->$type;
if (strpos($format, '%') !== false) {
return strftime($format, strtotime($date));
} else {
return date($format, strtotime($date));
}
} | [
"public",
"static",
"function",
"formatFromConfig",
"(",
"$",
"type",
",",
"$",
"date",
")",
"{",
"$",
"ini",
"=",
"Zend_Registry",
"::",
"get",
"(",
"'config'",
")",
";",
"$",
"format",
"=",
"$",
"ini",
"->",
"date",
"->",
"format",
"->",
"$",
"type... | Format a date according to a format set in the global configuration | [
"Format",
"a",
"date",
"according",
"to",
"a",
"format",
"set",
"in",
"the",
"global",
"configuration"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/DateTime.php#L31-L40 | train |
grrr-amsterdam/garp3 | library/Garp/Content/Export/Factory.php | Garp_Content_Export_Factory.getExporter | public static function getExporter($type) {
// normalize type
$className = 'Garp_Content_Export_' . ucfirst($type);
$obj = new $className();
if (!$obj instanceof Garp_Content_Export_Abstract) {
throw new Garp_Content_Export_Exception(
"Class $className does not implement Garp_Content_Export_Abstract."
);
}
return $obj;
} | php | public static function getExporter($type) {
// normalize type
$className = 'Garp_Content_Export_' . ucfirst($type);
$obj = new $className();
if (!$obj instanceof Garp_Content_Export_Abstract) {
throw new Garp_Content_Export_Exception(
"Class $className does not implement Garp_Content_Export_Abstract."
);
}
return $obj;
} | [
"public",
"static",
"function",
"getExporter",
"(",
"$",
"type",
")",
"{",
"// normalize type",
"$",
"className",
"=",
"'Garp_Content_Export_'",
".",
"ucfirst",
"(",
"$",
"type",
")",
";",
"$",
"obj",
"=",
"new",
"$",
"className",
"(",
")",
";",
"if",
"(... | Return instance of Garp_Content_Export_Abstract
@param string $type The requested export type
@return Garp_Content_Export_Abstract | [
"Return",
"instance",
"of",
"Garp_Content_Export_Abstract"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Content/Export/Factory.php#L17-L27 | train |
grrr-amsterdam/garp3 | library/Garp/I18n.php | Garp_I18n.getLocalizedRoutes | public static function getLocalizedRoutes(array $routes, array $locales) {
$localizedRoutes = array();
$defaultLocale = self::getDefaultLocale();
$requiredLocalesRegex = '^(' . join('|', $locales) . ')$';
foreach ($routes as $key => $value) {
// First let's add the default locale to this routes defaults.
$defaults = isset($value['defaults'])
? $value['defaults']
: array();
// Always default all routes to the Zend_Locale default
$value['defaults'] = array_merge(array('locale' => $defaultLocale ), $defaults);
//$routes[$key] = $value;
// Get our route and make sure to remove the first forward slash
// since it's not needed.
$routeString = $value['route'];
$routeString = ltrim($routeString, '/\\');
// Modify our normal route to have the locale parameter.
if (!isset($value['type']) || $value['type'] === 'Zend_Controller_Router_Route') {
$value['route'] = ':locale/' . $routeString;
$value['reqs']['locale'] = $requiredLocalesRegex;
$localizedRoutes['locale_' . $key] = $value;
} else if ($value['type'] === 'Zend_Controller_Router_Route_Regex') {
$value['route'] = '(' . join('|', $locales) . ')\/' . $routeString;
// Since we added the local regex match, we need to bump the existing
// match numbers plus one.
$map = isset($value['map']) ? $value['map'] : array();
foreach ($map as $index => $word) {
unset($map[$index++]);
$map[$index] = $word;
}
// Add our locale map
$map[1] = 'locale';
ksort($map);
$value['map'] = $map;
$localizedRoutes['locale_' . $key] = $value;
} elseif ($value['type'] === 'Zend_Controller_Router_Route_Static') {
foreach ($locales as $locale) {
$value['route'] = $locale . '/' . $routeString;
$value['defaults']['locale'] = $locale;
$routes['locale_' . $locale . '_' . $key] = $value;
}
}
}
return $localizedRoutes;
} | php | public static function getLocalizedRoutes(array $routes, array $locales) {
$localizedRoutes = array();
$defaultLocale = self::getDefaultLocale();
$requiredLocalesRegex = '^(' . join('|', $locales) . ')$';
foreach ($routes as $key => $value) {
// First let's add the default locale to this routes defaults.
$defaults = isset($value['defaults'])
? $value['defaults']
: array();
// Always default all routes to the Zend_Locale default
$value['defaults'] = array_merge(array('locale' => $defaultLocale ), $defaults);
//$routes[$key] = $value;
// Get our route and make sure to remove the first forward slash
// since it's not needed.
$routeString = $value['route'];
$routeString = ltrim($routeString, '/\\');
// Modify our normal route to have the locale parameter.
if (!isset($value['type']) || $value['type'] === 'Zend_Controller_Router_Route') {
$value['route'] = ':locale/' . $routeString;
$value['reqs']['locale'] = $requiredLocalesRegex;
$localizedRoutes['locale_' . $key] = $value;
} else if ($value['type'] === 'Zend_Controller_Router_Route_Regex') {
$value['route'] = '(' . join('|', $locales) . ')\/' . $routeString;
// Since we added the local regex match, we need to bump the existing
// match numbers plus one.
$map = isset($value['map']) ? $value['map'] : array();
foreach ($map as $index => $word) {
unset($map[$index++]);
$map[$index] = $word;
}
// Add our locale map
$map[1] = 'locale';
ksort($map);
$value['map'] = $map;
$localizedRoutes['locale_' . $key] = $value;
} elseif ($value['type'] === 'Zend_Controller_Router_Route_Static') {
foreach ($locales as $locale) {
$value['route'] = $locale . '/' . $routeString;
$value['defaults']['locale'] = $locale;
$routes['locale_' . $locale . '_' . $key] = $value;
}
}
}
return $localizedRoutes;
} | [
"public",
"static",
"function",
"getLocalizedRoutes",
"(",
"array",
"$",
"routes",
",",
"array",
"$",
"locales",
")",
"{",
"$",
"localizedRoutes",
"=",
"array",
"(",
")",
";",
"$",
"defaultLocale",
"=",
"self",
"::",
"getDefaultLocale",
"(",
")",
";",
"$",... | Generate localized versions of routes
@param array $routes The originals
@param array $locales
@return array | [
"Generate",
"localized",
"versions",
"of",
"routes"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/I18n.php#L61-L114 | train |
grrr-amsterdam/garp3 | library/Garp/I18n.php | Garp_I18n.languageToTerritory | public static function languageToTerritory($lang) {
$config = Zend_Registry::get('config');
$territory = isset($config->resources->locale->territories->{$lang}) ?
$config->resources->locale->territories->{$lang} :
Zend_Locale::getLocaleToTerritory($lang);
return $territory;
} | php | public static function languageToTerritory($lang) {
$config = Zend_Registry::get('config');
$territory = isset($config->resources->locale->territories->{$lang}) ?
$config->resources->locale->territories->{$lang} :
Zend_Locale::getLocaleToTerritory($lang);
return $territory;
} | [
"public",
"static",
"function",
"languageToTerritory",
"(",
"$",
"lang",
")",
"{",
"$",
"config",
"=",
"Zend_Registry",
"::",
"get",
"(",
"'config'",
")",
";",
"$",
"territory",
"=",
"isset",
"(",
"$",
"config",
"->",
"resources",
"->",
"locale",
"->",
"... | Go from language to territory
@param string $lang
@return string | [
"Go",
"from",
"language",
"to",
"territory"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/I18n.php#L122-L128 | train |
grrr-amsterdam/garp3 | library/Garp/I18n.php | Garp_I18n.getTranslateByLocale | public static function getTranslateByLocale(Zend_Locale $locale) {
$adapterParams = array(
'locale' => $locale,
'disableNotices' => true,
'scan' => Zend_Translate::LOCALE_FILENAME,
// Argh: the 'content' key is necessary in order to load the actual data,
// even when using an adapter that ignores it.
'content' => '!'
);
// Figure out which adapter to use
$translateAdapter = 'array';
$config = Zend_Registry::get('config');
if (!empty($config->resources->locale->translate->adapter)) {
$translateAdapter = $config->resources->locale->translate->adapter;
}
$adapterParams['adapter'] = $translateAdapter;
// Some additional configuration for the array adapter
if ($translateAdapter == 'array') {
$language = $locale->getLanguage();
// @todo Move this to applciation.ini?
$adapterParams['content'] = APPLICATION_PATH . '/data/i18n/' . $language . '.php';
// Turn on caching
if (Zend_Registry::isRegistered('CacheFrontend')) {
$adapterParams['cache'] = Zend_Registry::get('CacheFrontend');
}
}
$translate = new Zend_Translate($adapterParams);
return $translate;
} | php | public static function getTranslateByLocale(Zend_Locale $locale) {
$adapterParams = array(
'locale' => $locale,
'disableNotices' => true,
'scan' => Zend_Translate::LOCALE_FILENAME,
// Argh: the 'content' key is necessary in order to load the actual data,
// even when using an adapter that ignores it.
'content' => '!'
);
// Figure out which adapter to use
$translateAdapter = 'array';
$config = Zend_Registry::get('config');
if (!empty($config->resources->locale->translate->adapter)) {
$translateAdapter = $config->resources->locale->translate->adapter;
}
$adapterParams['adapter'] = $translateAdapter;
// Some additional configuration for the array adapter
if ($translateAdapter == 'array') {
$language = $locale->getLanguage();
// @todo Move this to applciation.ini?
$adapterParams['content'] = APPLICATION_PATH . '/data/i18n/' . $language . '.php';
// Turn on caching
if (Zend_Registry::isRegistered('CacheFrontend')) {
$adapterParams['cache'] = Zend_Registry::get('CacheFrontend');
}
}
$translate = new Zend_Translate($adapterParams);
return $translate;
} | [
"public",
"static",
"function",
"getTranslateByLocale",
"(",
"Zend_Locale",
"$",
"locale",
")",
"{",
"$",
"adapterParams",
"=",
"array",
"(",
"'locale'",
"=>",
"$",
"locale",
",",
"'disableNotices'",
"=>",
"true",
",",
"'scan'",
"=>",
"Zend_Translate",
"::",
"... | Create a Zend_Translate instance for the given locale.
@param Zend_Locale $locale
@return Zend_Translate | [
"Create",
"a",
"Zend_Translate",
"instance",
"for",
"the",
"given",
"locale",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/I18n.php#L136-L169 | train |
grrr-amsterdam/garp3 | library/Garp/Image/Scaler.php | Garp_Image_Scaler.getTemplateParameters | public function getTemplateParameters($template) {
if (count(self::$_config->template->{$template})) {
$tplConfig = self::$_config->template->{$template}->toArray();
return $tplConfig;
}
throw new Exception('The template "' . $template . '" is not configured.');
} | php | public function getTemplateParameters($template) {
if (count(self::$_config->template->{$template})) {
$tplConfig = self::$_config->template->{$template}->toArray();
return $tplConfig;
}
throw new Exception('The template "' . $template . '" is not configured.');
} | [
"public",
"function",
"getTemplateParameters",
"(",
"$",
"template",
")",
"{",
"if",
"(",
"count",
"(",
"self",
"::",
"$",
"_config",
"->",
"template",
"->",
"{",
"$",
"template",
"}",
")",
")",
"{",
"$",
"tplConfig",
"=",
"self",
"::",
"$",
"_config",... | Fetches the scaling parameters for this template.
@param string $template Name of this template
@return array | [
"Fetches",
"the",
"scaling",
"parameters",
"for",
"this",
"template",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Image/Scaler.php#L154-L160 | train |
grrr-amsterdam/garp3 | library/Garp/Image/Scaler.php | Garp_Image_Scaler.generateTemplateScaledImages | public function generateTemplateScaledImages($filename, $id, $overwrite = false) {
if (!$filename || !$id) {
throw new Exception(
'A filename and id were not provided. Filename [' . $filename . '] Id [' . $id . ']'
);
}
$templates = $this->getTemplateNames();
foreach ($templates as $t) {
try {
$this->scaleAndStore($filename, $id, $t, $overwrite);
} catch(Exception $e) {
throw new Exception(
"Error scaling " . $filename . " (#" . $id . "): " . $e->getMessage()
);
}
}
} | php | public function generateTemplateScaledImages($filename, $id, $overwrite = false) {
if (!$filename || !$id) {
throw new Exception(
'A filename and id were not provided. Filename [' . $filename . '] Id [' . $id . ']'
);
}
$templates = $this->getTemplateNames();
foreach ($templates as $t) {
try {
$this->scaleAndStore($filename, $id, $t, $overwrite);
} catch(Exception $e) {
throw new Exception(
"Error scaling " . $filename . " (#" . $id . "): " . $e->getMessage()
);
}
}
} | [
"public",
"function",
"generateTemplateScaledImages",
"(",
"$",
"filename",
",",
"$",
"id",
",",
"$",
"overwrite",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"$",
"filename",
"||",
"!",
"$",
"id",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'A filename and... | Generate versions of an image file that are scaled according to the
configured scaling templates.
@param string $filename The filename of the image to be scaled
@param int $id The database ID of the image record
@param bool $overwrite Whether to overwrite existing files
@return void | [
"Generate",
"versions",
"of",
"an",
"image",
"file",
"that",
"are",
"scaled",
"according",
"to",
"the",
"configured",
"scaling",
"templates",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Image/Scaler.php#L181-L198 | train |
grrr-amsterdam/garp3 | library/Garp/Image/Scaler.php | Garp_Image_Scaler.scaleAndStore | public function scaleAndStore($filename, $id, $template = null, $overwrite = false) {
$templates = !is_null($template) ?
(array)$template :
// template is left empty; scale source file along all configured templates
$templates = $this->getTemplateNames();
$file = new Garp_Image_File(Garp_File::FILE_VARIANT_UPLOAD);
$sourceData = $file->fetch($filename);
$imageType = $file->getImageType($filename);
foreach ($templates as $template) {
$this->_scaleAndStoreForTemplate($sourceData, $imageType, $id, $template, $overwrite);
}
} | php | public function scaleAndStore($filename, $id, $template = null, $overwrite = false) {
$templates = !is_null($template) ?
(array)$template :
// template is left empty; scale source file along all configured templates
$templates = $this->getTemplateNames();
$file = new Garp_Image_File(Garp_File::FILE_VARIANT_UPLOAD);
$sourceData = $file->fetch($filename);
$imageType = $file->getImageType($filename);
foreach ($templates as $template) {
$this->_scaleAndStoreForTemplate($sourceData, $imageType, $id, $template, $overwrite);
}
} | [
"public",
"function",
"scaleAndStore",
"(",
"$",
"filename",
",",
"$",
"id",
",",
"$",
"template",
"=",
"null",
",",
"$",
"overwrite",
"=",
"false",
")",
"{",
"$",
"templates",
"=",
"!",
"is_null",
"(",
"$",
"template",
")",
"?",
"(",
"array",
")",
... | Scales an image according to an image template, and stores it.
@param string $filename Filename of the source image
@param int $id Id of the database record corresponding to this image file
@param string $template Name of the template, if left empty,
scaled versions for all templates will be generated.
@param bool $overwrite
@return void | [
"Scales",
"an",
"image",
"according",
"to",
"an",
"image",
"template",
"and",
"stores",
"it",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Image/Scaler.php#L228-L241 | train |
grrr-amsterdam/garp3 | library/Garp/Image/Scaler.php | Garp_Image_Scaler._paintCanvas | private function _paintCanvas(&$image) {
if ($this->_params['type'] === IMAGETYPE_JPEG) {
if (!$this->_params['crop']
|| !$this->_params['grow']
) {
$this->_paintCanvasOpaque($image);
}
} else {
$this->_paintCanvasTransparent($image);
}
} | php | private function _paintCanvas(&$image) {
if ($this->_params['type'] === IMAGETYPE_JPEG) {
if (!$this->_params['crop']
|| !$this->_params['grow']
) {
$this->_paintCanvasOpaque($image);
}
} else {
$this->_paintCanvasTransparent($image);
}
} | [
"private",
"function",
"_paintCanvas",
"(",
"&",
"$",
"image",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_params",
"[",
"'type'",
"]",
"===",
"IMAGETYPE_JPEG",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"_params",
"[",
"'crop'",
"]",
"||",
"!",
"$... | Fills the canvas with the provided background color.
@param resource $image
@return void | [
"Fills",
"the",
"canvas",
"with",
"the",
"provided",
"background",
"color",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Image/Scaler.php#L365-L375 | train |
grrr-amsterdam/garp3 | library/Garp/Image/Scaler.php | Garp_Image_Scaler._renderToImageData | private function _renderToImageData(&$canvas) {
ob_start();
switch ($this->_params['type']) {
case IMAGETYPE_GIF:
imagegif($canvas);
break;
case IMAGETYPE_JPEG:
imagejpeg($canvas, null, $this->_params['quality']);
break;
case IMAGETYPE_PNG:
// Calculate PNG quality, because it runs from 0 (uncompressed) to 9,
// instead of 0 - 100.
$pngQuality = ($this->_params['quality'] - 100) / 11.111111;
$pngQuality = round(abs($pngQuality));
imagepng($canvas, null, $pngQuality, null);
break;
default:
throw new Exception('Sorry, this image type is not supported');
}
$imgData = ob_get_contents();
ob_end_clean();
return $imgData;
} | php | private function _renderToImageData(&$canvas) {
ob_start();
switch ($this->_params['type']) {
case IMAGETYPE_GIF:
imagegif($canvas);
break;
case IMAGETYPE_JPEG:
imagejpeg($canvas, null, $this->_params['quality']);
break;
case IMAGETYPE_PNG:
// Calculate PNG quality, because it runs from 0 (uncompressed) to 9,
// instead of 0 - 100.
$pngQuality = ($this->_params['quality'] - 100) / 11.111111;
$pngQuality = round(abs($pngQuality));
imagepng($canvas, null, $pngQuality, null);
break;
default:
throw new Exception('Sorry, this image type is not supported');
}
$imgData = ob_get_contents();
ob_end_clean();
return $imgData;
} | [
"private",
"function",
"_renderToImageData",
"(",
"&",
"$",
"canvas",
")",
"{",
"ob_start",
"(",
")",
";",
"switch",
"(",
"$",
"this",
"->",
"_params",
"[",
"'type'",
"]",
")",
"{",
"case",
"IMAGETYPE_GIF",
":",
"imagegif",
"(",
"$",
"canvas",
")",
";"... | Writes the graphical output to image file data.
@param resource $canvas
@return resource Scaled image data | [
"Writes",
"the",
"graphical",
"output",
"to",
"image",
"file",
"data",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Image/Scaler.php#L423-L447 | train |
grrr-amsterdam/garp3 | library/Garp/Image/Scaler.php | Garp_Image_Scaler._projectSourceOnCanvas | private function _projectSourceOnCanvas(&$source, &$canvas) {
$srcX = 0;
$srcY = 0;
list($projectionWidth, $projectionHeight) = $this->_getProjectionSize();
list($destX, $destY) = $this->_getLeftUpperCoordinateOnCanvas(
$projectionWidth,
$projectionHeight
);
imagecopyresampled(
$canvas,
$source,
$destX,
$destY,
$srcX,
$srcY,
$projectionWidth,
$projectionHeight,
$this->_params['sourceWidth'],
$this->_params['sourceHeight']
);
} | php | private function _projectSourceOnCanvas(&$source, &$canvas) {
$srcX = 0;
$srcY = 0;
list($projectionWidth, $projectionHeight) = $this->_getProjectionSize();
list($destX, $destY) = $this->_getLeftUpperCoordinateOnCanvas(
$projectionWidth,
$projectionHeight
);
imagecopyresampled(
$canvas,
$source,
$destX,
$destY,
$srcX,
$srcY,
$projectionWidth,
$projectionHeight,
$this->_params['sourceWidth'],
$this->_params['sourceHeight']
);
} | [
"private",
"function",
"_projectSourceOnCanvas",
"(",
"&",
"$",
"source",
",",
"&",
"$",
"canvas",
")",
"{",
"$",
"srcX",
"=",
"0",
";",
"$",
"srcY",
"=",
"0",
";",
"list",
"(",
"$",
"projectionWidth",
",",
"$",
"projectionHeight",
")",
"=",
"$",
"th... | Performs the actual projection of the source onto the canvas.
@param resource $source
@param resource $canvas
@return void | [
"Performs",
"the",
"actual",
"projection",
"of",
"the",
"source",
"onto",
"the",
"canvas",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Image/Scaler.php#L456-L476 | train |
grrr-amsterdam/garp3 | library/Garp/Image/Scaler.php | Garp_Image_Scaler._getLeftUpperCoordinateOnCanvas | private function _getLeftUpperCoordinateOnCanvas($projectionWidth, $projectionHeight) {
$canvasWidth = $this->_params['w'];
$canvasHeight = $this->_params['h'];
// Always center the projection horizontally.
if ($projectionWidth > $canvasWidth) {
$x = - (($projectionWidth / 2) - ($this->_params['w'] / 2));
} else {
$x = ($this->_params['w'] - $projectionWidth) / 2;
}
switch ($this->_params['cropfocus']) {
case 'face':
// If the image is taller than the canvas, move the starting point halfway up the center
if ($projectionHeight > $canvasHeight) {
$y = - ((($projectionHeight / 2) - ($this->_params['h'] / 2)) / 2);
} else {
$y = ($this->_params['h'] - $projectionHeight) / 2;
}
break;
case 'center':
default:
// center the projection vertically
if ($projectionHeight > $canvasHeight) {
$y = - (($projectionHeight / 2) - ($this->_params['h'] / 2));
} else {
$y = ($this->_params['h'] - $projectionHeight) / 2;
}
}
return array($x, $y);
} | php | private function _getLeftUpperCoordinateOnCanvas($projectionWidth, $projectionHeight) {
$canvasWidth = $this->_params['w'];
$canvasHeight = $this->_params['h'];
// Always center the projection horizontally.
if ($projectionWidth > $canvasWidth) {
$x = - (($projectionWidth / 2) - ($this->_params['w'] / 2));
} else {
$x = ($this->_params['w'] - $projectionWidth) / 2;
}
switch ($this->_params['cropfocus']) {
case 'face':
// If the image is taller than the canvas, move the starting point halfway up the center
if ($projectionHeight > $canvasHeight) {
$y = - ((($projectionHeight / 2) - ($this->_params['h'] / 2)) / 2);
} else {
$y = ($this->_params['h'] - $projectionHeight) / 2;
}
break;
case 'center':
default:
// center the projection vertically
if ($projectionHeight > $canvasHeight) {
$y = - (($projectionHeight / 2) - ($this->_params['h'] / 2));
} else {
$y = ($this->_params['h'] - $projectionHeight) / 2;
}
}
return array($x, $y);
} | [
"private",
"function",
"_getLeftUpperCoordinateOnCanvas",
"(",
"$",
"projectionWidth",
",",
"$",
"projectionHeight",
")",
"{",
"$",
"canvasWidth",
"=",
"$",
"this",
"->",
"_params",
"[",
"'w'",
"]",
";",
"$",
"canvasHeight",
"=",
"$",
"this",
"->",
"_params",
... | Calculates the coordinates of the projection location on the canvas
@param int $projectionWidth Width of the projection
@param int $projectionHeight Height of the projection
@return array Numeric array, containing x- and y-coordinates of the upper left
point of the projection on the canvas | [
"Calculates",
"the",
"coordinates",
"of",
"the",
"projection",
"location",
"on",
"the",
"canvas"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Image/Scaler.php#L487-L517 | train |
grrr-amsterdam/garp3 | library/Garp/Image/Scaler.php | Garp_Image_Scaler._getProjectionSize | private function _getProjectionSize() {
$sourceWidth = $this->_params['sourceWidth'];
$sourceHeight = $this->_params['sourceHeight'];
$sourceRatio = $sourceWidth / $sourceHeight;
$canvasWidth = $this->_params['w'];
$canvasHeight = $this->_params['h'];
$canvasRatio = $canvasWidth / $canvasHeight;
// the image is not allowed to be cut off in any dimension
if ($sourceRatio < $canvasRatio) {
// source is less landscape-like than canvas
$leadDimension = !$this->_params['crop'] ?
'Height' : 'Width';
} else {
// source is more landscape-like than canvas
$leadDimension = !$this->_params['crop'] ?
'Width' : 'Height';
}
if (!$this->_params['grow']
&& ${'source' . $leadDimension} < ${'canvas' . $leadDimension}
) {
${'projection' . $leadDimension} = ${'source' . $leadDimension};
} else {
${'projection' . $leadDimension} = ${'canvas' . $leadDimension};
}
if (isset($projectionWidth)) {
$projectionHeight = $projectionWidth / $sourceRatio;
} elseif (isset($projectionHeight)) {
$projectionWidth = $projectionHeight * $sourceRatio;
}
return array(round($projectionWidth), round($projectionHeight));
} | php | private function _getProjectionSize() {
$sourceWidth = $this->_params['sourceWidth'];
$sourceHeight = $this->_params['sourceHeight'];
$sourceRatio = $sourceWidth / $sourceHeight;
$canvasWidth = $this->_params['w'];
$canvasHeight = $this->_params['h'];
$canvasRatio = $canvasWidth / $canvasHeight;
// the image is not allowed to be cut off in any dimension
if ($sourceRatio < $canvasRatio) {
// source is less landscape-like than canvas
$leadDimension = !$this->_params['crop'] ?
'Height' : 'Width';
} else {
// source is more landscape-like than canvas
$leadDimension = !$this->_params['crop'] ?
'Width' : 'Height';
}
if (!$this->_params['grow']
&& ${'source' . $leadDimension} < ${'canvas' . $leadDimension}
) {
${'projection' . $leadDimension} = ${'source' . $leadDimension};
} else {
${'projection' . $leadDimension} = ${'canvas' . $leadDimension};
}
if (isset($projectionWidth)) {
$projectionHeight = $projectionWidth / $sourceRatio;
} elseif (isset($projectionHeight)) {
$projectionWidth = $projectionHeight * $sourceRatio;
}
return array(round($projectionWidth), round($projectionHeight));
} | [
"private",
"function",
"_getProjectionSize",
"(",
")",
"{",
"$",
"sourceWidth",
"=",
"$",
"this",
"->",
"_params",
"[",
"'sourceWidth'",
"]",
";",
"$",
"sourceHeight",
"=",
"$",
"this",
"->",
"_params",
"[",
"'sourceHeight'",
"]",
";",
"$",
"sourceRatio",
... | Calculate projection size of source image on canvas.
The resulting projection might be larger than the canvas; this function does
not consider cutoff by means of cropping.
@return array Numeric array containing projection width and height in pixels. | [
"Calculate",
"projection",
"size",
"of",
"source",
"image",
"on",
"canvas",
".",
"The",
"resulting",
"projection",
"might",
"be",
"larger",
"than",
"the",
"canvas",
";",
"this",
"function",
"does",
"not",
"consider",
"cutoff",
"by",
"means",
"of",
"cropping",
... | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Image/Scaler.php#L527-L563 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/ExtController.php | G_ExtController.smdAction | public function smdAction() {
$api = new Garp_Content_Api();
$this->view->api = $api->getLayout();
$this->_renderJs();
} | php | public function smdAction() {
$api = new Garp_Content_Api();
$this->view->api = $api->getLayout();
$this->_renderJs();
} | [
"public",
"function",
"smdAction",
"(",
")",
"{",
"$",
"api",
"=",
"new",
"Garp_Content_Api",
"(",
")",
";",
"$",
"this",
"->",
"view",
"->",
"api",
"=",
"$",
"api",
"->",
"getLayout",
"(",
")",
";",
"$",
"this",
"->",
"_renderJs",
"(",
")",
";",
... | Generate Ext.Direct API, publishing allowed actions to Ext.Direct,
according to Service Mapping Description JSON-RPC protocol.
@return Void | [
"Generate",
"Ext",
".",
"Direct",
"API",
"publishing",
"allowed",
"actions",
"to",
"Ext",
".",
"Direct",
"according",
"to",
"Service",
"Mapping",
"Description",
"JSON",
"-",
"RPC",
"protocol",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/ExtController.php#L44-L49 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/ExtController.php | G_ExtController.getlocaleAction | public function getlocaleAction() {
if (!Zend_Registry::isRegistered('Zend_Translate')) {
throw new Zend_Controller_Action_Exception(
'Zend_Translate was not registered in Zend_Registry.',
500
);
}
$translate = Zend_Registry::get('Zend_Translate');
$messages = $translate->getMessages();
$this->view->messages = $messages;
$this->_renderJs();
} | php | public function getlocaleAction() {
if (!Zend_Registry::isRegistered('Zend_Translate')) {
throw new Zend_Controller_Action_Exception(
'Zend_Translate was not registered in Zend_Registry.',
500
);
}
$translate = Zend_Registry::get('Zend_Translate');
$messages = $translate->getMessages();
$this->view->messages = $messages;
$this->_renderJs();
} | [
"public",
"function",
"getlocaleAction",
"(",
")",
"{",
"if",
"(",
"!",
"Zend_Registry",
"::",
"isRegistered",
"(",
"'Zend_Translate'",
")",
")",
"{",
"throw",
"new",
"Zend_Controller_Action_Exception",
"(",
"'Zend_Translate was not registered in Zend_Registry.'",
",",
... | Get translation table
@return Void | [
"Get",
"translation",
"table"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/ExtController.php#L64-L76 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/ExtController.php | G_ExtController.preDispatch | public function preDispatch() {
if ($this->getRequest()->isPost()) {
$post = $this->_getJsonRpcRequest();
$requests = Zend_Json::decode($post, Zend_Json::TYPE_ARRAY);
$modifiedRequests = array();
/**
* Check if this was a batch request. In that case the array is a plain array of
* arrays. If not, there will be a 'jsonrpc' key in the root of the array.
*/
$batch = !array_key_exists('jsonrpc', $requests);
if (!$batch) {
$requests = array($requests);
}
foreach ($requests as $i => $request) {
$this->_saveRequestForModification($request, $i);
if (array_key_exists('method', $request)) {
$methodParts = explode('.', $request['method']);
$method = array_pop($methodParts);
if (in_array($method, array('create', 'update', 'destroy'))) {
$modifyMethod = '_modifyBefore' . ucfirst($method);
$request = $this->{$modifyMethod}($request);
}
}
$modifiedRequests[] = $request;
}
if ($batch) {
$this->getRequest()->setPost('request', Zend_Json::encode($modifiedRequests));
} else {
$this->getRequest()->setPost('request', Zend_Json::encode($modifiedRequests[0]));
}
}
parent::preDispatch();
$this->_toggleCache(false);
} | php | public function preDispatch() {
if ($this->getRequest()->isPost()) {
$post = $this->_getJsonRpcRequest();
$requests = Zend_Json::decode($post, Zend_Json::TYPE_ARRAY);
$modifiedRequests = array();
/**
* Check if this was a batch request. In that case the array is a plain array of
* arrays. If not, there will be a 'jsonrpc' key in the root of the array.
*/
$batch = !array_key_exists('jsonrpc', $requests);
if (!$batch) {
$requests = array($requests);
}
foreach ($requests as $i => $request) {
$this->_saveRequestForModification($request, $i);
if (array_key_exists('method', $request)) {
$methodParts = explode('.', $request['method']);
$method = array_pop($methodParts);
if (in_array($method, array('create', 'update', 'destroy'))) {
$modifyMethod = '_modifyBefore' . ucfirst($method);
$request = $this->{$modifyMethod}($request);
}
}
$modifiedRequests[] = $request;
}
if ($batch) {
$this->getRequest()->setPost('request', Zend_Json::encode($modifiedRequests));
} else {
$this->getRequest()->setPost('request', Zend_Json::encode($modifiedRequests[0]));
}
}
parent::preDispatch();
$this->_toggleCache(false);
} | [
"public",
"function",
"preDispatch",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"getRequest",
"(",
")",
"->",
"isPost",
"(",
")",
")",
"{",
"$",
"post",
"=",
"$",
"this",
"->",
"_getJsonRpcRequest",
"(",
")",
";",
"$",
"requests",
"=",
"Zend_Json",... | Callback called before executing action.
Transforms requests to a format ExtJs accepts.
Also turns off caching, since the CMS always receives live data.
@return Void | [
"Callback",
"called",
"before",
"executing",
"action",
".",
"Transforms",
"requests",
"to",
"a",
"format",
"ExtJs",
"accepts",
".",
"Also",
"turns",
"off",
"caching",
"since",
"the",
"CMS",
"always",
"receives",
"live",
"data",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/ExtController.php#L85-L118 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/ExtController.php | G_ExtController.postDispatch | public function postDispatch() {
parent::postDispatch();
if (!empty($this->_postModifyMethods)) {
$response = Zend_Json::decode($this->view->response, Zend_Json::TYPE_ARRAY);
$modifiedResponse = array();
/**
* Check if this was a batch request. In that case the array is a plain array of
* arrays. If not, there will be a 'jsonrpc' key in the root of the array.
*/
$batch = !array_key_exists('jsonrpc', $response);
if (!$batch) {
$response = array($response);
}
/**
* Post modify methods are recorded from $this:preDispatch()
*/
foreach ($this->_postModifyMethods as $i => $postMethod) {
if (!empty($response[$i]) && !empty($this->_originalRequests[$i])) {
$modifyMethod = '_modifyAfter' . ucfirst($postMethod);
$response[$i] = $this->{$modifyMethod}(
$response[$i],
$this->_originalRequests[$i]
);
}
}
if ($batch) {
$this->view->response = Zend_Json::encode($response);
} else {
$this->view->response = Zend_Json::encode($response[0]);
}
}
$this->_toggleCache(true);
} | php | public function postDispatch() {
parent::postDispatch();
if (!empty($this->_postModifyMethods)) {
$response = Zend_Json::decode($this->view->response, Zend_Json::TYPE_ARRAY);
$modifiedResponse = array();
/**
* Check if this was a batch request. In that case the array is a plain array of
* arrays. If not, there will be a 'jsonrpc' key in the root of the array.
*/
$batch = !array_key_exists('jsonrpc', $response);
if (!$batch) {
$response = array($response);
}
/**
* Post modify methods are recorded from $this:preDispatch()
*/
foreach ($this->_postModifyMethods as $i => $postMethod) {
if (!empty($response[$i]) && !empty($this->_originalRequests[$i])) {
$modifyMethod = '_modifyAfter' . ucfirst($postMethod);
$response[$i] = $this->{$modifyMethod}(
$response[$i],
$this->_originalRequests[$i]
);
}
}
if ($batch) {
$this->view->response = Zend_Json::encode($response);
} else {
$this->view->response = Zend_Json::encode($response[0]);
}
}
$this->_toggleCache(true);
} | [
"public",
"function",
"postDispatch",
"(",
")",
"{",
"parent",
"::",
"postDispatch",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"_postModifyMethods",
")",
")",
"{",
"$",
"response",
"=",
"Zend_Json",
"::",
"decode",
"(",
"$",
"this... | Callback called after executing action.
Transforms requests to a format ExtJs accepts.
Also turns on caching, because this request might be chained.
@return Void | [
"Callback",
"called",
"after",
"executing",
"action",
".",
"Transforms",
"requests",
"to",
"a",
"format",
"ExtJs",
"accepts",
".",
"Also",
"turns",
"on",
"caching",
"because",
"this",
"request",
"might",
"be",
"chained",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/ExtController.php#L127-L159 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/ExtController.php | G_ExtController._saveRequestForModification | protected function _saveRequestForModification($request, $i) {
if (array_key_exists('method', $request)) {
$methodParts = explode('.', $request['method']);
$method = array_pop($methodParts);
if (in_array($method, array('fetch', 'create', 'update', 'destroy'))) {
$this->_postModifyMethods[$i] = $method;
$this->_originalRequests[$i] = $request;
}
}
} | php | protected function _saveRequestForModification($request, $i) {
if (array_key_exists('method', $request)) {
$methodParts = explode('.', $request['method']);
$method = array_pop($methodParts);
if (in_array($method, array('fetch', 'create', 'update', 'destroy'))) {
$this->_postModifyMethods[$i] = $method;
$this->_originalRequests[$i] = $request;
}
}
} | [
"protected",
"function",
"_saveRequestForModification",
"(",
"$",
"request",
",",
"$",
"i",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"'method'",
",",
"$",
"request",
")",
")",
"{",
"$",
"methodParts",
"=",
"explode",
"(",
"'.'",
",",
"$",
"request",
... | Save a request preDispatch for modification postDispatch
@param Array $request The request
@param Int $i The index under which the request should be filed in the array
@return Void | [
"Save",
"a",
"request",
"preDispatch",
"for",
"modification",
"postDispatch"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/ExtController.php#L168-L177 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/ExtController.php | G_ExtController._fetchTotal | protected function _fetchTotal($modelName, $conditions) {
if (!array_key_exists('query', $conditions)) {
$conditions['query'] = array();
}
$man = new Garp_Content_Manager($modelName);
return $man->count($conditions);
} | php | protected function _fetchTotal($modelName, $conditions) {
if (!array_key_exists('query', $conditions)) {
$conditions['query'] = array();
}
$man = new Garp_Content_Manager($modelName);
return $man->count($conditions);
} | [
"protected",
"function",
"_fetchTotal",
"(",
"$",
"modelName",
",",
"$",
"conditions",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"'query'",
",",
"$",
"conditions",
")",
")",
"{",
"$",
"conditions",
"[",
"'query'",
"]",
"=",
"array",
"(",
")",
... | Fetch total amount of records condoning to a set of conditions
@param String $modelName The entity name
@param Array $conditions Query modifiers
@return Int | [
"Fetch",
"total",
"amount",
"of",
"records",
"condoning",
"to",
"a",
"set",
"of",
"conditions"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/ExtController.php#L186-L192 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/ExtController.php | G_ExtController._modifyAfterFetch | protected function _modifyAfterFetch($response, $request) {
if (!$this->_methodFailed($response)) {
$rows = $response['result'];
$methodParts = explode('.', $request['method']);
$modelClass = Garp_Content_Api::modelAliasToClass(array_shift($methodParts));
$params = $request['params'];
$params = !empty($params) ? $params[0] : array();
$response['result'] = array(
'rows' => $rows,
'total' => $this->_fetchTotal($modelClass, $params)
);
}
return $response;
} | php | protected function _modifyAfterFetch($response, $request) {
if (!$this->_methodFailed($response)) {
$rows = $response['result'];
$methodParts = explode('.', $request['method']);
$modelClass = Garp_Content_Api::modelAliasToClass(array_shift($methodParts));
$params = $request['params'];
$params = !empty($params) ? $params[0] : array();
$response['result'] = array(
'rows' => $rows,
'total' => $this->_fetchTotal($modelClass, $params)
);
}
return $response;
} | [
"protected",
"function",
"_modifyAfterFetch",
"(",
"$",
"response",
",",
"$",
"request",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"_methodFailed",
"(",
"$",
"response",
")",
")",
"{",
"$",
"rows",
"=",
"$",
"response",
"[",
"'result'",
"]",
";",
... | Modify results after fetch
@param Array $response The original response
@param Array $request The original request
@return String | [
"Modify",
"results",
"after",
"fetch"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/ExtController.php#L228-L242 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/ExtController.php | G_ExtController._modifyAfterCreate | protected function _modifyAfterCreate($response, $request) {
if (!$this->_methodFailed($response)) {
// figure out model name (request.method)
$methodParts = explode('.', $request['method']);
$modelClass = Garp_Content_Api::modelAliasToClass(array_shift($methodParts));
$model = new $modelClass();
// combine primary keys to query params
$primaryKey = array_values((array)$model->info(Zend_Db_Table::PRIMARY));
$primaryKeyValues = array_values((array)$response['result']);
$query = array();
foreach ($primaryKey as $i => $key) {
$query[$key] = $primaryKeyValues[$i];
}
// find the newly inserted rows
$man = new Garp_Content_Manager(get_class($model));
$rows = $man->fetch(array('query' => $query));
$response['result'] = array(
'rows' => $rows
);
}
return $response;
} | php | protected function _modifyAfterCreate($response, $request) {
if (!$this->_methodFailed($response)) {
// figure out model name (request.method)
$methodParts = explode('.', $request['method']);
$modelClass = Garp_Content_Api::modelAliasToClass(array_shift($methodParts));
$model = new $modelClass();
// combine primary keys to query params
$primaryKey = array_values((array)$model->info(Zend_Db_Table::PRIMARY));
$primaryKeyValues = array_values((array)$response['result']);
$query = array();
foreach ($primaryKey as $i => $key) {
$query[$key] = $primaryKeyValues[$i];
}
// find the newly inserted rows
$man = new Garp_Content_Manager(get_class($model));
$rows = $man->fetch(array('query' => $query));
$response['result'] = array(
'rows' => $rows
);
}
return $response;
} | [
"protected",
"function",
"_modifyAfterCreate",
"(",
"$",
"response",
",",
"$",
"request",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"_methodFailed",
"(",
"$",
"response",
")",
")",
"{",
"// figure out model name (request.method)",
"$",
"methodParts",
"=",
"... | Modify results after create
@param Array $response The original response
@param Array $request The original request
@return String | [
"Modify",
"results",
"after",
"create"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/ExtController.php#L251-L272 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/ExtController.php | G_ExtController._modifyAfterUpdate | protected function _modifyAfterUpdate($response, $request) {
if ($this->_methodFailed($response)) {
return $response;
}
$methodParts = explode('.', $request['method']);
$modelClass = Garp_Content_Api::modelAliasToClass(array_shift($methodParts));
$man = new Garp_Content_Manager($modelClass);
$rows = $man->fetch(
array(
'query' => array('id' => $request['params'][0]['rows']['id'])
)
);
$response['result'] = array(
'rows' => $rows
);
return $response;
} | php | protected function _modifyAfterUpdate($response, $request) {
if ($this->_methodFailed($response)) {
return $response;
}
$methodParts = explode('.', $request['method']);
$modelClass = Garp_Content_Api::modelAliasToClass(array_shift($methodParts));
$man = new Garp_Content_Manager($modelClass);
$rows = $man->fetch(
array(
'query' => array('id' => $request['params'][0]['rows']['id'])
)
);
$response['result'] = array(
'rows' => $rows
);
return $response;
} | [
"protected",
"function",
"_modifyAfterUpdate",
"(",
"$",
"response",
",",
"$",
"request",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_methodFailed",
"(",
"$",
"response",
")",
")",
"{",
"return",
"$",
"response",
";",
"}",
"$",
"methodParts",
"=",
"explode... | Modify results after update
@param Array $response The original response
@param Array $request The original request
@return String | [
"Modify",
"results",
"after",
"update"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/ExtController.php#L281-L297 | train |
grrr-amsterdam/garp3 | library/Garp/Adobe/InDesign/SpreadNode.php | Garp_Adobe_InDesign_SpreadNode._getCoordinates | protected function _getCoordinates() {
$itemTransformString = (string)$this->_nodeConfig->attributes()->ItemTransform;
$itemTransformArray = explode(' ', $itemTransformString);
$coordinates = array(
'x' => $itemTransformArray[count($itemTransformArray) - 2],
'y' => $itemTransformArray[count($itemTransformArray) - 1]
);
return $coordinates;
} | php | protected function _getCoordinates() {
$itemTransformString = (string)$this->_nodeConfig->attributes()->ItemTransform;
$itemTransformArray = explode(' ', $itemTransformString);
$coordinates = array(
'x' => $itemTransformArray[count($itemTransformArray) - 2],
'y' => $itemTransformArray[count($itemTransformArray) - 1]
);
return $coordinates;
} | [
"protected",
"function",
"_getCoordinates",
"(",
")",
"{",
"$",
"itemTransformString",
"=",
"(",
"string",
")",
"$",
"this",
"->",
"_nodeConfig",
"->",
"attributes",
"(",
")",
"->",
"ItemTransform",
";",
"$",
"itemTransformArray",
"=",
"explode",
"(",
"' '",
... | Get x- and y-coordinate of a node in a InDesign Spread that has an ItemTransform property.
@return array An associative array with keys 'x' and 'y'. | [
"Get",
"x",
"-",
"and",
"y",
"-",
"coordinate",
"of",
"a",
"node",
"in",
"a",
"InDesign",
"Spread",
"that",
"has",
"an",
"ItemTransform",
"property",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Adobe/InDesign/SpreadNode.php#L63-L72 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/RestController.php | G_RestController._respondToError | protected function _respondToError($errorMessage, $httpCode) {
$this->_setHttpStatusCode($httpCode);
$this->view->result = array(
'success' => false,
'errorMessage' => $errorMessage
);
} | php | protected function _respondToError($errorMessage, $httpCode) {
$this->_setHttpStatusCode($httpCode);
$this->view->result = array(
'success' => false,
'errorMessage' => $errorMessage
);
} | [
"protected",
"function",
"_respondToError",
"(",
"$",
"errorMessage",
",",
"$",
"httpCode",
")",
"{",
"$",
"this",
"->",
"_setHttpStatusCode",
"(",
"$",
"httpCode",
")",
";",
"$",
"this",
"->",
"view",
"->",
"result",
"=",
"array",
"(",
"'success'",
"=>",
... | Format a response object for the view, and set the right error code
@param string $errorMessage
@param int $httpCode
@return void | [
"Format",
"a",
"response",
"object",
"for",
"the",
"view",
"and",
"set",
"the",
"right",
"error",
"code"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/RestController.php#L74-L80 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/RestController.php | G_RestController._validateMethod | protected function _validateMethod($method) {
if (in_array(strtoupper($method), $this->_validMethods)) {
return true;
}
$exception = new Garp_Content_Api_Rest_Exception('Method not allowed');
$exception->setHttpStatusCode(405);
throw $exception;
} | php | protected function _validateMethod($method) {
if (in_array(strtoupper($method), $this->_validMethods)) {
return true;
}
$exception = new Garp_Content_Api_Rest_Exception('Method not allowed');
$exception->setHttpStatusCode(405);
throw $exception;
} | [
"protected",
"function",
"_validateMethod",
"(",
"$",
"method",
")",
"{",
"if",
"(",
"in_array",
"(",
"strtoupper",
"(",
"$",
"method",
")",
",",
"$",
"this",
"->",
"_validMethods",
")",
")",
"{",
"return",
"true",
";",
"}",
"$",
"exception",
"=",
"new... | Wether the HTTP method is valid
@param string $method
@return bool | [
"Wether",
"the",
"HTTP",
"method",
"is",
"valid"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/RestController.php#L92-L99 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/RestController.php | G_RestController._parsePostData | protected function _parsePostData() {
$postData = $this->getRequest()->getRawBody();
if (!$postData) {
return array();
}
try {
$postData = Zend_Json::decode($postData);
} catch (Zend_Json_Exception $e) {
throw new Garp_Content_Api_Rest_Exception(
sprintf(Garp_Content_Api_Rest::EXCEPTION_INVALID_JSON, $e->getMessage())
);
}
return $postData;
} | php | protected function _parsePostData() {
$postData = $this->getRequest()->getRawBody();
if (!$postData) {
return array();
}
try {
$postData = Zend_Json::decode($postData);
} catch (Zend_Json_Exception $e) {
throw new Garp_Content_Api_Rest_Exception(
sprintf(Garp_Content_Api_Rest::EXCEPTION_INVALID_JSON, $e->getMessage())
);
}
return $postData;
} | [
"protected",
"function",
"_parsePostData",
"(",
")",
"{",
"$",
"postData",
"=",
"$",
"this",
"->",
"getRequest",
"(",
")",
"->",
"getRawBody",
"(",
")",
";",
"if",
"(",
"!",
"$",
"postData",
")",
"{",
"return",
"array",
"(",
")",
";",
"}",
"try",
"... | Parses post data as json
@return array | [
"Parses",
"post",
"data",
"as",
"json"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/RestController.php#L117-L130 | train |
grrr-amsterdam/garp3 | library/Garp/File/Unzipper.php | Garp_File_Unzipper.getUnpacked | public function getUnpacked() {
$tries = 0;
$obj = $this->_original;
while ($this->_dataLooksZipped($obj)) {
$unpacked = gzdecode($obj);
if (null === $unpacked || false === $unpacked) {
// If anything went wrong with decoding, return result of previous iteration
return $obj;
}
$obj = $unpacked;
$tries++;
if ($this->_maxDepthReached($tries)) {
// Zipped ridiculously deep? Screw that, return the original
return $this->_original;
}
}
return $obj;
} | php | public function getUnpacked() {
$tries = 0;
$obj = $this->_original;
while ($this->_dataLooksZipped($obj)) {
$unpacked = gzdecode($obj);
if (null === $unpacked || false === $unpacked) {
// If anything went wrong with decoding, return result of previous iteration
return $obj;
}
$obj = $unpacked;
$tries++;
if ($this->_maxDepthReached($tries)) {
// Zipped ridiculously deep? Screw that, return the original
return $this->_original;
}
}
return $obj;
} | [
"public",
"function",
"getUnpacked",
"(",
")",
"{",
"$",
"tries",
"=",
"0",
";",
"$",
"obj",
"=",
"$",
"this",
"->",
"_original",
";",
"while",
"(",
"$",
"this",
"->",
"_dataLooksZipped",
"(",
"$",
"obj",
")",
")",
"{",
"$",
"unpacked",
"=",
"gzdec... | Get unzipped data. Will recursively unpack data until it looks like it's no longer gzipped
@return string | [
"Get",
"unzipped",
"data",
".",
"Will",
"recursively",
"unpack",
"data",
"until",
"it",
"looks",
"like",
"it",
"s",
"no",
"longer",
"gzipped"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/File/Unzipper.php#L39-L59 | train |
grrr-amsterdam/garp3 | library/Garp/Model/ReferenceMapLocalizer.php | Garp_Model_ReferenceMapLocalizer.populate | public function populate($relatedModel, $ruleKey = null) {
// Sanity check: does the model have a reference to the
// given model in the first place?
// This will throw an exception if not.
$relatedModel = $relatedModel instanceof Garp_Model_Db ? get_class($relatedModel) : $relatedModel;
$relatedModel = (substr($relatedModel, 0, 6) !== 'Model_' ? 'Model_' : '') . $relatedModel;
$ref = $this->_model->getReference($relatedModel, $ruleKey);
$locales = Garp_I18n::getLocales();
foreach ($locales as $locale) {
$factory = new Garp_I18n_ModelFactory($locale);
$localizedModel = $factory->getModel($relatedModel);
$localizedModelName = get_class($localizedModel);
$cleanLocalizedName = $localizedModel->getNameWithoutNamespace();
$this->_model->addReference(
$cleanLocalizedName,
$ref[Zend_Db_Table_Abstract::COLUMNS],
$localizedModelName,
$ref[Zend_Db_Table_Abstract::REF_COLUMNS]
);
}
return $this;
} | php | public function populate($relatedModel, $ruleKey = null) {
// Sanity check: does the model have a reference to the
// given model in the first place?
// This will throw an exception if not.
$relatedModel = $relatedModel instanceof Garp_Model_Db ? get_class($relatedModel) : $relatedModel;
$relatedModel = (substr($relatedModel, 0, 6) !== 'Model_' ? 'Model_' : '') . $relatedModel;
$ref = $this->_model->getReference($relatedModel, $ruleKey);
$locales = Garp_I18n::getLocales();
foreach ($locales as $locale) {
$factory = new Garp_I18n_ModelFactory($locale);
$localizedModel = $factory->getModel($relatedModel);
$localizedModelName = get_class($localizedModel);
$cleanLocalizedName = $localizedModel->getNameWithoutNamespace();
$this->_model->addReference(
$cleanLocalizedName,
$ref[Zend_Db_Table_Abstract::COLUMNS],
$localizedModelName,
$ref[Zend_Db_Table_Abstract::REF_COLUMNS]
);
}
return $this;
} | [
"public",
"function",
"populate",
"(",
"$",
"relatedModel",
",",
"$",
"ruleKey",
"=",
"null",
")",
"{",
"// Sanity check: does the model have a reference to the",
"// given model in the first place?",
"// This will throw an exception if not.",
"$",
"relatedModel",
"=",
"$",
"... | Populate the subject model's referenceMap with
localized versions of the given model.
@param String|Garp_Model_Db $relatedModel
@return Void | [
"Populate",
"the",
"subject",
"model",
"s",
"referenceMap",
"with",
"localized",
"versions",
"of",
"the",
"given",
"model",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/ReferenceMapLocalizer.php#L32-L53 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Db/Snippet.php | Garp_Model_Db_Snippet.fetchByIdentifier | public function fetchByIdentifier($identifier) {
if (!$identifier) {
throw new InvalidArgumentException('Snippet identifier is required');
}
$select = $this->select()->where('identifier = ?', $identifier);
if ($result = $this->fetchRow($select)) {
return $result;
}
$ignoreMissing = Zend_Registry::get('config')->snippets->ignoreMissing ?? false;
if (!$ignoreMissing) {
throw new Exception('Snippet not found: ' . $identifier);
}
// Return fallback row, where text is set to $identifier, in order to provide some fallback.
return $this->createRow([
'has_text' => 1,
'text' => $identifier,
]);
} | php | public function fetchByIdentifier($identifier) {
if (!$identifier) {
throw new InvalidArgumentException('Snippet identifier is required');
}
$select = $this->select()->where('identifier = ?', $identifier);
if ($result = $this->fetchRow($select)) {
return $result;
}
$ignoreMissing = Zend_Registry::get('config')->snippets->ignoreMissing ?? false;
if (!$ignoreMissing) {
throw new Exception('Snippet not found: ' . $identifier);
}
// Return fallback row, where text is set to $identifier, in order to provide some fallback.
return $this->createRow([
'has_text' => 1,
'text' => $identifier,
]);
} | [
"public",
"function",
"fetchByIdentifier",
"(",
"$",
"identifier",
")",
"{",
"if",
"(",
"!",
"$",
"identifier",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Snippet identifier is required'",
")",
";",
"}",
"$",
"select",
"=",
"$",
"this",
"->",... | Fetch a snippet by its identifier
@param string $identifier
@return Garp_Db_Table_Row | [
"Fetch",
"a",
"snippet",
"by",
"its",
"identifier"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Db/Snippet.php#L16-L33 | train |
grrr-amsterdam/garp3 | library/Garp/Controller/Plugin/I18n.php | Garp_Controller_Plugin_I18n.routeShutdown | public function routeShutdown(Zend_Controller_Request_Abstract $request) {
$config = Zend_Registry::get('config');
$frontController = Zend_Controller_Front::getInstance();
$params = $request->getParams();
$registry = Zend_Registry::getInstance();
// Steps setting the locale.
// 1. Default language is set in config
// 2. TLD in host header
// 3. Locale params specified in request
$locale = $registry->get('Zend_Locale');
// Check host header TLD.
$tld = preg_replace('/^.*\./', '', $request->getHeader('Host'));
// Provide a list of tld's and their corresponding default languages
$tldLocales = $frontController->getParam('tldLocales');
if (is_array($tldLocales) && array_key_exists($tld, $tldLocales)) {
// The TLD in the request matches one of our specified TLD -> Locales
$locale->setLocale(strtolower($tldLocales[$tld]));
} elseif (isset($params['locale'])) {
// There is a locale specified in the request params.
$locale->setLocale(strtolower($params['locale']));
}
// Now that our locale is set, let's check which language has been selected
// and try to load a translation file for it.
$language = $locale->getLanguage();
$translate = Garp_I18n::getTranslateByLocale($locale);
Zend_Registry::set('Zend_Translate', $translate);
Zend_Form::setDefaultTranslator($translate);
if (!$config->resources->router->locale->enabled) {
return;
}
$path = '/' . ltrim($request->getPathInfo(), '/\\');
// If the language is in the path, then we will want to set the baseUrl
// to the specified language.
$langIsInUrl = preg_match('/^\/' . $language . '\/?/', $path);
$uiDefaultLangIsInUrl = false;
$uiDefaultLanguage = false;
if (isset($config->resources->locale->uiDefault)) {
$uiDefaultLanguage = $config->resources->locale->uiDefault;
$uiDefaultLangIsInUrl = preg_match('/^\/' . $uiDefaultLanguage . '\/?/', $path);
}
if ($langIsInUrl || $uiDefaultLangIsInUrl) {
if ($uiDefaultLangIsInUrl) {
$frontController->setBaseUrl(
$frontController->getBaseUrl() . '/' . $uiDefaultLanguage
);
} else {
$frontController->setBaseUrl($frontController->getBaseUrl() . '/' . $language);
}
} elseif (!empty($config->resources->router->locale->enabled)
&& $config->resources->router->locale->enabled
) {
$redirectUrl = '/' . $language . $path;
if ($frontController->getRouter()->getCurrentRouteName() === 'admin'
&& !empty($config->resources->locale->adminDefault)
) {
$adminDefaultLanguage = $config->resources->locale->adminDefault;
$redirectUrl = '/' . $adminDefaultLanguage . $path;
} elseif ($uiDefaultLanguage) {
$redirectUrl = '/' . $uiDefaultLanguage . $path;
}
if ($request->getQuery()) {
$redirectUrl .= '?' . http_build_query($request->getQuery());
}
$this->getResponse()
->setRedirect($redirectUrl, 301);
}
} | php | public function routeShutdown(Zend_Controller_Request_Abstract $request) {
$config = Zend_Registry::get('config');
$frontController = Zend_Controller_Front::getInstance();
$params = $request->getParams();
$registry = Zend_Registry::getInstance();
// Steps setting the locale.
// 1. Default language is set in config
// 2. TLD in host header
// 3. Locale params specified in request
$locale = $registry->get('Zend_Locale');
// Check host header TLD.
$tld = preg_replace('/^.*\./', '', $request->getHeader('Host'));
// Provide a list of tld's and their corresponding default languages
$tldLocales = $frontController->getParam('tldLocales');
if (is_array($tldLocales) && array_key_exists($tld, $tldLocales)) {
// The TLD in the request matches one of our specified TLD -> Locales
$locale->setLocale(strtolower($tldLocales[$tld]));
} elseif (isset($params['locale'])) {
// There is a locale specified in the request params.
$locale->setLocale(strtolower($params['locale']));
}
// Now that our locale is set, let's check which language has been selected
// and try to load a translation file for it.
$language = $locale->getLanguage();
$translate = Garp_I18n::getTranslateByLocale($locale);
Zend_Registry::set('Zend_Translate', $translate);
Zend_Form::setDefaultTranslator($translate);
if (!$config->resources->router->locale->enabled) {
return;
}
$path = '/' . ltrim($request->getPathInfo(), '/\\');
// If the language is in the path, then we will want to set the baseUrl
// to the specified language.
$langIsInUrl = preg_match('/^\/' . $language . '\/?/', $path);
$uiDefaultLangIsInUrl = false;
$uiDefaultLanguage = false;
if (isset($config->resources->locale->uiDefault)) {
$uiDefaultLanguage = $config->resources->locale->uiDefault;
$uiDefaultLangIsInUrl = preg_match('/^\/' . $uiDefaultLanguage . '\/?/', $path);
}
if ($langIsInUrl || $uiDefaultLangIsInUrl) {
if ($uiDefaultLangIsInUrl) {
$frontController->setBaseUrl(
$frontController->getBaseUrl() . '/' . $uiDefaultLanguage
);
} else {
$frontController->setBaseUrl($frontController->getBaseUrl() . '/' . $language);
}
} elseif (!empty($config->resources->router->locale->enabled)
&& $config->resources->router->locale->enabled
) {
$redirectUrl = '/' . $language . $path;
if ($frontController->getRouter()->getCurrentRouteName() === 'admin'
&& !empty($config->resources->locale->adminDefault)
) {
$adminDefaultLanguage = $config->resources->locale->adminDefault;
$redirectUrl = '/' . $adminDefaultLanguage . $path;
} elseif ($uiDefaultLanguage) {
$redirectUrl = '/' . $uiDefaultLanguage . $path;
}
if ($request->getQuery()) {
$redirectUrl .= '?' . http_build_query($request->getQuery());
}
$this->getResponse()
->setRedirect($redirectUrl, 301);
}
} | [
"public",
"function",
"routeShutdown",
"(",
"Zend_Controller_Request_Abstract",
"$",
"request",
")",
"{",
"$",
"config",
"=",
"Zend_Registry",
"::",
"get",
"(",
"'config'",
")",
";",
"$",
"frontController",
"=",
"Zend_Controller_Front",
"::",
"getInstance",
"(",
"... | Sets the application locale and translation based on the locale param, if
one is not provided it defaults to english
@param Zend_Controller_Request_Abstract $request
@return Void | [
"Sets",
"the",
"application",
"locale",
"and",
"translation",
"based",
"on",
"the",
"locale",
"param",
"if",
"one",
"is",
"not",
"provided",
"it",
"defaults",
"to",
"english"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Controller/Plugin/I18n.php#L21-L92 | train |
grrr-amsterdam/garp3 | library/Garp/Browsebox/Filter/Where.php | Garp_Browsebox_Filter_Where.modifySelect | public function modifySelect(Zend_Db_Select &$select) {
foreach ($this->_config as $i => $condition) {
$select->where($condition, $this->_values[$i]);
}
} | php | public function modifySelect(Zend_Db_Select &$select) {
foreach ($this->_config as $i => $condition) {
$select->where($condition, $this->_values[$i]);
}
} | [
"public",
"function",
"modifySelect",
"(",
"Zend_Db_Select",
"&",
"$",
"select",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"_config",
"as",
"$",
"i",
"=>",
"$",
"condition",
")",
"{",
"$",
"select",
"->",
"where",
"(",
"$",
"condition",
",",
"$",
... | Modify the Select object
@param Zend_Db_Select $select
@return Void | [
"Modify",
"the",
"Select",
"object"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Browsebox/Filter/Where.php#L47-L51 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Db/ClusterServer.php | Garp_Model_Db_ClusterServer.checkIn | public function checkIn() {
$now = date('Y-m-d H:i:s');
$serverRow = $this->_fetchServerRow();
if (!$serverRow) {
$serverRow = $this->createRow();
$serverRow->hostname = gethostname();
$lastCheckIn = $now;
} else {
$lastCheckIn = $serverRow->modified;
}
// set the modified date manually, to make sure the record is updated.
$serverRow->modified = $now;
$serverId = $serverRow->save();
return array(
$serverId,
$lastCheckIn
);
} | php | public function checkIn() {
$now = date('Y-m-d H:i:s');
$serverRow = $this->_fetchServerRow();
if (!$serverRow) {
$serverRow = $this->createRow();
$serverRow->hostname = gethostname();
$lastCheckIn = $now;
} else {
$lastCheckIn = $serverRow->modified;
}
// set the modified date manually, to make sure the record is updated.
$serverRow->modified = $now;
$serverId = $serverRow->save();
return array(
$serverId,
$lastCheckIn
);
} | [
"public",
"function",
"checkIn",
"(",
")",
"{",
"$",
"now",
"=",
"date",
"(",
"'Y-m-d H:i:s'",
")",
";",
"$",
"serverRow",
"=",
"$",
"this",
"->",
"_fetchServerRow",
"(",
")",
";",
"if",
"(",
"!",
"$",
"serverRow",
")",
"{",
"$",
"serverRow",
"=",
... | Registers this server node in the ClusterServer table, and returns information about the current server.
@return Array Numeric array, containing the serverId and the last check-in time. | [
"Registers",
"this",
"server",
"node",
"in",
"the",
"ClusterServer",
"table",
"and",
"returns",
"information",
"about",
"the",
"current",
"server",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Db/ClusterServer.php#L15-L35 | train |
grrr-amsterdam/garp3 | application/modules/g/views/helpers/Image.php | G_View_Helper_Image.render | public function render($image, $template = null, $htmlAttribs = array(), $partial = null) {
if ($this->_isFilename($image)) {
// When calling for a static image, you can use the second param as $htmlAttribs.
$htmlAttribs = $template ?: array();
return $this->_renderStatic($image, $htmlAttribs);
}
if (!$template) {
throw new Exception(self::ERROR_SCALING_TEMPLATE_MISSING);
}
return $this->_renderUpload($image, $template, $htmlAttribs, $partial);
} | php | public function render($image, $template = null, $htmlAttribs = array(), $partial = null) {
if ($this->_isFilename($image)) {
// When calling for a static image, you can use the second param as $htmlAttribs.
$htmlAttribs = $template ?: array();
return $this->_renderStatic($image, $htmlAttribs);
}
if (!$template) {
throw new Exception(self::ERROR_SCALING_TEMPLATE_MISSING);
}
return $this->_renderUpload($image, $template, $htmlAttribs, $partial);
} | [
"public",
"function",
"render",
"(",
"$",
"image",
",",
"$",
"template",
"=",
"null",
",",
"$",
"htmlAttribs",
"=",
"array",
"(",
")",
",",
"$",
"partial",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_isFilename",
"(",
"$",
"image",
")",
... | Render an HTML img tag.
@param mixed $image Database id for uploads, or a filename
in case of a static image asset.
@param string $template The id of the scaling template as defined in application.ini.
For instance: 'cms_preview'
@param array $htmlAttribs HTML attributes on the image tag
@param string $partial Custom partial for rendering an upload
@return string | [
"Render",
"an",
"HTML",
"img",
"tag",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/Image.php#L46-L56 | train |
grrr-amsterdam/garp3 | application/modules/g/views/helpers/Image.php | G_View_Helper_Image.getUrl | public function getUrl($image, $template = null) {
if ($this->_isFilename($image)) {
return $this->getStaticUrl($image);
}
if (!$template) {
throw new Exception(self::ERROR_SCALING_TEMPLATE_MISSING);
}
return $this->getScaledUrl($image, $template);
} | php | public function getUrl($image, $template = null) {
if ($this->_isFilename($image)) {
return $this->getStaticUrl($image);
}
if (!$template) {
throw new Exception(self::ERROR_SCALING_TEMPLATE_MISSING);
}
return $this->getScaledUrl($image, $template);
} | [
"public",
"function",
"getUrl",
"(",
"$",
"image",
",",
"$",
"template",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_isFilename",
"(",
"$",
"image",
")",
")",
"{",
"return",
"$",
"this",
"->",
"getStaticUrl",
"(",
"$",
"image",
")",
";",... | Return URL of scaled image
@param mixed $image Database id for uploads, or a filename
in case of a static image asset.
@param string $template The id of the scaling template as defined in application.ini.
For instance: 'cms_preview'
@return string | [
"Return",
"URL",
"of",
"scaled",
"image"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/Image.php#L67-L75 | train |
grrr-amsterdam/garp3 | application/modules/g/views/helpers/Image.php | G_View_Helper_Image.getSourceUrl | public function getSourceUrl($filename) {
if (!$this->_isFilename($filename)) {
throw new Exception(self::ERROR_ARGUMENT_IS_NOT_FILENAME);
}
$file = new Garp_Image_File();
return $file->getUrl($filename);
} | php | public function getSourceUrl($filename) {
if (!$this->_isFilename($filename)) {
throw new Exception(self::ERROR_ARGUMENT_IS_NOT_FILENAME);
}
$file = new Garp_Image_File();
return $file->getUrl($filename);
} | [
"public",
"function",
"getSourceUrl",
"(",
"$",
"filename",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"_isFilename",
"(",
"$",
"filename",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"self",
"::",
"ERROR_ARGUMENT_IS_NOT_FILENAME",
")",
";",
"}",
... | Returns the url to the source file of an upload.
@param string $filename The filename of the upload, without the path.
@return string | [
"Returns",
"the",
"url",
"to",
"the",
"source",
"file",
"of",
"an",
"upload",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/Image.php#L105-L111 | train |
grrr-amsterdam/garp3 | application/modules/g/views/helpers/Image.php | G_View_Helper_Image.getSourceUrlById | public function getSourceUrlById($id) {
$image = instance(new Model_Image)->fetchById($id);
if (!$image) {
throw new InvalidArgumentException(self::ERROR_IMAGE_NOT_FOUND);
}
return $this->getSourceUrl($image['filename']);
} | php | public function getSourceUrlById($id) {
$image = instance(new Model_Image)->fetchById($id);
if (!$image) {
throw new InvalidArgumentException(self::ERROR_IMAGE_NOT_FOUND);
}
return $this->getSourceUrl($image['filename']);
} | [
"public",
"function",
"getSourceUrlById",
"(",
"$",
"id",
")",
"{",
"$",
"image",
"=",
"instance",
"(",
"new",
"Model_Image",
")",
"->",
"fetchById",
"(",
"$",
"id",
")",
";",
"if",
"(",
"!",
"$",
"image",
")",
"{",
"throw",
"new",
"InvalidArgumentExce... | Returns the url to the source file of an upload by id
@param int $id The id of the upload
@return string | [
"Returns",
"the",
"url",
"to",
"the",
"source",
"file",
"of",
"an",
"upload",
"by",
"id"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/Image.php#L119-L125 | train |
grrr-amsterdam/garp3 | application/modules/g/views/helpers/Image.php | G_View_Helper_Image._renderStatic | protected function _renderStatic($filename, array $htmlAttribs = array()) {
$file = new Garp_Image_File(Garp_File::FILE_VARIANT_STATIC);
$src = $file->getUrl($filename);
if (!array_key_exists('alt', $htmlAttribs)) {
$htmlAttribs['alt'] = '';
}
return $this->view->htmlImage($src, $htmlAttribs);
} | php | protected function _renderStatic($filename, array $htmlAttribs = array()) {
$file = new Garp_Image_File(Garp_File::FILE_VARIANT_STATIC);
$src = $file->getUrl($filename);
if (!array_key_exists('alt', $htmlAttribs)) {
$htmlAttribs['alt'] = '';
}
return $this->view->htmlImage($src, $htmlAttribs);
} | [
"protected",
"function",
"_renderStatic",
"(",
"$",
"filename",
",",
"array",
"$",
"htmlAttribs",
"=",
"array",
"(",
")",
")",
"{",
"$",
"file",
"=",
"new",
"Garp_Image_File",
"(",
"Garp_File",
"::",
"FILE_VARIANT_STATIC",
")",
";",
"$",
"src",
"=",
"$",
... | Render a static image
@param string $filename
@param array $htmlAttribs
@return string | [
"Render",
"a",
"static",
"image"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/Image.php#L144-L153 | train |
grrr-amsterdam/garp3 | application/modules/g/views/helpers/Image.php | G_View_Helper_Image._renderUpload | protected function _renderUpload(
$imageIdOrRecord, $template = null, array $htmlAttribs = array(), $partial = ''
) {
if (!empty($template)) {
$scaler = $this->_getImageScaler();
$src = $scaler->getScaledUrl($imageIdOrRecord, $template);
$tplScalingParams = $scaler->getTemplateParameters($template);
$htmlAttribs = array_merge(
$htmlAttribs,
$this->_getHtmlAttribsFromSizeParams($tplScalingParams)
);
} else {
if ($imageIdOrRecord instanceof Garp_Db_Table_Row) {
$filename = $imageIdOrRecord->filename;
} else {
$imageModel = new Model_Image();
$filename = $imageModel->fetchFilenameById($imageIdOrRecord);
}
$file = new Garp_Image_File(Garp_File::FILE_VARIANT_UPLOAD);
$src = $file->getUrl($filename);
}
if (!array_key_exists('alt', $htmlAttribs)) {
$htmlAttribs['alt'] = '';
}
$htmlAttribs['src'] = $src;
$imgTag = '<img' . $this->_htmlAttribs($htmlAttribs) . '>';
if ($imageIdOrRecord instanceof Garp_Db_Table_Row) {
if ($partial) {
$module = 'default';
} else {
$partial = 'partials/image.phtml';
$module = 'g';
}
return $this->view->partial(
$partial,
$module,
array(
'imgTag' => $imgTag,
'imgObject' => $imageIdOrRecord
)
);
} else {
return $imgTag;
}
} | php | protected function _renderUpload(
$imageIdOrRecord, $template = null, array $htmlAttribs = array(), $partial = ''
) {
if (!empty($template)) {
$scaler = $this->_getImageScaler();
$src = $scaler->getScaledUrl($imageIdOrRecord, $template);
$tplScalingParams = $scaler->getTemplateParameters($template);
$htmlAttribs = array_merge(
$htmlAttribs,
$this->_getHtmlAttribsFromSizeParams($tplScalingParams)
);
} else {
if ($imageIdOrRecord instanceof Garp_Db_Table_Row) {
$filename = $imageIdOrRecord->filename;
} else {
$imageModel = new Model_Image();
$filename = $imageModel->fetchFilenameById($imageIdOrRecord);
}
$file = new Garp_Image_File(Garp_File::FILE_VARIANT_UPLOAD);
$src = $file->getUrl($filename);
}
if (!array_key_exists('alt', $htmlAttribs)) {
$htmlAttribs['alt'] = '';
}
$htmlAttribs['src'] = $src;
$imgTag = '<img' . $this->_htmlAttribs($htmlAttribs) . '>';
if ($imageIdOrRecord instanceof Garp_Db_Table_Row) {
if ($partial) {
$module = 'default';
} else {
$partial = 'partials/image.phtml';
$module = 'g';
}
return $this->view->partial(
$partial,
$module,
array(
'imgTag' => $imgTag,
'imgObject' => $imageIdOrRecord
)
);
} else {
return $imgTag;
}
} | [
"protected",
"function",
"_renderUpload",
"(",
"$",
"imageIdOrRecord",
",",
"$",
"template",
"=",
"null",
",",
"array",
"$",
"htmlAttribs",
"=",
"array",
"(",
")",
",",
"$",
"partial",
"=",
"''",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"template",... | Returns an HTML image tag, with the correct path to the image provided.
@param mixed $imageIdOrRecord Id of the image record, or a Garp_Db_Table_Row image record.
This can also be an instance of an Image model.
If so, the image will be rendered inside a partial that
includes its caption and other metadata.
@param array $template Template name.
@param array $htmlAttribs HTML attributes for this <img> tag, such as 'alt'.
@param string $partial Custom partial for rendering this image
@return string Full image tag string, containing attributes and full path | [
"Returns",
"an",
"HTML",
"image",
"tag",
"with",
"the",
"correct",
"path",
"to",
"the",
"image",
"provided",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/Image.php#L167-L214 | train |
grrr-amsterdam/garp3 | library/Garp/Service/Elasticsearch/Configuration.php | Garp_Service_Elasticsearch_Configuration._getDefaultIndex | protected function _getDefaultIndex() {
$config = Zend_Registry::get('config');
if (!isset($config->app->name)) {
throw new Exception(self::ERROR_NO_APP_NAME_CONFIGURED);
}
$appName = str_replace(' ', '', $config->app->name);
$appName = Garp_Util_String::camelcasedToDashed($appName);
if (!$appName) {
throw new Exception(self::ERROR_APP_NAME_EMPTY);
}
$indexName = $appName . '-' . APPLICATION_ENV;
return $indexName;
} | php | protected function _getDefaultIndex() {
$config = Zend_Registry::get('config');
if (!isset($config->app->name)) {
throw new Exception(self::ERROR_NO_APP_NAME_CONFIGURED);
}
$appName = str_replace(' ', '', $config->app->name);
$appName = Garp_Util_String::camelcasedToDashed($appName);
if (!$appName) {
throw new Exception(self::ERROR_APP_NAME_EMPTY);
}
$indexName = $appName . '-' . APPLICATION_ENV;
return $indexName;
} | [
"protected",
"function",
"_getDefaultIndex",
"(",
")",
"{",
"$",
"config",
"=",
"Zend_Registry",
"::",
"get",
"(",
"'config'",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"config",
"->",
"app",
"->",
"name",
")",
")",
"{",
"throw",
"new",
"Exception",... | Returns the database name for this environment, to be used as the index name for Elasticsearch. | [
"Returns",
"the",
"database",
"name",
"for",
"this",
"environment",
"to",
"be",
"used",
"as",
"the",
"index",
"name",
"for",
"Elasticsearch",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Service/Elasticsearch/Configuration.php#L94-L111 | train |
grrr-amsterdam/garp3 | library/Garp/Cli/Command/Shell.php | Garp_Cli_Command_Shell.main | public function main(array $args = array()) {
Garp_Cli::lineOut('Welcome to the Garp interactive shell.', Garp_Cli::YELLOW);
Garp_Cli::lineOut('Use Ctrl-C to quit.');
$this->_setErrorHandler();
$this->_tick();
} | php | public function main(array $args = array()) {
Garp_Cli::lineOut('Welcome to the Garp interactive shell.', Garp_Cli::YELLOW);
Garp_Cli::lineOut('Use Ctrl-C to quit.');
$this->_setErrorHandler();
$this->_tick();
} | [
"public",
"function",
"main",
"(",
"array",
"$",
"args",
"=",
"array",
"(",
")",
")",
"{",
"Garp_Cli",
"::",
"lineOut",
"(",
"'Welcome to the Garp interactive shell.'",
",",
"Garp_Cli",
"::",
"YELLOW",
")",
";",
"Garp_Cli",
"::",
"lineOut",
"(",
"'Use Ctrl-C t... | Main starting point
@param array $args
@return void | [
"Main",
"starting",
"point"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cli/Command/Shell.php#L39-L45 | train |
grrr-amsterdam/garp3 | library/Garp/Cli/Command/Shell.php | Garp_Cli_Command_Shell.output | public function output($buffer) {
if (!$buffer && !$this->__result) {
return '';
}
$out = '';
// Always include the output generated by the expression first
if ($buffer) {
$out .= Garp_Cli::lineOut($buffer, null, true, false);
}
// And follow-up with the populated result, if any
if ($this->__result) {
// Try to format as user-friendly as possible
$isObjWithToArray = is_object($this->__result) &&
method_exists($this->__result, 'toArray');
$this->__result = $isObjWithToArray ? $this->__result->toArray() : $this->__result;
$this->__result = var_export($this->__result, true);
$out .= Garp_Cli::lineOut($this->__result, Garp_Cli::BLUE, true, false);
}
return $out;
} | php | public function output($buffer) {
if (!$buffer && !$this->__result) {
return '';
}
$out = '';
// Always include the output generated by the expression first
if ($buffer) {
$out .= Garp_Cli::lineOut($buffer, null, true, false);
}
// And follow-up with the populated result, if any
if ($this->__result) {
// Try to format as user-friendly as possible
$isObjWithToArray = is_object($this->__result) &&
method_exists($this->__result, 'toArray');
$this->__result = $isObjWithToArray ? $this->__result->toArray() : $this->__result;
$this->__result = var_export($this->__result, true);
$out .= Garp_Cli::lineOut($this->__result, Garp_Cli::BLUE, true, false);
}
return $out;
} | [
"public",
"function",
"output",
"(",
"$",
"buffer",
")",
"{",
"if",
"(",
"!",
"$",
"buffer",
"&&",
"!",
"$",
"this",
"->",
"__result",
")",
"{",
"return",
"''",
";",
"}",
"$",
"out",
"=",
"''",
";",
"// Always include the output generated by the expression... | Output the result of the eval'd expression
@param string $buffer Buffered input
@return String | [
"Output",
"the",
"result",
"of",
"the",
"eval",
"d",
"expression"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cli/Command/Shell.php#L53-L75 | train |
grrr-amsterdam/garp3 | library/Garp/Cli/Command/Shell.php | Garp_Cli_Command_Shell._tick | protected function _tick() {
while (true) {
// Grab a line of PHP code from the prompt
$line = $this->_getInput();
/**
* Note that $this->__result will be populated, if no target variable is given
* in the expression. In other words, this will populate $this->__result:
* $someModel->fetchAll();
* But this won't:
* $rows = $someModel->fetchAll();
* ...because we assume the user wants to do something with the variable.
*/
if (!$this->_input && !preg_match('/^(\$\w+\s?\=)|print|echo/', $line)) {
$line = '$this->__result = ' . $line;
}
$this->_input .= $line;
// If no semicolon is found at the end, assume
// multi-line input. The user is therefore not finished,
// so we just continue here and wait for that semicolon.
if (substr($line, -1) !== ';') {
continue;
}
// Execute input, and grab its output
ob_start(array($this, 'output'));
eval($this->_input);
ob_end_flush();
// Clear result var
$this->__result = null;
// Reset input
$this->_input = '';
}
} | php | protected function _tick() {
while (true) {
// Grab a line of PHP code from the prompt
$line = $this->_getInput();
/**
* Note that $this->__result will be populated, if no target variable is given
* in the expression. In other words, this will populate $this->__result:
* $someModel->fetchAll();
* But this won't:
* $rows = $someModel->fetchAll();
* ...because we assume the user wants to do something with the variable.
*/
if (!$this->_input && !preg_match('/^(\$\w+\s?\=)|print|echo/', $line)) {
$line = '$this->__result = ' . $line;
}
$this->_input .= $line;
// If no semicolon is found at the end, assume
// multi-line input. The user is therefore not finished,
// so we just continue here and wait for that semicolon.
if (substr($line, -1) !== ';') {
continue;
}
// Execute input, and grab its output
ob_start(array($this, 'output'));
eval($this->_input);
ob_end_flush();
// Clear result var
$this->__result = null;
// Reset input
$this->_input = '';
}
} | [
"protected",
"function",
"_tick",
"(",
")",
"{",
"while",
"(",
"true",
")",
"{",
"// Grab a line of PHP code from the prompt",
"$",
"line",
"=",
"$",
"this",
"->",
"_getInput",
"(",
")",
";",
"/**\n * Note that $this->__result will be populated, if no target v... | One iteration in the main loop.
@return Void | [
"One",
"iteration",
"in",
"the",
"main",
"loop",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cli/Command/Shell.php#L82-L118 | train |
grrr-amsterdam/garp3 | library/Garp/Cli/Command/Shell.php | Garp_Cli_Command_Shell._getInput | protected function _getInput() {
if (function_exists('readline') && function_exists('readline_add_history')) {
$line = readline($this->_getPrompt());
readline_add_history($line);
return $line;
}
echo $this->_getPrompt();
$line = Garp_Cli::prompt();
return $line;
} | php | protected function _getInput() {
if (function_exists('readline') && function_exists('readline_add_history')) {
$line = readline($this->_getPrompt());
readline_add_history($line);
return $line;
}
echo $this->_getPrompt();
$line = Garp_Cli::prompt();
return $line;
} | [
"protected",
"function",
"_getInput",
"(",
")",
"{",
"if",
"(",
"function_exists",
"(",
"'readline'",
")",
"&&",
"function_exists",
"(",
"'readline_add_history'",
")",
")",
"{",
"$",
"line",
"=",
"readline",
"(",
"$",
"this",
"->",
"_getPrompt",
"(",
")",
... | Retrieve input from the user.
Prefer readline because it supports history.
@return String | [
"Retrieve",
"input",
"from",
"the",
"user",
".",
"Prefer",
"readline",
"because",
"it",
"supports",
"history",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cli/Command/Shell.php#L126-L135 | train |
grrr-amsterdam/garp3 | library/Garp/Content/Import/Abstract.php | Garp_Content_Import_Abstract.rollback | public function rollback(Garp_Model $model, array $primaryKeys) {
if (empty($primaryKeys)) {
return;
}
$primaryCols = (array)$model->info(Zend_Db_Table::PRIMARY);
$where = array();
foreach ($primaryKeys as $pk) {
$recordWhere = array();
foreach ((array)$pk as $i => $key) {
$recordWhere[] = $model->getAdapter()->quoteIdentifier(current($primaryCols)).' = '.
$model->getAdapter()->quote($key);
}
$recordWhere = implode(' AND ', $recordWhere);
$recordWhere = '('.$recordWhere.')';
$where[] = $recordWhere;
reset($primaryCols);
}
$where = implode(' OR ', $where);
if (empty($where)) {
return;
}
$model->delete($where);
} | php | public function rollback(Garp_Model $model, array $primaryKeys) {
if (empty($primaryKeys)) {
return;
}
$primaryCols = (array)$model->info(Zend_Db_Table::PRIMARY);
$where = array();
foreach ($primaryKeys as $pk) {
$recordWhere = array();
foreach ((array)$pk as $i => $key) {
$recordWhere[] = $model->getAdapter()->quoteIdentifier(current($primaryCols)).' = '.
$model->getAdapter()->quote($key);
}
$recordWhere = implode(' AND ', $recordWhere);
$recordWhere = '('.$recordWhere.')';
$where[] = $recordWhere;
reset($primaryCols);
}
$where = implode(' OR ', $where);
if (empty($where)) {
return;
}
$model->delete($where);
} | [
"public",
"function",
"rollback",
"(",
"Garp_Model",
"$",
"model",
",",
"array",
"$",
"primaryKeys",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"primaryKeys",
")",
")",
"{",
"return",
";",
"}",
"$",
"primaryCols",
"=",
"(",
"array",
")",
"$",
"model",
"... | Rollback all inserts when the import throws an error halfway
@param Garp_Model $model
@param Array $primaryKeys Collection of primary keys
@return Void | [
"Rollback",
"all",
"inserts",
"when",
"the",
"import",
"throws",
"an",
"error",
"halfway"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Content/Import/Abstract.php#L52-L74 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/Cachable.php | Garp_Model_Behavior_Cachable.beforeFetch | public function beforeFetch(&$args) {
$model = &$args[0];
$select = &$args[1];
// check if the cache is in use
if (!$model->getCacheQueries() || !Zend_Registry::get('readFromCache')) {
return;
}
$cacheKey = $this->createCacheKey($model, $select);
$results = Garp_Cache_Manager::readQueryCache($model, $cacheKey);
if ($results !== -1) {
$args[2] = $results;
} else {
$this->_openCacheKey = $cacheKey;
}
} | php | public function beforeFetch(&$args) {
$model = &$args[0];
$select = &$args[1];
// check if the cache is in use
if (!$model->getCacheQueries() || !Zend_Registry::get('readFromCache')) {
return;
}
$cacheKey = $this->createCacheKey($model, $select);
$results = Garp_Cache_Manager::readQueryCache($model, $cacheKey);
if ($results !== -1) {
$args[2] = $results;
} else {
$this->_openCacheKey = $cacheKey;
}
} | [
"public",
"function",
"beforeFetch",
"(",
"&",
"$",
"args",
")",
"{",
"$",
"model",
"=",
"&",
"$",
"args",
"[",
"0",
"]",
";",
"$",
"select",
"=",
"&",
"$",
"args",
"[",
"1",
"]",
";",
"// check if the cache is in use",
"if",
"(",
"!",
"$",
"model"... | Before fetch callback, checks the cache for valid data.
@param Array $args
@return Void | [
"Before",
"fetch",
"callback",
"checks",
"the",
"cache",
"for",
"valid",
"data",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/Cachable.php#L40-L54 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/Cachable.php | Garp_Model_Behavior_Cachable.afterFetch | public function afterFetch(&$args) {
if (!$this->_openCacheKey) {
return;
}
$model = $args[0];
$results = $args[1];
$cacheKey = $this->_openCacheKey;
Garp_Cache_Manager::writeQueryCache($model, $cacheKey, $results);
// reset the key
$this->_openCacheKey = '';
} | php | public function afterFetch(&$args) {
if (!$this->_openCacheKey) {
return;
}
$model = $args[0];
$results = $args[1];
$cacheKey = $this->_openCacheKey;
Garp_Cache_Manager::writeQueryCache($model, $cacheKey, $results);
// reset the key
$this->_openCacheKey = '';
} | [
"public",
"function",
"afterFetch",
"(",
"&",
"$",
"args",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"_openCacheKey",
")",
"{",
"return",
";",
"}",
"$",
"model",
"=",
"$",
"args",
"[",
"0",
"]",
";",
"$",
"results",
"=",
"$",
"args",
"[",
"1... | After fetch callback, writes data back to the cache.
@param Array $args
@return Void | [
"After",
"fetch",
"callback",
"writes",
"data",
"back",
"to",
"the",
"cache",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/Cachable.php#L61-L73 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/Cachable.php | Garp_Model_Behavior_Cachable.createCacheKey | public function createCacheKey(Garp_Model $model, Zend_Db_Select $select) {
$boundModels = serialize(Garp_Model_Db_BindingManager::getBindingTree(get_class($model)));
$hash = md5(
md5($select).
md5($boundModels)
);
return $hash;
} | php | public function createCacheKey(Garp_Model $model, Zend_Db_Select $select) {
$boundModels = serialize(Garp_Model_Db_BindingManager::getBindingTree(get_class($model)));
$hash = md5(
md5($select).
md5($boundModels)
);
return $hash;
} | [
"public",
"function",
"createCacheKey",
"(",
"Garp_Model",
"$",
"model",
",",
"Zend_Db_Select",
"$",
"select",
")",
"{",
"$",
"boundModels",
"=",
"serialize",
"(",
"Garp_Model_Db_BindingManager",
"::",
"getBindingTree",
"(",
"get_class",
"(",
"$",
"model",
")",
... | Create a unique hash for cache entries, based on the SELECT object,
but also on the registered bindings, because a query might be the same
with different results when bindings come into play.
@param Garp_Model $model
@param Zend_Db_Select $select
@return String | [
"Create",
"a",
"unique",
"hash",
"for",
"cache",
"entries",
"based",
"on",
"the",
"SELECT",
"object",
"but",
"also",
"on",
"the",
"registered",
"bindings",
"because",
"a",
"query",
"might",
"be",
"the",
"same",
"with",
"different",
"results",
"when",
"bindin... | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/Cachable.php#L115-L122 | train |
grrr-amsterdam/garp3 | library/Garp/Adobe/InDesign/Spread.php | Garp_Adobe_InDesign_Spread._buildStories | protected function _buildStories() {
$storiesByPageNumber = array();
$storiesByTag = array();
$pagesCount = count($this->pages);
// Build an array with all textframe positions, divided into the accompanying story XML tags
foreach ($this->textFrames as $textFrame) {
$story = new Garp_Adobe_InDesign_Story($textFrame->storyId, $this->_workingDir);
if ($tag = $story->getTag()) {
$storiesByTag[$tag][] = array(
'storyId' => $textFrame->storyId,
'x' => $textFrame->x
);
}
}
// sort the stories by horizontal position
$sortFunction = function ($storyA, $storyB) {
if ($storyA['x'] == $storyB['x']) {
return 0;
}
return $storyA['x'] > $storyB['x'] ? 1 : -1;
};
foreach ($storiesByTag as &$stories) {
usort($stories, $sortFunction);
}
// now divide the stories in pages
foreach ($storiesByTag as $tagStories) {
$tagStoriesCount = count($tagStories);
$tagStoriesPerPage = $tagStoriesCount / $pagesCount;
foreach ($tagStories as $s => $tagStory) {
$page = floor($s / $tagStoriesPerPage);
$pageNumber = $this->pages[$page]->index;
$storiesByPageNumber[$pageNumber][] = $tagStory['storyId'];
}
}
return $storiesByPageNumber;
} | php | protected function _buildStories() {
$storiesByPageNumber = array();
$storiesByTag = array();
$pagesCount = count($this->pages);
// Build an array with all textframe positions, divided into the accompanying story XML tags
foreach ($this->textFrames as $textFrame) {
$story = new Garp_Adobe_InDesign_Story($textFrame->storyId, $this->_workingDir);
if ($tag = $story->getTag()) {
$storiesByTag[$tag][] = array(
'storyId' => $textFrame->storyId,
'x' => $textFrame->x
);
}
}
// sort the stories by horizontal position
$sortFunction = function ($storyA, $storyB) {
if ($storyA['x'] == $storyB['x']) {
return 0;
}
return $storyA['x'] > $storyB['x'] ? 1 : -1;
};
foreach ($storiesByTag as &$stories) {
usort($stories, $sortFunction);
}
// now divide the stories in pages
foreach ($storiesByTag as $tagStories) {
$tagStoriesCount = count($tagStories);
$tagStoriesPerPage = $tagStoriesCount / $pagesCount;
foreach ($tagStories as $s => $tagStory) {
$page = floor($s / $tagStoriesPerPage);
$pageNumber = $this->pages[$page]->index;
$storiesByPageNumber[$pageNumber][] = $tagStory['storyId'];
}
}
return $storiesByPageNumber;
} | [
"protected",
"function",
"_buildStories",
"(",
")",
"{",
"$",
"storiesByPageNumber",
"=",
"array",
"(",
")",
";",
"$",
"storiesByTag",
"=",
"array",
"(",
")",
";",
"$",
"pagesCount",
"=",
"count",
"(",
"$",
"this",
"->",
"pages",
")",
";",
"// Build an a... | This method retrieves the Stories referenced by TextFrame entries on the current Spread,
that geometrically map to this page.
This has be calculated by geometry, since a TextFrame is not directly linked to a Page,
but to a Spread.
@return array | [
"This",
"method",
"retrieves",
"the",
"Stories",
"referenced",
"by",
"TextFrame",
"entries",
"on",
"the",
"current",
"Spread",
"that",
"geometrically",
"map",
"to",
"this",
"page",
".",
"This",
"has",
"be",
"calculated",
"by",
"geometry",
"since",
"a",
"TextFr... | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Adobe/InDesign/Spread.php#L151-L192 | train |
grrr-amsterdam/garp3 | library/Garp/Cli/Ui.php | Garp_Cli_Ui.advance | public function advance($newValue = null) {
if (!is_null($newValue)) {
$this->_currentValue = $newValue;
return;
}
$this->_currentValue++;
} | php | public function advance($newValue = null) {
if (!is_null($newValue)) {
$this->_currentValue = $newValue;
return;
}
$this->_currentValue++;
} | [
"public",
"function",
"advance",
"(",
"$",
"newValue",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"is_null",
"(",
"$",
"newValue",
")",
")",
"{",
"$",
"this",
"->",
"_currentValue",
"=",
"$",
"newValue",
";",
"return",
";",
"}",
"$",
"this",
"->",
"_cu... | Advances the progress bar by 1 step, if no argument is provided.
Otherwise, the progress bar is set to the provided value.
@param int $newValue The new value. Leave empty to advance 1 step.
This will be compared to $this->_totalValue.
@return void | [
"Advances",
"the",
"progress",
"bar",
"by",
"1",
"step",
"if",
"no",
"argument",
"is",
"provided",
".",
"Otherwise",
"the",
"progress",
"bar",
"is",
"set",
"to",
"the",
"provided",
"value",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cli/Ui.php#L42-L49 | train |
grrr-amsterdam/garp3 | library/Garp/3rdParty/facebook/src/base_facebook.php | BaseFacebook.getUserAccessToken | protected function getUserAccessToken() {
// first, consider a signed request if it's supplied.
// if there is a signed request, then it alone determines
// the access token.
$signed_request = $this->getSignedRequest();
if ($signed_request) {
// apps.facebook.com hands the access_token in the signed_request
if (array_key_exists('oauth_token', $signed_request)) {
$access_token = $signed_request['oauth_token'];
$this->setPersistentData('access_token', $access_token);
return $access_token;
}
// the JS SDK puts a code in with the redirect_uri of ''
if (array_key_exists('code', $signed_request)) {
$code = $signed_request['code'];
if ($code && $code == $this->getPersistentData('code')) {
// short-circuit if the code we have is the same as the one presented
return $this->getPersistentData('access_token');
}
$access_token = $this->getAccessTokenFromCode($code, '');
if ($access_token) {
$this->setPersistentData('code', $code);
$this->setPersistentData('access_token', $access_token);
return $access_token;
}
}
// signed request states there's no access token, so anything
// stored should be cleared.
$this->clearAllPersistentData();
return false; // respect the signed request's data, even
// if there's an authorization code or something else
}
$code = $this->getCode();
if ($code && $code != $this->getPersistentData('code')) {
$access_token = $this->getAccessTokenFromCode($code);
if ($access_token) {
$this->setPersistentData('code', $code);
$this->setPersistentData('access_token', $access_token);
return $access_token;
}
// code was bogus, so everything based on it should be invalidated.
$this->clearAllPersistentData();
return false;
}
// as a fallback, just return whatever is in the persistent
// store, knowing nothing explicit (signed request, authorization
// code, etc.) was present to shadow it (or we saw a code in $_REQUEST,
// but it's the same as what's in the persistent store)
return $this->getPersistentData('access_token');
} | php | protected function getUserAccessToken() {
// first, consider a signed request if it's supplied.
// if there is a signed request, then it alone determines
// the access token.
$signed_request = $this->getSignedRequest();
if ($signed_request) {
// apps.facebook.com hands the access_token in the signed_request
if (array_key_exists('oauth_token', $signed_request)) {
$access_token = $signed_request['oauth_token'];
$this->setPersistentData('access_token', $access_token);
return $access_token;
}
// the JS SDK puts a code in with the redirect_uri of ''
if (array_key_exists('code', $signed_request)) {
$code = $signed_request['code'];
if ($code && $code == $this->getPersistentData('code')) {
// short-circuit if the code we have is the same as the one presented
return $this->getPersistentData('access_token');
}
$access_token = $this->getAccessTokenFromCode($code, '');
if ($access_token) {
$this->setPersistentData('code', $code);
$this->setPersistentData('access_token', $access_token);
return $access_token;
}
}
// signed request states there's no access token, so anything
// stored should be cleared.
$this->clearAllPersistentData();
return false; // respect the signed request's data, even
// if there's an authorization code or something else
}
$code = $this->getCode();
if ($code && $code != $this->getPersistentData('code')) {
$access_token = $this->getAccessTokenFromCode($code);
if ($access_token) {
$this->setPersistentData('code', $code);
$this->setPersistentData('access_token', $access_token);
return $access_token;
}
// code was bogus, so everything based on it should be invalidated.
$this->clearAllPersistentData();
return false;
}
// as a fallback, just return whatever is in the persistent
// store, knowing nothing explicit (signed request, authorization
// code, etc.) was present to shadow it (or we saw a code in $_REQUEST,
// but it's the same as what's in the persistent store)
return $this->getPersistentData('access_token');
} | [
"protected",
"function",
"getUserAccessToken",
"(",
")",
"{",
"// first, consider a signed request if it's supplied.",
"// if there is a signed request, then it alone determines",
"// the access token.",
"$",
"signed_request",
"=",
"$",
"this",
"->",
"getSignedRequest",
"(",
")",
... | Determines and returns the user access token, first using
the signed request if present, and then falling back on
the authorization code if present. The intent is to
return a valid user access token, or false if one is determined
to not be available.
@return string A valid user access token, or false if one
could not be determined. | [
"Determines",
"and",
"returns",
"the",
"user",
"access",
"token",
"first",
"using",
"the",
"signed",
"request",
"if",
"present",
"and",
"then",
"falling",
"back",
"on",
"the",
"authorization",
"code",
"if",
"present",
".",
"The",
"intent",
"is",
"to",
"retur... | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/3rdParty/facebook/src/base_facebook.php#L426-L481 | train |
grrr-amsterdam/garp3 | library/Garp/3rdParty/facebook/src/base_facebook.php | BaseFacebook.getSignedRequest | public function getSignedRequest() {
if (!$this->signedRequest) {
if (!empty($_REQUEST['signed_request'])) {
$this->signedRequest = $this->parseSignedRequest(
$_REQUEST['signed_request']);
} else if (!empty($_COOKIE[$this->getSignedRequestCookieName()])) {
$this->signedRequest = $this->parseSignedRequest(
$_COOKIE[$this->getSignedRequestCookieName()]);
}
}
return $this->signedRequest;
} | php | public function getSignedRequest() {
if (!$this->signedRequest) {
if (!empty($_REQUEST['signed_request'])) {
$this->signedRequest = $this->parseSignedRequest(
$_REQUEST['signed_request']);
} else if (!empty($_COOKIE[$this->getSignedRequestCookieName()])) {
$this->signedRequest = $this->parseSignedRequest(
$_COOKIE[$this->getSignedRequestCookieName()]);
}
}
return $this->signedRequest;
} | [
"public",
"function",
"getSignedRequest",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"signedRequest",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"_REQUEST",
"[",
"'signed_request'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"signedRequest",
"=",
... | Retrieve the signed request, either from a request parameter or,
if not present, from a cookie.
@return string the signed request, if available, or null otherwise. | [
"Retrieve",
"the",
"signed",
"request",
"either",
"from",
"a",
"request",
"parameter",
"or",
"if",
"not",
"present",
"from",
"a",
"cookie",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/3rdParty/facebook/src/base_facebook.php#L489-L500 | train |
grrr-amsterdam/garp3 | library/Garp/3rdParty/facebook/src/base_facebook.php | BaseFacebook.getUser | public function getUser() {
if ($this->user !== null) {
// we've already determined this and cached the value.
return $this->user;
}
return $this->user = $this->getUserFromAvailableData();
} | php | public function getUser() {
if ($this->user !== null) {
// we've already determined this and cached the value.
return $this->user;
}
return $this->user = $this->getUserFromAvailableData();
} | [
"public",
"function",
"getUser",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"user",
"!==",
"null",
")",
"{",
"// we've already determined this and cached the value.",
"return",
"$",
"this",
"->",
"user",
";",
"}",
"return",
"$",
"this",
"->",
"user",
"=",
... | Get the UID of the connected user, or 0
if the Facebook user is not connected.
@return string the UID if available. | [
"Get",
"the",
"UID",
"of",
"the",
"connected",
"user",
"or",
"0",
"if",
"the",
"Facebook",
"user",
"is",
"not",
"connected",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/3rdParty/facebook/src/base_facebook.php#L508-L515 | train |
grrr-amsterdam/garp3 | library/Garp/3rdParty/facebook/src/base_facebook.php | BaseFacebook.getUserFromAvailableData | protected function getUserFromAvailableData() {
// if a signed request is supplied, then it solely determines
// who the user is.
$signed_request = $this->getSignedRequest();
if ($signed_request) {
if (array_key_exists('user_id', $signed_request)) {
$user = $signed_request['user_id'];
if($user != $this->getPersistentData('user_id')){
$this->clearAllPersistentData();
}
$this->setPersistentData('user_id', $signed_request['user_id']);
return $user;
}
// if the signed request didn't present a user id, then invalidate
// all entries in any persistent store.
$this->clearAllPersistentData();
return 0;
}
$user = $this->getPersistentData('user_id', $default = 0);
$persisted_access_token = $this->getPersistentData('access_token');
// use access_token to fetch user id if we have a user access_token, or if
// the cached access token has changed.
$access_token = $this->getAccessToken();
if ($access_token &&
$access_token != $this->getApplicationAccessToken() &&
!($user && $persisted_access_token == $access_token)) {
$user = $this->getUserFromAccessToken();
if ($user) {
$this->setPersistentData('user_id', $user);
} else {
$this->clearAllPersistentData();
}
}
return $user;
} | php | protected function getUserFromAvailableData() {
// if a signed request is supplied, then it solely determines
// who the user is.
$signed_request = $this->getSignedRequest();
if ($signed_request) {
if (array_key_exists('user_id', $signed_request)) {
$user = $signed_request['user_id'];
if($user != $this->getPersistentData('user_id')){
$this->clearAllPersistentData();
}
$this->setPersistentData('user_id', $signed_request['user_id']);
return $user;
}
// if the signed request didn't present a user id, then invalidate
// all entries in any persistent store.
$this->clearAllPersistentData();
return 0;
}
$user = $this->getPersistentData('user_id', $default = 0);
$persisted_access_token = $this->getPersistentData('access_token');
// use access_token to fetch user id if we have a user access_token, or if
// the cached access token has changed.
$access_token = $this->getAccessToken();
if ($access_token &&
$access_token != $this->getApplicationAccessToken() &&
!($user && $persisted_access_token == $access_token)) {
$user = $this->getUserFromAccessToken();
if ($user) {
$this->setPersistentData('user_id', $user);
} else {
$this->clearAllPersistentData();
}
}
return $user;
} | [
"protected",
"function",
"getUserFromAvailableData",
"(",
")",
"{",
"// if a signed request is supplied, then it solely determines",
"// who the user is.",
"$",
"signed_request",
"=",
"$",
"this",
"->",
"getSignedRequest",
"(",
")",
";",
"if",
"(",
"$",
"signed_request",
... | Determines the connected user by first examining any signed
requests, then considering an authorization code, and then
falling back to any persistent store storing the user.
@return integer The id of the connected Facebook user,
or 0 if no such user exists. | [
"Determines",
"the",
"connected",
"user",
"by",
"first",
"examining",
"any",
"signed",
"requests",
"then",
"considering",
"an",
"authorization",
"code",
"and",
"then",
"falling",
"back",
"to",
"any",
"persistent",
"store",
"storing",
"the",
"user",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/3rdParty/facebook/src/base_facebook.php#L525-L565 | train |
grrr-amsterdam/garp3 | library/Garp/3rdParty/facebook/src/base_facebook.php | BaseFacebook.getLoginStatusUrl | public function getLoginStatusUrl($params=array()) {
return $this->getUrl(
'www',
'extern/login_status.php',
array_merge(array(
'api_key' => $this->getAppId(),
'no_session' => $this->getCurrentUrl(),
'no_user' => $this->getCurrentUrl(),
'ok_session' => $this->getCurrentUrl(),
'session_version' => 3,
), $params)
);
} | php | public function getLoginStatusUrl($params=array()) {
return $this->getUrl(
'www',
'extern/login_status.php',
array_merge(array(
'api_key' => $this->getAppId(),
'no_session' => $this->getCurrentUrl(),
'no_user' => $this->getCurrentUrl(),
'ok_session' => $this->getCurrentUrl(),
'session_version' => 3,
), $params)
);
} | [
"public",
"function",
"getLoginStatusUrl",
"(",
"$",
"params",
"=",
"array",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"getUrl",
"(",
"'www'",
",",
"'extern/login_status.php'",
",",
"array_merge",
"(",
"array",
"(",
"'api_key'",
"=>",
"$",
"this",
"... | Get a login status URL to fetch the status from Facebook.
The parameters:
- ok_session: the URL to go to if a session is found
- no_session: the URL to go to if the user is not connected
- no_user: the URL to go to if the user is not signed into facebook
@param array $params Provide custom parameters
@return string The URL for the logout flow | [
"Get",
"a",
"login",
"status",
"URL",
"to",
"fetch",
"the",
"status",
"from",
"Facebook",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/3rdParty/facebook/src/base_facebook.php#L630-L642 | train |
grrr-amsterdam/garp3 | library/Garp/3rdParty/facebook/src/base_facebook.php | BaseFacebook.getCode | protected function getCode() {
if (isset($_REQUEST['code'])) {
if ($this->state !== null &&
isset($_REQUEST['state']) &&
$this->state === $_REQUEST['state']) {
// CSRF state has done its job, so clear it
$this->state = null;
$this->clearPersistentData('state');
return $_REQUEST['code'];
} else {
self::errorLog('CSRF state token does not match one provided.');
return false;
}
}
return false;
} | php | protected function getCode() {
if (isset($_REQUEST['code'])) {
if ($this->state !== null &&
isset($_REQUEST['state']) &&
$this->state === $_REQUEST['state']) {
// CSRF state has done its job, so clear it
$this->state = null;
$this->clearPersistentData('state');
return $_REQUEST['code'];
} else {
self::errorLog('CSRF state token does not match one provided.');
return false;
}
}
return false;
} | [
"protected",
"function",
"getCode",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"_REQUEST",
"[",
"'code'",
"]",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"state",
"!==",
"null",
"&&",
"isset",
"(",
"$",
"_REQUEST",
"[",
"'state'",
"]",
")",
"... | Get the authorization code from the query parameters, if it exists,
and otherwise return false to signal no authorization code was
discoverable.
@return mixed The authorization code, or false if the authorization
code could not be determined. | [
"Get",
"the",
"authorization",
"code",
"from",
"the",
"query",
"parameters",
"if",
"it",
"exists",
"and",
"otherwise",
"return",
"false",
"to",
"signal",
"no",
"authorization",
"code",
"was",
"discoverable",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/3rdParty/facebook/src/base_facebook.php#L690-L707 | train |
grrr-amsterdam/garp3 | library/Garp/3rdParty/facebook/src/base_facebook.php | BaseFacebook.makeRequest | protected function makeRequest($url, $params, $ch=null) {
if (!$ch) {
$ch = curl_init();
}
$opts = self::$CURL_OPTS;
if ($this->getFileUploadSupport()) {
$opts[CURLOPT_POSTFIELDS] = $params;
} else {
$opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
}
$opts[CURLOPT_URL] = $url;
// disable the 'Expect: 100-continue' behaviour. This causes CURL to wait
// for 2 seconds if the server does not support this header.
if (isset($opts[CURLOPT_HTTPHEADER])) {
$existing_headers = $opts[CURLOPT_HTTPHEADER];
$existing_headers[] = 'Expect:';
$opts[CURLOPT_HTTPHEADER] = $existing_headers;
} else {
$opts[CURLOPT_HTTPHEADER] = array('Expect:');
}
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
if (curl_errno($ch) == 60) { // CURLE_SSL_CACERT
self::errorLog('Invalid or no certificate authority found, '.
'using bundled information');
curl_setopt($ch, CURLOPT_CAINFO,
dirname(__FILE__) . '/fb_ca_chain_bundle.crt');
$result = curl_exec($ch);
}
// With dual stacked DNS responses, it's possible for a server to
// have IPv6 enabled but not have IPv6 connectivity. If this is
// the case, curl will try IPv4 first and if that fails, then it will
// fall back to IPv6 and the error EHOSTUNREACH is returned by the
// operating system.
if ($result === false && empty($opts[CURLOPT_IPRESOLVE])) {
$matches = array();
$regex = '/Failed to connect to ([^:].*): Network is unreachable/';
if (preg_match($regex, curl_error($ch), $matches)) {
if (strlen(@inet_pton($matches[1])) === 16) {
self::errorLog('Invalid IPv6 configuration on server, '.
'Please disable or get native IPv6 on your server.');
self::$CURL_OPTS[CURLOPT_IPRESOLVE] = CURL_IPRESOLVE_V4;
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$result = curl_exec($ch);
}
}
}
if ($result === false) {
$e = new FacebookApiException(array(
'error_code' => curl_errno($ch),
'error' => array(
'message' => curl_error($ch),
'type' => 'CurlException',
),
));
curl_close($ch);
throw $e;
}
curl_close($ch);
return $result;
} | php | protected function makeRequest($url, $params, $ch=null) {
if (!$ch) {
$ch = curl_init();
}
$opts = self::$CURL_OPTS;
if ($this->getFileUploadSupport()) {
$opts[CURLOPT_POSTFIELDS] = $params;
} else {
$opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
}
$opts[CURLOPT_URL] = $url;
// disable the 'Expect: 100-continue' behaviour. This causes CURL to wait
// for 2 seconds if the server does not support this header.
if (isset($opts[CURLOPT_HTTPHEADER])) {
$existing_headers = $opts[CURLOPT_HTTPHEADER];
$existing_headers[] = 'Expect:';
$opts[CURLOPT_HTTPHEADER] = $existing_headers;
} else {
$opts[CURLOPT_HTTPHEADER] = array('Expect:');
}
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
if (curl_errno($ch) == 60) { // CURLE_SSL_CACERT
self::errorLog('Invalid or no certificate authority found, '.
'using bundled information');
curl_setopt($ch, CURLOPT_CAINFO,
dirname(__FILE__) . '/fb_ca_chain_bundle.crt');
$result = curl_exec($ch);
}
// With dual stacked DNS responses, it's possible for a server to
// have IPv6 enabled but not have IPv6 connectivity. If this is
// the case, curl will try IPv4 first and if that fails, then it will
// fall back to IPv6 and the error EHOSTUNREACH is returned by the
// operating system.
if ($result === false && empty($opts[CURLOPT_IPRESOLVE])) {
$matches = array();
$regex = '/Failed to connect to ([^:].*): Network is unreachable/';
if (preg_match($regex, curl_error($ch), $matches)) {
if (strlen(@inet_pton($matches[1])) === 16) {
self::errorLog('Invalid IPv6 configuration on server, '.
'Please disable or get native IPv6 on your server.');
self::$CURL_OPTS[CURLOPT_IPRESOLVE] = CURL_IPRESOLVE_V4;
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$result = curl_exec($ch);
}
}
}
if ($result === false) {
$e = new FacebookApiException(array(
'error_code' => curl_errno($ch),
'error' => array(
'message' => curl_error($ch),
'type' => 'CurlException',
),
));
curl_close($ch);
throw $e;
}
curl_close($ch);
return $result;
} | [
"protected",
"function",
"makeRequest",
"(",
"$",
"url",
",",
"$",
"params",
",",
"$",
"ch",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"ch",
")",
"{",
"$",
"ch",
"=",
"curl_init",
"(",
")",
";",
"}",
"$",
"opts",
"=",
"self",
"::",
"$",
"CU... | Makes an HTTP request. This method can be overridden by subclasses if
developers want to do fancier things or use something other than curl to
make the request.
@param string $url The URL to make the request to
@param array $params The parameters to use for the POST body
@param CurlHandler $ch Initialized curl handle
@return string The response text | [
"Makes",
"an",
"HTTP",
"request",
".",
"This",
"method",
"can",
"be",
"overridden",
"by",
"subclasses",
"if",
"developers",
"want",
"to",
"do",
"fancier",
"things",
"or",
"use",
"something",
"other",
"than",
"curl",
"to",
"make",
"the",
"request",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/3rdParty/facebook/src/base_facebook.php#L923-L989 | train |
grrr-amsterdam/garp3 | library/Garp/3rdParty/facebook/src/base_facebook.php | BaseFacebook.makeSignedRequest | protected function makeSignedRequest($data) {
if (!is_array($data)) {
throw new InvalidArgumentException(
'makeSignedRequest expects an array. Got: ' . print_r($data, true));
}
$data['algorithm'] = self::SIGNED_REQUEST_ALGORITHM;
$data['issued_at'] = time();
$json = json_encode($data);
$b64 = self::base64UrlEncode($json);
$raw_sig = hash_hmac('sha256', $b64, $this->getAppSecret(), $raw = true);
$sig = self::base64UrlEncode($raw_sig);
return $sig.'.'.$b64;
} | php | protected function makeSignedRequest($data) {
if (!is_array($data)) {
throw new InvalidArgumentException(
'makeSignedRequest expects an array. Got: ' . print_r($data, true));
}
$data['algorithm'] = self::SIGNED_REQUEST_ALGORITHM;
$data['issued_at'] = time();
$json = json_encode($data);
$b64 = self::base64UrlEncode($json);
$raw_sig = hash_hmac('sha256', $b64, $this->getAppSecret(), $raw = true);
$sig = self::base64UrlEncode($raw_sig);
return $sig.'.'.$b64;
} | [
"protected",
"function",
"makeSignedRequest",
"(",
"$",
"data",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"data",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'makeSignedRequest expects an array. Got: '",
".",
"print_r",
"(",
"$",
"data... | Makes a signed_request blob using the given data.
@param array The data array.
@return string The signed request. | [
"Makes",
"a",
"signed_request",
"blob",
"using",
"the",
"given",
"data",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/3rdParty/facebook/src/base_facebook.php#L1027-L1039 | train |
grrr-amsterdam/garp3 | library/Garp/3rdParty/facebook/src/base_facebook.php | BaseFacebook.getApiUrl | protected function getApiUrl($method) {
static $READ_ONLY_CALLS =
array('admin.getallocation' => 1,
'admin.getappproperties' => 1,
'admin.getbannedusers' => 1,
'admin.getlivestreamvialink' => 1,
'admin.getmetrics' => 1,
'admin.getrestrictioninfo' => 1,
'application.getpublicinfo' => 1,
'auth.getapppublickey' => 1,
'auth.getsession' => 1,
'auth.getsignedpublicsessiondata' => 1,
'comments.get' => 1,
'connect.getunconnectedfriendscount' => 1,
'dashboard.getactivity' => 1,
'dashboard.getcount' => 1,
'dashboard.getglobalnews' => 1,
'dashboard.getnews' => 1,
'dashboard.multigetcount' => 1,
'dashboard.multigetnews' => 1,
'data.getcookies' => 1,
'events.get' => 1,
'events.getmembers' => 1,
'fbml.getcustomtags' => 1,
'feed.getappfriendstories' => 1,
'feed.getregisteredtemplatebundlebyid' => 1,
'feed.getregisteredtemplatebundles' => 1,
'fql.multiquery' => 1,
'fql.query' => 1,
'friends.arefriends' => 1,
'friends.get' => 1,
'friends.getappusers' => 1,
'friends.getlists' => 1,
'friends.getmutualfriends' => 1,
'gifts.get' => 1,
'groups.get' => 1,
'groups.getmembers' => 1,
'intl.gettranslations' => 1,
'links.get' => 1,
'notes.get' => 1,
'notifications.get' => 1,
'pages.getinfo' => 1,
'pages.isadmin' => 1,
'pages.isappadded' => 1,
'pages.isfan' => 1,
'permissions.checkavailableapiaccess' => 1,
'permissions.checkgrantedapiaccess' => 1,
'photos.get' => 1,
'photos.getalbums' => 1,
'photos.gettags' => 1,
'profile.getinfo' => 1,
'profile.getinfooptions' => 1,
'stream.get' => 1,
'stream.getcomments' => 1,
'stream.getfilters' => 1,
'users.getinfo' => 1,
'users.getloggedinuser' => 1,
'users.getstandardinfo' => 1,
'users.hasapppermission' => 1,
'users.isappuser' => 1,
'users.isverified' => 1,
'video.getuploadlimits' => 1);
$name = 'api';
if (isset($READ_ONLY_CALLS[strtolower($method)])) {
$name = 'api_read';
} else if (strtolower($method) == 'video.upload') {
$name = 'api_video';
}
return self::getUrl($name, 'restserver.php');
} | php | protected function getApiUrl($method) {
static $READ_ONLY_CALLS =
array('admin.getallocation' => 1,
'admin.getappproperties' => 1,
'admin.getbannedusers' => 1,
'admin.getlivestreamvialink' => 1,
'admin.getmetrics' => 1,
'admin.getrestrictioninfo' => 1,
'application.getpublicinfo' => 1,
'auth.getapppublickey' => 1,
'auth.getsession' => 1,
'auth.getsignedpublicsessiondata' => 1,
'comments.get' => 1,
'connect.getunconnectedfriendscount' => 1,
'dashboard.getactivity' => 1,
'dashboard.getcount' => 1,
'dashboard.getglobalnews' => 1,
'dashboard.getnews' => 1,
'dashboard.multigetcount' => 1,
'dashboard.multigetnews' => 1,
'data.getcookies' => 1,
'events.get' => 1,
'events.getmembers' => 1,
'fbml.getcustomtags' => 1,
'feed.getappfriendstories' => 1,
'feed.getregisteredtemplatebundlebyid' => 1,
'feed.getregisteredtemplatebundles' => 1,
'fql.multiquery' => 1,
'fql.query' => 1,
'friends.arefriends' => 1,
'friends.get' => 1,
'friends.getappusers' => 1,
'friends.getlists' => 1,
'friends.getmutualfriends' => 1,
'gifts.get' => 1,
'groups.get' => 1,
'groups.getmembers' => 1,
'intl.gettranslations' => 1,
'links.get' => 1,
'notes.get' => 1,
'notifications.get' => 1,
'pages.getinfo' => 1,
'pages.isadmin' => 1,
'pages.isappadded' => 1,
'pages.isfan' => 1,
'permissions.checkavailableapiaccess' => 1,
'permissions.checkgrantedapiaccess' => 1,
'photos.get' => 1,
'photos.getalbums' => 1,
'photos.gettags' => 1,
'profile.getinfo' => 1,
'profile.getinfooptions' => 1,
'stream.get' => 1,
'stream.getcomments' => 1,
'stream.getfilters' => 1,
'users.getinfo' => 1,
'users.getloggedinuser' => 1,
'users.getstandardinfo' => 1,
'users.hasapppermission' => 1,
'users.isappuser' => 1,
'users.isverified' => 1,
'video.getuploadlimits' => 1);
$name = 'api';
if (isset($READ_ONLY_CALLS[strtolower($method)])) {
$name = 'api_read';
} else if (strtolower($method) == 'video.upload') {
$name = 'api_video';
}
return self::getUrl($name, 'restserver.php');
} | [
"protected",
"function",
"getApiUrl",
"(",
"$",
"method",
")",
"{",
"static",
"$",
"READ_ONLY_CALLS",
"=",
"array",
"(",
"'admin.getallocation'",
"=>",
"1",
",",
"'admin.getappproperties'",
"=>",
"1",
",",
"'admin.getbannedusers'",
"=>",
"1",
",",
"'admin.getlives... | Build the URL for api given parameters.
@param $method String the method name.
@return string The URL for the given parameters | [
"Build",
"the",
"URL",
"for",
"api",
"given",
"parameters",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/3rdParty/facebook/src/base_facebook.php#L1047-L1116 | train |
grrr-amsterdam/garp3 | library/Garp/3rdParty/facebook/src/base_facebook.php | BaseFacebook.getUrl | protected function getUrl($name, $path='', $params=array()) {
$url = self::$DOMAIN_MAP[$name];
if ($path) {
if ($path[0] === '/') {
$path = substr($path, 1);
}
$url .= $path;
}
if ($params) {
$url .= '?' . http_build_query($params, null, '&');
}
return $url;
} | php | protected function getUrl($name, $path='', $params=array()) {
$url = self::$DOMAIN_MAP[$name];
if ($path) {
if ($path[0] === '/') {
$path = substr($path, 1);
}
$url .= $path;
}
if ($params) {
$url .= '?' . http_build_query($params, null, '&');
}
return $url;
} | [
"protected",
"function",
"getUrl",
"(",
"$",
"name",
",",
"$",
"path",
"=",
"''",
",",
"$",
"params",
"=",
"array",
"(",
")",
")",
"{",
"$",
"url",
"=",
"self",
"::",
"$",
"DOMAIN_MAP",
"[",
"$",
"name",
"]",
";",
"if",
"(",
"$",
"path",
")",
... | Build the URL for given domain alias, path and parameters.
@param $name string The name of the domain
@param $path string Optional path (without a leading slash)
@param $params array Optional query parameters
@return string The URL for the given parameters | [
"Build",
"the",
"URL",
"for",
"given",
"domain",
"alias",
"path",
"and",
"parameters",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/3rdParty/facebook/src/base_facebook.php#L1127-L1140 | train |
grrr-amsterdam/garp3 | library/Garp/3rdParty/facebook/src/base_facebook.php | BaseFacebook.getBaseDomain | protected function getBaseDomain() {
// The base domain is stored in the metadata cookie if not we fallback
// to the current hostname
$metadata = $this->getMetadataCookie();
if (array_key_exists('base_domain', $metadata) &&
!empty($metadata['base_domain'])) {
return trim($metadata['base_domain'], '.');
}
return $this->getHttpHost();
} | php | protected function getBaseDomain() {
// The base domain is stored in the metadata cookie if not we fallback
// to the current hostname
$metadata = $this->getMetadataCookie();
if (array_key_exists('base_domain', $metadata) &&
!empty($metadata['base_domain'])) {
return trim($metadata['base_domain'], '.');
}
return $this->getHttpHost();
} | [
"protected",
"function",
"getBaseDomain",
"(",
")",
"{",
"// The base domain is stored in the metadata cookie if not we fallback",
"// to the current hostname",
"$",
"metadata",
"=",
"$",
"this",
"->",
"getMetadataCookie",
"(",
")",
";",
"if",
"(",
"array_key_exists",
"(",
... | Get the base domain used for the cookie. | [
"Get",
"the",
"base",
"domain",
"used",
"for",
"the",
"cookie",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/3rdParty/facebook/src/base_facebook.php#L1172-L1181 | train |
grrr-amsterdam/garp3 | library/Garp/3rdParty/facebook/src/base_facebook.php | BaseFacebook.throwAPIException | protected function throwAPIException($result) {
$e = new FacebookApiException($result);
switch ($e->getType()) {
// OAuth 2.0 Draft 00 style
case 'OAuthException':
// OAuth 2.0 Draft 10 style
case 'invalid_token':
// REST server errors are just Exceptions
case 'Exception':
$message = $e->getMessage();
if ((strpos($message, 'Error validating access token') !== false) ||
(strpos($message, 'Invalid OAuth access token') !== false) ||
(strpos($message, 'An active access token must be used') !== false)
) {
$this->destroySession();
}
break;
}
throw $e;
} | php | protected function throwAPIException($result) {
$e = new FacebookApiException($result);
switch ($e->getType()) {
// OAuth 2.0 Draft 00 style
case 'OAuthException':
// OAuth 2.0 Draft 10 style
case 'invalid_token':
// REST server errors are just Exceptions
case 'Exception':
$message = $e->getMessage();
if ((strpos($message, 'Error validating access token') !== false) ||
(strpos($message, 'Invalid OAuth access token') !== false) ||
(strpos($message, 'An active access token must be used') !== false)
) {
$this->destroySession();
}
break;
}
throw $e;
} | [
"protected",
"function",
"throwAPIException",
"(",
"$",
"result",
")",
"{",
"$",
"e",
"=",
"new",
"FacebookApiException",
"(",
"$",
"result",
")",
";",
"switch",
"(",
"$",
"e",
"->",
"getType",
"(",
")",
")",
"{",
"// OAuth 2.0 Draft 00 style",
"case",
"'O... | Analyzes the supplied result to see if it was thrown
because the access token is no longer valid. If that is
the case, then we destroy the session.
@param $result array A record storing the error message returned
by a failed API call. | [
"Analyzes",
"the",
"supplied",
"result",
"to",
"see",
"if",
"it",
"was",
"thrown",
"because",
"the",
"access",
"token",
"is",
"no",
"longer",
"valid",
".",
"If",
"that",
"is",
"the",
"case",
"then",
"we",
"destroy",
"the",
"session",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/3rdParty/facebook/src/base_facebook.php#L1253-L1273 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.