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 | library/Garp/3rdParty/facebook/src/base_facebook.php | BaseFacebook.destroySession | public function destroySession() {
$this->accessToken = null;
$this->signedRequest = null;
$this->user = null;
$this->clearAllPersistentData();
// Javascript sets a cookie that will be used in getSignedRequest that we
// need to clear if we can
$cookie_name = $this->getSignedRequestCookieName();
if (array_key_exists($cookie_name, $_COOKIE)) {
unset($_COOKIE[$cookie_name]);
if (!headers_sent()) {
$base_domain = $this->getBaseDomain();
setcookie($cookie_name, '', 1, '/', '.'.$base_domain);
} else {
// @codeCoverageIgnoreStart
self::errorLog(
'There exists a cookie that we wanted to clear that we couldn\'t '.
'clear because headers was already sent. Make sure to do the first '.
'API call before outputing anything.'
);
// @codeCoverageIgnoreEnd
}
}
} | php | public function destroySession() {
$this->accessToken = null;
$this->signedRequest = null;
$this->user = null;
$this->clearAllPersistentData();
// Javascript sets a cookie that will be used in getSignedRequest that we
// need to clear if we can
$cookie_name = $this->getSignedRequestCookieName();
if (array_key_exists($cookie_name, $_COOKIE)) {
unset($_COOKIE[$cookie_name]);
if (!headers_sent()) {
$base_domain = $this->getBaseDomain();
setcookie($cookie_name, '', 1, '/', '.'.$base_domain);
} else {
// @codeCoverageIgnoreStart
self::errorLog(
'There exists a cookie that we wanted to clear that we couldn\'t '.
'clear because headers was already sent. Make sure to do the first '.
'API call before outputing anything.'
);
// @codeCoverageIgnoreEnd
}
}
} | [
"public",
"function",
"destroySession",
"(",
")",
"{",
"$",
"this",
"->",
"accessToken",
"=",
"null",
";",
"$",
"this",
"->",
"signedRequest",
"=",
"null",
";",
"$",
"this",
"->",
"user",
"=",
"null",
";",
"$",
"this",
"->",
"clearAllPersistentData",
"("... | Destroy the current session | [
"Destroy",
"the",
"current",
"session"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/3rdParty/facebook/src/base_facebook.php#L1324-L1348 | train |
grrr-amsterdam/garp3 | library/Garp/3rdParty/facebook/src/base_facebook.php | BaseFacebook.getMetadataCookie | protected function getMetadataCookie() {
$cookie_name = $this->getMetadataCookieName();
if (!array_key_exists($cookie_name, $_COOKIE)) {
return array();
}
// The cookie value can be wrapped in "-characters so remove them
$cookie_value = trim($_COOKIE[$cookie_name], '"');
if (empty($cookie_value)) {
return array();
}
$parts = explode('&', $cookie_value);
$metadata = array();
foreach ($parts as $part) {
$pair = explode('=', $part, 2);
if (!empty($pair[0])) {
$metadata[urldecode($pair[0])] =
(count($pair) > 1) ? urldecode($pair[1]) : '';
}
}
return $metadata;
} | php | protected function getMetadataCookie() {
$cookie_name = $this->getMetadataCookieName();
if (!array_key_exists($cookie_name, $_COOKIE)) {
return array();
}
// The cookie value can be wrapped in "-characters so remove them
$cookie_value = trim($_COOKIE[$cookie_name], '"');
if (empty($cookie_value)) {
return array();
}
$parts = explode('&', $cookie_value);
$metadata = array();
foreach ($parts as $part) {
$pair = explode('=', $part, 2);
if (!empty($pair[0])) {
$metadata[urldecode($pair[0])] =
(count($pair) > 1) ? urldecode($pair[1]) : '';
}
}
return $metadata;
} | [
"protected",
"function",
"getMetadataCookie",
"(",
")",
"{",
"$",
"cookie_name",
"=",
"$",
"this",
"->",
"getMetadataCookieName",
"(",
")",
";",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"cookie_name",
",",
"$",
"_COOKIE",
")",
")",
"{",
"return",
"arr... | Parses the metadata cookie that our Javascript API set
@return an array mapping key to value | [
"Parses",
"the",
"metadata",
"cookie",
"that",
"our",
"Javascript",
"API",
"set"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/3rdParty/facebook/src/base_facebook.php#L1355-L1379 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/ImageScalable.php | Garp_Model_Behavior_ImageScalable.scale | public function scale($filename, $id) {
$templates = instance(new Garp_Image_Scaler)->getTemplateNames();
// Divide templates into sync ones and async ones
$syncTemplates = array_intersect($templates, $this->_synchronouslyScaledTemplates);
$asyncTemplates = array_diff($templates, $this->_synchronouslyScaledTemplates);
foreach ($syncTemplates as $template) {
$this->_scaleSync($filename, $id, $template);
}
$this->_scaleAsync($filename, $id);
} | php | public function scale($filename, $id) {
$templates = instance(new Garp_Image_Scaler)->getTemplateNames();
// Divide templates into sync ones and async ones
$syncTemplates = array_intersect($templates, $this->_synchronouslyScaledTemplates);
$asyncTemplates = array_diff($templates, $this->_synchronouslyScaledTemplates);
foreach ($syncTemplates as $template) {
$this->_scaleSync($filename, $id, $template);
}
$this->_scaleAsync($filename, $id);
} | [
"public",
"function",
"scale",
"(",
"$",
"filename",
",",
"$",
"id",
")",
"{",
"$",
"templates",
"=",
"instance",
"(",
"new",
"Garp_Image_Scaler",
")",
"->",
"getTemplateNames",
"(",
")",
";",
"// Divide templates into sync ones and async ones",
"$",
"syncTemplate... | Perform the scaling | [
"Perform",
"the",
"scaling"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/ImageScalable.php#L65-L77 | train |
grrr-amsterdam/garp3 | library/Garp/Browsebox/Filter/Related.php | Garp_Browsebox_Filter_Related.fetchMaxChunks | public function fetchMaxChunks(Zend_Db_Select $select, Garp_Browsebox $browsebox) {
if (!empty($this->_params)) {
$model = $browsebox->getModel();
$filterModel = new $this->_config['model']();
$bindingModel = new $this->_config['bindingOptions']['bindingModel']();
$rule1 = !empty($this->_config['bindingOptions']['rule']) ? $this->_config['bindingOptions']['rule'] : null;
$rule2 = !empty($this->_config['bindingOptions']['rule2']) ? $this->_config['bindingOptions']['rule2'] : null;
$modelReference = $bindingModel->getReference(get_class($model), $rule1);
$filterModelReference = $bindingModel->getReference($this->_config['model'], $rule2);
$joinConditions = array();
foreach ($modelReference['refColumns'] as $i => $refColumn) {
$column = $modelReference['columns'][$i];
$joinCondition = '';
$joinCondition .= $bindingModel->getAdapter()->quoteIdentifier($refColumn);
$joinCondition .= ' = ';
$joinCondition .= $bindingModel->getAdapter()->quoteIdentifier($column);
$joinConditions[] = $joinCondition;
}
$joinConditions = implode(' AND ', $joinConditions);
$countSelect = $model->select()
->from($model->getName(), array('c' => 'COUNT(*)'))
->join($bindingModel->getName(), $joinConditions, array());
if ($where = $browsebox->getOption('conditions')) {
$countSelect->where($where);
}
foreach ($filterModelReference['columns'] as $i => $foreignKey) {
$countSelect->where($bindingModel->getAdapter()->quoteIdentifier($foreignKey).' = ?', $this->_params[$i]);
}
$result = $model->fetchRow($countSelect);
return $result->c;
} else {
throw new Garp_Browsebox_Filter_Exception_NotApplicable();
}
} | php | public function fetchMaxChunks(Zend_Db_Select $select, Garp_Browsebox $browsebox) {
if (!empty($this->_params)) {
$model = $browsebox->getModel();
$filterModel = new $this->_config['model']();
$bindingModel = new $this->_config['bindingOptions']['bindingModel']();
$rule1 = !empty($this->_config['bindingOptions']['rule']) ? $this->_config['bindingOptions']['rule'] : null;
$rule2 = !empty($this->_config['bindingOptions']['rule2']) ? $this->_config['bindingOptions']['rule2'] : null;
$modelReference = $bindingModel->getReference(get_class($model), $rule1);
$filterModelReference = $bindingModel->getReference($this->_config['model'], $rule2);
$joinConditions = array();
foreach ($modelReference['refColumns'] as $i => $refColumn) {
$column = $modelReference['columns'][$i];
$joinCondition = '';
$joinCondition .= $bindingModel->getAdapter()->quoteIdentifier($refColumn);
$joinCondition .= ' = ';
$joinCondition .= $bindingModel->getAdapter()->quoteIdentifier($column);
$joinConditions[] = $joinCondition;
}
$joinConditions = implode(' AND ', $joinConditions);
$countSelect = $model->select()
->from($model->getName(), array('c' => 'COUNT(*)'))
->join($bindingModel->getName(), $joinConditions, array());
if ($where = $browsebox->getOption('conditions')) {
$countSelect->where($where);
}
foreach ($filterModelReference['columns'] as $i => $foreignKey) {
$countSelect->where($bindingModel->getAdapter()->quoteIdentifier($foreignKey).' = ?', $this->_params[$i]);
}
$result = $model->fetchRow($countSelect);
return $result->c;
} else {
throw new Garp_Browsebox_Filter_Exception_NotApplicable();
}
} | [
"public",
"function",
"fetchMaxChunks",
"(",
"Zend_Db_Select",
"$",
"select",
",",
"Garp_Browsebox",
"$",
"browsebox",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"_params",
")",
")",
"{",
"$",
"model",
"=",
"$",
"browsebox",
"->",
"getMod... | Fetch max amount of chunks.
@param Zend_Db_Select $select The specific select for this instance.
@param Garp_Browsebox $browsebox The browsebox, made available to fetch metadata from.
@return Void | [
"Fetch",
"max",
"amount",
"of",
"chunks",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Browsebox/Filter/Related.php#L89-L125 | train |
grrr-amsterdam/garp3 | library/Garp/Cli/Command/Image.php | Garp_Cli_Command_Image.generateScaled | public function generateScaled($args) {
$overwrite = array_key_exists('overwrite', $args) || array_key_exists('force', $args);
if (array_key_exists('template', $args)
&& !empty($args['template'])
) {
return $this->_generateScaledImagesForTemplate($args['template'], $overwrite);
} elseif (array_key_exists('filename', $args)
&& !empty($args['filename'])
) {
return $this->_generateScaledImagesForFilename($args['filename'], $overwrite);
} elseif (array_key_exists('id', $args)
&& !empty($args['id'])
) {
return $this->_generateScaledImagesForId($args['id'], $overwrite);
}
return $this->_generateAllScaledImages($overwrite);
} | php | public function generateScaled($args) {
$overwrite = array_key_exists('overwrite', $args) || array_key_exists('force', $args);
if (array_key_exists('template', $args)
&& !empty($args['template'])
) {
return $this->_generateScaledImagesForTemplate($args['template'], $overwrite);
} elseif (array_key_exists('filename', $args)
&& !empty($args['filename'])
) {
return $this->_generateScaledImagesForFilename($args['filename'], $overwrite);
} elseif (array_key_exists('id', $args)
&& !empty($args['id'])
) {
return $this->_generateScaledImagesForId($args['id'], $overwrite);
}
return $this->_generateAllScaledImages($overwrite);
} | [
"public",
"function",
"generateScaled",
"(",
"$",
"args",
")",
"{",
"$",
"overwrite",
"=",
"array_key_exists",
"(",
"'overwrite'",
",",
"$",
"args",
")",
"||",
"array_key_exists",
"(",
"'force'",
",",
"$",
"args",
")",
";",
"if",
"(",
"array_key_exists",
"... | Generate scaled versions of uploaded images
@param array $args
@return bool | [
"Generate",
"scaled",
"versions",
"of",
"uploaded",
"images"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cli/Command/Image.php#L15-L31 | train |
grrr-amsterdam/garp3 | library/Garp/Cli/Command/Image.php | Garp_Cli_Command_Image._generateAllScaledImages | protected function _generateAllScaledImages($overwrite = false) {
$imageScaler = new Garp_Image_Scaler();
$templates = $imageScaler->getTemplateNames();
$success = 0;
foreach ($templates as $t) {
$success += (int)$this->_generateScaledImagesForTemplate($t, $overwrite);
}
return $success == count($templates);
} | php | protected function _generateAllScaledImages($overwrite = false) {
$imageScaler = new Garp_Image_Scaler();
$templates = $imageScaler->getTemplateNames();
$success = 0;
foreach ($templates as $t) {
$success += (int)$this->_generateScaledImagesForTemplate($t, $overwrite);
}
return $success == count($templates);
} | [
"protected",
"function",
"_generateAllScaledImages",
"(",
"$",
"overwrite",
"=",
"false",
")",
"{",
"$",
"imageScaler",
"=",
"new",
"Garp_Image_Scaler",
"(",
")",
";",
"$",
"templates",
"=",
"$",
"imageScaler",
"->",
"getTemplateNames",
"(",
")",
";",
"$",
"... | Generate scaled versions of all images in all templates.
@param bool $overwrite
@return bool | [
"Generate",
"scaled",
"versions",
"of",
"all",
"images",
"in",
"all",
"templates",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cli/Command/Image.php#L89-L99 | train |
grrr-amsterdam/garp3 | library/Garp/Cli/Command/Image.php | Garp_Cli_Command_Image._generateScaledImagesForTemplate | protected function _generateScaledImagesForTemplate($template, $overwrite = false) {
Garp_Cli::lineOut('Generating scaled images for template "' . $template . '".');
$imageModel = new Model_Image();
$records = $imageModel->fetchAll();
$file = new Garp_Image_File(Garp_File::FILE_VARIANT_UPLOAD);
$scaler = new Garp_Image_Scaler();
$success = 0;
foreach ($records as $record) {
$success += (int)$this->_scaleDatabaseImage(
$record, $file, $scaler, $template, $overwrite
);
}
Garp_Cli::lineOut('Done scaling images for template "' . $template . '".');
return $success == count($records);
} | php | protected function _generateScaledImagesForTemplate($template, $overwrite = false) {
Garp_Cli::lineOut('Generating scaled images for template "' . $template . '".');
$imageModel = new Model_Image();
$records = $imageModel->fetchAll();
$file = new Garp_Image_File(Garp_File::FILE_VARIANT_UPLOAD);
$scaler = new Garp_Image_Scaler();
$success = 0;
foreach ($records as $record) {
$success += (int)$this->_scaleDatabaseImage(
$record, $file, $scaler, $template, $overwrite
);
}
Garp_Cli::lineOut('Done scaling images for template "' . $template . '".');
return $success == count($records);
} | [
"protected",
"function",
"_generateScaledImagesForTemplate",
"(",
"$",
"template",
",",
"$",
"overwrite",
"=",
"false",
")",
"{",
"Garp_Cli",
"::",
"lineOut",
"(",
"'Generating scaled images for template \"'",
".",
"$",
"template",
".",
"'\".'",
")",
";",
"$",
"im... | Generate scaled versions of all source files, along given template.
@param string $template Template name, as it appears in configuration.
@param bool $overwrite
@return bool | [
"Generate",
"scaled",
"versions",
"of",
"all",
"source",
"files",
"along",
"given",
"template",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cli/Command/Image.php#L164-L181 | train |
grrr-amsterdam/garp3 | library/Garp/Service/HTMLPurifier/Filter/MyEmbed.php | Garp_Service_HTMLPurifier_Filter_MyEmbed.preFilter | public function preFilter($html, $config, $context) {
$regexp = '/<(\/?)embed( ?)([^>]+)?>/i';
$replace = '~$1embed$2$3~';
return preg_replace($regexp, $replace, $html);
} | php | public function preFilter($html, $config, $context) {
$regexp = '/<(\/?)embed( ?)([^>]+)?>/i';
$replace = '~$1embed$2$3~';
return preg_replace($regexp, $replace, $html);
} | [
"public",
"function",
"preFilter",
"(",
"$",
"html",
",",
"$",
"config",
",",
"$",
"context",
")",
"{",
"$",
"regexp",
"=",
"'/<(\\/?)embed( ?)([^>]+)?>/i'",
";",
"$",
"replace",
"=",
"'~$1embed$2$3~'",
";",
"return",
"preg_replace",
"(",
"$",
"regexp",
",",... | Pre-processor function, handles HTML before HTML Purifier
@param string $html
@param object $config
@param object $context
@return string | [
"Pre",
"-",
"processor",
"function",
"handles",
"HTML",
"before",
"HTML",
"Purifier"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Service/HTMLPurifier/Filter/MyEmbed.php#L25-L29 | train |
grrr-amsterdam/garp3 | library/Garp/Service/HTMLPurifier/Filter/MyEmbed.php | Garp_Service_HTMLPurifier_Filter_MyEmbed.postFilter | public function postFilter($html, $config, $context) {
$regexp = '/~(\/?)embed( ?)([^~]+)?~/i';
$replace = '<$1embed$2$3>';
return preg_replace($regexp, $replace, $html);
} | php | public function postFilter($html, $config, $context) {
$regexp = '/~(\/?)embed( ?)([^~]+)?~/i';
$replace = '<$1embed$2$3>';
return preg_replace($regexp, $replace, $html);
} | [
"public",
"function",
"postFilter",
"(",
"$",
"html",
",",
"$",
"config",
",",
"$",
"context",
")",
"{",
"$",
"regexp",
"=",
"'/~(\\/?)embed( ?)([^~]+)?~/i'",
";",
"$",
"replace",
"=",
"'<$1embed$2$3>'",
";",
"return",
"preg_replace",
"(",
"$",
"regexp",
","... | Post-processor function, handles HTML after HTML Purifier
@param string $html
@param object $config
@param object $context
@return string | [
"Post",
"-",
"processor",
"function",
"handles",
"HTML",
"after",
"HTML",
"Purifier"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Service/HTMLPurifier/Filter/MyEmbed.php#L39-L43 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/Sluggable.php | Garp_Model_Behavior_Sluggable._addSlugFromMultiple | protected function _addSlugFromMultiple(Garp_Model_Db $model, array &$targetData, array $referenceData) {
$baseFields = $this->_config['baseField'];
$slugField = $this->_config['slugField'][0];
$baseData = array();
if (!empty($targetData[$slugField])) {
return;
}
$lang = null;
if (isset($referenceData[Garp_Model_Behavior_Translatable::LANG_COLUMN])) {
$lang = $referenceData[Garp_Model_Behavior_Translatable::LANG_COLUMN];
}
foreach ((array)$baseFields as $baseColumn) {
$baseData[] = $this->_getBaseString($baseColumn, $referenceData);
}
$baseData = implode(' ', $baseData);
$targetData[$slugField] = $this->generateUniqueSlug($baseData, $model, $slugField, $lang);
} | php | protected function _addSlugFromMultiple(Garp_Model_Db $model, array &$targetData, array $referenceData) {
$baseFields = $this->_config['baseField'];
$slugField = $this->_config['slugField'][0];
$baseData = array();
if (!empty($targetData[$slugField])) {
return;
}
$lang = null;
if (isset($referenceData[Garp_Model_Behavior_Translatable::LANG_COLUMN])) {
$lang = $referenceData[Garp_Model_Behavior_Translatable::LANG_COLUMN];
}
foreach ((array)$baseFields as $baseColumn) {
$baseData[] = $this->_getBaseString($baseColumn, $referenceData);
}
$baseData = implode(' ', $baseData);
$targetData[$slugField] = $this->generateUniqueSlug($baseData, $model, $slugField, $lang);
} | [
"protected",
"function",
"_addSlugFromMultiple",
"(",
"Garp_Model_Db",
"$",
"model",
",",
"array",
"&",
"$",
"targetData",
",",
"array",
"$",
"referenceData",
")",
"{",
"$",
"baseFields",
"=",
"$",
"this",
"->",
"_config",
"[",
"'baseField'",
"]",
";",
"$",
... | Add single slug from multiple sources
@param Garp_Model_Db $model
@param Array $data Data that will be inserted: should receive the slug
@param Array $referenceData Data to base the slug on
@return Void | [
"Add",
"single",
"slug",
"from",
"multiple",
"sources"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/Sluggable.php#L152-L168 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/Sluggable.php | Garp_Model_Behavior_Sluggable._getBaseString | protected function _getBaseString($baseField, $data) {
$type = $baseField['type'];
$method = '_getBaseStringFrom' . ucfirst($type);
return $this->{$method}($data, $baseField);
} | php | protected function _getBaseString($baseField, $data) {
$type = $baseField['type'];
$method = '_getBaseStringFrom' . ucfirst($type);
return $this->{$method}($data, $baseField);
} | [
"protected",
"function",
"_getBaseString",
"(",
"$",
"baseField",
",",
"$",
"data",
")",
"{",
"$",
"type",
"=",
"$",
"baseField",
"[",
"'type'",
"]",
";",
"$",
"method",
"=",
"'_getBaseStringFrom'",
".",
"ucfirst",
"(",
"$",
"type",
")",
";",
"return",
... | Construct base string on which the slug will be based.
@param Array $baseFields Basefield configuration (per field)
@param Array $data Submitted data
@return String | [
"Construct",
"base",
"string",
"on",
"which",
"the",
"slug",
"will",
"be",
"based",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/Sluggable.php#L200-L204 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/Sluggable.php | Garp_Model_Behavior_Sluggable._getBaseStringFromText | protected function _getBaseStringFromText(array $data, array $baseField) {
$col = $baseField['column'];
if (!array_key_exists($col, $data)) {
return '';
}
return $data[$col];
} | php | protected function _getBaseStringFromText(array $data, array $baseField) {
$col = $baseField['column'];
if (!array_key_exists($col, $data)) {
return '';
}
return $data[$col];
} | [
"protected",
"function",
"_getBaseStringFromText",
"(",
"array",
"$",
"data",
",",
"array",
"$",
"baseField",
")",
"{",
"$",
"col",
"=",
"$",
"baseField",
"[",
"'column'",
"]",
";",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"col",
",",
"$",
"data",
... | Get base string from text column.
@param Array $data
@param Array $baseField Base field config
@return String | [
"Get",
"base",
"string",
"from",
"text",
"column",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/Sluggable.php#L212-L218 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/Sluggable.php | Garp_Model_Behavior_Sluggable._getBaseStringFromDate | protected function _getBaseStringFromDate(array $data, array $baseField) {
$col = $baseField['column'];
$format = $baseField['format'] ?: 'd-m-Y';
if (!array_key_exists($col, $data)) {
return '';
}
return date($format, strtotime($data[$col]));
} | php | protected function _getBaseStringFromDate(array $data, array $baseField) {
$col = $baseField['column'];
$format = $baseField['format'] ?: 'd-m-Y';
if (!array_key_exists($col, $data)) {
return '';
}
return date($format, strtotime($data[$col]));
} | [
"protected",
"function",
"_getBaseStringFromDate",
"(",
"array",
"$",
"data",
",",
"array",
"$",
"baseField",
")",
"{",
"$",
"col",
"=",
"$",
"baseField",
"[",
"'column'",
"]",
";",
"$",
"format",
"=",
"$",
"baseField",
"[",
"'format'",
"]",
"?",
":",
... | Get base string from date column.
@param Array $data
@param Array $baseField Base field config
@return String | [
"Get",
"base",
"string",
"from",
"date",
"column",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/Sluggable.php#L226-L233 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/Sluggable.php | Garp_Model_Behavior_Sluggable.generateUniqueSlug | public function generateUniqueSlug($base, $model, $slugField, $lang = null) {
$slug = $this->generateSlug($base);
$select = $model->getAdapter()->select()
->from($model->getName(), 'COUNT(*)')
;
$this->_setWhereClause($select, $slugField, $slug, $model, $lang);
$n = 1;
while ($this->_rowsExist($select)) {
$this->_incrementSlug($slug, ++$n, $base);
$this->_setWhereClause($select, $slugField, $slug, $model, $lang);
}
return $slug;
} | php | public function generateUniqueSlug($base, $model, $slugField, $lang = null) {
$slug = $this->generateSlug($base);
$select = $model->getAdapter()->select()
->from($model->getName(), 'COUNT(*)')
;
$this->_setWhereClause($select, $slugField, $slug, $model, $lang);
$n = 1;
while ($this->_rowsExist($select)) {
$this->_incrementSlug($slug, ++$n, $base);
$this->_setWhereClause($select, $slugField, $slug, $model, $lang);
}
return $slug;
} | [
"public",
"function",
"generateUniqueSlug",
"(",
"$",
"base",
",",
"$",
"model",
",",
"$",
"slugField",
",",
"$",
"lang",
"=",
"null",
")",
"{",
"$",
"slug",
"=",
"$",
"this",
"->",
"generateSlug",
"(",
"$",
"base",
")",
";",
"$",
"select",
"=",
"$... | Generate a slug from a base string that is unique in the database
@param String $base
@param Model $model Model object of this record
@param String $slugField Name of the slug column in the database
@param String $lang Optional language. Used with internationalized models
@return String $slug The generated unique slug | [
"Generate",
"a",
"slug",
"from",
"a",
"base",
"string",
"that",
"is",
"unique",
"in",
"the",
"database"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/Sluggable.php#L252-L264 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/Sluggable.php | Garp_Model_Behavior_Sluggable._setWhereClause | protected function _setWhereClause(Zend_Db_Select &$select, $slugField, $slug, Garp_Model_Db $model, $lang = null) {
$slugField = $model->getAdapter()->quoteIdentifier($slugField);
$select->reset(Zend_Db_Select::WHERE)
->where($slugField . ' = ?', $slug);
if ($lang) {
$select->where(Garp_Model_Behavior_Translatable::LANG_COLUMN . ' = ?', $lang);
}
} | php | protected function _setWhereClause(Zend_Db_Select &$select, $slugField, $slug, Garp_Model_Db $model, $lang = null) {
$slugField = $model->getAdapter()->quoteIdentifier($slugField);
$select->reset(Zend_Db_Select::WHERE)
->where($slugField . ' = ?', $slug);
if ($lang) {
$select->where(Garp_Model_Behavior_Translatable::LANG_COLUMN . ' = ?', $lang);
}
} | [
"protected",
"function",
"_setWhereClause",
"(",
"Zend_Db_Select",
"&",
"$",
"select",
",",
"$",
"slugField",
",",
"$",
"slug",
",",
"Garp_Model_Db",
"$",
"model",
",",
"$",
"lang",
"=",
"null",
")",
"{",
"$",
"slugField",
"=",
"$",
"model",
"->",
"getAd... | Set WHERE clause that checks for slug existence.
@param Zend_Db_Select $select
@param String $slugField
@param String $slug
@param Garp_Model_Db $model
@param String $lang
@return Void | [
"Set",
"WHERE",
"clause",
"that",
"checks",
"for",
"slug",
"existence",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/Sluggable.php#L275-L282 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/Sluggable.php | Garp_Model_Behavior_Sluggable._incrementSlug | protected function _incrementSlug(&$slug, $n, $original_input) {
$original_slug = $this->generateSlug($original_input);
$slug = $original_slug . static::VERSION_SEPARATOR . $n;
return;
} | php | protected function _incrementSlug(&$slug, $n, $original_input) {
$original_slug = $this->generateSlug($original_input);
$slug = $original_slug . static::VERSION_SEPARATOR . $n;
return;
} | [
"protected",
"function",
"_incrementSlug",
"(",
"&",
"$",
"slug",
",",
"$",
"n",
",",
"$",
"original_input",
")",
"{",
"$",
"original_slug",
"=",
"$",
"this",
"->",
"generateSlug",
"(",
"$",
"original_input",
")",
";",
"$",
"slug",
"=",
"$",
"original_sl... | Increment the version number in a slug
@param String $slug
@param Int $n Version number
@param String $original_input The original base string
@return Void Edits slug reference | [
"Increment",
"the",
"version",
"number",
"in",
"a",
"slug"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/Sluggable.php#L301-L305 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/Sluggable.php | Garp_Model_Behavior_Sluggable._normalizeBaseFieldConfiguration | protected function _normalizeBaseFieldConfiguration(&$config) {
$bf_config = (array)$config['baseField'];
$nbf_config = array();
$defaults = array(
'type' => 'text',
'format' => null
);
foreach ($bf_config as $bf) {
$bf = is_string($bf) ? array('column' => $bf) : $bf;
$bf = array_merge($defaults, $bf);
$nbf_config[] = $bf;
}
$config['baseField'] = $nbf_config;
} | php | protected function _normalizeBaseFieldConfiguration(&$config) {
$bf_config = (array)$config['baseField'];
$nbf_config = array();
$defaults = array(
'type' => 'text',
'format' => null
);
foreach ($bf_config as $bf) {
$bf = is_string($bf) ? array('column' => $bf) : $bf;
$bf = array_merge($defaults, $bf);
$nbf_config[] = $bf;
}
$config['baseField'] = $nbf_config;
} | [
"protected",
"function",
"_normalizeBaseFieldConfiguration",
"(",
"&",
"$",
"config",
")",
"{",
"$",
"bf_config",
"=",
"(",
"array",
")",
"$",
"config",
"[",
"'baseField'",
"]",
";",
"$",
"nbf_config",
"=",
"array",
"(",
")",
";",
"$",
"defaults",
"=",
"... | Normalize baseField configuration
@param Array $config
@return Void | [
"Normalize",
"baseField",
"configuration"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/Sluggable.php#L312-L325 | train |
grrr-amsterdam/garp3 | library/Garp/Mailer.php | Garp_Mailer.getDefaultAttachments | public function getDefaultAttachments() {
$config = Zend_Registry::get('config');
if (!isset($config->mailer->attachments)) {
return array();
}
return $config->mailer->attachments->toArray();
} | php | public function getDefaultAttachments() {
$config = Zend_Registry::get('config');
if (!isset($config->mailer->attachments)) {
return array();
}
return $config->mailer->attachments->toArray();
} | [
"public",
"function",
"getDefaultAttachments",
"(",
")",
"{",
"$",
"config",
"=",
"Zend_Registry",
"::",
"get",
"(",
"'config'",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"config",
"->",
"mailer",
"->",
"attachments",
")",
")",
"{",
"return",
"array",... | Read default attachments from config. Handy if you use images in your HTML template that are
in every mail.
@return array | [
"Read",
"default",
"attachments",
"from",
"config",
".",
"Handy",
"if",
"you",
"use",
"images",
"in",
"your",
"HTML",
"template",
"that",
"are",
"in",
"every",
"mail",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Mailer.php#L162-L168 | train |
grrr-amsterdam/garp3 | library/Garp/Mailer.php | Garp_Mailer._isMailingDisabled | protected function _isMailingDisabled() {
$config = Zend_Registry::get('config');
return (isset($config->mailer->sendMail) && !$config->mailer->sendMail) ||
($this->_isAmazonSesConfigured() &&
(isset($config->amazon->ses->sendMail) && !$config->amazon->ses->sendMail));
} | php | protected function _isMailingDisabled() {
$config = Zend_Registry::get('config');
return (isset($config->mailer->sendMail) && !$config->mailer->sendMail) ||
($this->_isAmazonSesConfigured() &&
(isset($config->amazon->ses->sendMail) && !$config->amazon->ses->sendMail));
} | [
"protected",
"function",
"_isMailingDisabled",
"(",
")",
"{",
"$",
"config",
"=",
"Zend_Registry",
"::",
"get",
"(",
"'config'",
")",
";",
"return",
"(",
"isset",
"(",
"$",
"config",
"->",
"mailer",
"->",
"sendMail",
")",
"&&",
"!",
"$",
"config",
"->",
... | For legacy reasons, mailing can be disabled both thru the mailer key or thru amazon ses
configuration.
@return void | [
"For",
"legacy",
"reasons",
"mailing",
"can",
"be",
"disabled",
"both",
"thru",
"the",
"mailer",
"key",
"or",
"thru",
"amazon",
"ses",
"configuration",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Mailer.php#L281-L286 | train |
grrr-amsterdam/garp3 | library/Garp/Store/Cookie.php | Garp_Store_Cookie.writeCookie | public function writeCookie() {
/**
* When Garp is used from the commandline, writing cookies is impossible.
* And that's okay.
*/
if (Zend_Registry::isRegistered('CLI') && Zend_Registry::get('CLI')) {
return true;
}
if (headers_sent($file, $line)) {
throw new Garp_Store_Exception(
'Error: headers are already sent, cannot set cookie. ' . "\n" .
'Output already started at: ' . $file . '::' . $line
);
}
$data = is_array($this->_data) ?
json_encode($this->_data, JSON_FORCE_OBJECT) :
$this->_data;
setcookie(
$this->_namespace,
$data,
time()+$this->_cookieDuration,
$this->_cookiePath,
$this->_cookieDomain
);
$this->_modified = false;
} | php | public function writeCookie() {
/**
* When Garp is used from the commandline, writing cookies is impossible.
* And that's okay.
*/
if (Zend_Registry::isRegistered('CLI') && Zend_Registry::get('CLI')) {
return true;
}
if (headers_sent($file, $line)) {
throw new Garp_Store_Exception(
'Error: headers are already sent, cannot set cookie. ' . "\n" .
'Output already started at: ' . $file . '::' . $line
);
}
$data = is_array($this->_data) ?
json_encode($this->_data, JSON_FORCE_OBJECT) :
$this->_data;
setcookie(
$this->_namespace,
$data,
time()+$this->_cookieDuration,
$this->_cookiePath,
$this->_cookieDomain
);
$this->_modified = false;
} | [
"public",
"function",
"writeCookie",
"(",
")",
"{",
"/**\n * When Garp is used from the commandline, writing cookies is impossible.\n * And that's okay.\n */",
"if",
"(",
"Zend_Registry",
"::",
"isRegistered",
"(",
"'CLI'",
")",
"&&",
"Zend_Registry",
"::",
... | Write internal array to actual cookie.
@return void | [
"Write",
"internal",
"array",
"to",
"actual",
"cookie",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Store/Cookie.php#L128-L155 | train |
grrr-amsterdam/garp3 | library/Garp/Store/Cookie.php | Garp_Store_Cookie.setFromArray | public function setFromArray(array $values) {
foreach ($values as $key => $val) {
$this->set($key, $val);
}
return $this;
} | php | public function setFromArray(array $values) {
foreach ($values as $key => $val) {
$this->set($key, $val);
}
return $this;
} | [
"public",
"function",
"setFromArray",
"(",
"array",
"$",
"values",
")",
"{",
"foreach",
"(",
"$",
"values",
"as",
"$",
"key",
"=>",
"$",
"val",
")",
"{",
"$",
"this",
"->",
"set",
"(",
"$",
"key",
",",
"$",
"val",
")",
";",
"}",
"return",
"$",
... | Store a bunch of values all at once
@param array $values
@return $this | [
"Store",
"a",
"bunch",
"of",
"values",
"all",
"at",
"once"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Store/Cookie.php#L194-L199 | train |
grrr-amsterdam/garp3 | library/Garp/Util/Memory.php | Garp_Util_Memory.useHighMemory | public function useHighMemory($mem = null) {
$ini = Zend_Registry::get('config');
if (empty($ini->app->highMemory)) {
return;
}
$highMemory = $ini->app->highMemory;
$currentMemoryLimit = $this->getCurrentMemoryLimit();
if (!empty($currentMemoryLimit)) {
$megs = (int)substr($currentMemoryLimit, 0, -1);
if ($megs < $highMemory) {
ini_set('memory_limit', $highMemory . 'M');
}
} else {
ini_set('memory_limit', $highMemory . 'M');
}
} | php | public function useHighMemory($mem = null) {
$ini = Zend_Registry::get('config');
if (empty($ini->app->highMemory)) {
return;
}
$highMemory = $ini->app->highMemory;
$currentMemoryLimit = $this->getCurrentMemoryLimit();
if (!empty($currentMemoryLimit)) {
$megs = (int)substr($currentMemoryLimit, 0, -1);
if ($megs < $highMemory) {
ini_set('memory_limit', $highMemory . 'M');
}
} else {
ini_set('memory_limit', $highMemory . 'M');
}
} | [
"public",
"function",
"useHighMemory",
"(",
"$",
"mem",
"=",
"null",
")",
"{",
"$",
"ini",
"=",
"Zend_Registry",
"::",
"get",
"(",
"'config'",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"ini",
"->",
"app",
"->",
"highMemory",
")",
")",
"{",
"return",
... | Raises PHP's RAM limit for extensive operations.
Takes its value from application.ini if not provided.
@param int $mem In MBs.
@return Void | [
"Raises",
"PHP",
"s",
"RAM",
"limit",
"for",
"extensive",
"operations",
".",
"Takes",
"its",
"value",
"from",
"application",
".",
"ini",
"if",
"not",
"provided",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Util/Memory.php#L17-L32 | train |
grrr-amsterdam/garp3 | application/modules/g/views/helpers/I18n.php | G_View_Helper_I18n.getAlternateUrl | public function getAlternateUrl(
$language, array $routeParams = array(), $route = null, $defaultToHome = true
) {
if (!$route) {
$router = Zend_Controller_Front::getInstance()->getRouter();
$route = $router->getCurrentRouteName();
}
if (empty($this->view->config()->resources->router->routesFile->{$language})) {
return null;
}
$routes = $this->_getRoutesWithFallback($language);
$localizedRoutes = Garp_I18n::getLocalizedRoutes($routes, array($language));
$router = new Zend_Controller_Router_Rewrite();
$router->addConfig(new Zend_Config($localizedRoutes));
$routeParams['locale'] = $language;
// @todo Also add existing GET params in the form of ?foo=bar
try {
$alternateRoute = $router->assemble($routeParams, $route);
} catch (Exception $e) {
// try to default to 'home'
if (!$defaultToHome) {
throw $e;
}
return $this->_constructHomeFallbackUrl($language);
}
// Remove the baseURl because it contains the current language
$alternateRoute = $this->view->string()->strReplaceOnce(
$this->view->baseUrl(), '', $alternateRoute
);
// Always use explicit localization
if ($alternateRoute == '/') {
$alternateRoute = '/' . $language;
}
return $alternateRoute;
} | php | public function getAlternateUrl(
$language, array $routeParams = array(), $route = null, $defaultToHome = true
) {
if (!$route) {
$router = Zend_Controller_Front::getInstance()->getRouter();
$route = $router->getCurrentRouteName();
}
if (empty($this->view->config()->resources->router->routesFile->{$language})) {
return null;
}
$routes = $this->_getRoutesWithFallback($language);
$localizedRoutes = Garp_I18n::getLocalizedRoutes($routes, array($language));
$router = new Zend_Controller_Router_Rewrite();
$router->addConfig(new Zend_Config($localizedRoutes));
$routeParams['locale'] = $language;
// @todo Also add existing GET params in the form of ?foo=bar
try {
$alternateRoute = $router->assemble($routeParams, $route);
} catch (Exception $e) {
// try to default to 'home'
if (!$defaultToHome) {
throw $e;
}
return $this->_constructHomeFallbackUrl($language);
}
// Remove the baseURl because it contains the current language
$alternateRoute = $this->view->string()->strReplaceOnce(
$this->view->baseUrl(), '', $alternateRoute
);
// Always use explicit localization
if ($alternateRoute == '/') {
$alternateRoute = '/' . $language;
}
return $alternateRoute;
} | [
"public",
"function",
"getAlternateUrl",
"(",
"$",
"language",
",",
"array",
"$",
"routeParams",
"=",
"array",
"(",
")",
",",
"$",
"route",
"=",
"null",
",",
"$",
"defaultToHome",
"=",
"true",
")",
"{",
"if",
"(",
"!",
"$",
"route",
")",
"{",
"$",
... | Get a route in a different language.
@param string $language
@param array $routeParams Parameters used in assembling the alternate route
@param string $route Which route to use. Defaults to current route.
@param bool $defaultToHome Wether to use home as a fallback alt route
@return string | [
"Get",
"a",
"route",
"in",
"a",
"different",
"language",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/I18n.php#L29-L66 | train |
grrr-amsterdam/garp3 | application/modules/g/views/helpers/I18n.php | G_View_Helper_I18n._getRoutesWithFallback | protected function _getRoutesWithFallback($language) {
$routesFile = $this->view->config()->resources->router->routesFile->{$language};
$config = new Garp_Config_Ini($routesFile, APPLICATION_ENV);
if ($config->routes) {
return $config->routes->toArray();
}
$routesFile = $this->view->config()->resources->router->routesFile->generic;
$config = new Garp_Config_Ini($routesFile, APPLICATION_ENV);
return $config->routes->toArray();
} | php | protected function _getRoutesWithFallback($language) {
$routesFile = $this->view->config()->resources->router->routesFile->{$language};
$config = new Garp_Config_Ini($routesFile, APPLICATION_ENV);
if ($config->routes) {
return $config->routes->toArray();
}
$routesFile = $this->view->config()->resources->router->routesFile->generic;
$config = new Garp_Config_Ini($routesFile, APPLICATION_ENV);
return $config->routes->toArray();
} | [
"protected",
"function",
"_getRoutesWithFallback",
"(",
"$",
"language",
")",
"{",
"$",
"routesFile",
"=",
"$",
"this",
"->",
"view",
"->",
"config",
"(",
")",
"->",
"resources",
"->",
"router",
"->",
"routesFile",
"->",
"{",
"$",
"language",
"}",
";",
"... | Return generic routes if routes file from language is empty
@param string $language
@return array | [
"Return",
"generic",
"routes",
"if",
"routes",
"file",
"from",
"language",
"is",
"empty"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/I18n.php#L103-L114 | train |
grrr-amsterdam/garp3 | library/Garp/Service/MailChimp.php | Garp_Service_MailChimp.listSubscribe | public function listSubscribe($options) {
if (!$options instanceof Garp_Util_Configuration) {
$options = new Garp_Util_Configuration($options);
}
$options->obligate('email_address')
->obligate('id')
->setDefault('merge_vars', array('LNAME' => '', 'FNAME' => ''))
;
$options['method'] = 'listSubscribe';
return $this->_send((array)$options);
} | php | public function listSubscribe($options) {
if (!$options instanceof Garp_Util_Configuration) {
$options = new Garp_Util_Configuration($options);
}
$options->obligate('email_address')
->obligate('id')
->setDefault('merge_vars', array('LNAME' => '', 'FNAME' => ''))
;
$options['method'] = 'listSubscribe';
return $this->_send((array)$options);
} | [
"public",
"function",
"listSubscribe",
"(",
"$",
"options",
")",
"{",
"if",
"(",
"!",
"$",
"options",
"instanceof",
"Garp_Util_Configuration",
")",
"{",
"$",
"options",
"=",
"new",
"Garp_Util_Configuration",
"(",
"$",
"options",
")",
";",
"}",
"$",
"options"... | Subscribe the provided email to a list.
@param Array|Garp_Util_Configuration $options
@return StdClass | [
"Subscribe",
"the",
"provided",
"email",
"to",
"a",
"list",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Service/MailChimp.php#L56-L66 | train |
grrr-amsterdam/garp3 | library/Garp/Service/MailChimp.php | Garp_Service_MailChimp._getApiKey | protected function _getApiKey() {
$ini = Zend_Registry::get('config');
if (!$apiKey = $ini->mailchimp->apiKey) {
throw new Garp_Service_MailChimp_Exception('No API key was given, nor found in application.ini');
}
return $apiKey;
} | php | protected function _getApiKey() {
$ini = Zend_Registry::get('config');
if (!$apiKey = $ini->mailchimp->apiKey) {
throw new Garp_Service_MailChimp_Exception('No API key was given, nor found in application.ini');
}
return $apiKey;
} | [
"protected",
"function",
"_getApiKey",
"(",
")",
"{",
"$",
"ini",
"=",
"Zend_Registry",
"::",
"get",
"(",
"'config'",
")",
";",
"if",
"(",
"!",
"$",
"apiKey",
"=",
"$",
"ini",
"->",
"mailchimp",
"->",
"apiKey",
")",
"{",
"throw",
"new",
"Garp_Service_M... | Get API key from ini file
@return String | [
"Get",
"API",
"key",
"from",
"ini",
"file"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Service/MailChimp.php#L128-L134 | train |
grrr-amsterdam/garp3 | library/Garp/Service/Vimeo/Pro/Method/Videos.php | Garp_Service_Vimeo_Pro_Method_Videos.addCast | public function addCast($user_id, $video_id, $role = null) {
if (!$this->getAccessToken()) {
throw new Garp_Service_Vimeo_Exception('This method requires an authenticated user. '.
'Please provide an access token.');
}
$params = array('user_id' => $user_id, 'video_id' => $video_id);
if ($role) {
$params['role'] = $role;
}
$response = $this->request('videos.addCast', $params);
return $response;
} | php | public function addCast($user_id, $video_id, $role = null) {
if (!$this->getAccessToken()) {
throw new Garp_Service_Vimeo_Exception('This method requires an authenticated user. '.
'Please provide an access token.');
}
$params = array('user_id' => $user_id, 'video_id' => $video_id);
if ($role) {
$params['role'] = $role;
}
$response = $this->request('videos.addCast', $params);
return $response;
} | [
"public",
"function",
"addCast",
"(",
"$",
"user_id",
",",
"$",
"video_id",
",",
"$",
"role",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"getAccessToken",
"(",
")",
")",
"{",
"throw",
"new",
"Garp_Service_Vimeo_Exception",
"(",
"'This meth... | Add a specified user as a cast member to the video.
@param String $user_id The user to add as a cast member.
@param String $video_id The video to add the cast member to.
@param String $role The role of the user in the video.
@return Array | [
"Add",
"a",
"specified",
"user",
"as",
"a",
"cast",
"member",
"to",
"the",
"video",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Service/Vimeo/Pro/Method/Videos.php#L20-L31 | train |
grrr-amsterdam/garp3 | library/Garp/Validate/GreaterThanOrEqualTo.php | Garp_Validate_GreaterThanOrEqualTo.isValid | public function isValid($value)
{
$this->_setValue($value);
if ($this->_min > $value) {
$this->_error(self::NOT_GREATER_OR_EQUAL_TO);
return false;
}
return true;
} | php | public function isValid($value)
{
$this->_setValue($value);
if ($this->_min > $value) {
$this->_error(self::NOT_GREATER_OR_EQUAL_TO);
return false;
}
return true;
} | [
"public",
"function",
"isValid",
"(",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"_setValue",
"(",
"$",
"value",
")",
";",
"if",
"(",
"$",
"this",
"->",
"_min",
">",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"_error",
"(",
"self",
"::",
"NOT_GRE... | Defined by Zend_Validate_Interface
Overwrites the function in Zend_Validate_GreaterThan to deal with equal to
Returns true if $value is greater than or equal to min option
@param mixed $value
@return boolean | [
"Defined",
"by",
"Zend_Validate_Interface",
"Overwrites",
"the",
"function",
"in",
"Zend_Validate_GreaterThan",
"to",
"deal",
"with",
"equal",
"to"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Validate/GreaterThanOrEqualTo.php#L30-L39 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Validator/MinLength.php | Garp_Model_Validator_MinLength.validate | public function validate(array $data, Garp_Model_Db $model, $onlyIfAvailable = true) {
$theFields = $this->_fields;
$applicableFields = array_keys(array_get_subset($data, array_keys($theFields)));
$tooShortFields = array_filter(
$applicableFields,
function ($field) use ($theFields, $data) {
return !is_null($data[$field]) && strlen($data[$field]) < $theFields[$field];
}
);
if (count($tooShortFields)) {
$first = current($tooShortFields);
throw new Garp_Model_Validator_Exception(
Garp_Util_String::interpolate(
__(self::ERROR_MESSAGE),
array(
'value' => $first,
'min' => $theFields[$first]
)
)
);
}
} | php | public function validate(array $data, Garp_Model_Db $model, $onlyIfAvailable = true) {
$theFields = $this->_fields;
$applicableFields = array_keys(array_get_subset($data, array_keys($theFields)));
$tooShortFields = array_filter(
$applicableFields,
function ($field) use ($theFields, $data) {
return !is_null($data[$field]) && strlen($data[$field]) < $theFields[$field];
}
);
if (count($tooShortFields)) {
$first = current($tooShortFields);
throw new Garp_Model_Validator_Exception(
Garp_Util_String::interpolate(
__(self::ERROR_MESSAGE),
array(
'value' => $first,
'min' => $theFields[$first]
)
)
);
}
} | [
"public",
"function",
"validate",
"(",
"array",
"$",
"data",
",",
"Garp_Model_Db",
"$",
"model",
",",
"$",
"onlyIfAvailable",
"=",
"true",
")",
"{",
"$",
"theFields",
"=",
"$",
"this",
"->",
"_fields",
";",
"$",
"applicableFields",
"=",
"array_keys",
"(",
... | Validate wether the given columns are long enough
@param array $data The data to validate
@param Garp_Model_Db $model
@param bool $onlyIfAvailable Wether to skip validation on fields that are not in the array
@return void
@throws Garp_Model_Validator_Exception | [
"Validate",
"wether",
"the",
"given",
"columns",
"are",
"long",
"enough"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Validator/MinLength.php#L38-L61 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/Draftable.php | Garp_Model_Behavior_Draftable.beforeFetch | public function beforeFetch(&$args) {
$model = $args[0];
$is_cms = $model->isCmsContext();
$is_preview = $this->_isPreview() && Garp_Auth::getInstance()->isLoggedIn();
$force = $this->_force;
if (($is_cms || $is_preview) && !$force) {
// don't use in the CMS, or in preview mode
return;
}
$model = &$args[0];
$select = &$args[1];
if ($this->_blockOfflineItems) {
$this->addWhereClause($model, $select);
}
} | php | public function beforeFetch(&$args) {
$model = $args[0];
$is_cms = $model->isCmsContext();
$is_preview = $this->_isPreview() && Garp_Auth::getInstance()->isLoggedIn();
$force = $this->_force;
if (($is_cms || $is_preview) && !$force) {
// don't use in the CMS, or in preview mode
return;
}
$model = &$args[0];
$select = &$args[1];
if ($this->_blockOfflineItems) {
$this->addWhereClause($model, $select);
}
} | [
"public",
"function",
"beforeFetch",
"(",
"&",
"$",
"args",
")",
"{",
"$",
"model",
"=",
"$",
"args",
"[",
"0",
"]",
";",
"$",
"is_cms",
"=",
"$",
"model",
"->",
"isCmsContext",
"(",
")",
";",
"$",
"is_preview",
"=",
"$",
"this",
"->",
"_isPreview"... | Before fetch callback.
Adds the WHERE clause.
@param array $args
@return void | [
"Before",
"fetch",
"callback",
".",
"Adds",
"the",
"WHERE",
"clause",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/Draftable.php#L80-L97 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/Draftable.php | Garp_Model_Behavior_Draftable.addWhereClause | public function addWhereClause(&$model, Zend_Db_Select &$select) {
$statusColumn = $model->getAdapter()->quoteIdentifier(self::STATUS_COLUMN);
$publishedColumn = $model->getAdapter()->quoteIdentifier(self::PUBLISHED_COLUMN);
if ($this->_modelAlias) {
$modelAlias = $this->_modelAlias;
$modelAlias = $model->getAdapter()->quoteIdentifier($modelAlias);
$statusColumn = "$modelAlias.$statusColumn";
$publishedColumn = "$modelAlias.$publishedColumn";
}
// Add online_status check
$select->where($statusColumn . ' = ?', self::ONLINE);
// Add published check
if ($this->_config['draft_only']) {
return;
}
$ini = Zend_Registry::get('config');
$timezone = !empty($ini->resources->db->params->timezone) ?
$ini->resources->db->params->timezone : null;
$timecalc = '';
if ($timezone == 'GMT' || $timezone == 'UTC') {
$dstStart = strtotime('Last Sunday of March');
$dstEnd = strtotime('Last Sunday of October');
$now = time();
$daylightSavingsTime = $now > $dstStart && $now < $dstEnd;
$timecalc = '+ INTERVAL';
if ($daylightSavingsTime) {
$timecalc .= ' 2 HOUR';
} else {
$timecalc .= ' 1 HOUR';
}
}
$select->where(
$publishedColumn . ' IS NULL OR ' . $publishedColumn . ' <= NOW() ' . $timecalc
);
} | php | public function addWhereClause(&$model, Zend_Db_Select &$select) {
$statusColumn = $model->getAdapter()->quoteIdentifier(self::STATUS_COLUMN);
$publishedColumn = $model->getAdapter()->quoteIdentifier(self::PUBLISHED_COLUMN);
if ($this->_modelAlias) {
$modelAlias = $this->_modelAlias;
$modelAlias = $model->getAdapter()->quoteIdentifier($modelAlias);
$statusColumn = "$modelAlias.$statusColumn";
$publishedColumn = "$modelAlias.$publishedColumn";
}
// Add online_status check
$select->where($statusColumn . ' = ?', self::ONLINE);
// Add published check
if ($this->_config['draft_only']) {
return;
}
$ini = Zend_Registry::get('config');
$timezone = !empty($ini->resources->db->params->timezone) ?
$ini->resources->db->params->timezone : null;
$timecalc = '';
if ($timezone == 'GMT' || $timezone == 'UTC') {
$dstStart = strtotime('Last Sunday of March');
$dstEnd = strtotime('Last Sunday of October');
$now = time();
$daylightSavingsTime = $now > $dstStart && $now < $dstEnd;
$timecalc = '+ INTERVAL';
if ($daylightSavingsTime) {
$timecalc .= ' 2 HOUR';
} else {
$timecalc .= ' 1 HOUR';
}
}
$select->where(
$publishedColumn . ' IS NULL OR ' . $publishedColumn . ' <= NOW() ' . $timecalc
);
} | [
"public",
"function",
"addWhereClause",
"(",
"&",
"$",
"model",
",",
"Zend_Db_Select",
"&",
"$",
"select",
")",
"{",
"$",
"statusColumn",
"=",
"$",
"model",
"->",
"getAdapter",
"(",
")",
"->",
"quoteIdentifier",
"(",
"self",
"::",
"STATUS_COLUMN",
")",
";"... | Add the WHERE clause that keeps offline items from appearing in the results
@param Garp_Model_Db $model
@param Zend_Db_Select $select
@return void | [
"Add",
"the",
"WHERE",
"clause",
"that",
"keeps",
"offline",
"items",
"from",
"appearing",
"in",
"the",
"results"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/Draftable.php#L106-L145 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/Draftable.php | Garp_Model_Behavior_Draftable.afterInsert | public function afterInsert(&$args) {
$model = $args[0];
$data = $args[1];
$this->afterSave($model, $data);
} | php | public function afterInsert(&$args) {
$model = $args[0];
$data = $args[1];
$this->afterSave($model, $data);
} | [
"public",
"function",
"afterInsert",
"(",
"&",
"$",
"args",
")",
"{",
"$",
"model",
"=",
"$",
"args",
"[",
"0",
"]",
";",
"$",
"data",
"=",
"$",
"args",
"[",
"1",
"]",
";",
"$",
"this",
"->",
"afterSave",
"(",
"$",
"model",
",",
"$",
"data",
... | After insert callback.
@param array $args
@return void | [
"After",
"insert",
"callback",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/Draftable.php#L153-L157 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/Draftable.php | Garp_Model_Behavior_Draftable.afterSave | public function afterSave($model, $data) {
// Check if the 'published column' is filled...
if (empty($data[self::PUBLISHED_COLUMN])) {
return;
}
// ...and that it's in the future
$publishTime = strtotime($data[self::PUBLISHED_COLUMN]);
if ($publishTime <= time()) {
return;
}
$tags = array(get_class($model));
$tags = array_merge($tags, $model->getBindableModels());
$tags = array_unique($tags);
Garp_Cache_Manager::scheduleClear($publishTime, $tags);
} | php | public function afterSave($model, $data) {
// Check if the 'published column' is filled...
if (empty($data[self::PUBLISHED_COLUMN])) {
return;
}
// ...and that it's in the future
$publishTime = strtotime($data[self::PUBLISHED_COLUMN]);
if ($publishTime <= time()) {
return;
}
$tags = array(get_class($model));
$tags = array_merge($tags, $model->getBindableModels());
$tags = array_unique($tags);
Garp_Cache_Manager::scheduleClear($publishTime, $tags);
} | [
"public",
"function",
"afterSave",
"(",
"$",
"model",
",",
"$",
"data",
")",
"{",
"// Check if the 'published column' is filled...",
"if",
"(",
"empty",
"(",
"$",
"data",
"[",
"self",
"::",
"PUBLISHED_COLUMN",
"]",
")",
")",
"{",
"return",
";",
"}",
"// ...a... | After save callback, called by afterInsert and afterUpdate.
Sets an `at` job that clears the Static Page cache at the exact moment of the Published date.
@param Garp_Model_Db $model
@param array $data
@return void | [
"After",
"save",
"callback",
"called",
"by",
"afterInsert",
"and",
"afterUpdate",
".",
"Sets",
"an",
"at",
"job",
"that",
"clears",
"the",
"Static",
"Page",
"cache",
"at",
"the",
"exact",
"moment",
"of",
"the",
"Published",
"date",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/Draftable.php#L179-L195 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/Bindable.php | Garp_Model_Behavior_Bindable.afterFetch | public function afterFetch(&$args) {
$model = $args[0];
$data = $args[1];
$this->_combineResultsWithBindings($model, $data);
} | php | public function afterFetch(&$args) {
$model = $args[0];
$data = $args[1];
$this->_combineResultsWithBindings($model, $data);
} | [
"public",
"function",
"afterFetch",
"(",
"&",
"$",
"args",
")",
"{",
"$",
"model",
"=",
"$",
"args",
"[",
"0",
"]",
";",
"$",
"data",
"=",
"$",
"args",
"[",
"1",
"]",
";",
"$",
"this",
"->",
"_combineResultsWithBindings",
"(",
"$",
"model",
",",
... | AfterFetch callback, combines results with related records.
@param array $args
@return void | [
"AfterFetch",
"callback",
"combines",
"results",
"with",
"related",
"records",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/Bindable.php#L32-L36 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/Bindable.php | Garp_Model_Behavior_Bindable._combineResultsWithBindings | protected function _combineResultsWithBindings(Garp_Model $model, $data) {
if (!$data) {
return;
}
$tableName = $model->getName();
$bindings = $model->getBindings();
if (empty($bindings)) {
return;
}
// check if it's a rowset or a single row
if (!$data instanceof Garp_Db_Table_Rowset) {
$data = array($data);
}
foreach ($bindings as $binding => $bindOptions) {
/**
* We keep tabs on the outer call to fetch() by checking getRecursion.
* If it is 0, this is the first call in the chain. That way we can
* clean up the recursion when we're done, since all subsequent fetch() calls
* will happen within this one and the if ($cleanup) line ahead will only
* fire on the first fetch(). Look at it like this:
*
* ```
* fetch()
* cleanup = 1
* fetch()
* fetch()
* fetch()
* fetch()
* fetch()
* fetch()
* if (cleanup) resetRecursion()
* ```
*/
$cleanup = false;
if (Garp_Model_Db_BindingManager::getRecursion(get_class($model), $binding) == 0) {
$cleanup = true;
}
if (Garp_Model_Db_BindingManager::isAllowedFetch(get_class($model), $binding)) {
Garp_Model_Db_BindingManager::registerFetch(get_class($model), $binding);
foreach ($data as $datum) {
// There's no relation possible if the primary key is not
// among the fetched columns.
$prim = (array)$model->info(Zend_Db_Table::PRIMARY);
foreach ($prim as $key) {
try {
$datum->$key;
} catch (Exception $e) {
break 2;
}
}
$relatedRowset = $this->_getRelatedRowset($model, $datum, $bindOptions);
$datum->setRelated($binding, $relatedRowset);
}
}
if ($cleanup) {
Garp_Model_Db_BindingManager::resetRecursion(get_class($model), $binding);
}
}
// return the pointer to 0
if ($data instanceof Garp_Db_Table_Rowset) {
$data->rewind();
}
} | php | protected function _combineResultsWithBindings(Garp_Model $model, $data) {
if (!$data) {
return;
}
$tableName = $model->getName();
$bindings = $model->getBindings();
if (empty($bindings)) {
return;
}
// check if it's a rowset or a single row
if (!$data instanceof Garp_Db_Table_Rowset) {
$data = array($data);
}
foreach ($bindings as $binding => $bindOptions) {
/**
* We keep tabs on the outer call to fetch() by checking getRecursion.
* If it is 0, this is the first call in the chain. That way we can
* clean up the recursion when we're done, since all subsequent fetch() calls
* will happen within this one and the if ($cleanup) line ahead will only
* fire on the first fetch(). Look at it like this:
*
* ```
* fetch()
* cleanup = 1
* fetch()
* fetch()
* fetch()
* fetch()
* fetch()
* fetch()
* if (cleanup) resetRecursion()
* ```
*/
$cleanup = false;
if (Garp_Model_Db_BindingManager::getRecursion(get_class($model), $binding) == 0) {
$cleanup = true;
}
if (Garp_Model_Db_BindingManager::isAllowedFetch(get_class($model), $binding)) {
Garp_Model_Db_BindingManager::registerFetch(get_class($model), $binding);
foreach ($data as $datum) {
// There's no relation possible if the primary key is not
// among the fetched columns.
$prim = (array)$model->info(Zend_Db_Table::PRIMARY);
foreach ($prim as $key) {
try {
$datum->$key;
} catch (Exception $e) {
break 2;
}
}
$relatedRowset = $this->_getRelatedRowset($model, $datum, $bindOptions);
$datum->setRelated($binding, $relatedRowset);
}
}
if ($cleanup) {
Garp_Model_Db_BindingManager::resetRecursion(get_class($model), $binding);
}
}
// return the pointer to 0
if ($data instanceof Garp_Db_Table_Rowset) {
$data->rewind();
}
} | [
"protected",
"function",
"_combineResultsWithBindings",
"(",
"Garp_Model",
"$",
"model",
",",
"$",
"data",
")",
"{",
"if",
"(",
"!",
"$",
"data",
")",
"{",
"return",
";",
"}",
"$",
"tableName",
"=",
"$",
"model",
"->",
"getName",
"(",
")",
";",
"$",
... | Check if there are bindings to fetch related records and
start the related rowset fetching.
@param Garp_Model $model The model that spawned this data
@param Garp_Db_Table_Row|Garp_Db_Table_Rowset $data The fetched root data
@return void | [
"Check",
"if",
"there",
"are",
"bindings",
"to",
"fetch",
"related",
"records",
"and",
"start",
"the",
"related",
"rowset",
"fetching",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/Bindable.php#L46-L112 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/Bindable.php | Garp_Model_Behavior_Bindable._getRelatedRowset | protected function _getRelatedRowset(
Garp_Model $model, Garp_Db_Table_Row $row, Garp_Util_Configuration $options
) {
/**
* An optional passed SELECT object will be passed by reference after every query.
* This results in an error when 'clone' is not used, because correlation names will be
* used twice (since they were set during the first iteration). Using 'clone' makes sure
* a brand new SELECT object is used every time that hasn't been soiled by a possible
* previous query.
*/
$conditions = is_null($options['conditions']) ? null : clone $options['conditions'];
$otherModel = $options['modelClass'];
if (!$otherModel instanceof Zend_Db_Table_Abstract) {
$otherModel = new $otherModel();
}
// Bound models should respect the CMS context settings of the root model
$otherModel->setCmsContext($model->isCmsContext());
/**
* Do not cache related queries. The "outside" query should be the only
* query that's cached.
*/
$originalCacheQueriesFlag = $otherModel->getCacheQueries();
$otherModel->setCacheQueries(false);
$modelName = get_class($otherModel);
$relatedRowset = null;
// many to many
if (!empty($options['bindingModel'])) {
$relatedRowset = $row->findManyToManyRowset(
$otherModel,
$options['bindingModel'],
$options['rule2'],
$options['rule'],
$conditions
);
} else {
/**
* 'mode' is used to clear ambiguity with homophilic relationships. For example,
* a Model_Doc can have have child Docs and one parent Doc.
* The conditionals below can never tell which method to call
* (findParentRow or findDependentRowset) from the referenceMap.
*
* Therefore, we can help the decision-making by passing "mode". This can either be
* "parent" or "dependent", which will then force a call to
* findParentRow and findDependentRowset, respectively.
*/
if (is_null($options['mode'])) {
// belongs to
try {
$model->getReference($modelName, $options['rule']);
$relatedRowset = $row->findParentRow(
$otherModel, $options['rule'], $conditions
);
} catch(Exception $e) {
if (!Garp_Content_Relation_Manager::isInvalidReferenceException($e)) {
throw $e;
}
try {
// one to many - one to one
// The following line triggers an exception if no reference is available
$otherModel->getReference(get_class($model), $options['rule']);
$relatedRowset = $row->findDependentRowset(
$otherModel,
$options['rule'],
$conditions
);
} catch (Exception $e) {
if (!Garp_Content_Relation_Manager::isInvalidReferenceException($e)) {
throw $e;
}
$bindingModel = $model->getBindingModel($modelName);
$relatedRowset = $row->findManyToManyRowset(
$otherModel,
$bindingModel,
$options['rule2'],
$options['rule'],
$conditions
);
}
}
} else {
switch ($options['mode']) {
case 'parent':
$relatedRowset = $row->findParentRow(
$otherModel,
$options['rule'],
$conditions
);
break;
case 'dependent':
$relatedRowset = $row->findDependentRowset(
$otherModel,
$options['rule'],
$conditions
);
break;
default:
throw new Garp_Model_Exception(
'Invalid value for "mode" given. Must be either "parent" or ' .
'"dependent", but "' . $options['mode'] . '" was given.'
);
break;
}
}
}
// Reset the cacheQueries value. It's a static property,
// so leaving it FALSE will affect all future fetch() calls to this
// model. Not good.
$otherModel->setCacheQueries($originalCacheQueriesFlag);
return $relatedRowset;
} | php | protected function _getRelatedRowset(
Garp_Model $model, Garp_Db_Table_Row $row, Garp_Util_Configuration $options
) {
/**
* An optional passed SELECT object will be passed by reference after every query.
* This results in an error when 'clone' is not used, because correlation names will be
* used twice (since they were set during the first iteration). Using 'clone' makes sure
* a brand new SELECT object is used every time that hasn't been soiled by a possible
* previous query.
*/
$conditions = is_null($options['conditions']) ? null : clone $options['conditions'];
$otherModel = $options['modelClass'];
if (!$otherModel instanceof Zend_Db_Table_Abstract) {
$otherModel = new $otherModel();
}
// Bound models should respect the CMS context settings of the root model
$otherModel->setCmsContext($model->isCmsContext());
/**
* Do not cache related queries. The "outside" query should be the only
* query that's cached.
*/
$originalCacheQueriesFlag = $otherModel->getCacheQueries();
$otherModel->setCacheQueries(false);
$modelName = get_class($otherModel);
$relatedRowset = null;
// many to many
if (!empty($options['bindingModel'])) {
$relatedRowset = $row->findManyToManyRowset(
$otherModel,
$options['bindingModel'],
$options['rule2'],
$options['rule'],
$conditions
);
} else {
/**
* 'mode' is used to clear ambiguity with homophilic relationships. For example,
* a Model_Doc can have have child Docs and one parent Doc.
* The conditionals below can never tell which method to call
* (findParentRow or findDependentRowset) from the referenceMap.
*
* Therefore, we can help the decision-making by passing "mode". This can either be
* "parent" or "dependent", which will then force a call to
* findParentRow and findDependentRowset, respectively.
*/
if (is_null($options['mode'])) {
// belongs to
try {
$model->getReference($modelName, $options['rule']);
$relatedRowset = $row->findParentRow(
$otherModel, $options['rule'], $conditions
);
} catch(Exception $e) {
if (!Garp_Content_Relation_Manager::isInvalidReferenceException($e)) {
throw $e;
}
try {
// one to many - one to one
// The following line triggers an exception if no reference is available
$otherModel->getReference(get_class($model), $options['rule']);
$relatedRowset = $row->findDependentRowset(
$otherModel,
$options['rule'],
$conditions
);
} catch (Exception $e) {
if (!Garp_Content_Relation_Manager::isInvalidReferenceException($e)) {
throw $e;
}
$bindingModel = $model->getBindingModel($modelName);
$relatedRowset = $row->findManyToManyRowset(
$otherModel,
$bindingModel,
$options['rule2'],
$options['rule'],
$conditions
);
}
}
} else {
switch ($options['mode']) {
case 'parent':
$relatedRowset = $row->findParentRow(
$otherModel,
$options['rule'],
$conditions
);
break;
case 'dependent':
$relatedRowset = $row->findDependentRowset(
$otherModel,
$options['rule'],
$conditions
);
break;
default:
throw new Garp_Model_Exception(
'Invalid value for "mode" given. Must be either "parent" or ' .
'"dependent", but "' . $options['mode'] . '" was given.'
);
break;
}
}
}
// Reset the cacheQueries value. It's a static property,
// so leaving it FALSE will affect all future fetch() calls to this
// model. Not good.
$otherModel->setCacheQueries($originalCacheQueriesFlag);
return $relatedRowset;
} | [
"protected",
"function",
"_getRelatedRowset",
"(",
"Garp_Model",
"$",
"model",
",",
"Garp_Db_Table_Row",
"$",
"row",
",",
"Garp_Util_Configuration",
"$",
"options",
")",
"{",
"/**\n * An optional passed SELECT object will be passed by reference after every query.\n ... | Find a related recordset.
@param Garp_Model $model The model that spawned this data
@param Garp_Db_Row $row The row object
@param Garp_Util_Configuration $options Various relation options
@return string The name of the method. | [
"Find",
"a",
"related",
"recordset",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/Bindable.php#L122-L232 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Db/AuthLocal.php | Garp_Model_Db_AuthLocal.tryLogin | public function tryLogin($identity, $credential, Garp_Util_Configuration $authVars, $sessionColumns = null) {
$theOtherModel = new $authVars['model']();
$theOtherTable = $theOtherModel->getName();
if (is_null($sessionColumns)) {
$sessionColumns = Zend_Db_Select::SQL_WILDCARD;
}
$select = $this->select()
->setIntegrityCheck(false)
->from($this->_name, array($authVars['credentialColumn']))
->joinInner($theOtherTable, $this->_name.'.user_id = '.$theOtherTable.'.id', $sessionColumns)
->where($theOtherTable.'.'.$authVars['identityColumn'].' = ?', $identity)
->order($this->_name.'.id')
;
$result = $this->fetchRow($select);
// update stats if we found a match
if (!$result) {
throw new Garp_Auth_Adapter_Db_UserNotFoundException();
return null;
}
$foundCredential = $result->{$authVars['credentialColumn']};
$testCredential = $authVars['hashMethod']($credential.$authVars['salt']);
if ($foundCredential != $testCredential) {
throw new Garp_Auth_Adapter_Db_InvalidPasswordException();
}
$this->getObserver('Authenticatable')->updateLoginStats($result->id);
unset($result->{$authVars['credentialColumn']});
return $result;
} | php | public function tryLogin($identity, $credential, Garp_Util_Configuration $authVars, $sessionColumns = null) {
$theOtherModel = new $authVars['model']();
$theOtherTable = $theOtherModel->getName();
if (is_null($sessionColumns)) {
$sessionColumns = Zend_Db_Select::SQL_WILDCARD;
}
$select = $this->select()
->setIntegrityCheck(false)
->from($this->_name, array($authVars['credentialColumn']))
->joinInner($theOtherTable, $this->_name.'.user_id = '.$theOtherTable.'.id', $sessionColumns)
->where($theOtherTable.'.'.$authVars['identityColumn'].' = ?', $identity)
->order($this->_name.'.id')
;
$result = $this->fetchRow($select);
// update stats if we found a match
if (!$result) {
throw new Garp_Auth_Adapter_Db_UserNotFoundException();
return null;
}
$foundCredential = $result->{$authVars['credentialColumn']};
$testCredential = $authVars['hashMethod']($credential.$authVars['salt']);
if ($foundCredential != $testCredential) {
throw new Garp_Auth_Adapter_Db_InvalidPasswordException();
}
$this->getObserver('Authenticatable')->updateLoginStats($result->id);
unset($result->{$authVars['credentialColumn']});
return $result;
} | [
"public",
"function",
"tryLogin",
"(",
"$",
"identity",
",",
"$",
"credential",
",",
"Garp_Util_Configuration",
"$",
"authVars",
",",
"$",
"sessionColumns",
"=",
"null",
")",
"{",
"$",
"theOtherModel",
"=",
"new",
"$",
"authVars",
"[",
"'model'",
"]",
"(",
... | Try to log a user in.
@param String $identity
@param String $credential
@param Garp_Util_Configuration $authVars
@param Array $sessionColumns Which columns to retrieve for storage in the session.
@return Garp_Db_Table_Row
@throws Garp_Auth_Adapter_Db_UserNotFoundException When the user is not found
@throws Garp_Auth_Adapter_Db_InvalidPasswordException When the password does not match | [
"Try",
"to",
"log",
"a",
"user",
"in",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Db/AuthLocal.php#L30-L59 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Db/AuthLocal.php | Garp_Model_Db_AuthLocal._hashPassword | protected function _hashPassword(array $data) {
$config = Zend_Registry::get('config');
if (!empty($config->auth->adapters->db)) {
$authVars = $config->auth->adapters->db;
$credentialColumn = $authVars->credentialColumn;
$hashMethod = $authVars->hashMethod;
$salt = $authVars->salt;
if (!empty($data[$credentialColumn])) {
$data[$credentialColumn] = new Zend_Db_Expr($hashMethod.'(CONCAT('.
$this->getAdapter()->quoteInto('?', $data[$credentialColumn]).
', '.$this->getAdapter()->quoteInto('?', $salt).'))');
}
}
return $data;
} | php | protected function _hashPassword(array $data) {
$config = Zend_Registry::get('config');
if (!empty($config->auth->adapters->db)) {
$authVars = $config->auth->adapters->db;
$credentialColumn = $authVars->credentialColumn;
$hashMethod = $authVars->hashMethod;
$salt = $authVars->salt;
if (!empty($data[$credentialColumn])) {
$data[$credentialColumn] = new Zend_Db_Expr($hashMethod.'(CONCAT('.
$this->getAdapter()->quoteInto('?', $data[$credentialColumn]).
', '.$this->getAdapter()->quoteInto('?', $salt).'))');
}
}
return $data;
} | [
"protected",
"function",
"_hashPassword",
"(",
"array",
"$",
"data",
")",
"{",
"$",
"config",
"=",
"Zend_Registry",
"::",
"get",
"(",
"'config'",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"config",
"->",
"auth",
"->",
"adapters",
"->",
"db",
")",
... | Hash an incoming password
@param Array $data The new userdata
@return Array The modified userdata | [
"Hash",
"an",
"incoming",
"password"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Db/AuthLocal.php#L89-L103 | train |
grrr-amsterdam/garp3 | library/Garp/Controller/Helper/Cache.php | Garp_Controller_Helper_Cache.setCacheHeaders | public function setCacheHeaders($expirationTimeInSeconds = 300) {
$expirationString = strtotime("+{$expirationTimeInSeconds} seconds");
$gmtDate = gmdate(DATE_RFC1123, $expirationString);
$this->getResponse()
->setHeader('Cache-Control', 'public', true)
->setHeader('Pragma', 'cache', true)
->setHeader('Expires', $gmtDate, true);
} | php | public function setCacheHeaders($expirationTimeInSeconds = 300) {
$expirationString = strtotime("+{$expirationTimeInSeconds} seconds");
$gmtDate = gmdate(DATE_RFC1123, $expirationString);
$this->getResponse()
->setHeader('Cache-Control', 'public', true)
->setHeader('Pragma', 'cache', true)
->setHeader('Expires', $gmtDate, true);
} | [
"public",
"function",
"setCacheHeaders",
"(",
"$",
"expirationTimeInSeconds",
"=",
"300",
")",
"{",
"$",
"expirationString",
"=",
"strtotime",
"(",
"\"+{$expirationTimeInSeconds} seconds\"",
")",
";",
"$",
"gmtDate",
"=",
"gmdate",
"(",
"DATE_RFC1123",
",",
"$",
"... | Sets the required HTTP headers to specify an expiration time.
@param int $expirationTimeInSeconds
@return void | [
"Sets",
"the",
"required",
"HTTP",
"headers",
"to",
"specify",
"an",
"expiration",
"time",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Controller/Helper/Cache.php#L32-L40 | train |
grrr-amsterdam/garp3 | library/Garp/Controller/Helper/Cache.php | Garp_Controller_Helper_Cache.setNoCacheHeaders | public function setNoCacheHeaders(Zend_Controller_Response_Http $response) {
$this->getResponse()
->setHeader('Cache-Control', 'no-cache', true)
->setHeader('Pragma', 'no-cache', true)
->setHeader('Expires', date(DATE_RFC1123, strtotime('-1 year')), true);
} | php | public function setNoCacheHeaders(Zend_Controller_Response_Http $response) {
$this->getResponse()
->setHeader('Cache-Control', 'no-cache', true)
->setHeader('Pragma', 'no-cache', true)
->setHeader('Expires', date(DATE_RFC1123, strtotime('-1 year')), true);
} | [
"public",
"function",
"setNoCacheHeaders",
"(",
"Zend_Controller_Response_Http",
"$",
"response",
")",
"{",
"$",
"this",
"->",
"getResponse",
"(",
")",
"->",
"setHeader",
"(",
"'Cache-Control'",
",",
"'no-cache'",
",",
"true",
")",
"->",
"setHeader",
"(",
"'Prag... | Sets the required HTTP headers to prevent this request from being cached by the browser.
@param Zend_Controller_Response_Http $response The HTTP response object.
Use $this->getResponse() from a controller.
@return void | [
"Sets",
"the",
"required",
"HTTP",
"headers",
"to",
"prevent",
"this",
"request",
"from",
"being",
"cached",
"by",
"the",
"browser",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Controller/Helper/Cache.php#L49-L54 | train |
grrr-amsterdam/garp3 | library/Garp/Controller/Helper/Cache.php | Garp_Controller_Helper_Cache.preDispatch | public function preDispatch() {
if ($this->getResponse()->isRedirect() || !$this->isEnabled() || $this->_requestUriTooLong()
) {
return true;
}
return parent::preDispatch();
} | php | public function preDispatch() {
if ($this->getResponse()->isRedirect() || !$this->isEnabled() || $this->_requestUriTooLong()
) {
return true;
}
return parent::preDispatch();
} | [
"public",
"function",
"preDispatch",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"getResponse",
"(",
")",
"->",
"isRedirect",
"(",
")",
"||",
"!",
"$",
"this",
"->",
"isEnabled",
"(",
")",
"||",
"$",
"this",
"->",
"_requestUriTooLong",
"(",
")",
")"... | Commence page caching for any cacheable actions
@return void | [
"Commence",
"page",
"caching",
"for",
"any",
"cacheable",
"actions"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Controller/Helper/Cache.php#L75-L81 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Db/User.php | Garp_Model_Db_User.fetchUserForSession | public function fetchUserForSession($userId) {
$select = $this->select()
->from($this->getName(), Garp_Auth::getInstance()->getSessionColumns())
->where('id = ?', $userId);
return $this->fetchRow($select);
} | php | public function fetchUserForSession($userId) {
$select = $this->select()
->from($this->getName(), Garp_Auth::getInstance()->getSessionColumns())
->where('id = ?', $userId);
return $this->fetchRow($select);
} | [
"public",
"function",
"fetchUserForSession",
"(",
"$",
"userId",
")",
"{",
"$",
"select",
"=",
"$",
"this",
"->",
"select",
"(",
")",
"->",
"from",
"(",
"$",
"this",
"->",
"getName",
"(",
")",
",",
"Garp_Auth",
"::",
"getInstance",
"(",
")",
"->",
"g... | Grab only session columns by userid
@param int $userId
@return Garp_Db_Table_Row | [
"Grab",
"only",
"session",
"columns",
"by",
"userid"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Db/User.php#L50-L55 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Db/User.php | Garp_Model_Db_User.updateUserWithActivationCode | public function updateUserWithActivationCode($userId, $activationCode, $activationExpiry) {
$authVars = Garp_Auth::getInstance()->getConfigValues('forgotpassword');
$expiresColumn = $authVars['activation_code_expiration_date_column'];
$tokenColumn = $authVars['activation_token_column'];
$quotedUserId = $this->getAdapter()->quote($userId);
return $this->update(
array(
$expiresColumn => $activationExpiry,
$tokenColumn => $activationCode
), "id = $quotedUserId"
);
} | php | public function updateUserWithActivationCode($userId, $activationCode, $activationExpiry) {
$authVars = Garp_Auth::getInstance()->getConfigValues('forgotpassword');
$expiresColumn = $authVars['activation_code_expiration_date_column'];
$tokenColumn = $authVars['activation_token_column'];
$quotedUserId = $this->getAdapter()->quote($userId);
return $this->update(
array(
$expiresColumn => $activationExpiry,
$tokenColumn => $activationCode
), "id = $quotedUserId"
);
} | [
"public",
"function",
"updateUserWithActivationCode",
"(",
"$",
"userId",
",",
"$",
"activationCode",
",",
"$",
"activationExpiry",
")",
"{",
"$",
"authVars",
"=",
"Garp_Auth",
"::",
"getInstance",
"(",
")",
"->",
"getConfigValues",
"(",
"'forgotpassword'",
")",
... | Update user with activation code and expire time.
Used when forgot password
@param int $userId
@param string $activationCode
@param string $activationExpiry
@return int updated rows | [
"Update",
"user",
"with",
"activation",
"code",
"and",
"expire",
"time",
".",
"Used",
"when",
"forgot",
"password"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Db/User.php#L66-L78 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Db/User.php | Garp_Model_Db_User._onEmailChange | protected function _onEmailChange($email, $updateOrInsert = 'insert') {
$authVars = Garp_Auth::getInstance()->getConfigValues('validateemail');
// See if validation of email is enabled
if (empty($authVars['enabled']) || !$authVars['enabled']) {
return;
}
$validationTokenColumn = $authVars['token_column'];
$emailValidColumn = $authVars['email_valid_column'];
// Fetch fresh user data by email
$users = $this->fetchAll(
$this->select()->from(
$this->getName(),
array('id', 'email', $validationTokenColumn, $emailValidColumn)
)
->where('email = ?', $email)
);
// Generate validation token for all the found users
foreach ($users as $user) {
$this->invalidateEmailAddress($user, $updateOrInsert);
}
} | php | protected function _onEmailChange($email, $updateOrInsert = 'insert') {
$authVars = Garp_Auth::getInstance()->getConfigValues('validateemail');
// See if validation of email is enabled
if (empty($authVars['enabled']) || !$authVars['enabled']) {
return;
}
$validationTokenColumn = $authVars['token_column'];
$emailValidColumn = $authVars['email_valid_column'];
// Fetch fresh user data by email
$users = $this->fetchAll(
$this->select()->from(
$this->getName(),
array('id', 'email', $validationTokenColumn, $emailValidColumn)
)
->where('email = ?', $email)
);
// Generate validation token for all the found users
foreach ($users as $user) {
$this->invalidateEmailAddress($user, $updateOrInsert);
}
} | [
"protected",
"function",
"_onEmailChange",
"(",
"$",
"email",
",",
"$",
"updateOrInsert",
"=",
"'insert'",
")",
"{",
"$",
"authVars",
"=",
"Garp_Auth",
"::",
"getInstance",
"(",
")",
"->",
"getConfigValues",
"(",
"'validateemail'",
")",
";",
"// See if validatio... | Respond to change in email address
@param String $email The new email address
@param String $updateOrInsert Wether this was caused by an insert or an update
@return Void | [
"Respond",
"to",
"change",
"in",
"email",
"address"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Db/User.php#L264-L287 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Db/User.php | Garp_Model_Db_User.invalidateEmailAddress | public function invalidateEmailAddress(Garp_Db_Table_Row $user, $updateOrInsert = 'insert') {
$authVars = Garp_Auth::getInstance()->getConfigValues('validateemail');
$validationTokenColumn = $authVars['token_column'];
$emailValidColumn = $authVars['email_valid_column'];
if ($updateOrInsert == 'insert' && array_get($user, $emailValidColumn)) {
return true;
}
// Generate the validation code
$validationToken = uniqid();
$validationCode = $this->generateEmailValidationCode($user, $validationToken);
if (!$user->isConnected()) {
$user->setTable($this);
}
// Store the token in the user record
$user->{$validationTokenColumn} = $validationToken;
// Invalidate the user's email
$user->{$emailValidColumn} = 0;
if ($user->save()) {
return $this->sendEmailValidationEmail($user, $validationCode, $updateOrInsert);
}
return false;
} | php | public function invalidateEmailAddress(Garp_Db_Table_Row $user, $updateOrInsert = 'insert') {
$authVars = Garp_Auth::getInstance()->getConfigValues('validateemail');
$validationTokenColumn = $authVars['token_column'];
$emailValidColumn = $authVars['email_valid_column'];
if ($updateOrInsert == 'insert' && array_get($user, $emailValidColumn)) {
return true;
}
// Generate the validation code
$validationToken = uniqid();
$validationCode = $this->generateEmailValidationCode($user, $validationToken);
if (!$user->isConnected()) {
$user->setTable($this);
}
// Store the token in the user record
$user->{$validationTokenColumn} = $validationToken;
// Invalidate the user's email
$user->{$emailValidColumn} = 0;
if ($user->save()) {
return $this->sendEmailValidationEmail($user, $validationCode, $updateOrInsert);
}
return false;
} | [
"public",
"function",
"invalidateEmailAddress",
"(",
"Garp_Db_Table_Row",
"$",
"user",
",",
"$",
"updateOrInsert",
"=",
"'insert'",
")",
"{",
"$",
"authVars",
"=",
"Garp_Auth",
"::",
"getInstance",
"(",
")",
"->",
"getConfigValues",
"(",
"'validateemail'",
")",
... | Start the email validation procedure
@param Garp_Db_Table_Row $user
@param String $updateOrInsert Wether this was caused by an insert or an update
@return Boolean Wether the procedure succeeded | [
"Start",
"the",
"email",
"validation",
"procedure"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Db/User.php#L296-L322 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Db/User.php | Garp_Model_Db_User.generateEmailValidationCode | public function generateEmailValidationCode(Garp_Db_Table_Row $user, $validationToken) {
$authVars = Garp_Auth::getInstance()->getConfigValues();
$validationCode = '';
$validationCode .= $validationToken;
$validationCode .= md5($user->email);
$validationCode .= md5($authVars['salt']);
$validationCode .= md5($user->id);
$validationCode = md5($validationCode);
return $validationCode;
} | php | public function generateEmailValidationCode(Garp_Db_Table_Row $user, $validationToken) {
$authVars = Garp_Auth::getInstance()->getConfigValues();
$validationCode = '';
$validationCode .= $validationToken;
$validationCode .= md5($user->email);
$validationCode .= md5($authVars['salt']);
$validationCode .= md5($user->id);
$validationCode = md5($validationCode);
return $validationCode;
} | [
"public",
"function",
"generateEmailValidationCode",
"(",
"Garp_Db_Table_Row",
"$",
"user",
",",
"$",
"validationToken",
")",
"{",
"$",
"authVars",
"=",
"Garp_Auth",
"::",
"getInstance",
"(",
")",
"->",
"getConfigValues",
"(",
")",
";",
"$",
"validationCode",
"=... | Generate unique email validation code for a user
@param Garp_Db_Table_Row $user
@param String $validationToken Unique random value
@return String | [
"Generate",
"unique",
"email",
"validation",
"code",
"for",
"a",
"user"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Db/User.php#L331-L341 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Db/User.php | Garp_Model_Db_User.sendEmailValidationEmail | public function sendEmailValidationEmail(
Garp_Db_Table_Row $user, $code, $updateOrInsert = 'insert'
) {
$authVars = Garp_Auth::getInstance()->getConfigValues('validateemail');
// Render the email message
$activationUrl = '/g/auth/validateemail/c/' . $code . '/e/' . md5($user->email) . '/';
if (!empty($authVars['email_partial'])) {
$view = Zend_Registry::get('application')->getBootstrap()
->getResource('view');
$emailMessage = $view->partial(
$authVars['email_partial'], 'default', array(
'user' => $user,
'activationUrl' => $activationUrl,
'updateOrInsert' => $updateOrInsert
)
);
$messageParam = 'htmlMessage';
} else {
$snippetId = 'validate email ';
$snippetId .= $updateOrInsert == 'insert' ? 'new user' : 'existing user';
$snippetId .= ' email';
$emailMessage = __($snippetId);
$emailMessage = Garp_Util_String::interpolate(
$emailMessage, array(
'USERNAME' => (string)new Garp_Util_FullName($user),
'ACTIVATION_URL' => (string)new Garp_Util_FullUrl($activationUrl)
)
);
$messageParam = 'message';
}
$mailer = new Garp_Mailer();
return $mailer->send(
array(
'to' => $user->email,
'subject' => __($authVars['email_subject']),
$messageParam => $emailMessage
)
);
} | php | public function sendEmailValidationEmail(
Garp_Db_Table_Row $user, $code, $updateOrInsert = 'insert'
) {
$authVars = Garp_Auth::getInstance()->getConfigValues('validateemail');
// Render the email message
$activationUrl = '/g/auth/validateemail/c/' . $code . '/e/' . md5($user->email) . '/';
if (!empty($authVars['email_partial'])) {
$view = Zend_Registry::get('application')->getBootstrap()
->getResource('view');
$emailMessage = $view->partial(
$authVars['email_partial'], 'default', array(
'user' => $user,
'activationUrl' => $activationUrl,
'updateOrInsert' => $updateOrInsert
)
);
$messageParam = 'htmlMessage';
} else {
$snippetId = 'validate email ';
$snippetId .= $updateOrInsert == 'insert' ? 'new user' : 'existing user';
$snippetId .= ' email';
$emailMessage = __($snippetId);
$emailMessage = Garp_Util_String::interpolate(
$emailMessage, array(
'USERNAME' => (string)new Garp_Util_FullName($user),
'ACTIVATION_URL' => (string)new Garp_Util_FullUrl($activationUrl)
)
);
$messageParam = 'message';
}
$mailer = new Garp_Mailer();
return $mailer->send(
array(
'to' => $user->email,
'subject' => __($authVars['email_subject']),
$messageParam => $emailMessage
)
);
} | [
"public",
"function",
"sendEmailValidationEmail",
"(",
"Garp_Db_Table_Row",
"$",
"user",
",",
"$",
"code",
",",
"$",
"updateOrInsert",
"=",
"'insert'",
")",
"{",
"$",
"authVars",
"=",
"Garp_Auth",
"::",
"getInstance",
"(",
")",
"->",
"getConfigValues",
"(",
"'... | Send validation email to the user
@param Garp_Db_Table_Row $user The user
@param String $code The validation code
@param String $updateOrInsert Wether this was caused by an insert or an update
@return Boolean | [
"Send",
"validation",
"email",
"to",
"the",
"user"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Db/User.php#L351-L393 | train |
grrr-amsterdam/garp3 | library/Garp/Cli/Command/Slugs.php | Garp_Cli_Command_Slugs.generate | public function generate(array $args = array()) {
if (empty($args)) {
$this->help();
return false;
}
$modelName = $args[0];
if (strpos($modelName, '_') === false) {
$modelName = 'Model_' . $modelName;
}
$overwrite = !empty($args[1]) ? $args[1] : false;
$model = new $modelName();
// No reason to cache queries. Use live data.
$model->setCacheQueries(false);
// Fetch Sluggable thru the model as to use the right slug-configuration
list($sluggable, $model) = $this->_resolveSluggableBehavior($model);
if (is_null($sluggable)) {
Garp_Cli::errorOut('This model is not sluggable.');
return false;
}
// Array to record fails
$fails = array();
$records = $model->fetchAll();
foreach ($records as $record) {
if (!$overwrite && $record->slug) {
continue;
}
// Mimic a beforeInsert to create the slug in a separate array $data
$args = array($model, $record->toArray());
$sluggable->beforeInsert($args);
// Since there might be more than one changed column, we use this loop
// to append those columns to the record
foreach ($args[1] as $key => $value) {
if ($value != $record->{$key}) {
$record->{$key} = $value;
}
}
// Save the record with its slug
if (!$record->save()) {
$pk = implode(', ', (array)$record->getPrimaryKey());
$fails[] = $pk;
}
}
Garp_Cli::lineOut('Done.');
if (count($fails)) {
Garp_Cli::errorOut(
'There were some failures. ' .
'Please perform a manual check on records with the following primary keys:'
);
Garp_Cli::lineOut(implode("\n-", $fails));
}
return true;
} | php | public function generate(array $args = array()) {
if (empty($args)) {
$this->help();
return false;
}
$modelName = $args[0];
if (strpos($modelName, '_') === false) {
$modelName = 'Model_' . $modelName;
}
$overwrite = !empty($args[1]) ? $args[1] : false;
$model = new $modelName();
// No reason to cache queries. Use live data.
$model->setCacheQueries(false);
// Fetch Sluggable thru the model as to use the right slug-configuration
list($sluggable, $model) = $this->_resolveSluggableBehavior($model);
if (is_null($sluggable)) {
Garp_Cli::errorOut('This model is not sluggable.');
return false;
}
// Array to record fails
$fails = array();
$records = $model->fetchAll();
foreach ($records as $record) {
if (!$overwrite && $record->slug) {
continue;
}
// Mimic a beforeInsert to create the slug in a separate array $data
$args = array($model, $record->toArray());
$sluggable->beforeInsert($args);
// Since there might be more than one changed column, we use this loop
// to append those columns to the record
foreach ($args[1] as $key => $value) {
if ($value != $record->{$key}) {
$record->{$key} = $value;
}
}
// Save the record with its slug
if (!$record->save()) {
$pk = implode(', ', (array)$record->getPrimaryKey());
$fails[] = $pk;
}
}
Garp_Cli::lineOut('Done.');
if (count($fails)) {
Garp_Cli::errorOut(
'There were some failures. ' .
'Please perform a manual check on records with the following primary keys:'
);
Garp_Cli::lineOut(implode("\n-", $fails));
}
return true;
} | [
"public",
"function",
"generate",
"(",
"array",
"$",
"args",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"args",
")",
")",
"{",
"$",
"this",
"->",
"help",
"(",
")",
";",
"return",
"false",
";",
"}",
"$",
"modelName",
"=",
"$... | Generate the slugs
@param array $args
@return bool | [
"Generate",
"the",
"slugs"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cli/Command/Slugs.php#L16-L73 | train |
grrr-amsterdam/garp3 | library/Garp/File/Storage/S3.php | Garp_File_Storage_S3.getList | public function getList(): array {
$this->_verifyPath();
// strip off preceding slash, add trailing one.
$path = substr($this->_config['path'], 1) . '/';
return $this->_getApi()->listObjects([
'Bucket' => $this->_config['bucket'],
'Prefix' => $path
])->get('Contents');
} | php | public function getList(): array {
$this->_verifyPath();
// strip off preceding slash, add trailing one.
$path = substr($this->_config['path'], 1) . '/';
return $this->_getApi()->listObjects([
'Bucket' => $this->_config['bucket'],
'Prefix' => $path
])->get('Contents');
} | [
"public",
"function",
"getList",
"(",
")",
":",
"array",
"{",
"$",
"this",
"->",
"_verifyPath",
"(",
")",
";",
"// strip off preceding slash, add trailing one.",
"$",
"path",
"=",
"substr",
"(",
"$",
"this",
"->",
"_config",
"[",
"'path'",
"]",
",",
"1",
"... | Lists all files in the upload directory.
@return array | [
"Lists",
"all",
"files",
"in",
"the",
"upload",
"directory",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/File/Storage/S3.php#L104-L113 | train |
grrr-amsterdam/garp3 | library/Garp/File/Storage/S3.php | Garp_File_Storage_S3._getUri | protected function _getUri($filename): string {
$this->_verifyPath();
// Note: AWS SDK does not want the URI to start with a slash, as opposed to the old Zend
// Framework implementation.
$path = trim($this->_config['path'], '/');
return $path . '/' . $filename;
} | php | protected function _getUri($filename): string {
$this->_verifyPath();
// Note: AWS SDK does not want the URI to start with a slash, as opposed to the old Zend
// Framework implementation.
$path = trim($this->_config['path'], '/');
return $path . '/' . $filename;
} | [
"protected",
"function",
"_getUri",
"(",
"$",
"filename",
")",
":",
"string",
"{",
"$",
"this",
"->",
"_verifyPath",
"(",
")",
";",
"// Note: AWS SDK does not want the URI to start with a slash, as opposed to the old Zend",
"// Framework implementation.",
"$",
"path",
"=",
... | Returns the uri for internal Zend_Service_Amazon_S3 use.
@param string $filename
@return string | [
"Returns",
"the",
"uri",
"for",
"internal",
"Zend_Service_Amazon_S3",
"use",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/File/Storage/S3.php#L235-L241 | train |
grrr-amsterdam/garp3 | library/Garp/Image/File.php | Garp_Image_File.show | public function show($path, $timestamp = null, $mime = null) {
$headers = function_exists('apache_request_headers') ?
apache_request_headers() :
array();
if (is_null($timestamp))
$timestamp = $this->_readTimestampFromFile($path);
if (is_null($mime)) {
$mime = $this->_readMimeTypeFromFile($path);
}
header("Content-Type: $mime");
header("Cache-Control: maxage=".(24*60*60).', must-revalidate'); //In seconds
header("Pragma: public");
// Checking if the client is validating his cache and if it is current.
if (
isset($headers['If-Modified-Since']) &&
strtotime($headers['If-Modified-Since']) == $timestamp
) {
// Client's cache IS current, so we just respond '304 Not Modified'.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $timestamp).' GMT', true, 304);
} else {
// Image not cached or cache outdated, we respond '200 OK' and output the image.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $timestamp).' GMT', true, 200);
header('Content-Length: '.filesize($path));
$resource = fopen($path, 'rb');
rewind($resource);
fpassthru($resource);
fclose($resource);
}
} | php | public function show($path, $timestamp = null, $mime = null) {
$headers = function_exists('apache_request_headers') ?
apache_request_headers() :
array();
if (is_null($timestamp))
$timestamp = $this->_readTimestampFromFile($path);
if (is_null($mime)) {
$mime = $this->_readMimeTypeFromFile($path);
}
header("Content-Type: $mime");
header("Cache-Control: maxage=".(24*60*60).', must-revalidate'); //In seconds
header("Pragma: public");
// Checking if the client is validating his cache and if it is current.
if (
isset($headers['If-Modified-Since']) &&
strtotime($headers['If-Modified-Since']) == $timestamp
) {
// Client's cache IS current, so we just respond '304 Not Modified'.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $timestamp).' GMT', true, 304);
} else {
// Image not cached or cache outdated, we respond '200 OK' and output the image.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $timestamp).' GMT', true, 200);
header('Content-Length: '.filesize($path));
$resource = fopen($path, 'rb');
rewind($resource);
fpassthru($resource);
fclose($resource);
}
} | [
"public",
"function",
"show",
"(",
"$",
"path",
",",
"$",
"timestamp",
"=",
"null",
",",
"$",
"mime",
"=",
"null",
")",
"{",
"$",
"headers",
"=",
"function_exists",
"(",
"'apache_request_headers'",
")",
"?",
"apache_request_headers",
"(",
")",
":",
"array"... | Lets the browser render an image file
@param String $path The path to the image file
@param String $timestamp Cache timestamp - if not provided, this will have to be found out (at the cost of disk access)
@param String $mime The image mimetype - if not provided, this will have to be found out (at the cost of disk access)
@return Void | [
"Lets",
"the",
"browser",
"render",
"an",
"image",
"file"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Image/File.php#L51-L82 | train |
grrr-amsterdam/garp3 | library/Garp/Controller/Helper/Download.php | Garp_Controller_Helper_Download.force | public function force($bytes, $filename, Zend_Controller_Response_Abstract $response) {
if (!strlen($bytes)) {
$response->setBody('Sorry, we could not find the requested file.');
} else {
// Disable view and layout rendering
Zend_Controller_Action_HelperBroker::getExistingHelper('viewRenderer')->setNoRender();
Zend_Controller_Action_HelperBroker::getExistingHelper('layout')->disableLayout();
// Process the download
$this->_setHeaders($bytes, $filename, $response);
$response->setBody($bytes);
}
} | php | public function force($bytes, $filename, Zend_Controller_Response_Abstract $response) {
if (!strlen($bytes)) {
$response->setBody('Sorry, we could not find the requested file.');
} else {
// Disable view and layout rendering
Zend_Controller_Action_HelperBroker::getExistingHelper('viewRenderer')->setNoRender();
Zend_Controller_Action_HelperBroker::getExistingHelper('layout')->disableLayout();
// Process the download
$this->_setHeaders($bytes, $filename, $response);
$response->setBody($bytes);
}
} | [
"public",
"function",
"force",
"(",
"$",
"bytes",
",",
"$",
"filename",
",",
"Zend_Controller_Response_Abstract",
"$",
"response",
")",
"{",
"if",
"(",
"!",
"strlen",
"(",
"$",
"bytes",
")",
")",
"{",
"$",
"response",
"->",
"setBody",
"(",
"'Sorry, we coul... | Force download dialog
@param String $bytes The bytes that are to be downloaded
@param String $filename The filename of the downloaded file
@param Zend_Controller_Response_Abstract $response The response object
@return Void | [
"Force",
"download",
"dialog"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Controller/Helper/Download.php#L22-L34 | train |
grrr-amsterdam/garp3 | library/Garp/Controller/Helper/Download.php | Garp_Controller_Helper_Download._setHeaders | protected function _setHeaders($bytes, $filename, Zend_Controller_Response_Abstract $response) {
// fix for IE catching or PHP bug issue
$response->setHeader('Pragma', 'public');
// set expiration time
$response->setHeader('Expires', '0');
// browser must download file from server instead of cache
$response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
// force download dialog
$response->setHeader('Content-Type', 'application/octet-stream');
// use the Content-Disposition header to supply a recommended filename and
// force the browser to display the save dialog.
$response->setHeader(
'Content-Disposition',
'attachment; filename="'.basename($filename).'"'
);
/*
The Content-transfer-encoding header should be binary, since the file will be read
directly from the disk and the raw bytes passed to the downloading computer.
The Content-length header is useful to set for downloads. The browser will be able to
show a progress meter as a file downloads. The content-length can be determined by
filesize function returns the size of a file.
*/
$response->setHeader('Content-Transfer-Encoding', 'binary');
$response->setHeader('Content-Length', strlen($bytes));
} | php | protected function _setHeaders($bytes, $filename, Zend_Controller_Response_Abstract $response) {
// fix for IE catching or PHP bug issue
$response->setHeader('Pragma', 'public');
// set expiration time
$response->setHeader('Expires', '0');
// browser must download file from server instead of cache
$response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
// force download dialog
$response->setHeader('Content-Type', 'application/octet-stream');
// use the Content-Disposition header to supply a recommended filename and
// force the browser to display the save dialog.
$response->setHeader(
'Content-Disposition',
'attachment; filename="'.basename($filename).'"'
);
/*
The Content-transfer-encoding header should be binary, since the file will be read
directly from the disk and the raw bytes passed to the downloading computer.
The Content-length header is useful to set for downloads. The browser will be able to
show a progress meter as a file downloads. The content-length can be determined by
filesize function returns the size of a file.
*/
$response->setHeader('Content-Transfer-Encoding', 'binary');
$response->setHeader('Content-Length', strlen($bytes));
} | [
"protected",
"function",
"_setHeaders",
"(",
"$",
"bytes",
",",
"$",
"filename",
",",
"Zend_Controller_Response_Abstract",
"$",
"response",
")",
"{",
"// fix for IE catching or PHP bug issue",
"$",
"response",
"->",
"setHeader",
"(",
"'Pragma'",
",",
"'public'",
")",
... | Set the neccessary headers for forcing the download dialog
@param String $bytes The bytes that are to be downloaded
@param String $filename The filename of the downloaded file
@param Zend_Controller_Response_Abstract $response The response object
@return Void | [
"Set",
"the",
"neccessary",
"headers",
"for",
"forcing",
"the",
"download",
"dialog"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Controller/Helper/Download.php#L45-L72 | train |
grrr-amsterdam/garp3 | application/modules/g/views/helpers/Social.php | G_View_Helper_Social.tweetUrl | public function tweetUrl($msg, $shortenUrls = false) {
$url = 'http://twitter.com/?status=';
if ($shortenUrls) {
$msg = preg_replace_callback(
'~https?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?~i',
function ($matches) {
$_this = new G_View_Helper_Social();
return $_this->tinyUrl($matches[0]);
},
$msg
);
}
$url .= urlencode($msg);
return $url;
} | php | public function tweetUrl($msg, $shortenUrls = false) {
$url = 'http://twitter.com/?status=';
if ($shortenUrls) {
$msg = preg_replace_callback(
'~https?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?~i',
function ($matches) {
$_this = new G_View_Helper_Social();
return $_this->tinyUrl($matches[0]);
},
$msg
);
}
$url .= urlencode($msg);
return $url;
} | [
"public",
"function",
"tweetUrl",
"(",
"$",
"msg",
",",
"$",
"shortenUrls",
"=",
"false",
")",
"{",
"$",
"url",
"=",
"'http://twitter.com/?status='",
";",
"if",
"(",
"$",
"shortenUrls",
")",
"{",
"$",
"msg",
"=",
"preg_replace_callback",
"(",
"'~https?://([\... | Generate a "Tweet this!" URL.
Note that the status is automatically cut off at 140 characters.
@param string $msg The tweet
@param bool $shortenUrls Wether to shorten the URLs
@return string | [
"Generate",
"a",
"Tweet",
"this!",
"URL",
".",
"Note",
"that",
"the",
"status",
"is",
"automatically",
"cut",
"off",
"at",
"140",
"characters",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/Social.php#L40-L54 | train |
grrr-amsterdam/garp3 | application/modules/g/views/helpers/Social.php | G_View_Helper_Social.tweetButton | public function tweetButton(array $params = array()) {
$params = new Garp_Util_Configuration($params);
$params->setDefault('url', null)
->setDefault('text', null)
->setDefault('via', null)
->setDefault('related', null)
->setDefault('lang', null)
->setDefault('count', 'horizontal')
->setDefault('loadScript', true);
// set required parameters
$attributes = array(
'class' => 'twitter-share-button',
'data-count' => $params['count']
);
// set optional attributes
$params['url'] && $attributes['data-url'] = $params['url'];
$params['text'] && $attributes['data-text'] = $params['text'];
$params['via'] && $attributes['data-via'] = $params['via'];
$params['related'] && $attributes['data-related'] = $params['related'];
$params['lang'] && $attributes['data-lang'] = $params['lang'];
$html = $this->view->htmlLink(
'http://twitter.com/share',
'Tweet',
$attributes
);
if ($params['loadScript']) {
// Add the Twitter Javascript to the stack
// Must be rendered in the view using "$this->script()->render()"
$this->view->script()->src('http://platform.twitter.com/widgets.js');
}
return $html;
} | php | public function tweetButton(array $params = array()) {
$params = new Garp_Util_Configuration($params);
$params->setDefault('url', null)
->setDefault('text', null)
->setDefault('via', null)
->setDefault('related', null)
->setDefault('lang', null)
->setDefault('count', 'horizontal')
->setDefault('loadScript', true);
// set required parameters
$attributes = array(
'class' => 'twitter-share-button',
'data-count' => $params['count']
);
// set optional attributes
$params['url'] && $attributes['data-url'] = $params['url'];
$params['text'] && $attributes['data-text'] = $params['text'];
$params['via'] && $attributes['data-via'] = $params['via'];
$params['related'] && $attributes['data-related'] = $params['related'];
$params['lang'] && $attributes['data-lang'] = $params['lang'];
$html = $this->view->htmlLink(
'http://twitter.com/share',
'Tweet',
$attributes
);
if ($params['loadScript']) {
// Add the Twitter Javascript to the stack
// Must be rendered in the view using "$this->script()->render()"
$this->view->script()->src('http://platform.twitter.com/widgets.js');
}
return $html;
} | [
"public",
"function",
"tweetButton",
"(",
"array",
"$",
"params",
"=",
"array",
"(",
")",
")",
"{",
"$",
"params",
"=",
"new",
"Garp_Util_Configuration",
"(",
"$",
"params",
")",
";",
"$",
"params",
"->",
"setDefault",
"(",
"'url'",
",",
"null",
")",
"... | Create a Tweet button.
@param array $params
@return string
@see http://twitter.com/about/resources/tweetbutton | [
"Create",
"a",
"Tweet",
"button",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/Social.php#L87-L122 | train |
grrr-amsterdam/garp3 | application/modules/g/views/helpers/Social.php | G_View_Helper_Social.hyvesTipUrl | public function hyvesTipUrl($title, $body, $categoryId = 12, $rating = 5) {
$url = 'http://www.hyves-share.nl/button/tip/?tipcategoryid=%s&rating=%s&title=%s&body=%s';
$title = $title;
$body = $body;
return sprintf($url, $categoryId, $rating, $title, $body);
} | php | public function hyvesTipUrl($title, $body, $categoryId = 12, $rating = 5) {
$url = 'http://www.hyves-share.nl/button/tip/?tipcategoryid=%s&rating=%s&title=%s&body=%s';
$title = $title;
$body = $body;
return sprintf($url, $categoryId, $rating, $title, $body);
} | [
"public",
"function",
"hyvesTipUrl",
"(",
"$",
"title",
",",
"$",
"body",
",",
"$",
"categoryId",
"=",
"12",
",",
"$",
"rating",
"=",
"5",
")",
"{",
"$",
"url",
"=",
"'http://www.hyves-share.nl/button/tip/?tipcategoryid=%s&rating=%s&title=%s&body=%s'",
";",
"$",
... | Generate a Hyves "Smart button" URL.
@param string $title
@param string $body
@param int $categoryId
@param int $rating
@return string | [
"Generate",
"a",
"Hyves",
"Smart",
"button",
"URL",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/Social.php#L133-L139 | train |
grrr-amsterdam/garp3 | application/modules/g/views/helpers/Social.php | G_View_Helper_Social.facebookShareUrl | public function facebookShareUrl($url = null, $text = null) {
$shareUrl = is_null($url) ? $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] : $url;
$url = 'http://facebook.com/sharer.php?u=' . urlencode($shareUrl);
if (!is_null($text)) {
$url .= '&t=' . $text;
}
return $url;
} | php | public function facebookShareUrl($url = null, $text = null) {
$shareUrl = is_null($url) ? $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] : $url;
$url = 'http://facebook.com/sharer.php?u=' . urlencode($shareUrl);
if (!is_null($text)) {
$url .= '&t=' . $text;
}
return $url;
} | [
"public",
"function",
"facebookShareUrl",
"(",
"$",
"url",
"=",
"null",
",",
"$",
"text",
"=",
"null",
")",
"{",
"$",
"shareUrl",
"=",
"is_null",
"(",
"$",
"url",
")",
"?",
"$",
"_SERVER",
"[",
"'HTTP_HOST'",
"]",
".",
"$",
"_SERVER",
"[",
"'REQUEST_... | Generate a Facebook share URL
@param string $url Defaults to $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
@param string $text
@return string | [
"Generate",
"a",
"Facebook",
"share",
"URL"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/Social.php#L192-L199 | train |
grrr-amsterdam/garp3 | application/modules/g/views/helpers/Social.php | G_View_Helper_Social.facebookComments | public function facebookComments(array $params = array()) {
$this->_needsFacebookInit = true;
$params = new Garp_Util_Configuration($params);
$params->setDefault(
'href',
array_key_exists('href', $params) && $params['href'] ?
$params['href'] :
$this->view->fullUrl($this->view->url())
)
->setDefault('width', 400) /* Minimum recommended width: 400 */
->setDefault('num_posts', 10)
->setDefault('colorscheme', 'light');
$html = '<fb:comments ' . $this->_renderHtmlAttribs($params) . '></fb:comments>';
return $html;
} | php | public function facebookComments(array $params = array()) {
$this->_needsFacebookInit = true;
$params = new Garp_Util_Configuration($params);
$params->setDefault(
'href',
array_key_exists('href', $params) && $params['href'] ?
$params['href'] :
$this->view->fullUrl($this->view->url())
)
->setDefault('width', 400) /* Minimum recommended width: 400 */
->setDefault('num_posts', 10)
->setDefault('colorscheme', 'light');
$html = '<fb:comments ' . $this->_renderHtmlAttribs($params) . '></fb:comments>';
return $html;
} | [
"public",
"function",
"facebookComments",
"(",
"array",
"$",
"params",
"=",
"array",
"(",
")",
")",
"{",
"$",
"this",
"->",
"_needsFacebookInit",
"=",
"true",
";",
"$",
"params",
"=",
"new",
"Garp_Util_Configuration",
"(",
"$",
"params",
")",
";",
"$",
"... | Display Facebook comments widget
@param array $params Various Facebook URL parameters
@return string | [
"Display",
"Facebook",
"comments",
"widget"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/Social.php#L254-L269 | train |
grrr-amsterdam/garp3 | application/modules/g/views/helpers/Social.php | G_View_Helper_Social.facebookFacepile | public function facebookFacepile(array $params = array(), $useFacebookPageAsUrl = false) {
$this->_needsFacebookInit = true;
$params = new Garp_Util_Configuration($params);
$params->setDefault(
'href', array_key_exists('href', $params) && $params['href'] ?
$params['href'] :
$this->_getCurrentUrl()
)
->setDefault('max_rows', 1)
->setDefault('width', 450)
->setDefault('colorscheme', 'light');
if ($useFacebookPageAsUrl) {
$this->_setFacebookPageUrlAsHref($params);
}
$html = '<fb:facepile ' . $this->_renderHtmlAttribs($params) . '></fb:facepile>';
return $html;
} | php | public function facebookFacepile(array $params = array(), $useFacebookPageAsUrl = false) {
$this->_needsFacebookInit = true;
$params = new Garp_Util_Configuration($params);
$params->setDefault(
'href', array_key_exists('href', $params) && $params['href'] ?
$params['href'] :
$this->_getCurrentUrl()
)
->setDefault('max_rows', 1)
->setDefault('width', 450)
->setDefault('colorscheme', 'light');
if ($useFacebookPageAsUrl) {
$this->_setFacebookPageUrlAsHref($params);
}
$html = '<fb:facepile ' . $this->_renderHtmlAttribs($params) . '></fb:facepile>';
return $html;
} | [
"public",
"function",
"facebookFacepile",
"(",
"array",
"$",
"params",
"=",
"array",
"(",
")",
",",
"$",
"useFacebookPageAsUrl",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"_needsFacebookInit",
"=",
"true",
";",
"$",
"params",
"=",
"new",
"Garp_Util_Configur... | Generate a Facebook facepile.
@param array $params Various Facebook URL parameters
@param bool $useFacebookPageAsUrl
@return string | [
"Generate",
"a",
"Facebook",
"facepile",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/Social.php#L278-L296 | train |
grrr-amsterdam/garp3 | application/modules/g/views/helpers/Social.php | G_View_Helper_Social.linkedinShareButton | public function linkedinShareButton(array $params = array()) {
$html = '<script type="in/share" ';
if (!empty($params['url'])) {
$html .= 'data-url="' . $this->view->escape($params['url']) . '" ';
}
if (!empty($params['counter'])) {
$html .= 'data-counter="' . $this->view->escape($params['counter']) . '" ';
}
$html .= '></script>';
// Add the LinkedIn Javascript to the stack
// Must be rendered in the view using "$this->script()->render()"
$this->view->script()->src('http://platform.linkedin.com/in.js');
return $html;
} | php | public function linkedinShareButton(array $params = array()) {
$html = '<script type="in/share" ';
if (!empty($params['url'])) {
$html .= 'data-url="' . $this->view->escape($params['url']) . '" ';
}
if (!empty($params['counter'])) {
$html .= 'data-counter="' . $this->view->escape($params['counter']) . '" ';
}
$html .= '></script>';
// Add the LinkedIn Javascript to the stack
// Must be rendered in the view using "$this->script()->render()"
$this->view->script()->src('http://platform.linkedin.com/in.js');
return $html;
} | [
"public",
"function",
"linkedinShareButton",
"(",
"array",
"$",
"params",
"=",
"array",
"(",
")",
")",
"{",
"$",
"html",
"=",
"'<script type=\"in/share\" '",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"params",
"[",
"'url'",
"]",
")",
")",
"{",
"$",
"html... | Generate a LinkedIn share button
@param array $params
@return string
@see http://www.linkedin.com/publishers | [
"Generate",
"a",
"LinkedIn",
"share",
"button"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/Social.php#L390-L404 | train |
grrr-amsterdam/garp3 | application/modules/g/views/helpers/Social.php | G_View_Helper_Social._getCurrentUrl | protected function _getCurrentUrl() {
$url = $this->view->fullUrl($this->view->url());
$quesPos = strpos($url, '?');
if ($quesPos !== false) {
$url = substr($url, 0, $quesPos);
}
return $url;
} | php | protected function _getCurrentUrl() {
$url = $this->view->fullUrl($this->view->url());
$quesPos = strpos($url, '?');
if ($quesPos !== false) {
$url = substr($url, 0, $quesPos);
}
return $url;
} | [
"protected",
"function",
"_getCurrentUrl",
"(",
")",
"{",
"$",
"url",
"=",
"$",
"this",
"->",
"view",
"->",
"fullUrl",
"(",
"$",
"this",
"->",
"view",
"->",
"url",
"(",
")",
")",
";",
"$",
"quesPos",
"=",
"strpos",
"(",
"$",
"url",
",",
"'?'",
")... | Returns current url, stripped of any possible url queries.
@return string | [
"Returns",
"current",
"url",
"stripped",
"of",
"any",
"possible",
"url",
"queries",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/Social.php#L431-L438 | train |
grrr-amsterdam/garp3 | application/modules/g/views/helpers/Social.php | G_View_Helper_Social._setFacebookPageUrlAsHref | protected function _setFacebookPageUrlAsHref(Garp_Util_Configuration $params) {
$ini = Zend_Registry::get('config');
if (!$ini->organization->facebook) {
throw new Exception("Missing url: organization.facebook in application.ini");
}
$params['href'] = $ini->organization->facebook;
} | php | protected function _setFacebookPageUrlAsHref(Garp_Util_Configuration $params) {
$ini = Zend_Registry::get('config');
if (!$ini->organization->facebook) {
throw new Exception("Missing url: organization.facebook in application.ini");
}
$params['href'] = $ini->organization->facebook;
} | [
"protected",
"function",
"_setFacebookPageUrlAsHref",
"(",
"Garp_Util_Configuration",
"$",
"params",
")",
"{",
"$",
"ini",
"=",
"Zend_Registry",
"::",
"get",
"(",
"'config'",
")",
";",
"if",
"(",
"!",
"$",
"ini",
"->",
"organization",
"->",
"facebook",
")",
... | Modify params by making the organization's Facebook page the href.
@param Garp_Util_Configuration $params
@return void | [
"Modify",
"params",
"by",
"making",
"the",
"organization",
"s",
"Facebook",
"page",
"the",
"href",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/views/helpers/Social.php#L460-L466 | train |
grrr-amsterdam/garp3 | library/Garp/Spawn/Config/Model/Base.php | Garp_Spawn_Config_Model_Base._addIdField | protected function _addIdField() {
$params = array(
'type' => 'numeric',
'editable' => false,
'visible' => false,
// next to being primary, an extra index key is also needed,
// to enable the flexibility to modify primary keys.
'index' => true
);
$params['primary'] = !$this->_primaryKeyFieldIsPresent();
$this['inputs'] = array('id' => $params) + $this['inputs'];
} | php | protected function _addIdField() {
$params = array(
'type' => 'numeric',
'editable' => false,
'visible' => false,
// next to being primary, an extra index key is also needed,
// to enable the flexibility to modify primary keys.
'index' => true
);
$params['primary'] = !$this->_primaryKeyFieldIsPresent();
$this['inputs'] = array('id' => $params) + $this['inputs'];
} | [
"protected",
"function",
"_addIdField",
"(",
")",
"{",
"$",
"params",
"=",
"array",
"(",
"'type'",
"=>",
"'numeric'",
",",
"'editable'",
"=>",
"false",
",",
"'visible'",
"=>",
"false",
",",
"// next to being primary, an extra index key is also needed,",
"// to enabl... | Adds an 'id' field to the model structure.
Make it the primary key if there is no other primary key defined yet. | [
"Adds",
"an",
"id",
"field",
"to",
"the",
"model",
"structure",
".",
"Make",
"it",
"the",
"primary",
"key",
"if",
"there",
"is",
"no",
"other",
"primary",
"key",
"defined",
"yet",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Spawn/Config/Model/Base.php#L32-L45 | train |
grrr-amsterdam/garp3 | library/Garp/Social/Facebook.php | Garp_Social_Facebook.mapFriends | public function mapFriends(array $config) {
$config = $config instanceof Garp_Util_Configuration ? $config : new Garp_Util_Configuration($config);
$config->obligate('bindingModel')
->obligate('user_id')
->setDefault('accessToken', $this->getAccessToken())
;
if (!$config['accessToken']) {
// Find the auth record
$authModel = new Model_AuthFacebook();
$authRow = $authModel->fetchRow($authModel->select()->where('user_id = ?', $config['user_id']));
if (!$authRow || !$authRow->access_token) {
return false;
}
// Use the stored access token to create a user session. Me() in the FQL ahead will contain the user's Facebook ID.
// Note that the access token is available for a very limited time. Chances are it's not valid anymore.
$accessToken = $authRow->access_token;
}
try {
$this->_client->setAccessToken($config['accessToken']);
// Find the friends' Facebook UIDs
$friends = $this->_client->api(array(
'method' => 'fql.query',
'query' => 'SELECT uid2 FROM friend WHERE uid1 = me()'
));
// Find local user records
$userModel = new Model_User();
$userTable = $userModel->getName();
$authFbModel = new Model_AuthFacebook();
$authFbTable = $authFbModel->getName();
$fbIds = '';
$friendCount = count($friends);
foreach ($friends as $i => $friend) {
$fbIds .= $userModel->getAdapter()->quote($friend['uid2']);
if ($i < ($friendCount-1)) {
$fbIds .= ',';
}
}
$friendQuery = $userModel->select()
->setIntegrityCheck(false)
->from($userTable, array('id'))
->join($authFbTable, $authFbTable.'.user_id = '.$userTable.'.id', array())
->where('facebook_uid IN ('.$fbIds.')')
->order($userTable.'.id')
;
$localUsers = $userModel->fetchAll($friendQuery);
$localUserCount = count($localUsers);
// Insert new friendships into binding model
$bindingModel = new $config['bindingModel'];
$insertSql = 'INSERT IGNORE INTO '.$bindingModel->getName().' (user1_id, user2_id) VALUES ';
foreach ($localUsers as $i => $localUser) {
$insertSql .= '('.$localUser->id.','.$config['user_id'].'),';
$insertSql .= '('.$config['user_id'].','.$localUser->id.')';
if ($i < ($localUserCount-1)) {
$insertSql .= ',';
}
}
$result = $bindingModel->getAdapter()->query($insertSql);
// Clear cache manually, since the table isn't updated thru conventional paths.
Garp_Cache_Manager::purge($bindingModel);
return !!$result;
} catch (Exception $e) {
return false;
}
} | php | public function mapFriends(array $config) {
$config = $config instanceof Garp_Util_Configuration ? $config : new Garp_Util_Configuration($config);
$config->obligate('bindingModel')
->obligate('user_id')
->setDefault('accessToken', $this->getAccessToken())
;
if (!$config['accessToken']) {
// Find the auth record
$authModel = new Model_AuthFacebook();
$authRow = $authModel->fetchRow($authModel->select()->where('user_id = ?', $config['user_id']));
if (!$authRow || !$authRow->access_token) {
return false;
}
// Use the stored access token to create a user session. Me() in the FQL ahead will contain the user's Facebook ID.
// Note that the access token is available for a very limited time. Chances are it's not valid anymore.
$accessToken = $authRow->access_token;
}
try {
$this->_client->setAccessToken($config['accessToken']);
// Find the friends' Facebook UIDs
$friends = $this->_client->api(array(
'method' => 'fql.query',
'query' => 'SELECT uid2 FROM friend WHERE uid1 = me()'
));
// Find local user records
$userModel = new Model_User();
$userTable = $userModel->getName();
$authFbModel = new Model_AuthFacebook();
$authFbTable = $authFbModel->getName();
$fbIds = '';
$friendCount = count($friends);
foreach ($friends as $i => $friend) {
$fbIds .= $userModel->getAdapter()->quote($friend['uid2']);
if ($i < ($friendCount-1)) {
$fbIds .= ',';
}
}
$friendQuery = $userModel->select()
->setIntegrityCheck(false)
->from($userTable, array('id'))
->join($authFbTable, $authFbTable.'.user_id = '.$userTable.'.id', array())
->where('facebook_uid IN ('.$fbIds.')')
->order($userTable.'.id')
;
$localUsers = $userModel->fetchAll($friendQuery);
$localUserCount = count($localUsers);
// Insert new friendships into binding model
$bindingModel = new $config['bindingModel'];
$insertSql = 'INSERT IGNORE INTO '.$bindingModel->getName().' (user1_id, user2_id) VALUES ';
foreach ($localUsers as $i => $localUser) {
$insertSql .= '('.$localUser->id.','.$config['user_id'].'),';
$insertSql .= '('.$config['user_id'].','.$localUser->id.')';
if ($i < ($localUserCount-1)) {
$insertSql .= ',';
}
}
$result = $bindingModel->getAdapter()->query($insertSql);
// Clear cache manually, since the table isn't updated thru conventional paths.
Garp_Cache_Manager::purge($bindingModel);
return !!$result;
} catch (Exception $e) {
return false;
}
} | [
"public",
"function",
"mapFriends",
"(",
"array",
"$",
"config",
")",
"{",
"$",
"config",
"=",
"$",
"config",
"instanceof",
"Garp_Util_Configuration",
"?",
"$",
"config",
":",
"new",
"Garp_Util_Configuration",
"(",
"$",
"config",
")",
";",
"$",
"config",
"->... | Find friends of logged in user and map to local friends table.
@param Array $config
@return Bool Success | [
"Find",
"friends",
"of",
"logged",
"in",
"user",
"and",
"map",
"to",
"local",
"friends",
"table",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Social/Facebook.php#L87-L156 | train |
grrr-amsterdam/garp3 | library/Garp/Social/Facebook.php | Garp_Social_Facebook._getClient | protected function _getClient(array $config) {
$ini = Zend_Registry::get('config');
$type = !empty($ini->store->type) ? $ini->store->type : 'Session';
if ($type == 'Cookie') {
return new Garp_Social_Facebook_Client($config);
} else {
require_once APPLICATION_PATH.'/../garp/library/Garp/3rdParty/facebook/src/facebook.php';
$facebook = new Facebook($config);
return $facebook;
}
} | php | protected function _getClient(array $config) {
$ini = Zend_Registry::get('config');
$type = !empty($ini->store->type) ? $ini->store->type : 'Session';
if ($type == 'Cookie') {
return new Garp_Social_Facebook_Client($config);
} else {
require_once APPLICATION_PATH.'/../garp/library/Garp/3rdParty/facebook/src/facebook.php';
$facebook = new Facebook($config);
return $facebook;
}
} | [
"protected",
"function",
"_getClient",
"(",
"array",
"$",
"config",
")",
"{",
"$",
"ini",
"=",
"Zend_Registry",
"::",
"get",
"(",
"'config'",
")",
";",
"$",
"type",
"=",
"!",
"empty",
"(",
"$",
"ini",
"->",
"store",
"->",
"type",
")",
"?",
"$",
"in... | Create Facebook SDK
@param Array $config
@return Facebook | [
"Create",
"Facebook",
"SDK"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Social/Facebook.php#L174-L184 | train |
grrr-amsterdam/garp3 | library/Garp/Cache/Store/Versioned.php | Garp_Cache_Store_Versioned.write | public function write($key, $data) {
$cache = Zend_Registry::get('CacheFrontend');
// include the current version in the cached results
$version = (int)$cache->load($this->_versionKey);
// save the data to cache but include the version number
return $cache->save(
array(
'data' => $data,
'version' => $version
),
$key
);
} | php | public function write($key, $data) {
$cache = Zend_Registry::get('CacheFrontend');
// include the current version in the cached results
$version = (int)$cache->load($this->_versionKey);
// save the data to cache but include the version number
return $cache->save(
array(
'data' => $data,
'version' => $version
),
$key
);
} | [
"public",
"function",
"write",
"(",
"$",
"key",
",",
"$",
"data",
")",
"{",
"$",
"cache",
"=",
"Zend_Registry",
"::",
"get",
"(",
"'CacheFrontend'",
")",
";",
"// include the current version in the cached results",
"$",
"version",
"=",
"(",
"int",
")",
"$",
... | Write data to cache
@param string $key The cache id
@param mixed $data Data
@return bool | [
"Write",
"data",
"to",
"cache"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cache/Store/Versioned.php#L36-L48 | train |
grrr-amsterdam/garp3 | library/Garp/Cache/Store/Versioned.php | Garp_Cache_Store_Versioned.read | public function read($key) {
$cache = Zend_Registry::get('CacheFrontend');
// fetch results from cache
if ($cache->test($key)) {
$results = $cache->load($key);
if (!is_array($results)) {
return -1;
}
$version = (int)$cache->load($this->_versionKey);
// compare version numbers
if (array_key_exists('version', $results) && (int)$results['version'] === $version) {
return $results['data'];
}
}
return -1;
} | php | public function read($key) {
$cache = Zend_Registry::get('CacheFrontend');
// fetch results from cache
if ($cache->test($key)) {
$results = $cache->load($key);
if (!is_array($results)) {
return -1;
}
$version = (int)$cache->load($this->_versionKey);
// compare version numbers
if (array_key_exists('version', $results) && (int)$results['version'] === $version) {
return $results['data'];
}
}
return -1;
} | [
"public",
"function",
"read",
"(",
"$",
"key",
")",
"{",
"$",
"cache",
"=",
"Zend_Registry",
"::",
"get",
"(",
"'CacheFrontend'",
")",
";",
"// fetch results from cache",
"if",
"(",
"$",
"cache",
"->",
"test",
"(",
"$",
"key",
")",
")",
"{",
"$",
"resu... | Read data from cache
@param string $key The cache id
@return mixed -1 if no valid cache is found. | [
"Read",
"data",
"from",
"cache"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cache/Store/Versioned.php#L57-L72 | train |
grrr-amsterdam/garp3 | library/Garp/Cache/Store/Versioned.php | Garp_Cache_Store_Versioned.incrementVersion | public function incrementVersion() {
$cache = Zend_Registry::get('CacheFrontend');
$version = (int)$cache->load($this->_versionKey);
$version += 1;
$cache->save($version, $this->_versionKey);
return $this;
} | php | public function incrementVersion() {
$cache = Zend_Registry::get('CacheFrontend');
$version = (int)$cache->load($this->_versionKey);
$version += 1;
$cache->save($version, $this->_versionKey);
return $this;
} | [
"public",
"function",
"incrementVersion",
"(",
")",
"{",
"$",
"cache",
"=",
"Zend_Registry",
"::",
"get",
"(",
"'CacheFrontend'",
")",
";",
"$",
"version",
"=",
"(",
"int",
")",
"$",
"cache",
"->",
"load",
"(",
"$",
"this",
"->",
"_versionKey",
")",
";... | Increment the cached version. This invalidates the current cached results.
@return Garp_Cache_Store_Versioned $this | [
"Increment",
"the",
"cached",
"version",
".",
"This",
"invalidates",
"the",
"current",
"cached",
"results",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cache/Store/Versioned.php#L79-L85 | train |
grrr-amsterdam/garp3 | library/Garp/Cache/Manager.php | Garp_Cache_Manager.readQueryCache | public static function readQueryCache(Garp_Model_Db $model, $key) {
$cache = new Garp_Cache_Store_Versioned($model->getName() . '_version');
return $cache->read($key);
} | php | public static function readQueryCache(Garp_Model_Db $model, $key) {
$cache = new Garp_Cache_Store_Versioned($model->getName() . '_version');
return $cache->read($key);
} | [
"public",
"static",
"function",
"readQueryCache",
"(",
"Garp_Model_Db",
"$",
"model",
",",
"$",
"key",
")",
"{",
"$",
"cache",
"=",
"new",
"Garp_Cache_Store_Versioned",
"(",
"$",
"model",
"->",
"getName",
"(",
")",
".",
"'_version'",
")",
";",
"return",
"$... | Read query cache
@param Garp_Model_Db $model
@param String $key
@return Mixed | [
"Read",
"query",
"cache"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cache/Manager.php#L18-L21 | train |
grrr-amsterdam/garp3 | library/Garp/Cache/Manager.php | Garp_Cache_Manager.writeQueryCache | public static function writeQueryCache(Garp_Model_Db $model, $key, $results) {
$cache = new Garp_Cache_Store_Versioned($model->getName() . '_version');
$cache->write($key, $results);
} | php | public static function writeQueryCache(Garp_Model_Db $model, $key, $results) {
$cache = new Garp_Cache_Store_Versioned($model->getName() . '_version');
$cache->write($key, $results);
} | [
"public",
"static",
"function",
"writeQueryCache",
"(",
"Garp_Model_Db",
"$",
"model",
",",
"$",
"key",
",",
"$",
"results",
")",
"{",
"$",
"cache",
"=",
"new",
"Garp_Cache_Store_Versioned",
"(",
"$",
"model",
"->",
"getName",
"(",
")",
".",
"'_version'",
... | Write query cache
@param Garp_Model_Db $model
@param String $key
@param Mixed $results
@return Void | [
"Write",
"query",
"cache"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cache/Manager.php#L31-L34 | train |
grrr-amsterdam/garp3 | library/Garp/Cache/Manager.php | Garp_Cache_Manager.purge | public static function purge($tags = array(), $createClusterJob = true, $cacheDir = false) {
$messageBag = array();
if ($tags instanceof Garp_Model_Db) {
$tags = self::getTagsFromModel($tags);
}
$clearOpcache = !empty($tags['opcache']);
unset($tags['opcache']);
$messageBag = self::purgeStaticCache($tags, $cacheDir, $messageBag);
$messageBag = self::purgeMemcachedCache($tags, $messageBag);
if ($clearOpcache) {
$messageBag = self::purgeOpcache($messageBag);
}
$ini = Zend_Registry::get('config');
if ($createClusterJob && $ini->app->clusteredHosting) {
Garp_Cache_Store_Cluster::createJob($tags);
$messageBag[] = 'Cluster: created clear cache job for cluster';
}
return $messageBag;
} | php | public static function purge($tags = array(), $createClusterJob = true, $cacheDir = false) {
$messageBag = array();
if ($tags instanceof Garp_Model_Db) {
$tags = self::getTagsFromModel($tags);
}
$clearOpcache = !empty($tags['opcache']);
unset($tags['opcache']);
$messageBag = self::purgeStaticCache($tags, $cacheDir, $messageBag);
$messageBag = self::purgeMemcachedCache($tags, $messageBag);
if ($clearOpcache) {
$messageBag = self::purgeOpcache($messageBag);
}
$ini = Zend_Registry::get('config');
if ($createClusterJob && $ini->app->clusteredHosting) {
Garp_Cache_Store_Cluster::createJob($tags);
$messageBag[] = 'Cluster: created clear cache job for cluster';
}
return $messageBag;
} | [
"public",
"static",
"function",
"purge",
"(",
"$",
"tags",
"=",
"array",
"(",
")",
",",
"$",
"createClusterJob",
"=",
"true",
",",
"$",
"cacheDir",
"=",
"false",
")",
"{",
"$",
"messageBag",
"=",
"array",
"(",
")",
";",
"if",
"(",
"$",
"tags",
"ins... | Purge all cache system wide
@param Array|Garp_Model_Db $tags
@param Boolean $createClusterJob Whether this purge should create a job to clear the other
nodes in this server cluster, if applicable.
@param String $cacheDir Directory which stores static HTML cache files.
@return Void | [
"Purge",
"all",
"cache",
"system",
"wide"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cache/Manager.php#L45-L69 | train |
grrr-amsterdam/garp3 | library/Garp/Cache/Manager.php | Garp_Cache_Manager.purgeMemcachedCache | public static function purgeMemcachedCache($modelNames = array(), $messageBag = array()) {
if (!Zend_Registry::isRegistered('CacheFrontend')) {
$messageBag[] = 'Memcached: No caching enabled';
return $messageBag;
}
if (!Zend_Registry::get('CacheFrontend')->getOption('caching')) {
$messageBag[] = 'Memcached: No caching enabled';
return $messageBag;;
}
if ($modelNames instanceof Garp_Model_Db) {
$modelNames = self::getTagsFromModel($modelNames);
}
if (empty($modelNames)) {
$cacheFront = Zend_Registry::get('CacheFrontend');
$cacheFront->clean(Zend_Cache::CLEANING_MODE_ALL);
$messageBag[] = 'Memcached: Purged All';
return $messageBag;
}
foreach ($modelNames as $modelName) {
$model = new $modelName();
self::_incrementMemcacheVersion($model);
if (!$model->getObserver('Translatable')) {
continue;
}
// Make sure cache is cleared for all languages.
$locales = Garp_I18n::getLocales();
foreach ($locales as $locale) {
try {
$modelFactory = new Garp_I18n_ModelFactory($locale);
$i18nModel = $modelFactory->getModel($model);
self::_incrementMemcacheVersion($i18nModel);
} catch (Garp_I18n_ModelFactory_Exception_ModelAlreadyLocalized $e) {
// all good in the hood 。^‿^。
}
}
}
$messageBag[] = 'Memcached: Purged all given models';
return $messageBag;
} | php | public static function purgeMemcachedCache($modelNames = array(), $messageBag = array()) {
if (!Zend_Registry::isRegistered('CacheFrontend')) {
$messageBag[] = 'Memcached: No caching enabled';
return $messageBag;
}
if (!Zend_Registry::get('CacheFrontend')->getOption('caching')) {
$messageBag[] = 'Memcached: No caching enabled';
return $messageBag;;
}
if ($modelNames instanceof Garp_Model_Db) {
$modelNames = self::getTagsFromModel($modelNames);
}
if (empty($modelNames)) {
$cacheFront = Zend_Registry::get('CacheFrontend');
$cacheFront->clean(Zend_Cache::CLEANING_MODE_ALL);
$messageBag[] = 'Memcached: Purged All';
return $messageBag;
}
foreach ($modelNames as $modelName) {
$model = new $modelName();
self::_incrementMemcacheVersion($model);
if (!$model->getObserver('Translatable')) {
continue;
}
// Make sure cache is cleared for all languages.
$locales = Garp_I18n::getLocales();
foreach ($locales as $locale) {
try {
$modelFactory = new Garp_I18n_ModelFactory($locale);
$i18nModel = $modelFactory->getModel($model);
self::_incrementMemcacheVersion($i18nModel);
} catch (Garp_I18n_ModelFactory_Exception_ModelAlreadyLocalized $e) {
// all good in the hood 。^‿^。
}
}
}
$messageBag[] = 'Memcached: Purged all given models';
return $messageBag;
} | [
"public",
"static",
"function",
"purgeMemcachedCache",
"(",
"$",
"modelNames",
"=",
"array",
"(",
")",
",",
"$",
"messageBag",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"!",
"Zend_Registry",
"::",
"isRegistered",
"(",
"'CacheFrontend'",
")",
")",
"{",
... | Clear the Memcached cache that stores queries and ini files and whatnot.
@param Array|Garp_Model_Db $modelNames
@param Array $messageBag
@return Void | [
"Clear",
"the",
"Memcached",
"cache",
"that",
"stores",
"queries",
"and",
"ini",
"files",
"and",
"whatnot",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cache/Manager.php#L78-L120 | train |
grrr-amsterdam/garp3 | library/Garp/Cache/Manager.php | Garp_Cache_Manager.purgeStaticCache | public static function purgeStaticCache($modelNames = array(), $cacheDir = false, $messageBag = array()) {
if (!Zend_Registry::get('CacheFrontend')->getOption('caching')) {
// caching is disabled (yes, this particular frontend is not in charge of static
// cache, but in practice this toggle is used to enable/disable caching globally, so
// this matches developer expectations better, probably)
$messageBag[] = 'Static cache: No caching enabled';
return $messageBag;
}
if ($modelNames instanceof Garp_Model_Db) {
$modelNames = self::getTagsFromModel($modelNames);
}
$cacheDir = $cacheDir ?: self::_getStaticCacheDir();
if (!$cacheDir) {
$messageBag[] = 'Static cache: No cache directory configured';
return $messageBag;
}
$cacheDir = str_replace(' ', '\ ', $cacheDir);
$cacheDir = rtrim($cacheDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
// Destroy all if no model names are given
if (empty($modelNames)) {
$allPath = $cacheDir . '*';
$response = self::_deleteStaticCacheFile($allPath);
$messageBag[] = $response
? 'Static cache: Deleted all static cache files'
: 'Static cache: There was a problem with deleting the static cache files';
return $messageBag;
}
// Fetch model names from configuration
if (!$tagList = self::_getTagList()) {
$messageBag[] = 'Static cache: No cache tags found';
return $messageBag;
}
$_purged = array();
foreach ($modelNames as $tag) {
if (!$tagList->{$tag}) {
continue;
}
foreach ($tagList->{$tag} as $path) {
while (strpos($path, '..') !== false) {
$path = str_replace('..', '.', $path);
}
$filePath = $cacheDir . $path;
// Keep track of purged paths, forget about duplicates
if (in_array($filePath, $_purged)) {
continue;
}
self::_deleteStaticCacheFile($filePath);
$_purged[] = $filePath;
}
}
$messageBag[] = 'Static cache: purged';
return $messageBag;
} | php | public static function purgeStaticCache($modelNames = array(), $cacheDir = false, $messageBag = array()) {
if (!Zend_Registry::get('CacheFrontend')->getOption('caching')) {
// caching is disabled (yes, this particular frontend is not in charge of static
// cache, but in practice this toggle is used to enable/disable caching globally, so
// this matches developer expectations better, probably)
$messageBag[] = 'Static cache: No caching enabled';
return $messageBag;
}
if ($modelNames instanceof Garp_Model_Db) {
$modelNames = self::getTagsFromModel($modelNames);
}
$cacheDir = $cacheDir ?: self::_getStaticCacheDir();
if (!$cacheDir) {
$messageBag[] = 'Static cache: No cache directory configured';
return $messageBag;
}
$cacheDir = str_replace(' ', '\ ', $cacheDir);
$cacheDir = rtrim($cacheDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
// Destroy all if no model names are given
if (empty($modelNames)) {
$allPath = $cacheDir . '*';
$response = self::_deleteStaticCacheFile($allPath);
$messageBag[] = $response
? 'Static cache: Deleted all static cache files'
: 'Static cache: There was a problem with deleting the static cache files';
return $messageBag;
}
// Fetch model names from configuration
if (!$tagList = self::_getTagList()) {
$messageBag[] = 'Static cache: No cache tags found';
return $messageBag;
}
$_purged = array();
foreach ($modelNames as $tag) {
if (!$tagList->{$tag}) {
continue;
}
foreach ($tagList->{$tag} as $path) {
while (strpos($path, '..') !== false) {
$path = str_replace('..', '.', $path);
}
$filePath = $cacheDir . $path;
// Keep track of purged paths, forget about duplicates
if (in_array($filePath, $_purged)) {
continue;
}
self::_deleteStaticCacheFile($filePath);
$_purged[] = $filePath;
}
}
$messageBag[] = 'Static cache: purged';
return $messageBag;
} | [
"public",
"static",
"function",
"purgeStaticCache",
"(",
"$",
"modelNames",
"=",
"array",
"(",
")",
",",
"$",
"cacheDir",
"=",
"false",
",",
"$",
"messageBag",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"!",
"Zend_Registry",
"::",
"get",
"(",
"'Cache... | This clears Zend's Static caching.
@param Array|Garp_Model_Db $modelNames Clear the cache of a specific bunch of models.
@param String $cacheDir Directory containing the cache files
@param Array $messageBag
@return Void | [
"This",
"clears",
"Zend",
"s",
"Static",
"caching",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cache/Manager.php#L130-L185 | train |
grrr-amsterdam/garp3 | library/Garp/Cache/Manager.php | Garp_Cache_Manager.purgeOpcache | public static function purgeOpcache($messageBag = array()) {
// This only clears the Opcache on CLI,
// which is often separate from the HTTP Opcache.
if (function_exists('opcache_reset')) {
opcache_reset();
$messageBag[] = 'OPCache: purged on the CLI';
}
if (function_exists('apc_clear_cache')) {
apc_clear_cache();
$messageBag[] = 'APC: purged on the CLI';
}
// Next, trigger the Opcache clear calls through HTTP.
$deployConfig = new Garp_Deploy_Config;
if (!$deployConfig->isConfigured(APPLICATION_ENV)) {
return $messageBag;
}
$hostName = Zend_Registry::get('config')->app->domain;
foreach (self::_getServerNames() as $serverName) {
$opcacheResetWithServerName = self::_resetOpcacheHttp($serverName, $hostName);
if ($opcacheResetWithServerName) {
$messageBag[] = "OPCache: http purged on `{$serverName}`";
}
if (!$opcacheResetWithServerName) {
$opcacheResetWithHostName = self::_resetOpcacheHttp($hostName, $hostName);
$messageBag[] = $opcacheResetWithHostName
? "OPCache: http purged on `{$hostName}`"
: "OPCache: failed purging OPCache in http context on `{$hostName}`";
}
}
return $messageBag;
} | php | public static function purgeOpcache($messageBag = array()) {
// This only clears the Opcache on CLI,
// which is often separate from the HTTP Opcache.
if (function_exists('opcache_reset')) {
opcache_reset();
$messageBag[] = 'OPCache: purged on the CLI';
}
if (function_exists('apc_clear_cache')) {
apc_clear_cache();
$messageBag[] = 'APC: purged on the CLI';
}
// Next, trigger the Opcache clear calls through HTTP.
$deployConfig = new Garp_Deploy_Config;
if (!$deployConfig->isConfigured(APPLICATION_ENV)) {
return $messageBag;
}
$hostName = Zend_Registry::get('config')->app->domain;
foreach (self::_getServerNames() as $serverName) {
$opcacheResetWithServerName = self::_resetOpcacheHttp($serverName, $hostName);
if ($opcacheResetWithServerName) {
$messageBag[] = "OPCache: http purged on `{$serverName}`";
}
if (!$opcacheResetWithServerName) {
$opcacheResetWithHostName = self::_resetOpcacheHttp($hostName, $hostName);
$messageBag[] = $opcacheResetWithHostName
? "OPCache: http purged on `{$hostName}`"
: "OPCache: failed purging OPCache in http context on `{$hostName}`";
}
}
return $messageBag;
} | [
"public",
"static",
"function",
"purgeOpcache",
"(",
"$",
"messageBag",
"=",
"array",
"(",
")",
")",
"{",
"// This only clears the Opcache on CLI,",
"// which is often separate from the HTTP Opcache.",
"if",
"(",
"function_exists",
"(",
"'opcache_reset'",
")",
")",
"{",
... | This clears the Opcache, and APC for legacy systems.
This reset can only be done with an http request.
@param Array $messageBag
@return Void | [
"This",
"clears",
"the",
"Opcache",
"and",
"APC",
"for",
"legacy",
"systems",
".",
"This",
"reset",
"can",
"only",
"be",
"done",
"with",
"an",
"http",
"request",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cache/Manager.php#L195-L228 | train |
grrr-amsterdam/garp3 | library/Garp/Cache/Manager.php | Garp_Cache_Manager.scheduleClear | public static function scheduleClear($timestamp, array $tags = array()) {
// Use ScheduledJob model if available, otherwise fall back to `at`
if (!class_exists('Model_ScheduledJob')) {
return static::createAtCommand($timestamp, $tags);
}
return static::createScheduledJob($timestamp, $tags);
} | php | public static function scheduleClear($timestamp, array $tags = array()) {
// Use ScheduledJob model if available, otherwise fall back to `at`
if (!class_exists('Model_ScheduledJob')) {
return static::createAtCommand($timestamp, $tags);
}
return static::createScheduledJob($timestamp, $tags);
} | [
"public",
"static",
"function",
"scheduleClear",
"(",
"$",
"timestamp",
",",
"array",
"$",
"tags",
"=",
"array",
"(",
")",
")",
"{",
"// Use ScheduledJob model if available, otherwise fall back to `at`",
"if",
"(",
"!",
"class_exists",
"(",
"'Model_ScheduledJob'",
")"... | Schedule a cache clear in the future.
@param Int $timestamp
@param Array $tags
@see Garp_Model_Behavior_Draftable for a likely pairing
@return Bool A guesstimate of wether the command has successfully been scheduled.
Note that it's hard to determine if this is true. I have, for instance,
not yet found a way to determine if the atrun daemon actually is active. | [
"Schedule",
"a",
"cache",
"clear",
"in",
"the",
"future",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cache/Manager.php#L281-L287 | train |
grrr-amsterdam/garp3 | library/Garp/Cache/Manager.php | Garp_Cache_Manager.getTagsFromModel | public static function getTagsFromModel(Garp_Model_Db $model) {
$tags = array(get_class($model));
foreach ($model->getBindableModels() as $modelName) {
if (!in_array($modelName, $tags)) {
$tags[] = $modelName;
}
}
return $tags;
} | php | public static function getTagsFromModel(Garp_Model_Db $model) {
$tags = array(get_class($model));
foreach ($model->getBindableModels() as $modelName) {
if (!in_array($modelName, $tags)) {
$tags[] = $modelName;
}
}
return $tags;
} | [
"public",
"static",
"function",
"getTagsFromModel",
"(",
"Garp_Model_Db",
"$",
"model",
")",
"{",
"$",
"tags",
"=",
"array",
"(",
"get_class",
"(",
"$",
"model",
")",
")",
";",
"foreach",
"(",
"$",
"model",
"->",
"getBindableModels",
"(",
")",
"as",
"$",... | Get cache tags used with a given model.
@param Garp_Model_Db $model
@return Array | [
"Get",
"cache",
"tags",
"used",
"with",
"a",
"given",
"model",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cache/Manager.php#L354-L362 | train |
grrr-amsterdam/garp3 | library/Garp/Cache/Manager.php | Garp_Cache_Manager._getStaticCacheDir | protected static function _getStaticCacheDir() {
$config = Zend_Registry::get('config');
if (!isset($config->resources->cacheManager->page->backend->options->public_dir)) {
return false;
}
return $config->resources->cacheManager->page->backend->options->public_dir;
/**
* Cache dir used to be read from the Front controller, which I would prefer under normal
* circumstances. But the front controller is not bootstrapped in CLI environment, so I've
* refactored to read from cache. I'm leaving this for future me to think about some more
*
* (full disclaimer: I'm probably never going to think about it anymore)
*
$front = Zend_Controller_Front::getInstance();
if (!$front->getParam('bootstrap')
|| !$front->getParam('bootstrap')->getResource('cachemanager')) {
Garp_Cli::errorOut('no bootstrap or whatever');
return false;
}
$cacheManager = $front->getParam('bootstrap')->getResource('cachemanager');
$cache = $cacheManager->getCache(Zend_Cache_Manager::PAGECACHE);
$cacheDir = $cache->getBackend()->getOption('public_dir');
return $cacheDir;
*/
} | php | protected static function _getStaticCacheDir() {
$config = Zend_Registry::get('config');
if (!isset($config->resources->cacheManager->page->backend->options->public_dir)) {
return false;
}
return $config->resources->cacheManager->page->backend->options->public_dir;
/**
* Cache dir used to be read from the Front controller, which I would prefer under normal
* circumstances. But the front controller is not bootstrapped in CLI environment, so I've
* refactored to read from cache. I'm leaving this for future me to think about some more
*
* (full disclaimer: I'm probably never going to think about it anymore)
*
$front = Zend_Controller_Front::getInstance();
if (!$front->getParam('bootstrap')
|| !$front->getParam('bootstrap')->getResource('cachemanager')) {
Garp_Cli::errorOut('no bootstrap or whatever');
return false;
}
$cacheManager = $front->getParam('bootstrap')->getResource('cachemanager');
$cache = $cacheManager->getCache(Zend_Cache_Manager::PAGECACHE);
$cacheDir = $cache->getBackend()->getOption('public_dir');
return $cacheDir;
*/
} | [
"protected",
"static",
"function",
"_getStaticCacheDir",
"(",
")",
"{",
"$",
"config",
"=",
"Zend_Registry",
"::",
"get",
"(",
"'config'",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"config",
"->",
"resources",
"->",
"cacheManager",
"->",
"page",
"->",
... | Fetch the cache directory for static caching
@return String | [
"Fetch",
"the",
"cache",
"directory",
"for",
"static",
"caching"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cache/Manager.php#L393-L418 | train |
grrr-amsterdam/garp3 | library/Garp/Cache/Manager.php | Garp_Cache_Manager._getTagList | protected static function _getTagList() {
$config = Zend_Registry::get('config');
if (!empty($config->staticcaching->tags)) {
return $config->staticcaching->tags;
}
// For backward-compatibility: fall back to a separate cache.ini
$ini = new Garp_Config_Ini(APPLICATION_PATH . '/configs/cache.ini', APPLICATION_ENV);
if (!empty($ini->tags)) {
return $ini->tags;
}
return null;
} | php | protected static function _getTagList() {
$config = Zend_Registry::get('config');
if (!empty($config->staticcaching->tags)) {
return $config->staticcaching->tags;
}
// For backward-compatibility: fall back to a separate cache.ini
$ini = new Garp_Config_Ini(APPLICATION_PATH . '/configs/cache.ini', APPLICATION_ENV);
if (!empty($ini->tags)) {
return $ini->tags;
}
return null;
} | [
"protected",
"static",
"function",
"_getTagList",
"(",
")",
"{",
"$",
"config",
"=",
"Zend_Registry",
"::",
"get",
"(",
"'config'",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"config",
"->",
"staticcaching",
"->",
"tags",
")",
")",
"{",
"return",
"$"... | Fetch mapping of available tags to file paths
@return Zend_Config | [
"Fetch",
"mapping",
"of",
"available",
"tags",
"to",
"file",
"paths"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cache/Manager.php#L425-L438 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Db/Info.php | Garp_Model_Db_Info.fetchAsConfig | public function fetchAsConfig(Zend_Db_Select $select = null, $env = APPLICATION_ENV) {
if (is_null($select)) {
$select = $this->select();
}
$results = $this->fetchAll($select);
$ini = $this->_createIniFromResults($results, $env);
return $ini;
} | php | public function fetchAsConfig(Zend_Db_Select $select = null, $env = APPLICATION_ENV) {
if (is_null($select)) {
$select = $this->select();
}
$results = $this->fetchAll($select);
$ini = $this->_createIniFromResults($results, $env);
return $ini;
} | [
"public",
"function",
"fetchAsConfig",
"(",
"Zend_Db_Select",
"$",
"select",
"=",
"null",
",",
"$",
"env",
"=",
"APPLICATION_ENV",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"select",
")",
")",
"{",
"$",
"select",
"=",
"$",
"this",
"->",
"select",
"(",
... | Fetch results and converts to Zend_Config object
@param Zend_Db_Select $select A select object to filter results
@param String $env Which application env to use
@return Zend_Config | [
"Fetch",
"results",
"and",
"converts",
"to",
"Zend_Config",
"object"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Db/Info.php#L27-L35 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Db/Info.php | Garp_Model_Db_Info._createIniFromResults | protected function _createIniFromResults($results, $env) {
// Create a parse_ini_string() compatible string.
$ini = "[$env]\n";
foreach ($results as $result) {
$keyValue = "{$result->key} = \"{$result->value}\"\n";
$ini .= $keyValue;
}
$iniObj = Garp_Config_Ini::fromString($ini);
return $iniObj;
} | php | protected function _createIniFromResults($results, $env) {
// Create a parse_ini_string() compatible string.
$ini = "[$env]\n";
foreach ($results as $result) {
$keyValue = "{$result->key} = \"{$result->value}\"\n";
$ini .= $keyValue;
}
$iniObj = Garp_Config_Ini::fromString($ini);
return $iniObj;
} | [
"protected",
"function",
"_createIniFromResults",
"(",
"$",
"results",
",",
"$",
"env",
")",
"{",
"// Create a parse_ini_string() compatible string.",
"$",
"ini",
"=",
"\"[$env]\\n\"",
";",
"foreach",
"(",
"$",
"results",
"as",
"$",
"result",
")",
"{",
"$",
"key... | Create a Zend_Config instance from database results
@param Zend_Db_Table_Rowset $results
@param Array $config The array that's recursively filled with the right keys
@return Zend_Config | [
"Create",
"a",
"Zend_Config",
"instance",
"from",
"database",
"results"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Db/Info.php#L44-L54 | train |
grrr-amsterdam/garp3 | library/Garp/Cli/Command/Log.php | Garp_Cli_Command_Log.clean | public function clean(array $args = array()) {
// Resolve parameters
$logRoot = array_get($args, 'root', APPLICATION_PATH . '/data/logs');
$pattern = array_get($args, 'pattern', '/\.log$/i');
$threshold = array_get($args, 'threshold', '1 month ago');
$verbose = array_get($args, 'verbose', false);
$count = 0;
$leanOut = '';
$verboseOut = '';
if ($handle = opendir($logRoot)) {
while (false !== ($entry = readdir($handle))) {
$isLogFile = preg_match($pattern, $entry);
$isTooOld = filemtime($logRoot . '/' . $entry) < strtotime($threshold);
if ($isLogFile && $isTooOld) {
@unlink($logRoot . '/' . $entry);
++$count;
$verboseOut .= " - $entry\n";
}
}
$leanOut = "$count log files successfully removed";
$verboseOut = $leanOut . ":\n" . $verboseOut;
closedir($handle);
}
if ($count) {
if ($verbose) {
Garp_Cli::lineOut($verboseOut);
} else {
Garp_Cli::lineOut($leanOut);
}
} else {
Garp_Cli::lineOut('No log files matched the given criteria.');
}
return true;
} | php | public function clean(array $args = array()) {
// Resolve parameters
$logRoot = array_get($args, 'root', APPLICATION_PATH . '/data/logs');
$pattern = array_get($args, 'pattern', '/\.log$/i');
$threshold = array_get($args, 'threshold', '1 month ago');
$verbose = array_get($args, 'verbose', false);
$count = 0;
$leanOut = '';
$verboseOut = '';
if ($handle = opendir($logRoot)) {
while (false !== ($entry = readdir($handle))) {
$isLogFile = preg_match($pattern, $entry);
$isTooOld = filemtime($logRoot . '/' . $entry) < strtotime($threshold);
if ($isLogFile && $isTooOld) {
@unlink($logRoot . '/' . $entry);
++$count;
$verboseOut .= " - $entry\n";
}
}
$leanOut = "$count log files successfully removed";
$verboseOut = $leanOut . ":\n" . $verboseOut;
closedir($handle);
}
if ($count) {
if ($verbose) {
Garp_Cli::lineOut($verboseOut);
} else {
Garp_Cli::lineOut($leanOut);
}
} else {
Garp_Cli::lineOut('No log files matched the given criteria.');
}
return true;
} | [
"public",
"function",
"clean",
"(",
"array",
"$",
"args",
"=",
"array",
"(",
")",
")",
"{",
"// Resolve parameters",
"$",
"logRoot",
"=",
"array_get",
"(",
"$",
"args",
",",
"'root'",
",",
"APPLICATION_PATH",
".",
"'/data/logs'",
")",
";",
"$",
"pattern",
... | Cleanup log files
@param array $args
@return bool | [
"Cleanup",
"log",
"files"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cli/Command/Log.php#L33-L69 | train |
grrr-amsterdam/garp3 | library/Garp/Image/PngQuant.php | Garp_Image_PngQuant.optimizeData | public function optimizeData($data) {
if (!$this->isPngData($data)) {
return $data;
}
// store data in a temporary file to feed pngquant
$sourcePath = $this->_getNewTempFilePath();
$this->_store($sourcePath, $data);
// run pngquant on temporary file
$this->_createOptimizedFile($sourcePath);
// retrieve data from optimized file
$optimizedFilePath = $this->_getOptimizedFilePath($sourcePath);
$optimizedData = $this->_fetchFileData($optimizedFilePath);
// verify data
$this->_verifyData($optimizedData);
unlink($sourcePath);
unlink($optimizedFilePath);
return $optimizedData;
} | php | public function optimizeData($data) {
if (!$this->isPngData($data)) {
return $data;
}
// store data in a temporary file to feed pngquant
$sourcePath = $this->_getNewTempFilePath();
$this->_store($sourcePath, $data);
// run pngquant on temporary file
$this->_createOptimizedFile($sourcePath);
// retrieve data from optimized file
$optimizedFilePath = $this->_getOptimizedFilePath($sourcePath);
$optimizedData = $this->_fetchFileData($optimizedFilePath);
// verify data
$this->_verifyData($optimizedData);
unlink($sourcePath);
unlink($optimizedFilePath);
return $optimizedData;
} | [
"public",
"function",
"optimizeData",
"(",
"$",
"data",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isPngData",
"(",
"$",
"data",
")",
")",
"{",
"return",
"$",
"data",
";",
"}",
"// store data in a temporary file to feed pngquant",
"$",
"sourcePath",
"=",... | Optimizes PNG data. If this is not a PNG, the original data is returned.
@param String $data Binary image data
@return String $data Optimized binary image data | [
"Optimizes",
"PNG",
"data",
".",
"If",
"this",
"is",
"not",
"a",
"PNG",
"the",
"original",
"data",
"is",
"returned",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Image/PngQuant.php#L12-L35 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/Bitlyable.php | Garp_Model_Behavior_Bitlyable.beforeUpdate | public function beforeUpdate(array &$args) {
$model = $args[0];
$data = &$args[1];
$where = $args[2];
// When updating, it's quite possible {$this->_column} is not in $data.
// If so, collect it live.
if (empty($data[$this->_column])) {
$row = $model->fetchRow($where);
if ($row->{$this->_column}) {
$data[$this->_column] = $row->{$this->_column};
}
}
$this->_setBitlyUrl($data);
} | php | public function beforeUpdate(array &$args) {
$model = $args[0];
$data = &$args[1];
$where = $args[2];
// When updating, it's quite possible {$this->_column} is not in $data.
// If so, collect it live.
if (empty($data[$this->_column])) {
$row = $model->fetchRow($where);
if ($row->{$this->_column}) {
$data[$this->_column] = $row->{$this->_column};
}
}
$this->_setBitlyUrl($data);
} | [
"public",
"function",
"beforeUpdate",
"(",
"array",
"&",
"$",
"args",
")",
"{",
"$",
"model",
"=",
"$",
"args",
"[",
"0",
"]",
";",
"$",
"data",
"=",
"&",
"$",
"args",
"[",
"1",
"]",
";",
"$",
"where",
"=",
"$",
"args",
"[",
"2",
"]",
";",
... | Before update callback
@param Array $args
#return Void | [
"Before",
"update",
"callback"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/Bitlyable.php#L79-L93 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/Bitlyable.php | Garp_Model_Behavior_Bitlyable._setBitlyUrl | protected function _setBitlyUrl(array &$data) {
if (!empty($data[$this->_column])) {
$bitly = new Garp_Service_Bitly();
$view = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getResource('view');
$url = sprintf($this->_url, $data[$this->_column]);
$response = $bitly->shorten(array(
'longUrl' => $view->fullUrl($url)
));
if ($response['status_code'] == 200) {
$shortenedUrl = $response['data']['url'];
$data[$this->_targetColumn] = $shortenedUrl;
}
}
} | php | protected function _setBitlyUrl(array &$data) {
if (!empty($data[$this->_column])) {
$bitly = new Garp_Service_Bitly();
$view = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getResource('view');
$url = sprintf($this->_url, $data[$this->_column]);
$response = $bitly->shorten(array(
'longUrl' => $view->fullUrl($url)
));
if ($response['status_code'] == 200) {
$shortenedUrl = $response['data']['url'];
$data[$this->_targetColumn] = $shortenedUrl;
}
}
} | [
"protected",
"function",
"_setBitlyUrl",
"(",
"array",
"&",
"$",
"data",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"data",
"[",
"$",
"this",
"->",
"_column",
"]",
")",
")",
"{",
"$",
"bitly",
"=",
"new",
"Garp_Service_Bitly",
"(",
")",
";",
"$",... | Set Bit.ly URL
@param Array $data Record data passed to an update or insert call
@return Void | [
"Set",
"Bit",
".",
"ly",
"URL"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/Bitlyable.php#L101-L114 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/AuthController.php | G_AuthController.resetpasswordAction | public function resetpasswordAction() {
$this->view->title = __('reset password page title');
$authVars = Garp_Auth::getInstance()->getConfigValues();
$activationCode = $this->getRequest()->getParam('c');
$activationEmail = $this->getRequest()->getParam('e');
$expirationColumn = $authVars['forgotpassword']['activation_code_expiration_date_column'];
$userModel = new Model_User();
$activationCodeClause = 'MD5(CONCAT(' .
$userModel->getAdapter()->quoteIdentifier(
$authVars['forgotpassword']['activation_token_column']
) . ',' .
'MD5(email),' .
'MD5(' . $userModel->getAdapter()->quote($authVars['salt']) . '),' .
'MD5(id)' .
')) = ?'
;
$select = $userModel->select()
// check if a user matches up to the given code
->where($activationCodeClause, $activationCode)
// check if the given email address is part of the same user record
->where('MD5(email) = ?', $activationEmail);
$user = $userModel->fetchRow($select);
if (!$user) {
$this->view->error = __('reset password user not found');
return;
}
if (strtotime($user->{$expirationColumn}) < time()) {
$this->view->error = __('reset password link expired');
return;
}
if (!$this->getRequest()->isPost()) {
return;
}
$password = $this->getRequest()->getPost('password');
if (!$password) {
$this->view->formError = sprintf(__('%s is a required field'), ucfirst(__('password')));
return;
}
if (!empty($authVars['forgotpassword']['repeatPassword'])
&& !empty($authVars['forgotpassword']['repeatPasswordField'])
) {
$repeatPasswordField = $this->getRequest()->getPost(
$authVars['forgotpassword']['repeatPasswordField']
);
if ($password != $repeatPasswordField) {
$this->view->formError = __('the passwords do not match');
return;
}
}
// Update the user's password and send him along to the login page
$updateClause = $userModel->getAdapter()->quoteInto('id = ?', $user->id);
$userModel->update(
array(
'password' => $password,
$authVars['forgotpassword']['activation_token_column'] => null,
$authVars['forgotpassword']['activation_code_expiration_date_column'] => null
), $updateClause
);
$this->_helper->flashMessenger(__($authVars['resetpassword']['success_message']));
$this->_redirect('/g/auth/login');
} | php | public function resetpasswordAction() {
$this->view->title = __('reset password page title');
$authVars = Garp_Auth::getInstance()->getConfigValues();
$activationCode = $this->getRequest()->getParam('c');
$activationEmail = $this->getRequest()->getParam('e');
$expirationColumn = $authVars['forgotpassword']['activation_code_expiration_date_column'];
$userModel = new Model_User();
$activationCodeClause = 'MD5(CONCAT(' .
$userModel->getAdapter()->quoteIdentifier(
$authVars['forgotpassword']['activation_token_column']
) . ',' .
'MD5(email),' .
'MD5(' . $userModel->getAdapter()->quote($authVars['salt']) . '),' .
'MD5(id)' .
')) = ?'
;
$select = $userModel->select()
// check if a user matches up to the given code
->where($activationCodeClause, $activationCode)
// check if the given email address is part of the same user record
->where('MD5(email) = ?', $activationEmail);
$user = $userModel->fetchRow($select);
if (!$user) {
$this->view->error = __('reset password user not found');
return;
}
if (strtotime($user->{$expirationColumn}) < time()) {
$this->view->error = __('reset password link expired');
return;
}
if (!$this->getRequest()->isPost()) {
return;
}
$password = $this->getRequest()->getPost('password');
if (!$password) {
$this->view->formError = sprintf(__('%s is a required field'), ucfirst(__('password')));
return;
}
if (!empty($authVars['forgotpassword']['repeatPassword'])
&& !empty($authVars['forgotpassword']['repeatPasswordField'])
) {
$repeatPasswordField = $this->getRequest()->getPost(
$authVars['forgotpassword']['repeatPasswordField']
);
if ($password != $repeatPasswordField) {
$this->view->formError = __('the passwords do not match');
return;
}
}
// Update the user's password and send him along to the login page
$updateClause = $userModel->getAdapter()->quoteInto('id = ?', $user->id);
$userModel->update(
array(
'password' => $password,
$authVars['forgotpassword']['activation_token_column'] => null,
$authVars['forgotpassword']['activation_code_expiration_date_column'] => null
), $updateClause
);
$this->_helper->flashMessenger(__($authVars['resetpassword']['success_message']));
$this->_redirect('/g/auth/login');
} | [
"public",
"function",
"resetpasswordAction",
"(",
")",
"{",
"$",
"this",
"->",
"view",
"->",
"title",
"=",
"__",
"(",
"'reset password page title'",
")",
";",
"$",
"authVars",
"=",
"Garp_Auth",
"::",
"getInstance",
"(",
")",
"->",
"getConfigValues",
"(",
")"... | Allow a user to reset his password after he had forgotten it.
@return void | [
"Allow",
"a",
"user",
"to",
"reset",
"his",
"password",
"after",
"he",
"had",
"forgotten",
"it",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/AuthController.php#L355-L419 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/AuthController.php | G_AuthController.validateemailAction | public function validateemailAction() {
$this->view->title = __('activate email page title');
$auth = Garp_Auth::getInstance();
$authVars = $auth->getConfigValues();
$request = $this->getRequest();
$activationCode = $request->getParam('c');
$activationEmail = $request->getParam('e');
$emailValidColumn = $authVars['validateemail']['email_valid_column'];
if (!$activationEmail || !$activationCode) {
throw new Zend_Controller_Action_Exception('Invalid request.', 404);
}
$userModel = new Model_User();
// always collect fresh data for this one
$userModel->setCacheQueries(false);
$activationCodeClause = 'MD5(CONCAT(' .
$userModel->getAdapter()->quoteIdentifier(
$authVars['validateemail']['token_column']
) . ',' .
'MD5(email),' .
'MD5(' . $userModel->getAdapter()->quote($authVars['salt']) . '),' .
'MD5(id)' .
')) = ?'
;
$select = $userModel->select()
// check if a user matches up to the given code
->where($activationCodeClause, $activationCode)
// check if the given email address is part of the same user record
->where('MD5(email) = ?', $activationEmail);
$user = $userModel->fetchRow($select);
if (!$user) {
$this->view->error = __('invalid email activation code');
} else {
$user->{$emailValidColumn} = 1;
if (!$user->save()) {
$this->view->error = __('activate email error');
} elseif ($auth->isLoggedIn()) {
// If the user is currently logged in, update the cookie
$method = $auth->getStore()->method;
$userData = $auth->getUserData();
// Sanity check: is the user that has just validated his email address
// the currently logged in user?
if ($userData['id'] == $user->id) {
$userData[$emailValidColumn] = 1;
$auth->store($userData, $method);
}
}
$this->view->user = $user;
}
} | php | public function validateemailAction() {
$this->view->title = __('activate email page title');
$auth = Garp_Auth::getInstance();
$authVars = $auth->getConfigValues();
$request = $this->getRequest();
$activationCode = $request->getParam('c');
$activationEmail = $request->getParam('e');
$emailValidColumn = $authVars['validateemail']['email_valid_column'];
if (!$activationEmail || !$activationCode) {
throw new Zend_Controller_Action_Exception('Invalid request.', 404);
}
$userModel = new Model_User();
// always collect fresh data for this one
$userModel->setCacheQueries(false);
$activationCodeClause = 'MD5(CONCAT(' .
$userModel->getAdapter()->quoteIdentifier(
$authVars['validateemail']['token_column']
) . ',' .
'MD5(email),' .
'MD5(' . $userModel->getAdapter()->quote($authVars['salt']) . '),' .
'MD5(id)' .
')) = ?'
;
$select = $userModel->select()
// check if a user matches up to the given code
->where($activationCodeClause, $activationCode)
// check if the given email address is part of the same user record
->where('MD5(email) = ?', $activationEmail);
$user = $userModel->fetchRow($select);
if (!$user) {
$this->view->error = __('invalid email activation code');
} else {
$user->{$emailValidColumn} = 1;
if (!$user->save()) {
$this->view->error = __('activate email error');
} elseif ($auth->isLoggedIn()) {
// If the user is currently logged in, update the cookie
$method = $auth->getStore()->method;
$userData = $auth->getUserData();
// Sanity check: is the user that has just validated his email address
// the currently logged in user?
if ($userData['id'] == $user->id) {
$userData[$emailValidColumn] = 1;
$auth->store($userData, $method);
}
}
$this->view->user = $user;
}
} | [
"public",
"function",
"validateemailAction",
"(",
")",
"{",
"$",
"this",
"->",
"view",
"->",
"title",
"=",
"__",
"(",
"'activate email page title'",
")",
";",
"$",
"auth",
"=",
"Garp_Auth",
"::",
"getInstance",
"(",
")",
";",
"$",
"authVars",
"=",
"$",
"... | Validate email address. In scenarios where users receive an email validation email,
this action is used to validate the address.
@return void | [
"Validate",
"email",
"address",
".",
"In",
"scenarios",
"where",
"users",
"receive",
"an",
"email",
"validation",
"email",
"this",
"action",
"is",
"used",
"to",
"validate",
"the",
"address",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/AuthController.php#L427-L478 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/AuthController.php | G_AuthController._setViewSettings | protected function _setViewSettings($action) {
$authVars = Garp_Auth::getInstance()->getConfigValues();
if (!isset($authVars[$action])) {
return;
}
$authVars = $authVars[$action];
$module = isset($authVars['module']) ? $authVars['module'] : 'default';
$moduleDirectory = $this->getFrontController()
->getModuleDirectory($module);
$viewPath = $moduleDirectory . '/views/scripts/';
$this->view->addScriptPath($viewPath);
$view = isset($authVars['view']) ? $authVars['view'] : $action;
$this->_helper->viewRenderer($view);
$layout = isset($authVars['layout']) ? $authVars['layout'] : 'layout';
if ($this->_helper->layout->isEnabled()) {
$this->_helper->layout->setLayoutPath($moduleDirectory . '/views/layouts');
$this->_helper->layout->setLayout($layout);
}
} | php | protected function _setViewSettings($action) {
$authVars = Garp_Auth::getInstance()->getConfigValues();
if (!isset($authVars[$action])) {
return;
}
$authVars = $authVars[$action];
$module = isset($authVars['module']) ? $authVars['module'] : 'default';
$moduleDirectory = $this->getFrontController()
->getModuleDirectory($module);
$viewPath = $moduleDirectory . '/views/scripts/';
$this->view->addScriptPath($viewPath);
$view = isset($authVars['view']) ? $authVars['view'] : $action;
$this->_helper->viewRenderer($view);
$layout = isset($authVars['layout']) ? $authVars['layout'] : 'layout';
if ($this->_helper->layout->isEnabled()) {
$this->_helper->layout->setLayoutPath($moduleDirectory . '/views/layouts');
$this->_helper->layout->setLayout($layout);
}
} | [
"protected",
"function",
"_setViewSettings",
"(",
"$",
"action",
")",
"{",
"$",
"authVars",
"=",
"Garp_Auth",
"::",
"getInstance",
"(",
")",
"->",
"getConfigValues",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"authVars",
"[",
"$",
"action",
"]",
... | Render a configured view
@param string $action Config key
@return void | [
"Render",
"a",
"configured",
"view"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/AuthController.php#L503-L523 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/AuthController.php | G_AuthController._storeRoleInCookie | protected function _storeRoleInCookie() {
$userRecord = Garp_Auth::getInstance()->getUserData();
if (!empty($userRecord['role'])) {
$cookie = new Garp_Store_Cookie('Garp_Auth');
$cookie->userData = array('role' => $userRecord['role']);
}
} | php | protected function _storeRoleInCookie() {
$userRecord = Garp_Auth::getInstance()->getUserData();
if (!empty($userRecord['role'])) {
$cookie = new Garp_Store_Cookie('Garp_Auth');
$cookie->userData = array('role' => $userRecord['role']);
}
} | [
"protected",
"function",
"_storeRoleInCookie",
"(",
")",
"{",
"$",
"userRecord",
"=",
"Garp_Auth",
"::",
"getInstance",
"(",
")",
"->",
"getUserData",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"userRecord",
"[",
"'role'",
"]",
")",
")",
"{",
"$... | Store user role in cookie, so it can be used with Javascript
@return void | [
"Store",
"user",
"role",
"in",
"cookie",
"so",
"it",
"can",
"be",
"used",
"with",
"Javascript"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/AuthController.php#L530-L536 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/AuthController.php | G_AuthController._beforeLogin | protected function _beforeLogin(
array $authVars, Garp_Auth_Adapter_Abstract $adapter, array $postData
) {
if ($loginHelper = $this->_getLoginHelper()) {
$loginHelper->beforeLogin($authVars, $adapter, $postData);
}
} | php | protected function _beforeLogin(
array $authVars, Garp_Auth_Adapter_Abstract $adapter, array $postData
) {
if ($loginHelper = $this->_getLoginHelper()) {
$loginHelper->beforeLogin($authVars, $adapter, $postData);
}
} | [
"protected",
"function",
"_beforeLogin",
"(",
"array",
"$",
"authVars",
",",
"Garp_Auth_Adapter_Abstract",
"$",
"adapter",
",",
"array",
"$",
"postData",
")",
"{",
"if",
"(",
"$",
"loginHelper",
"=",
"$",
"this",
"->",
"_getLoginHelper",
"(",
")",
")",
"{",
... | Before login hook
@param array $authVars Containing auth-related configuration.
@param Garp_Auth_Adapter_Abstract $adapter The chosen adapter.
@param array $postData
@return void | [
"Before",
"login",
"hook"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/AuthController.php#L580-L586 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/AuthController.php | G_AuthController._afterLogin | protected function _afterLogin(array $userData, &$targetUrl) {
if ($loginHelper = $this->_getLoginHelper()) {
$loginHelper->afterLogin($userData, $targetUrl);
}
} | php | protected function _afterLogin(array $userData, &$targetUrl) {
if ($loginHelper = $this->_getLoginHelper()) {
$loginHelper->afterLogin($userData, $targetUrl);
}
} | [
"protected",
"function",
"_afterLogin",
"(",
"array",
"$",
"userData",
",",
"&",
"$",
"targetUrl",
")",
"{",
"if",
"(",
"$",
"loginHelper",
"=",
"$",
"this",
"->",
"_getLoginHelper",
"(",
")",
")",
"{",
"$",
"loginHelper",
"->",
"afterLogin",
"(",
"$",
... | After login hook
@param array $userData The data of the logged in user
@param string $targetUrl The URL the user is being redirected to
@return void | [
"After",
"login",
"hook"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/AuthController.php#L595-L599 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/AuthController.php | G_AuthController._getLoginHelper | protected function _getLoginHelper() {
$loginHelper = $this->_helper->getHelper('Login');
if (!$loginHelper) {
return null;
}
if (!$loginHelper instanceof Garp_Controller_Helper_Login) {
throw new Garp_Auth_Exception(self::EXCEPTION_INVALID_LOGIN_HELPER);
}
return $loginHelper;
} | php | protected function _getLoginHelper() {
$loginHelper = $this->_helper->getHelper('Login');
if (!$loginHelper) {
return null;
}
if (!$loginHelper instanceof Garp_Controller_Helper_Login) {
throw new Garp_Auth_Exception(self::EXCEPTION_INVALID_LOGIN_HELPER);
}
return $loginHelper;
} | [
"protected",
"function",
"_getLoginHelper",
"(",
")",
"{",
"$",
"loginHelper",
"=",
"$",
"this",
"->",
"_helper",
"->",
"getHelper",
"(",
"'Login'",
")",
";",
"if",
"(",
"!",
"$",
"loginHelper",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"!",
"... | Get the Login helper, if registered.
@return Zend_Controller_Action_Helper_Abstract | [
"Get",
"the",
"Login",
"helper",
"if",
"registered",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/AuthController.php#L630-L639 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/AuthController.php | G_AuthController._getRegisterHelper | protected function _getRegisterHelper() {
$registerHelper = $this->_helper->getHelper('Register');
if (!$registerHelper) {
return null;
}
if (!$registerHelper instanceof Garp_Controller_Helper_Register) {
throw new Garp_Auth_Exception(self::EXCEPTION_INVALID_REGISTER_HELPER);
}
return $registerHelper;
} | php | protected function _getRegisterHelper() {
$registerHelper = $this->_helper->getHelper('Register');
if (!$registerHelper) {
return null;
}
if (!$registerHelper instanceof Garp_Controller_Helper_Register) {
throw new Garp_Auth_Exception(self::EXCEPTION_INVALID_REGISTER_HELPER);
}
return $registerHelper;
} | [
"protected",
"function",
"_getRegisterHelper",
"(",
")",
"{",
"$",
"registerHelper",
"=",
"$",
"this",
"->",
"_helper",
"->",
"getHelper",
"(",
"'Register'",
")",
";",
"if",
"(",
"!",
"$",
"registerHelper",
")",
"{",
"return",
"null",
";",
"}",
"if",
"("... | Get the Register helper, if registered.
@return Zend_Controller_Action_Helper_Abstract | [
"Get",
"the",
"Register",
"helper",
"if",
"registered",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/AuthController.php#L646-L655 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/AuthController.php | G_AuthController._respondToFaultyProcess | protected function _respondToFaultyProcess(Garp_Auth_Adapter_Abstract $authAdapter) {
if ($redirectUrl = $authAdapter->getRedirect()) {
$this->_helper->redirector->gotoUrl($redirectUrl);
return;
}
// Show the login page again.
$request = clone $this->getRequest();
$request->setActionName('login')
->setParam('errors', $authAdapter->getErrors())
->setParam('postData', $this->getRequest()->getPost());
$this->_helper->actionStack($request);
$this->_setViewSettings('login');
} | php | protected function _respondToFaultyProcess(Garp_Auth_Adapter_Abstract $authAdapter) {
if ($redirectUrl = $authAdapter->getRedirect()) {
$this->_helper->redirector->gotoUrl($redirectUrl);
return;
}
// Show the login page again.
$request = clone $this->getRequest();
$request->setActionName('login')
->setParam('errors', $authAdapter->getErrors())
->setParam('postData', $this->getRequest()->getPost());
$this->_helper->actionStack($request);
$this->_setViewSettings('login');
} | [
"protected",
"function",
"_respondToFaultyProcess",
"(",
"Garp_Auth_Adapter_Abstract",
"$",
"authAdapter",
")",
"{",
"if",
"(",
"$",
"redirectUrl",
"=",
"$",
"authAdapter",
"->",
"getRedirect",
"(",
")",
")",
"{",
"$",
"this",
"->",
"_helper",
"->",
"redirector"... | Auth adapters may return false if no user is logged in yet.
We then have a couple of options on how to respond. Showing the login page again
with errors would be the default, but some adapters require a redirect to an external site.
@param Garp_Auth_Adapter_Abstract $authAdapter
@return void | [
"Auth",
"adapters",
"may",
"return",
"false",
"if",
"no",
"user",
"is",
"logged",
"in",
"yet",
".",
"We",
"then",
"have",
"a",
"couple",
"of",
"options",
"on",
"how",
"to",
"respond",
".",
"Showing",
"the",
"login",
"page",
"again",
"with",
"errors",
"... | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/AuthController.php#L665-L677 | train |
grrr-amsterdam/garp3 | library/Garp/Cli/Command/Snippet.php | Garp_Cli_Command_Snippet.create | public function create(array $args = array()) {
$this->_overwrite = isset($args['overwrite']) && $args['overwrite'];
if (isset($args['i']) || isset($args['interactive'])) {
return $this->_createInteractive();
}
$file = $this->_parseFileFromArguments($args);
$file = APPLICATION_PATH . '/configs/' . $file;
$this->_createFromFile($file);
return true;
} | php | public function create(array $args = array()) {
$this->_overwrite = isset($args['overwrite']) && $args['overwrite'];
if (isset($args['i']) || isset($args['interactive'])) {
return $this->_createInteractive();
}
$file = $this->_parseFileFromArguments($args);
$file = APPLICATION_PATH . '/configs/' . $file;
$this->_createFromFile($file);
return true;
} | [
"public",
"function",
"create",
"(",
"array",
"$",
"args",
"=",
"array",
"(",
")",
")",
"{",
"$",
"this",
"->",
"_overwrite",
"=",
"isset",
"(",
"$",
"args",
"[",
"'overwrite'",
"]",
")",
"&&",
"$",
"args",
"[",
"'overwrite'",
"]",
";",
"if",
"(",
... | Create new snippet
@param array $args
@return bool | [
"Create",
"new",
"snippet"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cli/Command/Snippet.php#L36-L45 | train |
grrr-amsterdam/garp3 | library/Garp/Cli/Command/Snippet.php | Garp_Cli_Command_Snippet._createFromFile | protected function _createFromFile($file) {
if (!file_exists($file)) {
Garp_Cli::errorOut("File not found: {$file}. Adding no snippets.");
return false;
}
$config = new Garp_Config_Ini($file, APPLICATION_ENV);
if (!isset($config->snippets)) {
Garp_Cli::lineOut('Could not find any snippets. I\'m stopping now... This is awkward.');
return true;
}
$snippetNoun = 'snippets';
$snippetCount = count($config->snippets);
if ($snippetCount === 1) {
$snippetNoun = 'snippet';
}
Garp_Cli::lineOut("About to add {$snippetCount} {$snippetNoun} from {$file}");
Garp_Cli::lineOut('');
$this->_createSnippets($config->snippets);
Garp_Cli::lineOut('Done.');
Garp_Cli::lineOut('');
return true;
} | php | protected function _createFromFile($file) {
if (!file_exists($file)) {
Garp_Cli::errorOut("File not found: {$file}. Adding no snippets.");
return false;
}
$config = new Garp_Config_Ini($file, APPLICATION_ENV);
if (!isset($config->snippets)) {
Garp_Cli::lineOut('Could not find any snippets. I\'m stopping now... This is awkward.');
return true;
}
$snippetNoun = 'snippets';
$snippetCount = count($config->snippets);
if ($snippetCount === 1) {
$snippetNoun = 'snippet';
}
Garp_Cli::lineOut("About to add {$snippetCount} {$snippetNoun} from {$file}");
Garp_Cli::lineOut('');
$this->_createSnippets($config->snippets);
Garp_Cli::lineOut('Done.');
Garp_Cli::lineOut('');
return true;
} | [
"protected",
"function",
"_createFromFile",
"(",
"$",
"file",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"file",
")",
")",
"{",
"Garp_Cli",
"::",
"errorOut",
"(",
"\"File not found: {$file}. Adding no snippets.\"",
")",
";",
"return",
"false",
";",
"}"... | Create a bunch of snippets from a file
@param string $file
@return bool | [
"Create",
"a",
"bunch",
"of",
"snippets",
"from",
"a",
"file"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cli/Command/Snippet.php#L91-L113 | train |
grrr-amsterdam/garp3 | library/Garp/Cli/Command/Snippet.php | Garp_Cli_Command_Snippet._createInteractive | protected function _createInteractive() {
Garp_Cli::lineOut('Please provide the following values');
$data = array(
'identifier' => Garp_Cli::prompt('Identifier')
);
if ($snippet = $this->_fetchExisting($data['identifier'])) {
Garp_Cli::lineOut('Snippet already exists. Id: #' . $snippet->id, Garp_Cli::GREEN);
return true;
}
$data['uri'] = Garp_Cli::prompt('Url');
$checks = array(
array('has_name', 'Does this snippet have a name?', 'y'),
array('has_html', 'Does this snippet contain HTML?', 'y'),
array('has_text', 'Does this snippet contain text?', 'n'),
array('has_image', 'Does this snippet have an image?', 'n'),
);
foreach ($checks as $check) {
$key = $check[0];
$question = $check[1];
$default = $check[2];
if ($default == 'y') {
$question .= ' Yn';
} elseif ($default == 'n') {
$question .= ' yN';
}
$userResponse = trim(Garp_Cli::prompt($question));
if (!$userResponse) {
$userResponse = $default;
}
if (strtolower($userResponse) == 'y' || $userResponse == 1) {
$data[$key] = 1;
} elseif (strtolower($userResponse) == 'n' || $userResponse == 0) {
$data[$key] = 0;
}
}
$snippet = $this->_create($data);
Garp_Cli::lineOut(
'New snippet inserted. Id: #' . $snippet->id . ', Identifier: "' .
$snippet->identifier . '"'
);
return true;
} | php | protected function _createInteractive() {
Garp_Cli::lineOut('Please provide the following values');
$data = array(
'identifier' => Garp_Cli::prompt('Identifier')
);
if ($snippet = $this->_fetchExisting($data['identifier'])) {
Garp_Cli::lineOut('Snippet already exists. Id: #' . $snippet->id, Garp_Cli::GREEN);
return true;
}
$data['uri'] = Garp_Cli::prompt('Url');
$checks = array(
array('has_name', 'Does this snippet have a name?', 'y'),
array('has_html', 'Does this snippet contain HTML?', 'y'),
array('has_text', 'Does this snippet contain text?', 'n'),
array('has_image', 'Does this snippet have an image?', 'n'),
);
foreach ($checks as $check) {
$key = $check[0];
$question = $check[1];
$default = $check[2];
if ($default == 'y') {
$question .= ' Yn';
} elseif ($default == 'n') {
$question .= ' yN';
}
$userResponse = trim(Garp_Cli::prompt($question));
if (!$userResponse) {
$userResponse = $default;
}
if (strtolower($userResponse) == 'y' || $userResponse == 1) {
$data[$key] = 1;
} elseif (strtolower($userResponse) == 'n' || $userResponse == 0) {
$data[$key] = 0;
}
}
$snippet = $this->_create($data);
Garp_Cli::lineOut(
'New snippet inserted. Id: #' . $snippet->id . ', Identifier: "' .
$snippet->identifier . '"'
);
return true;
} | [
"protected",
"function",
"_createInteractive",
"(",
")",
"{",
"Garp_Cli",
"::",
"lineOut",
"(",
"'Please provide the following values'",
")",
";",
"$",
"data",
"=",
"array",
"(",
"'identifier'",
"=>",
"Garp_Cli",
"::",
"prompt",
"(",
"'Identifier'",
")",
")",
";... | Create snippet interactively
@return bool | [
"Create",
"snippet",
"interactively"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cli/Command/Snippet.php#L150-L193 | train |
grrr-amsterdam/garp3 | library/Garp/Cli/Command/Snippet.php | Garp_Cli_Command_Snippet._create | protected function _create(array $data) {
$this->_validateLoadable();
$snippetModel = new Model_Snippet();
try {
$snippetID = $snippetModel->insert($data);
$snippet = $snippetModel->fetchRow(
$snippetModel->select()->where('id = ?', $snippetID)
);
return $snippet;
} catch (Garp_Model_Validator_Exception $e) {
Garp_Cli::errorOut($e->getMessage());
}
} | php | protected function _create(array $data) {
$this->_validateLoadable();
$snippetModel = new Model_Snippet();
try {
$snippetID = $snippetModel->insert($data);
$snippet = $snippetModel->fetchRow(
$snippetModel->select()->where('id = ?', $snippetID)
);
return $snippet;
} catch (Garp_Model_Validator_Exception $e) {
Garp_Cli::errorOut($e->getMessage());
}
} | [
"protected",
"function",
"_create",
"(",
"array",
"$",
"data",
")",
"{",
"$",
"this",
"->",
"_validateLoadable",
"(",
")",
";",
"$",
"snippetModel",
"=",
"new",
"Model_Snippet",
"(",
")",
";",
"try",
"{",
"$",
"snippetID",
"=",
"$",
"snippetModel",
"->",... | Insert new snippet
@param array $data Snippet data
@return Garp_Db_Table_Row | [
"Insert",
"new",
"snippet"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cli/Command/Snippet.php#L201-L213 | train |
grrr-amsterdam/garp3 | library/Garp/Cli/Command/Snippet.php | Garp_Cli_Command_Snippet._fetchExisting | protected function _fetchExisting($identifier) {
$this->_validateLoadable();
$snippetModel = new Model_Snippet();
$select = $snippetModel->select()
->where('identifier = ?', $identifier);
$row = $snippetModel->fetchRow($select);
return $row;
} | php | protected function _fetchExisting($identifier) {
$this->_validateLoadable();
$snippetModel = new Model_Snippet();
$select = $snippetModel->select()
->where('identifier = ?', $identifier);
$row = $snippetModel->fetchRow($select);
return $row;
} | [
"protected",
"function",
"_fetchExisting",
"(",
"$",
"identifier",
")",
"{",
"$",
"this",
"->",
"_validateLoadable",
"(",
")",
";",
"$",
"snippetModel",
"=",
"new",
"Model_Snippet",
"(",
")",
";",
"$",
"select",
"=",
"$",
"snippetModel",
"->",
"select",
"(... | Fetch existing snippet by identifier
@param string $identifier
@return Garp_Db_Table_Row | [
"Fetch",
"existing",
"snippet",
"by",
"identifier"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cli/Command/Snippet.php#L235-L242 | train |
grrr-amsterdam/garp3 | library/Garp/Cli/Command/Snippet.php | Garp_Cli_Command_Snippet._validateLoadable | protected function _validateLoadable() {
if ($this->_loadable) {
return true;
}
if (!class_exists('Model_Snippet')) {
throw new Exception(
'The Snippet model could not be autoloaded. Spawn it first, dumbass!'
);
}
$this->_loadable = true;
return $this->_loadable;
} | php | protected function _validateLoadable() {
if ($this->_loadable) {
return true;
}
if (!class_exists('Model_Snippet')) {
throw new Exception(
'The Snippet model could not be autoloaded. Spawn it first, dumbass!'
);
}
$this->_loadable = true;
return $this->_loadable;
} | [
"protected",
"function",
"_validateLoadable",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_loadable",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"!",
"class_exists",
"(",
"'Model_Snippet'",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'The S... | Make sure the snippet model is loadable
@return bool | [
"Make",
"sure",
"the",
"snippet",
"model",
"is",
"loadable"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cli/Command/Snippet.php#L249-L260 | train |
grrr-amsterdam/garp3 | library/Garp/Cli/Command/Snippet.php | Garp_Cli_Command_Snippet._loadI18nStrings | protected function _loadI18nStrings($locale) {
$file = APPLICATION_PATH . '/data/i18n/' . $locale . '.php';
if (!file_exists($file)) {
throw new Exception('File not found: ' . $file);
}
ob_start();
$data = include $file;
ob_end_clean();
return $data;
} | php | protected function _loadI18nStrings($locale) {
$file = APPLICATION_PATH . '/data/i18n/' . $locale . '.php';
if (!file_exists($file)) {
throw new Exception('File not found: ' . $file);
}
ob_start();
$data = include $file;
ob_end_clean();
return $data;
} | [
"protected",
"function",
"_loadI18nStrings",
"(",
"$",
"locale",
")",
"{",
"$",
"file",
"=",
"APPLICATION_PATH",
".",
"'/data/i18n/'",
".",
"$",
"locale",
".",
"'.php'",
";",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"file",
")",
")",
"{",
"throw",
"new",... | Load i18n strings
@param string $locale
@return array | [
"Load",
"i18n",
"strings"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Cli/Command/Snippet.php#L268-L277 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.