sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public static function reflectFunction($function, $argv = false, $namespace = '')
{
if (!is_string($function) || !function_exists($function)) {
require_once 'Zend/Server/Reflection/Exception.php';
throw new Zend_Server_Reflection_Exception('Invalid function "' . $function . '" passed to reflectFunction');
}
if ($argv && !is_array($argv)) {
require_once 'Zend/Server/Reflection/Exception.php';
throw new Zend_Server_Reflection_Exception('Invalid argv argument passed to reflectClass');
}
return new Zend_Server_Reflection_Function(new ReflectionFunction($function), $namespace, $argv);
} | Perform function reflection to create dispatch signatures
Creates dispatch prototypes for a function. It returns a
{@link Zend_Server_Reflection_Function} object.
If extra arguments should be passed to the dispatchable function, these
may be provided as an array to $argv.
@param string $function Function name
@param null|array $argv Optional arguments to be used during the method call
@param string $namespace Optional namespace with which to prefix the
function name (used for the signature key). Primarily to avoid
collisions, also for XmlRpc namespacing
@return Zend_Server_Reflection_Function
@throws Zend_Server_Reflection_Exception | entailment |
public static function getIconTcaSelectItems(int $id = 1, int $typeNum = 0): array
{
$icons = [['---', '']];
foreach (self::getIcons($id, $typeNum) as $iconBasename => $iconName) {
$icons[] = [$iconName, $iconBasename];
}
return $icons;
} | Return all icons as TCA select items
@param int $id Page ID
@param int $typeNum Page type
@return array[] Icon TCA select items
@throws ServiceUnavailableException | entailment |
public static function getIcons(int $id = 1, int $typeNum = 0): array
{
$icons = [];
$typoScriptKey = 'plugin.tx_twcomponentlibrary.settings.iconDirectories';
$iconDirectories = TypoScriptUtility::extractTypoScriptKeyForPidAndType($id, $typeNum, $typoScriptKey);
$iconDirectories = GeneralUtility::trimExplode(',', $iconDirectories['iconDirectories'], true);
foreach ($iconDirectories as $iconDirectory) {
$iconsBaseDirectory = GeneralUtility::getFileAbsFileName($iconDirectory);
foreach (glob($iconsBaseDirectory.DIRECTORY_SEPARATOR.'*.svg') as $iconFile) {
$iconBasename = basename($iconFile);
$iconName = trim(preg_replace('/([A-Z])/', " $1",
pathinfo($iconBasename, PATHINFO_FILENAME)));
$icons[$iconBasename] = $iconName;
}
}
asort($icons);
return $icons;
} | Return all icon assets
@param int $id Page ID
@param int $typeNum Page type
@return string[] Icon assets
@throws ServiceUnavailableException | entailment |
public function generateId()
{
return sprintf(
'%08X-%04X-%04X-%02X%02X-%012X',
mt_rand(),
mt_rand(0, 65535),
bindec(substr_replace(
sprintf('%016b', mt_rand(0, 65535)), '0100', 11, 4)
),
bindec(substr_replace(sprintf('%08b', mt_rand(0, 255)), '01', 5, 2)),
mt_rand(0, 255),
mt_rand()
);
} | generate a unique id
Format is: ########-####-####-####-############
Where # is an uppercase letter or number
example: 6D9DC7EC-A273-83A9-ABE3-00005FD752D6
@return string | entailment |
public static function randomUid($length = 16)
{
if(!isset($length) || intval($length) <= 8 ){
$length = 16;
}
if (function_exists('random_bytes')) {
return bin2hex(random_bytes($length));
}
if (function_exists('mcrypt_create_iv')) {
return bin2hex(mcrypt_create_iv($length, MCRYPT_DEV_URANDOM));
}
if (function_exists('openssl_random_pseudo_bytes')) {
return bin2hex(openssl_random_pseudo_bytes($length));
}
} | По умолчанию длина 32 символа, если количество символов не передано в параметре $length | entailment |
public static function clean($value = "") {
$value = trim($value); // Убираем пробелы вначале и в конце
$value = stripslashes($value); // Убираем слеши, если надо // Удаляет экранирование символов
$value = strip_tags($value); // Удаляет HTML и PHP-теги из строки
$value = htmlspecialchars($value, ENT_QUOTES); // Заменяем служебные символы HTML на эквиваленты // Преобразует специальные символы в HTML-сущности
return $value;
} | Функция клинер. Усиленная замена htmlspecialchars | entailment |
public function classNameForEvent($event): string
{
if ( ! isset($this->eventClasses[$event])) {
throw new \InvalidArgumentException("Could not find a class for the event {$event}.");
}
return $this->eventClasses[$event];
} | retrieve the fully qualified class name for an 'event name'
@param $event
@return string | entailment |
public function setType($type)
{
if (!in_array($type, $this->_types)) {
require_once 'Zend/Server/Exception.php';
throw new Zend_Server_Exception('Invalid method callback type passed to ' . __CLASS__ . '::' . __METHOD__);
}
$this->_type = $type;
return $this;
} | Set callback type
@param string $type
@return Zend_Server_Method_Callback
@throws Zend_Server_Exception | entailment |
public function toArray()
{
$type = $this->getType();
$array = array(
'type' => $type,
);
if ('function' == $type) {
$array['function'] = $this->getFunction();
} else {
$array['class'] = $this->getClass();
$array['method'] = $this->getMethod();
}
return $array;
} | Cast callback to array
@return array | entailment |
public function introspect($serviceClass, $options = array())
{
$this->_options = $options;
if (strpbrk($serviceClass, '\\/<>')) {
return $this->_returnError('Invalid service name');
}
// Transform com.foo.Bar into com_foo_Bar
$serviceClass = str_replace('.' , '_', $serviceClass);
// Introspect!
if (!class_exists($serviceClass)) {
require_once 'Zend/Loader.php';
Zend_Loader::loadClass($serviceClass, $this->_getServicePath());
}
$serv = $this->_xml->createElement('service-description');
$serv->setAttribute('xmlns', 'http://ns.adobe.com/flex/service-description/2008');
$this->_types = $this->_xml->createElement('types');
$this->_ops = $this->_xml->createElement('operations');
$r = Zend_Server_Reflection::reflectClass($serviceClass);
$this->_addService($r, $this->_ops);
$serv->appendChild($this->_types);
$serv->appendChild($this->_ops);
$this->_xml->appendChild($serv);
return $this->_xml->saveXML();
} | Create XML definition on an AMF service class
@param string $serviceClass Service class name
@param array $options invocation options
@return string XML with service class introspection | entailment |
protected function _addClassAttributes($typename, DOMElement $typexml)
{
// Do not try to autoload here because _phpTypeToAS should
// have already attempted to load this class
if (!class_exists($typename, false)) {
return;
}
$rc = new Zend_Reflection_Class($typename);
foreach ($rc->getProperties() as $prop) {
if (!$prop->isPublic()) {
continue;
}
$propxml = $this->_xml->createElement('property');
$propxml->setAttribute('name', $prop->getName());
$type = $this->_registerType($this->_getPropertyType($prop));
$propxml->setAttribute('type', $type);
$typexml->appendChild($propxml);
}
} | Generate map of public class attributes
@param string $typename type name
@param DOMElement $typexml target XML element
@return void | entailment |
protected function _addService(Zend_Server_Reflection_Class $refclass, DOMElement $target)
{
foreach ($refclass->getMethods() as $method) {
if (!$method->isPublic()
|| $method->isConstructor()
|| ('__' == substr($method->name, 0, 2))
) {
continue;
}
foreach ($method->getPrototypes() as $proto) {
$op = $this->_xml->createElement('operation');
$op->setAttribute('name', $method->getName());
$rettype = $this->_registerType($proto->getReturnType());
$op->setAttribute('returnType', $rettype);
foreach ($proto->getParameters() as $param) {
$arg = $this->_xml->createElement('argument');
$arg->setAttribute('name', $param->getName());
$type = $param->getType();
if ($type == 'mixed' && ($pclass = $param->getClass())) {
$type = $pclass->getName();
}
$ptype = $this->_registerType($type);
$arg->setAttribute('type', $ptype);
if($param->isDefaultValueAvailable()) {
$arg->setAttribute('defaultvalue', $param->getDefaultValue());
}
$op->appendChild($arg);
}
$target->appendChild($op);
}
}
} | Build XML service description from reflection class
@param Zend_Server_Reflection_Class $refclass
@param DOMElement $target target XML element
@return void | entailment |
protected function _getPropertyType(Zend_Reflection_Property $prop)
{
$docBlock = $prop->getDocComment();
if (!$docBlock) {
return 'Unknown';
}
if (!$docBlock->hasTag('var')) {
return 'Unknown';
}
$tag = $docBlock->getTag('var');
return trim($tag->getDescription());
} | Extract type of the property from DocBlock
@param Zend_Reflection_Property $prop reflection property object
@return string Property type | entailment |
protected function _getServicePath()
{
if (isset($this->_options['server'])) {
return $this->_options['server']->getDirectory();
}
if (isset($this->_options['directories'])) {
return $this->_options['directories'];
}
return array();
} | Get the array of service directories
@return array Service class directories | entailment |
protected function _phpTypeToAS($typename)
{
if (class_exists($typename)) {
$vars = get_class_vars($typename);
if (isset($vars['_explicitType'])) {
return $vars['_explicitType'];
}
}
if (false !== ($asname = Zend_Amf_Parse_TypeLoader::getMappedClassName($typename))) {
return $asname;
}
return $typename;
} | Map from PHP type name to AS type name
@param string $typename PHP type name
@return string AS type name | entailment |
protected function _registerType($typename)
{
// Known type - return its AS name
if (isset($this->_typesMap[$typename])) {
return $this->_typesMap[$typename];
}
// Standard types
if (in_array($typename, array('void', 'null', 'mixed', 'unknown_type'))) {
return 'Unknown';
}
// Arrays
if ('array' == $typename) {
return 'Unknown[]';
}
if (in_array($typename, array('int', 'integer', 'bool', 'boolean', 'float', 'string', 'object', 'Unknown', 'stdClass'))) {
return $typename;
}
// Resolve and store AS name
$asTypeName = $this->_phpTypeToAS($typename);
$this->_typesMap[$typename] = $asTypeName;
// Create element for the name
$typeEl = $this->_xml->createElement('type');
$typeEl->setAttribute('name', $asTypeName);
$this->_addClassAttributes($typename, $typeEl);
$this->_types->appendChild($typeEl);
return $asTypeName;
} | Register new type on the system
@param string $typename type name
@return string New type name | entailment |
public function getLanguages() {
$response=CodeBank_ClientAPI::responseBase();
//Ensure logged in
if(!Permission::check('CODE_BANK_ACCESS')) {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied');
return $response;
}
$languages=SnippetLanguage::get();
$response['data']=array();
foreach($languages as $lang) {
if($lang->Hidden && $lang->Snippets()->Count()==0) {
continue;
}
$response['data'][]=array(
'language'=>$lang->Name,
'file_extension'=>$lang->FileExtension,
'shjs_code'=>$lang->HighlightCode,
'hidden'=>$lang->Hidden,
'id'=>$lang->ID
);
}
return $response;
} | Gets the list of languages
@return {array} Standard response base | entailment |
public function getSnippets() {
$response=CodeBank_ClientAPI::responseBase();
//Ensure logged in
if(!Permission::check('CODE_BANK_ACCESS')) {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied');
return $response;
}
$languages=SnippetLanguage::get();
foreach($languages as $lang) {
if($lang->Snippets()->Count()>0) {
$snippets=$this->overviewList($lang->Snippets()->filter('FolderID', 0), 'Title', 'ID', 'LanguageID');
$response['data'][]=array(
'id'=>$lang->ID,
'language'=>$lang->Name,
'folders'=>$this->mapFolders($lang->Folders()),
'snippets'=>$snippets
);
}
}
return $response;
} | Gets a list of snippets in an array of languages
@return {array} Standard response base | entailment |
private function mapFolders(SS_List $folders, $searchQuery=null) {
$result=array();
foreach($folders as $folder) {
if(!empty($searchQuery) && $searchQuery!==false) {
$searchEngine=Config::inst()->get('CodeBank', 'snippet_search_engine');
if($searchEngine && class_exists($searchEngine) && in_array('ICodeBankSearchEngine', class_implements($searchEngine))) {
$searchEngine=new $searchEngine();
}else {
//Class is missing or invalid so fallback to the default
$searchEngine=new DefaultCodeBankSearchEngine();
}
$snippets=$searchEngine->doSnippetSearch($searchQuery, false, $folder->ID);
}else {
$snippets=$folder->Snippets();
}
$snippets=$this->overviewList($snippets, 'Title', 'ID', 'LanguageID');
if(!empty($searchQuery) && $searchQuery!==false && count($snippets)==0) {
continue;
}
$result[]=array(
'id'=>$folder->ID,
'name'=>$folder->Name,
'languageID'=>$folder->LanguageID,
'folders'=>$this->mapFolders($folder->Folders(), $searchQuery),
'snippets'=>$snippets
);
}
return $result;
} | Maps the folder and its decendents through recurrsion
@param {SS_List} $folders List of folders to be mapped
@param {string} $searchQuery Search Query
@return {array} Nested array of folder data | entailment |
public function getSnippetsByLanguage($data) {
$response=CodeBank_ClientAPI::responseBase();
//Ensure logged in
if(!Permission::check('CODE_BANK_ACCESS')) {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied');
return $response;
}
$lang=SnippetLanguage::get()->byID(intval($data->id));
if(!empty($lang) && $lang!==false && $lang->ID!=0 && $lang->Snippets()->Count()>0) {
$snippets=$this->arrayUnmap($lang->Snippets()->filter('FolderID', 0)->map('ID', 'Title')->toArray());
$response['data'][]=array(
'id'=>$lang->ID,
'language'=>$lang->Name,
'folders'=>$this->mapFolders($lang->Folders()),
'snippets'=>$snippets
);
}
return $response;
} | Gets a list of snippets that are in the selected index in an array of languages
@param {stdClass} $data Data passed from ActionScript
@return {array} Standard response base | entailment |
public function searchSnippets($data) {
$response=CodeBank_ClientAPI::responseBase();
//Ensure logged in
if(!Permission::check('CODE_BANK_ACCESS')) {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied');
return $response;
}
$languages=SnippetLanguage::get();
foreach($languages as $lang) {
$searchEngine=Config::inst()->get('CodeBank', 'snippet_search_engine');
if($searchEngine && class_exists($searchEngine) && in_array('ICodeBankSearchEngine', class_implements($searchEngine))) {
$searchEngine=new $searchEngine();
}else {
//Class is missing or invalid so fallback to the default
$searchEngine=new DefaultCodeBankSearchEngine();
}
$snippets=$searchEngine->doSnippetSearch($data->query, $lang->ID);
if($snippets->Count()>0) {
$snippets=$this->arrayUnmap($snippets->filter('FolderID', 0)->map('ID', 'Title')->toArray());
$response['data'][]=array(
'id'=>$lang->ID,
'language'=>$lang->Name,
'folders'=>$this->mapFolders($lang->Folders(), $data->query),
'snippets'=>$snippets
);
}
}
return $response;
} | Searches for snippets that match the information the client in the search field
@param {stdClass} $data Data passed from ActionScript
@return {array} Standard response base | entailment |
public function getSnippetInfo($data) {
$response=CodeBank_ClientAPI::responseBase();
//Ensure logged in
if(!Permission::check('CODE_BANK_ACCESS')) {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied');
return $response;
}
$snippet=Snippet::get()->byID($data->id);
if(!empty($snippet) && $snippet!==false && $snippet->ID!=0) {
$packageDetails=null;
if($snippet->Package()) {
$packageDetails=array(
'id'=>$snippet->Package()->ID,
'title'=>$snippet->Package()->Title,
'snippets'=>$this->sortToTop($snippet->ID, 'id', $this->overviewList($snippet->Package()->Snippets()))
);
}
$response['data'][]=array(
'id'=>$snippet->ID,
'title'=>$snippet->Title,
'text'=>$snippet->getSnippetText(),
'description'=>$snippet->Description,
'tags'=>$snippet->Tags,
'languageID'=>$snippet->LanguageID,
'lastModified'=>$snippet->LastEdited,
'creatorID'=>$snippet->CreatorID,
'creator'=>($snippet->Creator() && $snippet->Creator()->ID>0 ? $snippet->Creator()->Name:_t('CodeBank.UNKNOWN_USER', '_Unknown User')),
'lastEditor'=>($snippet->LastEditor() && $snippet->LastEditor()->ID>0 ? $snippet->LastEditor()->Name:($snippet->LastEditorID!=0 ? _t('CodeBank.UNKNOWN_USER', '_Unknown User'):'')),
'language'=>$snippet->Language()->Name,
'fileType'=>$snippet->Language()->FileExtension,
'shjs_code'=>$snippet->Language()->HighlightCode,
'package'=>$packageDetails
);
$snippetScript='<script type="text/javascript" src="app:/tools/external/syntaxhighlighter/brushes/shBrush'.$response['data'][0]['shjs_code'].'.js"></script>';
if($snippet->Language()->UserLanguage==true && !empty($snippet->Language()->BrushFile)) {
$snippetScript="<script type=\"text/javascript\">\n".@file_get_contents(Director::baseFolder().'/'.$snippet->Language()->BrushFile)."\n</script>";
}
$response['data'][0]['text']=preg_replace('/\r\n|\n|\r/', "\n", $response['data'][0]['text']);
$response['data'][0]['formatedText']='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'.
'<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">'.
'<head>'.
'<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'.
'<link type="text/css" rel="stylesheet" href="app:/tools/external/syntaxhighlighter/themes/shCore.css"/>'.
'<link type="text/css" rel="stylesheet" href="app:/tools/external/syntaxhighlighter/themes/shCore'.$data->style.'.css"/>'.
'<link type="text/css" rel="stylesheet" href="app:/tools/external/syntaxhighlighter/themes/shTheme'.$data->style.'.css"/>'.
'<link type="text/css" rel="stylesheet" href="app:/tools/syntaxhighlighter.css"/>'.
'<script type="text/javascript" src="app:/tools/external/syntaxhighlighter/brushes/shCore.js"></script>'.
$snippetScript.
'<script type="text/javascript" src="app:/tools/external/jquery-packed.js"></script>'.
'<script type="text/javascript" src="app:/tools/highlight_helper.js"></script>'.
'</head>'.
'<body>'.
'<pre class="brush: '.strtolower($response['data'][0]['shjs_code']).'" style="font-size:10pt;">'.htmlentities(preg_replace('/\r\n|\n|\r/', "\n", $response['data'][0]['text']), null, 'UTF-8').'</pre>'.
'</body>'.
'</html>';
if($response['data'][0]['language']=='ActionScript 3') {
$response['data'][0]['fileType']='zip';
}
}else {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.SNIPPET_NOT_FOUND', '_Snippet not found');
}
return $response;
} | Gets a snippet's information
@param {stdClass} $data Data passed from ActionScript
@return {array} Standard response base | entailment |
public function getSnippetRevisions($data) {
$response=CodeBank_ClientAPI::responseBase();
//Ensure logged in
if(!Permission::check('CODE_BANK_ACCESS')) {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied');
return $response;
}
$snippet=Snippet::get()->byID($data->id);
if(!empty($snippet) && $snippet!==false && $snippet->ID!=0) {
$revisions=$snippet->Versions()->map('ID', 'Created');
$i=0;
foreach($revisions as $id=>$date) {
$response['data'][]=array(
'id'=>$id,
'date'=>($i==0 ? '{Current Revision}':$date)
);
$i++;
}
}else {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.SNIPPET_NOT_FOUND', '_Snippet not found');
}
return $response;
} | Gets a revisions of the snippet
@param {stdClass} $data Data passed from ActionScript
@return {array} Standard response base | entailment |
public function getSnippetTextFromRevision($data) {
$response=CodeBank_ClientAPI::responseBase();
//Ensure logged in
if(!Permission::check('CODE_BANK_ACCESS')) {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied');
return $response;
}
$revision=SnippetVersion::get()->byID(intval($data->id));
if(!empty($revision) && $revision!==false && $revision->ID!=0) {
$lang=$revision->Parent()->Language();
$snippetScript='<script type="text/javascript" src="app:/tools/external/syntaxhighlighter/brushes/shBrush'.$lang->HighlightCode.'.js"></script>';
if($lang->UserLanguage==true && !empty($lang->BrushFile)) {
$snippetScript="<script type=\"text/javascript\">\n".@file_get_contents(Director::baseFolder().'/'.$lang->BrushFile)."\n</script>";
}
$response['data']='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'.
'<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">'.
'<head>'.
'<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'.
'<link type="text/css" rel="stylesheet" href="app:/tools/external/syntaxhighlighter/themes/shCore.css"/>'.
'<link type="text/css" rel="stylesheet" href="app:/tools/external/syntaxhighlighter/themes/shCore'.$data->style.'.css"/>'.
'<link type="text/css" rel="stylesheet" href="app:/tools/external/syntaxhighlighter/themes/shTheme'.$data->style.'.css"/>'.
'<link type="text/css" rel="stylesheet" href="app:/tools/syntaxhighlighter.css"/>'.
'<script type="text/javascript" src="app:/tools/external/syntaxhighlighter/brushes/shCore.js"></script>'.
$snippetScript.
'<script type="text/javascript" src="app:/tools/external/jquery-packed.js"></script>'.
'<script type="text/javascript" src="app:/tools/highlight_helper.js"></script>'.
'</head>'.
'<body>'.
'<pre class="brush: '.strtolower($lang->HighlightCode).'" style="font-size:10pt;">'.htmlentities(preg_replace('/\r\n|\n|\r/', "\n", $revision->Text), null, 'UTF-8').'</pre>'.
'</body>'.
'</html>';
}else {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.REVISION_NOT_FOUND', '_Revision not found');
}
return $response;
} | Gets the of the snippet from a revision
@param {stdClass} $data Data passed from ActionScript
@return {array} Standard response base | entailment |
public function newSnippet($data) {
$response=CodeBank_ClientAPI::responseBase();
//Ensure logged in
if(!Permission::check('CODE_BANK_ACCESS')) {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied');
return $response;
}
try {
$snippet=new Snippet();
$snippet->Title=$data->title;
$snippet->Description=$data->description;
$snippet->Text=$data->code;
$snippet->Tags=$data->tags;
$snippet->LanguageID=$data->language;
$snippet->CreatorID=Member::currentUserID();
$snippet->PackageID=$data->packageID;
if($data->folderID>0) {
$folder=SnippetFolder::get()->byID(intval($data->folderID));
if(empty($folder) || $folder===false || $folder->ID==0) {
$response['status']="EROR";
$response['message']=_t('CodeBankAPI.FOLDER_DOES_NOT_EXIST', '_Folder does not exist');
return $response;
}
if($folder->LanguageID!=$snippet->LanguageID) {
$response['status']="EROR";
$response['message']=_t('CodeBankAPI.FOLDER_NOT_LANGUAGE', '_Folder is not in the same language as the snippet');
return $response;
}
}
$snippet->write();
$response['status']="HELO";
}catch(Exception $e) {
$response['status']="EROR";
$response['message']="Internal Server error occured";
}
return $response;
} | Saves a new snippet
@param {stdClass} $data Data passed from ActionScript
@return {array} Standard response base | entailment |
public function saveSnippet($data) {
$response=CodeBank_ClientAPI::responseBase();
//Ensure logged in
if(!Permission::check('CODE_BANK_ACCESS')) {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied');
return $response;
}
try {
$snippet=Snippet::get()->byID(intval($data->id));
if(!empty($snippet) && $snippet!==false && $snippet->ID!=0) {
$snippet->Title=$data->title;
$snippet->Description=$data->description;
$snippet->Text=$data->code;
$snippet->Tags=$data->tags;
//Ensure we're not assigning to another hidden language
if($snippet->LanguageID!=$data->language) {
$lang=SnippetLanguage::get()->byID(intval($data->language));
if(!empty($lang) && $lang!==false && $lang->ID>0) {
if($lang->Hidden) {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.LANGUAGE_HIDDEN', '_You cannot assign this snippet to a hidden language');
return $response;
}
}else {
throw new Exception('Language not found');
}
}
$snippet->LanguageID=$data->language;
$snippet->LastEditorID=Member::currentUserID();
$snippet->PackageID=$data->packageID;
$snippet->write();
$response['status']='HELO';
}else {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.SNIPPET_NOT_FOUND', '_Snippet not found');
}
}catch(Exception $e) {
$response['status']="EROR";
$response['message']="Internal Server error occured";
}
return $response;
} | Saves an existing snippet
@param {stdClass} $data Data passed from ActionScript
@return {array} Standard response base | entailment |
public function deleteSnippet($data) {
$response=CodeBank_ClientAPI::responseBase();
try {
$snippet=Snippet::get()->byID(intval($data->id));
if(!empty($snippet) && $snippet!==false && $snippet->ID!=0) {
if($snippet->canDelete()==false) {
$response['status']="EROR";
$response['message']="Not authorized";
return $response;
}
//Delete the snippet
$snippet->delete();
$response['status']='HELO';
}else {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.SNIPPET_NOT_FOUND', '_Snippet not found');
}
}catch(Exception $e) {
$response['status']="EROR";
$response['message']="Internal Server error occured";
}
return $response;
} | Deletes a snippet from the database
@param {stdClass} $data Data passed from ActionScript
@return {array} Standard response base | entailment |
public function getSnippetDiff($data) {
$response=CodeBank_ClientAPI::responseBase();
//Get the Main Revision
$snippet1=SnippetVersion::get()->byID(intval($data->mainRev));
if(empty($snippet1) || $snippet1===false || $snippet1->ID==0) {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.MAIN_REVISION_NOT_FOUND', '_Main revision not found');
return $response;
}
$snippet1=preg_replace('/\r\n|\n|\r/', "\n", $snippet1->Text);
//Get the Comparision Revision
$snippet2=SnippetVersion::get()->byID(intval($data->compRev));
if(empty($snippet2) || $snippet1===false || $snippet2->ID==0) {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.COMPARE_REVISION_NOT_FOUND', '_Compare revision not found');
return $response;
}
$snippet2=preg_replace('/\r\n|\n|\r/', "\n", $snippet2->Text);
//Generate the diff file
$diff=new Text_Diff('auto', array(preg_split('/\n/', $snippet2), preg_split('/\n/', $snippet1)));
$renderer=new Text_Diff_Renderer_unified(array('leading_context_lines'=>1, 'trailing_context_lines'=>1));
$response['data']=array('mainRev'=>$snippet1, 'compRev'=>$snippet2, 'diff'=>$renderer->render($diff));
return $response;
} | Gets the snippet text for the two revisions as well as a unified diff file of the revisions
@param {stdClass} $data Data passed from ActionScript
@return {array} Standard response base | entailment |
public function getPackages() {
$response=CodeBank_ClientAPI::responseBase();
//Ensure logged in
if(!Permission::check('CODE_BANK_ACCESS')) {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied');
return $response;
}
$response['data']=$this->overviewList(SnippetPackage::get());
return $response;
} | Gets the list of packages
@return {array} Standard response base | entailment |
public function getPackageInfo($data) {
$response=CodeBank_ClientAPI::responseBase();
//Ensure logged in
if(!Permission::check('CODE_BANK_ACCESS')) {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied');
return $response;
}
$package=SnippetPackage::get()->byID(intval($data->id));
if(!empty($package) && $package!==false && $package->ID!=0) {
$response['data']=array(
'id'=>$package->ID,
'title'=>$package->Title,
'snippets'=>$this->overviewList($package->Snippets(), 'Title', 'ID', 'Language.Title')
);
$response['status']='HELO';
}else {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PACKAGE_NOT_FOUND', '_Package not found');
}
return $response;
} | Gets the details of a package
@param {stdClass} $data Data passed from ActionScript
@return {array} Standard response base | entailment |
public function packageRemoveSnippet($data) {
$response=CodeBank_ClientAPI::responseBase();
//Ensure logged in
if(!Permission::check('CODE_BANK_ACCESS')) {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied');
return $response;
}
$package=SnippetPackage::get()->byID(intval($data->packageID));
if(!empty($package) && $package!==false && $package->ID!=0) {
$package->Snippets()->removeByID(intval($data->snippetID));
$response['status']='HELO';
}else {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PACKAGE_NOT_FOUND', '_Package not found');
}
return $response;
} | Removes a snippet from a package
@param {stdClass} $data Data passed from ActionScript
@return {array} Standard response base | entailment |
public function findSnippetAutoComplete($data) {
$response=CodeBank_ClientAPI::responseBase();
//Ensure logged in
if(!Permission::check('CODE_BANK_ACCESS')) {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied');
return $response;
}
//Lookup snippets
$snippets=Snippet::get()->filter('Title:StartsWith', Convert::raw2sql($data->pattern))->limit(20);
$response['status']='HELO';
$response['data']=$this->overviewList($snippets);
return $response;
} | Finds a snippet begining with the data passed
@param {stdClass} $data Data passed from ActionScript
@return {array} Standard response base | entailment |
public function addSnippetToPackage($data) {
$response=CodeBank_ClientAPI::responseBase();
//Ensure logged in
if(!Permission::check('CODE_BANK_ACCESS')) {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied');
return $response;
}
$package=SnippetPackage::get()->byID(intval($data->packageID));
if(!empty($package) && $package!==false && $package->ID!=0) {
$snippet=Snippet::get()->byID(intval($data->snippetID));
if(!empty($snippet) && $snippet!==false && $snippet->ID!=0) {
$package->Snippets()->add($snippet);
$response['status']='HELO';
}else {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.SNIPPET_NOT_FOUND', '_Snippet not found');
}
$response['status']='HELO';
}else {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PACKAGE_NOT_FOUND', '_Package not found');
}
return $response;
} | Adds a snippet to a package
@param {stdClass} $data Data passed from ActionScript
@return {array} Standard response base | entailment |
public function savePackage($data) {
$response=CodeBank_ClientAPI::responseBase();
//Ensure logged in
if(!Permission::check('CODE_BANK_ACCESS')) {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied');
return $response;
}
$package=SnippetPackage::get()->byID(intval($data->packageID));
if(!empty($package) && $package!==false && $package->ID!=0) {
if(!empty($data->title)) {
$package->Title=$data->title;
$package->write();
$response['status']='HELO';
}else {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PACKAGES_TITLE_REQUIRED', '_Packages must have a title');
}
}else {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PACKAGE_NOT_FOUND', '_Package not found');
}
return $response;
} | Saves a package
@param {stdClass} $data Data passed from ActionScript
@return {array} Standard response base | entailment |
public function createPackage($data) {
$response=CodeBank_ClientAPI::responseBase();
//Ensure logged in
if(!Permission::check('CODE_BANK_ACCESS')) {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied');
return $response;
}
if(!empty($data->title)) {
$package=new SnippetPackage();
$package->Title=$data->title;
$package->write();
$response['status']='HELO';
$response['data']=$package->ID;
}else {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PACKAGES_TITLE_REQUIRED', '_Packages must have a title');
}
return $response;
} | Saves a package
@param {stdClass} $data Data passed from ActionScript
@return {array} Standard response base | entailment |
public function deletePackage($data) {
$response=CodeBank_ClientAPI::responseBase();
//Ensure logged in
if(!Permission::check('CODE_BANK_ACCESS')) {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied');
return $response;
}
$package=SnippetPackage::get()->byID(intval($data->id));
if(!empty($package) && $package!==false && $package->ID!=0) {
$package->delete();
$response['status']='HELO';
}else {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PACKAGE_NOT_FOUND', '_Package not found');
}
return $response;
} | Deletes a package
@param {stdClass} $data Data passed from ActionScript
@return {array} Standard response base | entailment |
public function newFolder($data) {
$response=CodeBank_ClientAPI::responseBase();
//Ensure logged in
if(!Permission::check('CODE_BANK_ACCESS')) {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied');
return $response;
}
$language=SnippetLanguage::get()->byID(intval($data->languageID));
if(empty($language) || $language===false || $language->ID==0) {
$response['status']="EROR";
$response['message']=_t('CodeBankAPI.LANGUAGE_NOT_FOUND', '_Language not found');
return $response;
}
if($data->parentID>0) {
$folder=SnippetFolder::get()->byID(intval($data->parentID));
if(empty($folder) || $folder===false || $folder->ID==0) {
$response['status']="EROR";
$response['message']=_t('CodeBankAPI.FOLDER_DOES_NOT_EXIST', '_Folder does not exist');
return $response;
}
if($folder->LanguageID!=$language->ID) {
$response['status']="EROR";
$response['message']=_t('CodeBankAPI.FOLDER_NOT_LANGUAGE', '_Folder is not in the same language as the snippet');
return $response;
}
}
//Check existing
$existingCheck=SnippetFolder::get()->filter('Name:nocase', Convert::raw2sql($data->name))->filter('LanguageID', $language->ID)->filter('ParentID', $data->parentID);
if($existingCheck->Count()>0) {
$response['status']="EROR";
$response['message']=_t('CodeBank.FOLDER_EXISTS', '_A folder already exists with that name');
return $response;
}
try {
$snippetFolder=new SnippetFolder();
$snippetFolder->Name=$data->name;
$snippetFolder->LanguageID=$data->languageID;
$snippetFolder->ParentID=$data->parentID;
$snippetFolder->write();
$response['status']="HELO";
}catch(Exception $e) {
$response['status']="EROR";
$response['message']="Internal Server error occured";
}
return $response;
} | Saves a new folder
@param {stdClass} $data Data passed from ActionScript
@return {array} Standard response base | entailment |
public function renameFolder($data) {
$response=CodeBank_ClientAPI::responseBase();
//Ensure logged in
if(!Permission::check('CODE_BANK_ACCESS')) {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied');
return $response;
}
$snippetFolder=SnippetFolder::get()->byID(intval($data->id));
if(empty($snippetFolder) || $snippetFolder===false || $snippetFolder->ID==0) {
$response['status']="EROR";
$response['message']=_t('CodeBankAPI.FOLDER_DOES_NOT_EXIST', '_Folder does not exist');
return $response;
}
//Check existing
$existingCheck=SnippetFolder::get()
->filter('ID:not', $snippetFolder->ID)
->filter('Name:nocase', Convert::raw2sql($data->name))
->filter('LanguageID', $snippetFolder->LanguageID)
->filter('ParentID', $snippetFolder->ParentID);
if($existingCheck->Count()>0) {
$response['status']="EROR";
$response['message']=_t('CodeBank.FOLDER_EXISTS', '_A folder already exists with that name');
return $response;
}
try {
$snippetFolder->Name=$data->name;
$snippetFolder->write();
$response['status']="HELO";
}catch(Exception $e) {
$response['status']="EROR";
$response['message']="Internal Server error occured";
}
return $response;
} | Renames a folder
@param {stdClass} $data Data passed from ActionScript
@return {array} Standard response base | entailment |
public function deleteFolder($data) {
$response=CodeBank_ClientAPI::responseBase();
//Ensure logged in
if(!Permission::check('CODE_BANK_ACCESS')) {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied');
return $response;
}
$snippetFolder=SnippetFolder::get()->byID(intval($data->id));
if(empty($snippetFolder) || $snippetFolder===false || $snippetFolder->ID==0) {
$response['status']="EROR";
$response['message']=_t('CodeBankAPI.FOLDER_DOES_NOT_EXIST', '_Folder does not exist');
return $response;
}
try {
$snippetFolder->delete();
$response['status']="HELO";
}catch(Exception $e) {
$response['status']="EROR";
$response['message']="Internal Server error occured";
}
return $response;
} | Deletes a folder
@param {stdClass} $data Data passed from ActionScript
@return {array} Standard response base | entailment |
public function moveSnippet($data) {
$response=CodeBank_ClientAPI::responseBase();
//Ensure logged in
if(!Permission::check('CODE_BANK_ACCESS')) {
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied');
return $response;
}
$snippet=Snippet::get()->byID(intval($data->id));
if(empty($snippet) || $snippet===false || $snippet->ID==0) {
$response['status']="EROR";
$response['message']=_t('CodeBankAPI.SNIPPET_NOT_FOUND', '_Snippet not found');
return $response;
}
if($data->folderID!=0) {
$snippetFolder=SnippetFolder::get()->byID(intval($data->folderID));
if(empty($snippetFolder) || $snippetFolder===false || $snippetFolder->ID==0) {
$response['status']="EROR";
$response['message']=_t('CodeBankAPI.FOLDER_DOES_NOT_EXIST', '_Folder does not exist');
return $response;
}
if($snippetFolder->LanguageID!=$snippet->LanguageID) {
$response['status']="EROR";
$response['message']=_t('CodeBankAPI.LANGUAGE_NOT_SAME', '_Folder is not in the same language as the snippet');
return $response;
}
}
try {
$snippet->FolderID=$data->folderID;
$snippet->write();
$response['status']="HELO";
}catch(Exception $e) {
$response['status']="EROR";
$response['message']="Internal Server error occured";
}
return $response;
} | Deletes a folder
@param {stdClass} $data Data passed from ActionScript
@return {array} Standard response base | entailment |
final protected function arrayUnmap($array, $keyLbl='id', $valueLbl='title') {
$result=array();
foreach($array as $key=>$value) {
$result[]=array(
$keyLbl=>$key,
$valueLbl=>$value
);
}
//Return the resulting array
return $result;
} | Converts an array where the key and value should be mapped to a nested array
@param {array} $array Source Array
@param {string} $keyLbl Array's Key mapping name
@param {string} $valueLbl Key's value mapping name
@return {array} Unmapped array | entailment |
final protected function overviewList(SS_List $list, $labelField='Title', $idField='ID') {
$result=array();
$idFieldLower=strtolower($idField);
$labelFieldLower=strtolower($labelField);
$args=func_get_args();
unset($args[0]);
unset($args[1]);
unset($args[2]);
foreach($list as $item) {
$obj=new stdClass();
$obj->$idFieldLower=$item->$idField;
$obj->$labelFieldLower=$item->$labelField;
if(count($args)>0) {
foreach($args as $field) {
$fieldLower=strtolower($field);
//If the field contains a dot assume relationship and loop through till field is found
if(strpos($field, '.')!==false) {
$fieldLower=str_replace('.', '-', $fieldLower);
$fieldBits=explode('.', $field);
$value=$item;
for($i=0;$i<count($fieldBits);$i++) {
$fieldBit=$fieldBits[$i];
if($i==count($fieldBits)-1) {
$value=$value->$fieldBit;
}else {
$value=$value->$fieldBit();
}
}
if(!is_object($value)) {
$obj->$fieldLower=$value;
}
}else {
$obj->$fieldLower=$item->$field;
}
}
}
$result[]=$obj;
}
return $result;
} | Converts an SS_List into an array of items with and id and a title key
@param {SS_List} $list List to parse
@param {string} $labelField Label Field
@param {string} $idField ID Field
@param {string} ... Overloaded for additional fields, allows for silverstripe relation formatting ex: Relationship.Field the dot is replaced with a dash in the resulting object
@return {array} Nested array of items, each item has an id and a title key | entailment |
final protected function sortToTop($value, $field, $array) {
foreach($array as $key=>$item) {
if($item->$field==$value) {
unset($array[$key]);
array_unshift($array, $item);
break;
}
}
return $array;
} | Sorts an item to the top of the list
@param {mixed} $value Value to look for
@param {mixed} $field Field to look on
@param {array} $array Array to sort
@return {array} Finalized array | entailment |
public function send($mobile, $content)
{
if ($this->fileMode && $this->_sendAsFile($mobile, $content)) {
$this->message = '短信发送成功!';
return true;
}
return false;
} | 发送短信
@param string $mobile 对方手机号码
@param string $content 短信内容
@return boolean 短信是否发送成功 | entailment |
public function sendByTemplate($mobile, $data, $id)
{
if ($this->fileMode) {
$content = print_r($data, true);
if ($this->_sendAsFile($mobile, $content)) {
$this->message = '短信发送成功!';
return true;
}
}
return false;
} | 发送模板短信
@param string $mobile 对方手机号码
@param mixed $data 键值对
@param number $id 模板id
@return boolean 短信是否发送成功 | entailment |
private function _sendAsFile($mobile, $content)
{
$dir = Yii::getAlias('@app/runtime/smser');
try {
if (!FileHelper::createDirectory($dir)) {
throw new \Exception('无法创建目录:' . $dir);
}
$filename = $dir . DIRECTORY_SEPARATOR . time() . mt_rand(1000, 9999) . '.msg';
if (!touch($filename)) {
throw new \Exception('无法创建文件:' . $filename);
}
if (!file_put_contents($filename, "TO - $mobile" . PHP_EOL . "CONTENT - $content")) {
throw new \Exception('短信发送失败!');
}
return true;
} catch (\Exception $e) {
$this->message = $e->getMessage();
return false;
}
} | 用于存储短信内容
@param string $mobile
@param string $content
@throws \Exception
@return boolean | entailment |
protected function getDependencyTemplateResources()
{
$templateResources = [];
// Run through all component dependencies
foreach ($this->dependencies as $dependency) {
$templateResources[] = $this->objectManager->get($dependency)->getPreviewTemplateResources();
}
return $templateResources;
} | Get the template resources of component dependencies
@return TemplateResources[] Component dependency templace resources | entailment |
protected function determineExtensionName()
{
$reflectionClass = new \ReflectionClass($this);
$componentFilePath = dirname($reflectionClass->getFileName());
// If the file path is invalid
$extensionDirPosition = strpos($componentFilePath, 'ext'.DIRECTORY_SEPARATOR);
if ($extensionDirPosition === false) {
throw new \RuntimeException('Invalid component path', 1481360976);
}
// Extract the extension key
$componentPath = explode(
DIRECTORY_SEPARATOR,
substr($componentFilePath, $extensionDirPosition + strlen('ext'.DIRECTORY_SEPARATOR))
);
$extensionKey = array_shift($componentPath);
// If the extension is unknown
if (!in_array($extensionKey, ExtensionManagementUtility::getLoadedExtensionListArray())) {
throw new \RuntimeException(sprintf('Unknown extension key "%s"', $extensionKey), 1481361198);
}
// Register the extension key & name
$this->extensionKey = $extensionKey;
$this->extensionName = GeneralUtility::underscoredToUpperCamelCase($extensionKey);
// Process the component path
if (array_shift($componentPath) !== 'Components') {
throw new \RuntimeException('Invalid component path', 1481360976);
}
$this->componentPath = array_map([static::class, 'expandComponentName'], $componentPath);
} | Find the extension name the current component belongs to
@throws \RuntimeException If the component path is invalid
@throws \ReflectionException | entailment |
protected function determineNameAndVariant()
{
$reflectionClass = new \ReflectionClass($this);
$componentName = preg_replace('/Component$/', '', $reflectionClass->getShortName());
list($this->basename, $variant) = preg_split('/_+/', $componentName, 2);
$this->name = self::expandComponentName($this->basename);
$this->variant = self::expandComponentName($variant);
} | Determine the component name and variant | entailment |
public static function expandComponentName($componentPath)
{
return trim(
implode(
' ',
array_map(
'ucwords', preg_split('/_+/', GeneralUtility::camelCaseToLowerCaseUnderscored($componentPath))
)
)
) ?: null;
} | Prepare a component path
@param string $componentPath Component path
@return string Component name | entailment |
protected function addDocumentation()
{
$docDirectory = $this->getDocumentationDirectory();
// If there's a documentation directory
if (is_dir($docDirectory)) {
$validIndexDocuments = [
'index.md',
'readme.md',
strtolower($this->basename.'.md')
];
$indexDocument = null;
$documents = [];
// Run through all documentation files
foreach (scandir($docDirectory) as $document) {
if (!is_file($docDirectory.DIRECTORY_SEPARATOR.$document)) {
continue;
}
// If there's a valid documentation index file
if (in_array(strtolower($document), $validIndexDocuments)) {
if ($indexDocument === null) {
$indexDocument = $docDirectory.DIRECTORY_SEPARATOR.$document;
}
continue;
}
$documents[] = $docDirectory.DIRECTORY_SEPARATOR.$document;
}
// If there's an index document
if ($indexDocument !== null) {
$this->addNotice(file_get_contents($indexDocument));
return;
}
// If there are remaining documents: Auto-create a simple listing
if (count($documents)) {
$listing = [];
// Run through all documents
foreach ($documents as $document) {
$extension = strtolower(pathinfo($document, PATHINFO_EXTENSION));
$listing[] = '* '.(in_array($extension, ['jpg', 'jpeg', 'png', 'gif', 'svg']) ? '!' : '').
'['.pathinfo($document, PATHINFO_FILENAME).']('.basename($document).')';
}
$this->addNotice(implode(PHP_EOL, $listing));
}
}
} | Add an external documentation | entailment |
protected function getDocumentationDirectory($rootRelative = false)
{
$reflectionObject = new \ReflectionObject($this);
$componentFile = $reflectionObject->getFileName();
$docDirectory = dirname($componentFile).DIRECTORY_SEPARATOR.$this->basename;
return $rootRelative ? substr($docDirectory, strlen(PATH_site) - 1) : $docDirectory;
} | Return the documentation directory for this component
@param bool $rootRelative Return a root relative path
@return string Documentation directory | entailment |
protected function addNotice($notice)
{
if (!$this->variant) {
$notice = trim($notice);
$this->notice = strlen($notice) ? $this->exportNotice($notice) : null;
}
} | Add a notice
@param string $notice Notice | entailment |
protected function exportNotice($notice)
{
$docDirectoryPath = strtr($this->getDocumentationDirectory(true), [DIRECTORY_SEPARATOR => '/']).'/';
return preg_replace_callback('/\[([^\]]*?)\]\(([^\)]*?)\)/', function($match) use ($docDirectoryPath) {
return '['.$match[1].']('
.(preg_match('%^https?\:\/\/%i', $match[2]) ? '' : $docDirectoryPath)
.$match[2].')';
}, $notice);
} | Export a notice
@param $notice
@return mixed | entailment |
final public function export()
{
$properties = [
'status' => $this->status,
'name' => $this->name,
'variant' => $this->variant,
'label' => $this->label,
'class' => get_class($this),
'type' => $this->type,
'valid' => false,
'path' => $this->componentPath,
'docs' => $this->getDocumentationDirectory(),
];
// Export the component properties
try {
$properties = array_merge($properties, $this->exportInternal());
$properties['request'] = $this->exportRequest();
$properties['valid'] = true;
// In case of an error
} catch (\Exception $e) {
$properties['error'] = $e->getMessage();
}
return $properties;
} | Export the component's properties
@return array Properties | entailment |
protected function exportInternal()
{
$properties = [];
// Export the configuration & $template
if (!$this->config) {
throw new \RuntimeException('Invalid configuration', 1481363496);
}
$properties['config'] = $this->config;
$properties['template'] = $this->template;
$properties['extension'] = $this->extension;
// Export the associated resources
if (count($this->resources)) {
$properties['resources'] = $this->resources;
}
// Export the notice
if (strlen(trim($this->notice))) {
$properties['notice'] = trim($this->notice);
}
// If this is the default variant
if (!$this->variant) {
$preview = trim(strval($this->preview));
if (strlen($preview)) {
$properties['preview'] = $preview;
}
}
return $properties;
} | Return component specific properties
Override this method in sub classes to export specific properties.
@return array Component specific properties | entailment |
protected function exportRequest()
{
// Set the request language
if ($this->languageParameter) {
$this->request->setArgument($this->languageParameter, $this->sysLanguage);
}
$this->request->setControllerExtensionName($this->extensionName);
// Set page ID and type
$this->request->setArgument('id', $this->page);
if (intval($this->typeNum)) {
$this->request->setArgument('type', intval($this->typeNum));
}
return [
'method' => $this->request->getMethod(),
'arguments' => $this->request->getArguments(),
];
} | Export the request options
@return array | entailment |
protected function addResource($resource)
{
$resource = trim($resource);
if (strlen($resource)) {
$this->resources[] = $resource;
}
} | Add an associated resource
@param string $resource Associated resource | entailment |
protected function setPreview($preview)
{
if (!($preview instanceof TemplateInterface) && !is_string($preview) && ($preview !== null)) {
throw new \RuntimeException('Invalid preview preview', 1481368492);
}
$this->preview = $preview;
} | Set a preview template
@param TemplateInterface|string|null $preview Preview template | entailment |
protected function initializeTSFE()
{
$GLOBALS['TSFE'] = TypoScriptUtility::getTSFE($this->page, $this->typeNum);
$GLOBALS['TSFE']->cObj = new ContentObjectRenderer($GLOBALS['TSFE']);
$GLOBALS['TSFE']->cObj->start($GLOBALS['TSFE']->page, 'pages');
return $GLOBALS['TSFE']->cObj;
} | Initialize a global Frontend renderer and return a content object renderer instance
@return ContentObjectRenderer Content object renderer
@throws \Exception
@throws \TYPO3\CMS\Core\Error\Http\ServiceUnavailableException | entailment |
protected function addError($property, $message)
{
$this->validationErrors->forProperty($property)->addError(new Error($message, time()));
} | Register a validation error
@param string $property Property
@param string $message Validation error message | entailment |
function _added( $lines, $encode = true ) {
$r = '';
foreach ($lines as $line) {
if ( $encode )
$line = htmlspecialchars( $line );
$r .= '<tr>' . $this->emptyLine() . $this->addedLine( $line ) . "</tr>\n";
}
return $r;
} | @ignore
@access private
@param array $lines
@param bool $encode
@return string | entailment |
function _deleted( $lines, $encode = true ) {
$r = '';
foreach ($lines as $line) {
if ( $encode )
$line = htmlspecialchars( $line );
$r .= '<tr>' . $this->deletedLine( $line ) . $this->emptyLine() . "</tr>\n";
}
return $r;
} | @ignore
@access private
@param array $lines
@param bool $encode
@return string | entailment |
function _context( $lines, $encode = true ) {
$r = '';
foreach ($lines as $line) {
if ( $encode )
$line = htmlspecialchars( $line );
$r .= '<tr>' .
$this->contextLine( $line ) . $this->contextLine( $line ) . "</tr>\n";
}
return $r;
} | @ignore
@access private
@param array $lines
@param bool $encode
@return string | entailment |
function _changed( $orig, $final ) {
$r = '';
// Does the aforementioned additional processing
// *_matches tell what rows are "the same" in orig and final. Those pairs will be diffed to get word changes
// match is numeric: an index in other column
// match is 'X': no match. It is a new row
// *_rows are column vectors for the orig column and the final column.
// row >= 0: an indix of the $orig or $final array
// row < 0: a blank row for that column
list($orig_matches, $final_matches, $orig_rows, $final_rows) = $this->interleave_changed_lines( $orig, $final );
// These will hold the word changes as determined by an inline diff
$orig_diffs = array();
$final_diffs = array();
// Compute word diffs for each matched pair using the inline diff
foreach ( $orig_matches as $o => $f ) {
if ( is_numeric($o) && is_numeric($f) ) {
$text_diff = new Text_Diff( 'auto', array( array($orig[$o]), array($final[$f]) ) );
$renderer = new $this->inline_diff_renderer;
$diff = $renderer->render( $text_diff );
// If they're too different, don't include any <ins> or <dels>
if ( $diff_count = preg_match_all( '!(<ins>.*?</ins>|<del>.*?</del>)!', $diff, $diff_matches ) ) {
// length of all text between <ins> or <del>
$stripped_matches = strlen(strip_tags( join(' ', $diff_matches[0]) ));
// since we count lengith of text between <ins> or <del> (instead of picking just one),
// we double the length of chars not in those tags.
$stripped_diff = strlen(strip_tags( $diff )) * 2 - $stripped_matches;
$diff_ratio = $stripped_matches / $stripped_diff;
if ( $diff_ratio > $this->_diff_threshold )
continue; // Too different. Don't save diffs.
}
// Un-inline the diffs by removing del or ins
$orig_diffs[$o] = preg_replace( '|<ins>.*?</ins>|', '', $diff );
$final_diffs[$f] = preg_replace( '|<del>.*?</del>|', '', $diff );
}
}
foreach ( array_keys($orig_rows) as $row ) {
// Both columns have blanks. Ignore them.
if ( $orig_rows[$row] < 0 && $final_rows[$row] < 0 )
continue;
// If we have a word based diff, use it. Otherwise, use the normal line.
if ( isset( $orig_diffs[$orig_rows[$row]] ) )
$orig_line = $orig_diffs[$orig_rows[$row]];
elseif ( isset( $orig[$orig_rows[$row]] ) )
$orig_line = htmlspecialchars($orig[$orig_rows[$row]]);
else
$orig_line = '';
if ( isset( $final_diffs[$final_rows[$row]] ) )
$final_line = $final_diffs[$final_rows[$row]];
elseif ( isset( $final[$final_rows[$row]] ) )
$final_line = htmlspecialchars($final[$final_rows[$row]]);
else
$final_line = '';
if ( $orig_rows[$row] < 0 ) { // Orig is blank. This is really an added row.
$r .= $this->_added( array($final_line), false );
} elseif ( $final_rows[$row] < 0 ) { // Final is blank. This is really a deleted row.
$r .= $this->_deleted( array($orig_line), false );
} else { // A true changed row.
$r .= '<tr>' . $this->deletedLine( $orig_line ) . $this->addedLine( $final_line ) . "</tr>\n";
}
}
return $r;
} | Process changed lines to do word-by-word diffs for extra highlighting.
(TRAC style) sometimes these lines can actually be deleted or added rows.
We do additional processing to figure that out
@access private
@since 2.6.0
@param array $orig
@param array $final
@return string | entailment |
function interleave_changed_lines( $orig, $final ) {
// Contains all pairwise string comparisons. Keys are such that this need only be a one dimensional array.
$matches = array();
foreach ( array_keys($orig) as $o ) {
foreach ( array_keys($final) as $f ) {
$matches["$o,$f"] = $this->compute_string_distance( $orig[$o], $final[$f] );
}
}
asort($matches); // Order by string distance.
$orig_matches = array();
$final_matches = array();
foreach ( $matches as $keys => $difference ) {
list($o, $f) = explode(',', $keys);
$o = (int) $o;
$f = (int) $f;
// Already have better matches for these guys
if ( isset($orig_matches[$o]) && isset($final_matches[$f]) )
continue;
// First match for these guys. Must be best match
if ( !isset($orig_matches[$o]) && !isset($final_matches[$f]) ) {
$orig_matches[$o] = $f;
$final_matches[$f] = $o;
continue;
}
// Best match of this final is already taken? Must mean this final is a new row.
if ( isset($orig_matches[$o]) )
$final_matches[$f] = 'x';
// Best match of this orig is already taken? Must mean this orig is a deleted row.
elseif ( isset($final_matches[$f]) )
$orig_matches[$o] = 'x';
}
// We read the text in this order
ksort($orig_matches);
ksort($final_matches);
// Stores rows and blanks for each column.
$orig_rows = $orig_rows_copy = array_keys($orig_matches);
$final_rows = array_keys($final_matches);
// Interleaves rows with blanks to keep matches aligned.
// We may end up with some extraneous blank rows, but we'll just ignore them later.
foreach ( $orig_rows_copy as $orig_row ) {
$final_pos = array_search($orig_matches[$orig_row], $final_rows, true);
$orig_pos = (int) array_search($orig_row, $orig_rows, true);
if ( false === $final_pos ) { // This orig is paired with a blank final.
array_splice( $final_rows, $orig_pos, 0, -1 );
} elseif ( $final_pos < $orig_pos ) { // This orig's match is up a ways. Pad final with blank rows.
$diff_pos = $final_pos - $orig_pos;
while ( $diff_pos < 0 )
array_splice( $final_rows, $orig_pos, 0, $diff_pos++ );
} elseif ( $final_pos > $orig_pos ) { // This orig's match is down a ways. Pad orig with blank rows.
$diff_pos = $orig_pos - $final_pos;
while ( $diff_pos < 0 )
array_splice( $orig_rows, $orig_pos, 0, $diff_pos++ );
}
}
// Pad the ends with blank rows if the columns aren't the same length
$diff_count = count($orig_rows) - count($final_rows);
if ( $diff_count < 0 ) {
while ( $diff_count < 0 )
array_push($orig_rows, $diff_count++);
} elseif ( $diff_count > 0 ) {
$diff_count = -1 * $diff_count;
while ( $diff_count < 0 )
array_push($final_rows, $diff_count++);
}
return array($orig_matches, $final_matches, $orig_rows, $final_rows);
} | Takes changed blocks and matches which rows in orig turned into which rows in final.
Returns
*_matches ( which rows match with which )
*_rows ( order of rows in each column interleaved with blank rows as
necessary )
@since 2.6.0
@param unknown_type $orig
@param unknown_type $final
@return unknown | entailment |
function compute_string_distance( $string1, $string2 ) {
// Vectors containing character frequency for all chars in each string
$chars1 = count_chars($string1);
$chars2 = count_chars($string2);
// L1-norm of difference vector.
$difference = array_sum( array_map( array(&$this, 'difference'), $chars1, $chars2 ) );
// $string1 has zero length? Odd. Give huge penalty by not dividing.
if ( !$string1 )
return $difference;
// Return distance per charcter (of string1)
return $difference / strlen($string1);
} | Computes a number that is intended to reflect the "distance" between two strings.
@since 2.6.0
@param string $string1
@param string $string2
@return int | entailment |
function _splitOnWords($string, $newlineEscape = "\n") {
$string = str_replace("\0", '', $string);
$words = preg_split( '/([^\w])/u', $string, -1, PREG_SPLIT_DELIM_CAPTURE );
$words = str_replace( "\n", $newlineEscape, $words );
return $words;
} | @ignore
@since 2.6.0
@param string $string
@param string $newlineEscape
@return string | entailment |
public function setAuth(Zend_Amf_Auth_Abstract $auth)
{
$this->_auth = $auth;
if ((null === $this->getAcl()) && method_exists($auth, 'getAcl')) {
$this->setAcl($auth->getAcl());
}
return $this;
} | Set authentication adapter
If the authentication adapter implements a "getAcl()" method, populate
the ACL of this instance with it (if none exists already).
@param Zend_Amf_Auth_Abstract $auth
@return Zend_Amf_Server | entailment |
protected function _checkAcl($object, $function)
{
if(!$this->_acl) {
return true;
}
if($object) {
$class = is_object($object)?get_class($object):$object;
if(!$this->_acl->has($class)) {
require_once 'Zend/Acl/Resource.php';
$this->_acl->add(new Zend_Acl_Resource($class));
}
$call = array($object, "initAcl");
if(is_callable($call) && !call_user_func($call, $this->_acl)) {
// if initAcl returns false, no ACL check
return true;
}
} else {
$class = null;
}
$auth = Zend_Auth::getInstance();
if($auth->hasIdentity()) {
$role = $auth->getIdentity()->role;
} else {
if($this->_acl->hasRole(Zend_Amf_Constants::GUEST_ROLE)) {
$role = Zend_Amf_Constants::GUEST_ROLE;
} else {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception("Unauthenticated access not allowed");
}
}
if($this->_acl->isAllowed($role, $class, $function)) {
return true;
} else {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception("Access not allowed");
}
} | Check if the ACL allows accessing the function or method
@param string|object $object Object or class being accessed
@param string $function Function or method being accessed
@return unknown_type | entailment |
protected function _loadCommandMessage(Zend_Amf_Value_Messaging_CommandMessage $message)
{
require_once 'Zend/Amf/Value/Messaging/AcknowledgeMessage.php';
switch($message->operation) {
case Zend_Amf_Value_Messaging_CommandMessage::DISCONNECT_OPERATION :
case Zend_Amf_Value_Messaging_CommandMessage::CLIENT_PING_OPERATION :
$return = new Zend_Amf_Value_Messaging_AcknowledgeMessage($message);
break;
case Zend_Amf_Value_Messaging_CommandMessage::LOGIN_OPERATION :
$data = explode(':', base64_decode($message->body));
$userid = $data[0];
$password = isset($data[1])?$data[1]:"";
if(empty($userid)) {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Login failed: username not supplied');
}
if(!$this->_handleAuth($userid, $password)) {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Authentication failed');
}
$return = new Zend_Amf_Value_Messaging_AcknowledgeMessage($message);
break;
case Zend_Amf_Value_Messaging_CommandMessage::LOGOUT_OPERATION :
if($this->_auth) {
Zend_Auth::getInstance()->clearIdentity();
}
$return = new Zend_Amf_Value_Messaging_AcknowledgeMessage($message);
break;
default :
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('CommandMessage::' . $message->operation . ' not implemented');
break;
}
return $return;
} | Handles each of the 11 different command message types.
A command message is a flex.messaging.messages.CommandMessage
@see Zend_Amf_Value_Messaging_CommandMessage
@param Zend_Amf_Value_Messaging_CommandMessage $message
@return Zend_Amf_Value_Messaging_AcknowledgeMessage | entailment |
protected function _errorMessage($objectEncoding, $message, $description, $detail, $code, $line)
{
$return = null;
switch ($objectEncoding) {
case Zend_Amf_Constants::AMF0_OBJECT_ENCODING :
return array (
'description' => ($this->isProduction ()) ? '' : $description,
'detail' => ($this->isProduction ()) ? '' : $detail,
'line' => ($this->isProduction ()) ? 0 : $line,
'code' => $code
);
case Zend_Amf_Constants::AMF3_OBJECT_ENCODING :
require_once 'Zend/Amf/Value/Messaging/ErrorMessage.php';
$return = new Zend_Amf_Value_Messaging_ErrorMessage ( $message );
$return->faultString = $this->isProduction () ? '' : $description;
$return->faultCode = $code;
$return->faultDetail = $this->isProduction () ? '' : $detail;
break;
}
return $return;
} | Create appropriate error message
@param int $objectEncoding Current AMF encoding
@param string $message Message that was being processed when error happened
@param string $description Error description
@param mixed $detail Detailed data about the error
@param int $code Error code
@param int $line Error line
@return Zend_Amf_Value_Messaging_ErrorMessage|array | entailment |
protected function _handleAuth( $userid, $password)
{
if (!$this->_auth) {
return true;
}
$this->_auth->setCredentials($userid, $password);
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($this->_auth);
if ($result->isValid()) {
if (!$this->isSession()) {
$this->setSession();
}
return true;
} else {
// authentication failed, good bye
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception(
"Authentication failed: " . join("\n",
$result->getMessages()), $result->getCode());
}
} | Handle AMF authentication
@param string $userid
@param string $password
@return boolean | entailment |
protected function _handle(Zend_Amf_Request $request)
{
// Get the object encoding of the request.
$objectEncoding = $request->getObjectEncoding();
// create a response object to place the output from the services.
$response = $this->getResponse();
// set response encoding
$response->setObjectEncoding($objectEncoding);
// Authenticate, if we have credential headers
$error = false;
$headers = $request->getAmfHeaders();
if (isset($headers[Zend_Amf_Constants::CREDENTIALS_HEADER])
&& isset($headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->userid)
&& isset($headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->password)
) {
try {
if ($this->_handleAuth(
$headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->userid,
$headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->password
)) {
// use RequestPersistentHeader to clear credentials
$response->addAmfHeader(
new Zend_Amf_Value_MessageHeader(
Zend_Amf_Constants::PERSISTENT_HEADER,
false,
new Zend_Amf_Value_MessageHeader(
Zend_Amf_Constants::CREDENTIALS_HEADER,
false, null
)
)
);
}
} catch (Exception $e) {
// Error during authentication; report it
$error = $this->_errorMessage(
$objectEncoding,
'',
$e->getMessage(),
$e->getTraceAsString(),
$e->getCode(),
$e->getLine()
);
$responseType = Zend_AMF_Constants::STATUS_METHOD;
}
}
// Iterate through each of the service calls in the AMF request
foreach($request->getAmfBodies() as $body)
{
if ($error) {
// Error during authentication; just report it and be done
$responseURI = $body->getResponseURI() . $responseType;
$newBody = new Zend_Amf_Value_MessageBody($responseURI, null, $error);
$response->addAmfBody($newBody);
continue;
}
try {
switch ($objectEncoding) {
case Zend_Amf_Constants::AMF0_OBJECT_ENCODING:
// AMF0 Object Encoding
$targetURI = $body->getTargetURI();
$message = '';
// Split the target string into its values.
$source = substr($targetURI, 0, strrpos($targetURI, '.'));
if ($source) {
// Break off method name from namespace into source
$method = substr(strrchr($targetURI, '.'), 1);
$return = $this->_dispatch($method, $body->getData(), $source);
} else {
// Just have a method name.
$return = $this->_dispatch($targetURI, $body->getData());
}
break;
case Zend_Amf_Constants::AMF3_OBJECT_ENCODING:
default:
// AMF3 read message type
$message = $body->getData();
if ($message instanceof Zend_Amf_Value_Messaging_CommandMessage) {
// async call with command message
$return = $this->_loadCommandMessage($message);
} elseif ($message instanceof Zend_Amf_Value_Messaging_RemotingMessage) {
require_once 'Zend/Amf/Value/Messaging/AcknowledgeMessage.php';
$return = new Zend_Amf_Value_Messaging_AcknowledgeMessage($message);
$return->body = $this->_dispatch($message->operation, $message->body, $message->source);
} else {
// Amf3 message sent with netConnection
$targetURI = $body->getTargetURI();
// Split the target string into its values.
$source = substr($targetURI, 0, strrpos($targetURI, '.'));
if ($source) {
// Break off method name from namespace into source
$method = substr(strrchr($targetURI, '.'), 1);
$return = $this->_dispatch($method, $body->getData(), $source);
} else {
// Just have a method name.
$return = $this->_dispatch($targetURI, $body->getData());
}
}
break;
}
$responseType = Zend_AMF_Constants::RESULT_METHOD;
} catch (Exception $e) {
$return = $this->_errorMessage($objectEncoding, $message,
$e->getMessage(), $e->getTraceAsString(),$e->getCode(), $e->getLine());
$responseType = Zend_AMF_Constants::STATUS_METHOD;
}
$responseURI = $body->getResponseURI() . $responseType;
$newBody = new Zend_Amf_Value_MessageBody($responseURI, null, $return);
$response->addAmfBody($newBody);
}
// Add a session header to the body if session is requested.
if($this->isSession()) {
$currentID = session_id();
$joint = "?";
if(isset($_SERVER['QUERY_STRING'])) {
if(!strpos($_SERVER['QUERY_STRING'], $currentID) !== FALSE) {
if(strrpos($_SERVER['QUERY_STRING'], "?") !== FALSE) {
$joint = "&";
}
}
}
// create a new AMF message header with the session id as a variable.
$sessionValue = $joint . $this->_sessionName . "=" . $currentID;
$sessionHeader = new Zend_Amf_Value_MessageHeader(Zend_Amf_Constants::URL_APPEND_HEADER, false, $sessionValue);
$response->addAmfHeader($sessionHeader);
}
// serialize the response and return serialized body.
$response->finalize();
} | Takes the deserialized AMF request and performs any operations.
@todo should implement and SPL observer pattern for custom AMF headers
@todo DescribeService support
@param Zend_Amf_Request $request
@return Zend_Amf_Response
@throws Zend_Amf_server_Exception|Exception | entailment |
public function handle($request = null)
{
// Check if request was passed otherwise get it from the server
if ($request === null || !$request instanceof Zend_Amf_Request) {
$request = $this->getRequest();
} else {
$this->setRequest($request);
}
if ($this->isSession()) {
// Check if a session is being sent from the amf call
if (isset($_COOKIE[$this->_sessionName])) {
session_id($_COOKIE[$this->_sessionName]);
}
}
// Check for errors that may have happend in deserialization of Request.
try {
// Take converted PHP objects and handle service call.
// Serialize to Zend_Amf_response for output stream
$this->_handle($request);
$response = $this->getResponse();
} catch (Exception $e) {
// Handle any errors in the serialization and service calls.
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Handle error: ' . $e->getMessage() . ' ' . $e->getLine(), 0, $e);
}
// Return the Amf serialized output string
return $response;
} | Handle an AMF call from the gateway.
@param null|Zend_Amf_Request $request Optional
@return Zend_Amf_Response | entailment |
public function setRequest($request)
{
if (is_string($request) && class_exists($request)) {
$request = new $request();
if (!$request instanceof Zend_Amf_Request) {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Invalid request class');
}
} elseif (!$request instanceof Zend_Amf_Request) {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Invalid request object');
}
$this->_request = $request;
return $this;
} | Set request object
@param string|Zend_Amf_Request $request
@return Zend_Amf_Server | entailment |
public function setResponse($response)
{
if (is_string($response) && class_exists($response)) {
$response = new $response();
if (!$response instanceof Zend_Amf_Response) {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Invalid response class');
}
} elseif (!$response instanceof Zend_Amf_Response) {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Invalid response object');
}
$this->_response = $response;
return $this;
} | Public access method to private Zend_Amf_Server_Response reference
@param string|Zend_Amf_Server_Response $response
@return Zend_Amf_Server | entailment |
public function getResponse()
{
if (null === ($response = $this->_response)) {
require_once 'Zend/Amf/Response/Http.php';
$this->setResponse(new Zend_Amf_Response_Http());
}
return $this->_response;
} | get a reference to the Zend_Amf_response instance
@return Zend_Amf_Server_Response | entailment |
public function setClass($class, $namespace = '', $argv = null)
{
if (is_string($class) && !class_exists($class)){
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Invalid method or class');
} elseif (!is_string($class) && !is_object($class)) {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Invalid method or class; must be a classname or object');
}
$argv = null;
if (2 < func_num_args()) {
$argv = array_slice(func_get_args(), 2);
}
// Use the class name as the name space by default.
if ($namespace == '') {
$namespace = is_object($class) ? get_class($class) : $class;
}
$this->_classAllowed[is_object($class) ? get_class($class) : $class] = true;
$this->_methods[] = Zend_Server_Reflection::reflectClass($class, $argv, $namespace);
$this->_buildDispatchTable();
return $this;
} | Attach a class or object to the server
Class may be either a class name or an instantiated object. Reflection
is done on the class or object to determine the available public
methods, and each is attached to the server as and available method. If
a $namespace has been provided, that namespace is used to prefix
AMF service call.
@param string|object $class
@param string $namespace Optional
@param mixed $arg Optional arguments to pass to a method
@return Zend_Amf_Server
@throws Zend_Amf_Server_Exception on invalid input | entailment |
public function addFunction($function, $namespace = '')
{
if (!is_string($function) && !is_array($function)) {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Unable to attach function');
}
$argv = null;
if (2 < func_num_args()) {
$argv = array_slice(func_get_args(), 2);
}
$function = (array) $function;
foreach ($function as $func) {
if (!is_string($func) || !function_exists($func)) {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Unable to attach function');
}
$this->_methods[] = Zend_Server_Reflection::reflectFunction($func, $argv, $namespace);
}
$this->_buildDispatchTable();
return $this;
} | Attach a function to the server
Additional arguments to pass to the function at dispatch may be passed;
any arguments following the namespace will be aggregated and passed at
dispatch time.
@param string|array $function Valid callback
@param string $namespace Optional namespace prefix
@return Zend_Amf_Server
@throws Zend_Amf_Server_Exception | entailment |
public function getCMSFields() {
$fields=new FieldList(
new TabSet('Root',
new Tab('Main', _t('SnippetPackage.MAIN', '_Main'),
new TextField('Title', _t('SnippetPackage.TITLE', '_Title'), null, 300)
)
),
new HiddenField('ID', 'ID')
);
if($this->ID==0) {
$fields->addFieldToTab('Root.Main', new LabelField('Snippets', _t('SnippetPackage.SNIPPETS_AFTER_FIRST_SAVE', '_Snippets can be added after saving for the first time')));
}else {
$packageGrid=new GridField('Snippets', _t('SnippetPackage.PACKAGE_SNIPPETS', '_Package Snippets'), $this->Snippets(), GridFieldConfig_RelationEditor::create(10));
$packageGrid->getConfig()->removeComponentsByType('GridFieldEditButton')
->removeComponentsByType('GridFieldAddNewButton')
->addComponent(new PackageViewButton())
->getComponentByType('GridFieldAddExistingAutocompleter')->setSearchFields(array('Title'))->setplaceholderText(_t('SnippetPackage.FIND_SNIPPETS_BY_TITLE', '_Find Snippets by Title'));
$fields->addFieldToTab('Root.Main', new LiteralField('SnippetAddWarning', '<p class="message warning">'._t('SnippetPackage.ADD_WARNING', '_Warning if you link a snippet that is already in another package it will be moved to this package').'</p>'));
$fields->addFieldToTab('Root.Main', $packageGrid);
}
return $fields;
} | Gets fields used in the cms
@return {FieldList} Fields to be used | entailment |
public function handleAuthenticationSuccess(TokenInterface $token, Request $request, GuardAuthenticatorInterface $guardAuthenticator, $providerKey)
{
$response = $guardAuthenticator->onAuthenticationSuccess($request, $token, $providerKey);
// check that it's a Response or null
if ($response instanceof Response || null === $response) {
return $response;
}
throw new \UnexpectedValueException(sprintf(
'The %s::onAuthenticationSuccess method must return null or a Response object. You returned %s.',
get_class($guardAuthenticator),
is_object($response) ? get_class($response) : gettype($response)
));
} | Returns the "on success" response for the given GuardAuthenticator.
@param TokenInterface $token
@param Request $request
@param GuardAuthenticatorInterface $guardAuthenticator
@param string $providerKey The provider (i.e. firewall) key
@return null|Response | entailment |
public function authenticateUserAndHandleSuccess(UserInterface $user, Request $request, GuardAuthenticatorInterface $authenticator, $providerKey)
{
// create an authenticated token for the User
$token = $authenticator->createAuthenticatedToken($user, $providerKey);
// authenticate this in the system
$this->authenticateWithToken($token, $request);
// return the success metric
return $this->handleAuthenticationSuccess($token, $request, $authenticator, $providerKey);
} | Convenience method for authenticating the user and returning the
Response *if any* for success.
@param UserInterface $user
@param Request $request
@param GuardAuthenticatorInterface $authenticator
@param string $providerKey The provider (i.e. firewall) key
@return Response|null | entailment |
public function handleAuthenticationFailure(AuthenticationException $authenticationException, Request $request, GuardAuthenticatorInterface $guardAuthenticator)
{
$this->tokenStorage->setToken(null);
$response = $guardAuthenticator->onAuthenticationFailure($request, $authenticationException);
if ($response instanceof Response || null === $response) {
// returning null is ok, it means they want the request to continue
return $response;
}
throw new \UnexpectedValueException(sprintf(
'The %s::onAuthenticationFailure method must return null or a Response object. You returned %s.',
get_class($guardAuthenticator),
is_object($response) ? get_class($response) : gettype($response)
));
} | Handles an authentication failure and returns the Response for the
GuardAuthenticator.
@param AuthenticationException $authenticationException
@param Request $request
@param GuardAuthenticatorInterface $guardAuthenticator
@return null|Response | entailment |
public function readBytes($length)
{
if (($length + $this->_needle) > $this->_streamLength) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Buffer underrun at needle position: ' . $this->_needle . ' while requesting length: ' . $length);
}
$bytes = substr($this->_stream, $this->_needle, $length);
$this->_needle+= $length;
return $bytes;
} | Read the number of bytes in a row for the length supplied.
@todo Should check that there are enough bytes left in the stream we are about to read.
@param int $length
@return string
@throws Zend_Amf_Exception for buffer underrun | entailment |
public function readByte()
{
if (($this->_needle + 1) > $this->_streamLength) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Buffer underrun at needle position: ' . $this->_needle . ' while requesting length: ' . $length);
}
return ord($this->_stream{$this->_needle++});
} | Reads a signed byte
@return int Value is in the range of -128 to 127. | entailment |
public function writeUtf($stream)
{
$this->writeInt(strlen($stream));
$this->_stream.= $stream;
return $this;
} | Wite a UTF-8 string to the outputstream
@param string $stream
@return Zend_Amf_Util_BinaryStream | entailment |
public function readDouble()
{
$bytes = substr($this->_stream, $this->_needle, 8);
$this->_needle+= 8;
if (!$this->_bigEndian) {
$bytes = strrev($bytes);
}
$double = unpack('dflt', $bytes);
return $double['flt'];
} | Reads an IEEE 754 double-precision floating point number from the data stream.
@return double Floating point number | entailment |
public function writeDouble($stream)
{
$stream = pack('d', $stream);
if (!$this->_bigEndian) {
$stream = strrev($stream);
}
$this->_stream.= $stream;
return $this;
} | Writes an IEEE 754 double-precision floating point number from the data stream.
@param string|double $stream
@return Zend_Amf_Util_BinaryStream | entailment |
public function setFile($path)
{
if (empty($path) || !is_readable($path)) {
/**
* @see Zend_Auth_Adapter_Http_Resolver_Exception
*/
require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php';
throw new Zend_Auth_Adapter_Http_Resolver_Exception('Path not readable: ' . $path);
}
$this->_file = $path;
return $this;
} | Set the path to the credentials file
@param string $path
@throws Zend_Auth_Adapter_Http_Resolver_Exception
@return Zend_Auth_Adapter_Http_Resolver_File Provides a fluent interface | entailment |
public function resolve($username, $realm)
{
if (empty($username)) {
/**
* @see Zend_Auth_Adapter_Http_Resolver_Exception
*/
require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php';
throw new Zend_Auth_Adapter_Http_Resolver_Exception('Username is required');
} else if (!ctype_print($username) || strpos($username, ':') !== false) {
/**
* @see Zend_Auth_Adapter_Http_Resolver_Exception
*/
require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php';
throw new Zend_Auth_Adapter_Http_Resolver_Exception('Username must consist only of printable characters, '
. 'excluding the colon');
}
if (empty($realm)) {
/**
* @see Zend_Auth_Adapter_Http_Resolver_Exception
*/
require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php';
throw new Zend_Auth_Adapter_Http_Resolver_Exception('Realm is required');
} else if (!ctype_print($realm) || strpos($realm, ':') !== false) {
/**
* @see Zend_Auth_Adapter_Http_Resolver_Exception
*/
require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php';
throw new Zend_Auth_Adapter_Http_Resolver_Exception('Realm must consist only of printable characters, '
. 'excluding the colon.');
}
// Open file, read through looking for matching credentials
$fp = @fopen($this->_file, 'r');
if (!$fp) {
/**
* @see Zend_Auth_Adapter_Http_Resolver_Exception
*/
require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php';
throw new Zend_Auth_Adapter_Http_Resolver_Exception('Unable to open password file: ' . $this->_file);
}
// No real validation is done on the contents of the password file. The
// assumption is that we trust the administrators to keep it secure.
while (($line = fgetcsv($fp, 512, ':')) !== false) {
if ($line[0] == $username && $line[1] == $realm) {
$password = $line[2];
fclose($fp);
return $password;
}
}
fclose($fp);
return false;
} | Resolve credentials
Only the first matching username/realm combination in the file is
returned. If the file contains credentials for Digest authentication,
the returned string is the password hash, or h(a1) from RFC 2617. The
returned string is the plain-text password for Basic authentication.
The expected format of the file is:
username:realm:sharedSecret
That is, each line consists of the user's username, the applicable
authentication realm, and the password or hash, each delimited by
colons.
@param string $username Username
@param string $realm Authentication Realm
@throws Zend_Auth_Adapter_Http_Resolver_Exception
@return string|false User's shared secret, if the user is found in the
realm, false otherwise. | entailment |
public function positiveMatch(string $name, $subject, array $arguments): ?\PhpSpec\Wrapper\DelayedCall
{
list($realEvents, $targetEvents) = $this->formatArguments($subject, $arguments);
$notFoundEvents = $this->eventsNotFound($realEvents, $targetEvents);
if ( ! empty($notFoundEvents)) {
$eventNames = join(', ', array_map(function (DomainEvent $event) {
return '<label>' . get_class($event) . '</label>';
}, $notFoundEvents));
throw new FailureException("Expected matching event(s) {$eventNames} not found.");
}
return null;
} | Evaluates positive match.
Yes, I know that this is some really hard to understand code.
This is one of the more interesting areas to improve upon
@param string $name
@param mixed $subject
@param array $arguments | entailment |
private function eventIsFound(DomainEvent $targetEvent, DomainEvents $realEvents)
{
$found = $realEvents->filter(function ($realEvent) use ($targetEvent) {
try {
$eventsAreEqual = $this->eventsAreEqual($realEvent, $targetEvent);
} catch (FailureException $e) {
$eventsAreEqual = false;
}
return $eventsAreEqual;
});
return $found->count() != 0;
} | returns true if an event is found | entailment |
private function eventsAreEqual($e1, $e2)
{
// events aren't equal if they have different classes
if (get_class($e1) != get_class($e2)) {
return false;
}
// compare their values..
$reflection = new \ReflectionClass($e1);
$fields = array_map(function ($property) {
return $property->name;
}, $reflection->getProperties());
$allMatch = true;
foreach ($fields as $field) {
// compare the single field across both events
$property = new \ReflectionProperty(get_class($e1), $field);
$property->setAccessible(true);
$e1Value = $property->getValue($e1);
$e2Value = $property->getValue($e2);
if (is_array($e1Value)) {
// this part isn't done, jsut copied, think it through
for ($i = 0; $i < count($e1Value); $i++) {
$setMatches = $this->compareProperties($e1, $e1Value[$i], $e2Value[$i], $property);
if ( ! $setMatches) {
$allMatch = false;
}
}
} else {
$setMatches = $this->compareProperties($e1, $e1Value, $e2Value, $property);
if ( ! $setMatches) {
$allMatch = false;
}
}
}
return $allMatch;
} | pull requests accepted | entailment |
public function uploadFileAction(Request $request, $dir_path)
{
/** @var FileManagerService $service */
$service = $this->get('youwe.file_manager.service');
/** @var FileManagerDriver $driver */
$driver = $this->get('youwe.file_manager.driver');
$parameters = $this->container->getParameter('youwe_file_manager');
$fileManager = $service->createFileManager($parameters, $driver, $dir_path);
$form = $this->createForm(new FileManagerType);
if ('POST' === $request->getMethod()) {
$form->handleRequest($request);
if ($form->isValid()) {
$fileManager->checkPath();
$files = $form->get("file")->getData();
if (!is_null($files)) {
$service->handleUploadFiles($files);
}
} else {
throw new \Exception("Form is invalid", 500);
}
}
return new Response();
} | @Route(
"/upload/{dir_path}",
name="youwe_file_manager_upload",
options={"expose":true},
requirements={"dir_path":".+"}
)
@Route("/upload/", name="youwe_file_manager_upload_root", options={"expose":true}, defaults={"dir_path":""})
@param Request $request
@param string $dir_path
@return Response
@throws \Exception when form is not valid | entailment |
public function fileActions(Request $request, $action)
{
if ($action === FileManager::FILE_PASTE && !$this->get('session')->has('copy')) {
return new Response();
}
/** @var FileManagerService $service */
$service = $this->get('youwe.file_manager.service');
if (!$service->isAllowedGetAction($action) && $request->getMethod() === 'GET') {
throw new \Exception("Method Not Allowed", 405);
}
/** @var FileManagerDriver $driver */
$driver = $this->get('youwe.file_manager.driver');
$parameters = $this->container->getParameter('youwe_file_manager');
$fileManager = $service->createFileManager($parameters, $driver);
$fileManager->resolveRequest($request, $action);
return $service->handleAction($fileManager, $request, $action);
} | @Route("/delete", name="youwe_file_manager_delete", defaults={"action":FileManager::FILE_DELETE}, options={"expose":true})
@Route("/move", name="youwe_file_manager_move", defaults={"action":FileManager::FILE_MOVE}, options={"expose":true})
@Route("/extract", name="youwe_file_manager_extract", defaults={"action":FileManager::FILE_EXTRACT}, options={"expose":true})
@Route("/rename", name="youwe_file_manager_rename", defaults={"action":FileManager::FILE_RENAME}, options={"expose":true})
@Route("/new-dir", name="youwe_file_manager_new_dir", defaults={"action":FileManager::FILE_NEW_DIR}, options={"expose":true})
@Route("/copy", name="youwe_file_manager_copy", defaults={"action":FileManager::FILE_COPY}, options={"expose":true})
@Route("/cut", name="youwe_file_manager_cut", defaults={"action":FileManager::FILE_CUT}, options={"expose":true})
@Route("/paste", name="youwe_file_manager_paste", defaults={"action":FileManager::FILE_PASTE}, options={"expose":true})
@Route("/fileinfo", name="youwe_file_manager_fileinfo", defaults={"action":FileManager::FILE_INFO}, options={"expose":true})
@param Request $request
@param string $action the action that is requested
@return Response
@throws \Exception when the request method is not allowed | entailment |
public function DownloadAction(Request $request, $path)
{
/** @var FileManagerService $service */
$service = $this->get('youwe.file_manager.service');
$service->checkToken($request->get('token'));
/** @var FileManagerDriver $driver */
$driver = $this->get('youwe.file_manager.driver');
$parameters = $this->container->getParameter('youwe_file_manager');
$fileManager = $service->createFileManager($parameters, $driver);
$filepath = $fileManager->getPath($path, null, true);
$content = file_get_contents($filepath);
$filename = basename($path);
$response = new Response();
$response->headers->set('Content-Type', 'mime/type');
$response->headers->set('Content-Disposition', 'attachment;filename="' . $filename . '"');
$response->setContent($content);
return $response;
} | @Route(
"/download/{token}/{path}",
name="youwe_file_manager_download",
requirements={"path"=".+"},
options={"expose":true}
)
@param Request $request
@param string $path the path of the file that is downloaded
@return Response | entailment |
public function authenticate() {
$id = $this->_id;
if (!empty($id)) {
$consumer = new Zend_OpenId_Consumer($this->_storage);
$consumer->setHttpClient($this->_httpClient);
/* login() is never returns on success */
if (!$this->_check_immediate) {
if (!$consumer->login($id,
$this->_returnTo,
$this->_root,
$this->_extensions,
$this->_response)) {
return new Zend_Auth_Result(
Zend_Auth_Result::FAILURE,
$id,
array("Authentication failed", $consumer->getError()));
}
} else {
if (!$consumer->check($id,
$this->_returnTo,
$this->_root,
$this->_extensions,
$this->_response)) {
return new Zend_Auth_Result(
Zend_Auth_Result::FAILURE,
$id,
array("Authentication failed", $consumer->getError()));
}
}
} else {
$params = (isset($_SERVER['REQUEST_METHOD']) &&
$_SERVER['REQUEST_METHOD']=='POST') ? $_POST: $_GET;
$consumer = new Zend_OpenId_Consumer($this->_storage);
$consumer->setHttpClient($this->_httpClient);
if ($consumer->verify(
$params,
$id,
$this->_extensions)) {
return new Zend_Auth_Result(
Zend_Auth_Result::SUCCESS,
$id,
array("Authentication successful"));
} else {
return new Zend_Auth_Result(
Zend_Auth_Result::FAILURE,
$id,
array("Authentication failed", $consumer->getError()));
}
}
} | Authenticates the given OpenId identity.
Defined by Zend_Auth_Adapter_Interface.
@throws Zend_Auth_Adapter_Exception If answering the authentication query is impossible
@return Zend_Auth_Result | entailment |
protected function guardType($items) : void {
// this allows guardType($items) to receive
// both a single item or an array of items
if ( ! is_array($items)) {
$items = array($items);
}
// throw an exception if any items are not
// an instance of the required type
foreach ($items as $item) {
if ( ! $item instanceof $this->collectionType) {
throw new \InvalidArgumentException(
"Got " . (is_object($item) ? get_class($item) : $item) . " but expected " . $this->collectionType
);
}
}
} | ensure that items added to the collection conform to
the defined collection type
@param $items | entailment |
public function map(Callable $f) : Collection {
try {
return new static(array_map($f, $this->items));
} catch (\Exception $e) {
return new Collection(array_map($f, $this->items));
}
} | return a new instance of this collection with values that
have been transformed by the provided function.
if the values conform to the defined type for this collection
then the new collection instance will be of the same type
as the original.
if the values do not conform to the defined type then a
generic untyped collection will be returned instead.
@param callable $f
@return Collection | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.