repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
oat-sa/tao-core
models/classes/metadata/import/OntologyMetadataImporter.php
OntologyMetadataImporter.getInjectors
protected function getInjectors() { if (empty($this->injectors)) { try { foreach(array_keys($this->getOptions()) as $injectorName) { /** @var Injector $injector */ $injector = $this->getSubService($injectorName, Injector::class); $injector->createInjectorHelpers(); $this->injectors[$injectorName] = $injector; } } catch (ServiceNotFoundException $e) { throw new InconsistencyConfigException($e->getMessage()); } catch (InvalidService $e) { throw new InconsistencyConfigException($e->getMessage()); } if (empty($this->injectors)) { throw new InconsistencyConfigException('No injector found into config.'); } } return $this->injectors; }
php
protected function getInjectors() { if (empty($this->injectors)) { try { foreach(array_keys($this->getOptions()) as $injectorName) { /** @var Injector $injector */ $injector = $this->getSubService($injectorName, Injector::class); $injector->createInjectorHelpers(); $this->injectors[$injectorName] = $injector; } } catch (ServiceNotFoundException $e) { throw new InconsistencyConfigException($e->getMessage()); } catch (InvalidService $e) { throw new InconsistencyConfigException($e->getMessage()); } if (empty($this->injectors)) { throw new InconsistencyConfigException('No injector found into config.'); } } return $this->injectors; }
[ "protected", "function", "getInjectors", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "injectors", ")", ")", "{", "try", "{", "foreach", "(", "array_keys", "(", "$", "this", "->", "getOptions", "(", ")", ")", "as", "$", "injectorName", ...
Get metadata injectors from config @return Injector[] @throws InconsistencyConfigException
[ "Get", "metadata", "injectors", "from", "config" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/metadata/import/OntologyMetadataImporter.php#L121-L142
oat-sa/tao-core
scripts/class.Runner.php
tao_scripts_Runner.validateInput
private function validateInput() { $returnValue = (bool) false; $returnValue = true; /** * Parse the arguments from the command lines * and set them into the parameter variable. * All the current formats are allowed: * <code> * php script.php -arg1 value1 -arg2 value2 * php script.php --arg1 value1 --arg2 value2 * php script.php -arg1=value1 -arg2=value2 * php script.php --arg1=value1 --arg2=value2 * php script.php value1 value2 //the key will be numeric * </code> */ $i = 1; while($i < count($this->argv)){ $arg = trim($this->argv[$i]); if(!empty($arg)){ // command -(-)arg1=value1 if(preg_match("/^[\-]{1,2}\w+=(.*)+$/", $arg)){ $sequence = explode('=', preg_replace("/^[\-]{1,}/", '', $arg)); if(count($sequence) >= 2){ $this->parameters[$sequence[0]] = $sequence[1]; } } // command -(-)arg1 value1 value2 else if(preg_match("/^[\-]{1,2}\w+$/", $arg)){ $key = preg_replace("/^[\-]{1,}/", '', $arg); $this->parameters[$key] = ''; while(isset($this->argv[$i + 1]) && substr(trim($this->argv[$i + 1]),0,1)!='-') { $this->parameters[$key] .= trim($this->argv[++$i]).' '; } $this->parameters[$key] = substr($this->parameters[$key], 0, -1); } // command value1 value2 else{ $this->parameters[$i] = $arg; } } $i++; } //replaces shortcuts by their original names if (isset($this->inputFormat['parameters'])) { foreach($this->inputFormat['parameters'] as $parameter){ if(isset($parameter['shortcut'])){ $short = $parameter['shortcut']; $long = $parameter['name']; if(array_key_exists($short, $this->parameters) && !array_key_exists($long, $this->parameters)){ $this->parameters[$long] = $this->parameters[$short]; unset($this->parameters[$short]); } } } } //one we have the parameters, we can validate it if(isset($this->inputFormat['min'])){ $min = (int) $this->inputFormat['min']; $found = count($this->parameters); if($found < $min){ $this->err("Invalid parameter count: $found parameters found ($min expected)"); $returnValue = false; } } if(isset($this->inputFormat['required']) && is_array($this->inputFormat['required']) && count($this->inputFormat['required'])){ $requireds = array(); if(!is_array($this->inputFormat['required'][0])){ $requireds = array($this->inputFormat['required']); }else{ $requireds = $this->inputFormat['required']; } $found = false; foreach($requireds as $required){ $matched = 0; foreach($required as $parameter){ if(array_key_exists($parameter, $this->parameters)){ $matched++; } } if($matched == count($required)){ $found = true; break; } } if(!$found){ $this->err("Unable to find required arguments"); $returnValue = false; } } if($returnValue && isset($this->inputFormat['parameters'])){ foreach($this->inputFormat['parameters'] as $parameter){ if(isset($this->parameters[$parameter['name']])){ $input = $this->parameters[$parameter['name']]; switch($parameter['type']){ case 'file': if( !is_file($input) || !file_exists($input) || !is_readable($input)) { $this->err("Unable to access to the file: $input"); $returnValue = false; } break; case 'dir': if( !is_dir($input) || !is_readable($input)) { $this->err("Unable to access to the directory: $input"); $returnValue = false; } break; case 'path': if( !is_dir(dirname($input)) ) { $this->err("Wrong path given: $input"); $returnValue = false; } break; case 'int': case 'float': case 'double': if(!is_numeric($input)){ $this->err("$input is not a valid ".$parameter['type']); $returnValue = false; } break; case 'string': if(!is_string($input)){ $this->err("$input is not a valid ".$parameter['type']); $returnValue = false; } break; case 'boolean': if(!is_bool($input) && strtolower($input) != 'true' && strtolower($input) != 'false' && !empty($input)){ $this->err("$input is not a valid ".$parameter['type']); $returnValue = false; }else{ if(is_bool($input)){ $this->parameters[$parameter['name']] = $input = settype($input, 'boolean'); } else if(!empty($input)){ $this->parameters[$parameter['name']] = ((strtolower($input) == 'true') ? true : false); } else{ $this->parameters[$parameter['name']] = true; } } break; } } } } return (bool) $returnValue; }
php
private function validateInput() { $returnValue = (bool) false; $returnValue = true; /** * Parse the arguments from the command lines * and set them into the parameter variable. * All the current formats are allowed: * <code> * php script.php -arg1 value1 -arg2 value2 * php script.php --arg1 value1 --arg2 value2 * php script.php -arg1=value1 -arg2=value2 * php script.php --arg1=value1 --arg2=value2 * php script.php value1 value2 //the key will be numeric * </code> */ $i = 1; while($i < count($this->argv)){ $arg = trim($this->argv[$i]); if(!empty($arg)){ // command -(-)arg1=value1 if(preg_match("/^[\-]{1,2}\w+=(.*)+$/", $arg)){ $sequence = explode('=', preg_replace("/^[\-]{1,}/", '', $arg)); if(count($sequence) >= 2){ $this->parameters[$sequence[0]] = $sequence[1]; } } // command -(-)arg1 value1 value2 else if(preg_match("/^[\-]{1,2}\w+$/", $arg)){ $key = preg_replace("/^[\-]{1,}/", '', $arg); $this->parameters[$key] = ''; while(isset($this->argv[$i + 1]) && substr(trim($this->argv[$i + 1]),0,1)!='-') { $this->parameters[$key] .= trim($this->argv[++$i]).' '; } $this->parameters[$key] = substr($this->parameters[$key], 0, -1); } // command value1 value2 else{ $this->parameters[$i] = $arg; } } $i++; } //replaces shortcuts by their original names if (isset($this->inputFormat['parameters'])) { foreach($this->inputFormat['parameters'] as $parameter){ if(isset($parameter['shortcut'])){ $short = $parameter['shortcut']; $long = $parameter['name']; if(array_key_exists($short, $this->parameters) && !array_key_exists($long, $this->parameters)){ $this->parameters[$long] = $this->parameters[$short]; unset($this->parameters[$short]); } } } } //one we have the parameters, we can validate it if(isset($this->inputFormat['min'])){ $min = (int) $this->inputFormat['min']; $found = count($this->parameters); if($found < $min){ $this->err("Invalid parameter count: $found parameters found ($min expected)"); $returnValue = false; } } if(isset($this->inputFormat['required']) && is_array($this->inputFormat['required']) && count($this->inputFormat['required'])){ $requireds = array(); if(!is_array($this->inputFormat['required'][0])){ $requireds = array($this->inputFormat['required']); }else{ $requireds = $this->inputFormat['required']; } $found = false; foreach($requireds as $required){ $matched = 0; foreach($required as $parameter){ if(array_key_exists($parameter, $this->parameters)){ $matched++; } } if($matched == count($required)){ $found = true; break; } } if(!$found){ $this->err("Unable to find required arguments"); $returnValue = false; } } if($returnValue && isset($this->inputFormat['parameters'])){ foreach($this->inputFormat['parameters'] as $parameter){ if(isset($this->parameters[$parameter['name']])){ $input = $this->parameters[$parameter['name']]; switch($parameter['type']){ case 'file': if( !is_file($input) || !file_exists($input) || !is_readable($input)) { $this->err("Unable to access to the file: $input"); $returnValue = false; } break; case 'dir': if( !is_dir($input) || !is_readable($input)) { $this->err("Unable to access to the directory: $input"); $returnValue = false; } break; case 'path': if( !is_dir(dirname($input)) ) { $this->err("Wrong path given: $input"); $returnValue = false; } break; case 'int': case 'float': case 'double': if(!is_numeric($input)){ $this->err("$input is not a valid ".$parameter['type']); $returnValue = false; } break; case 'string': if(!is_string($input)){ $this->err("$input is not a valid ".$parameter['type']); $returnValue = false; } break; case 'boolean': if(!is_bool($input) && strtolower($input) != 'true' && strtolower($input) != 'false' && !empty($input)){ $this->err("$input is not a valid ".$parameter['type']); $returnValue = false; }else{ if(is_bool($input)){ $this->parameters[$parameter['name']] = $input = settype($input, 'boolean'); } else if(!empty($input)){ $this->parameters[$parameter['name']] = ((strtolower($input) == 'true') ? true : false); } else{ $this->parameters[$parameter['name']] = true; } } break; } } } } return (bool) $returnValue; }
[ "private", "function", "validateInput", "(", ")", "{", "$", "returnValue", "=", "(", "bool", ")", "false", ";", "$", "returnValue", "=", "true", ";", "/**\r\n * Parse the arguments from the command lines \r\n * and set them into the parameter variable.\r\n ...
Short description of method validateInput @access private @author firstname and lastname of author, <author@example.org> @return boolean
[ "Short", "description", "of", "method", "validateInput" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/scripts/class.Runner.php#L132-L304
oat-sa/tao-core
scripts/class.Runner.php
tao_scripts_Runner.out
public function out($message, $options = array()) { $returnValue = $this->isCli ? $this->renderCliOutput($message,$options) : $this->renderHtmlOutput($message,$options); if ($this->logOny){ //do nothing } else{ echo $returnValue ; } common_Logger::i($message, array('SCRIPTS_RUNNER')); }
php
public function out($message, $options = array()) { $returnValue = $this->isCli ? $this->renderCliOutput($message,$options) : $this->renderHtmlOutput($message,$options); if ($this->logOny){ //do nothing } else{ echo $returnValue ; } common_Logger::i($message, array('SCRIPTS_RUNNER')); }
[ "public", "function", "out", "(", "$", "message", ",", "$", "options", "=", "array", "(", ")", ")", "{", "$", "returnValue", "=", "$", "this", "->", "isCli", "?", "$", "this", "->", "renderCliOutput", "(", "$", "message", ",", "$", "options", ")", ...
Short description of method out @access public @author firstname and lastname of author, <author@example.org> @param string message @param array options
[ "Short", "description", "of", "method", "out" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/scripts/class.Runner.php#L422-L434
oat-sa/tao-core
scripts/class.Runner.php
tao_scripts_Runner.err
protected function err($message, $stopExec = false) { common_Logger::e($message); echo $this->out($message, array('color' => 'light_red')); if($stopExec == true){ $this->handleError(new Exception($message, 1)); } }
php
protected function err($message, $stopExec = false) { common_Logger::e($message); echo $this->out($message, array('color' => 'light_red')); if($stopExec == true){ $this->handleError(new Exception($message, 1)); } }
[ "protected", "function", "err", "(", "$", "message", ",", "$", "stopExec", "=", "false", ")", "{", "common_Logger", "::", "e", "(", "$", "message", ")", ";", "echo", "$", "this", "->", "out", "(", "$", "message", ",", "array", "(", "'color'", "=>", ...
Short description of method err @access protected @author firstname and lastname of author, <author@example.org> @param string message @param boolean stopExec
[ "Short", "description", "of", "method", "err" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/scripts/class.Runner.php#L444-L452
oat-sa/tao-core
scripts/class.Runner.php
tao_scripts_Runner.handleError
protected function handleError(Exception $e) { if($this->isCli){ $errorCode = $e->getCode(); exit((empty($errorCode)) ? 1 : $errorCode); //exit the program with an error } else { throw new Exception($e->getMessage()); } }
php
protected function handleError(Exception $e) { if($this->isCli){ $errorCode = $e->getCode(); exit((empty($errorCode)) ? 1 : $errorCode); //exit the program with an error } else { throw new Exception($e->getMessage()); } }
[ "protected", "function", "handleError", "(", "Exception", "$", "e", ")", "{", "if", "(", "$", "this", "->", "isCli", ")", "{", "$", "errorCode", "=", "$", "e", "->", "getCode", "(", ")", ";", "exit", "(", "(", "empty", "(", "$", "errorCode", ")", ...
Handles a fatal error situation. @param Exception $e @throws Exception
[ "Handles", "a", "fatal", "error", "situation", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/scripts/class.Runner.php#L461-L470
oat-sa/tao-core
scripts/class.Runner.php
tao_scripts_Runner.help
protected function help() { $usage = "Usage:php {$this->argv[0]} [arguments]\n"; $usage .= "\nArguments list:\n"; foreach($this->inputFormat['parameters'] as $parameter){ $line = ''; if(isset($parameter['required'])){ if($parameter['required'] == true){ $line .= "Required"; } else{ $line .= "Optional"; } } else{ //$usage .= "\t"; } $line = str_pad($line, 15).' '; $line .= "--{$parameter['name']}"; if(isset($parameter['shortcut'])){ $line .= "|-{$parameter['shortcut']}"; } $line = str_pad($line, 39).' '; $line .= "{$parameter['description']}"; $usage .= $line."\n"; } $this->out($usage, array('color' => 'light_blue')); }
php
protected function help() { $usage = "Usage:php {$this->argv[0]} [arguments]\n"; $usage .= "\nArguments list:\n"; foreach($this->inputFormat['parameters'] as $parameter){ $line = ''; if(isset($parameter['required'])){ if($parameter['required'] == true){ $line .= "Required"; } else{ $line .= "Optional"; } } else{ //$usage .= "\t"; } $line = str_pad($line, 15).' '; $line .= "--{$parameter['name']}"; if(isset($parameter['shortcut'])){ $line .= "|-{$parameter['shortcut']}"; } $line = str_pad($line, 39).' '; $line .= "{$parameter['description']}"; $usage .= $line."\n"; } $this->out($usage, array('color' => 'light_blue')); }
[ "protected", "function", "help", "(", ")", "{", "$", "usage", "=", "\"Usage:php {$this->argv[0]} [arguments]\\n\"", ";", "$", "usage", ".=", "\"\\nArguments list:\\n\"", ";", "foreach", "(", "$", "this", "->", "inputFormat", "[", "'parameters'", "]", "as", "$", ...
Short description of method help @access protected @author firstname and lastname of author, <author@example.org> @return mixed
[ "Short", "description", "of", "method", "help" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/scripts/class.Runner.php#L479-L510
oat-sa/tao-core
scripts/class.Runner.php
tao_scripts_Runner.outVerbose
public function outVerbose($message, $options = array()) { common_Logger::i($message); if (isset($this->parameters['verbose']) && $this->parameters['verbose'] === true) { $this->out($message, $options); } }
php
public function outVerbose($message, $options = array()) { common_Logger::i($message); if (isset($this->parameters['verbose']) && $this->parameters['verbose'] === true) { $this->out($message, $options); } }
[ "public", "function", "outVerbose", "(", "$", "message", ",", "$", "options", "=", "array", "(", ")", ")", "{", "common_Logger", "::", "i", "(", "$", "message", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "parameters", "[", "'verbose'", "]"...
Short description of method outVerbose @access public @author firstname and lastname of author, <author@example.org> @param string message @param array options @return mixed
[ "Short", "description", "of", "method", "outVerbose" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/scripts/class.Runner.php#L521-L529
oat-sa/tao-core
helpers/form/elements/xhtml/class.File.php
tao_helpers_form_elements_xhtml_File.feed
public function feed() { if (isset($_FILES[$this->getName()])) { $this->setValue($_FILES[$this->getName()]); } else { throw new tao_helpers_form_Exception('cannot evaluate the element ' . __CLASS__); } }
php
public function feed() { if (isset($_FILES[$this->getName()])) { $this->setValue($_FILES[$this->getName()]); } else { throw new tao_helpers_form_Exception('cannot evaluate the element ' . __CLASS__); } }
[ "public", "function", "feed", "(", ")", "{", "if", "(", "isset", "(", "$", "_FILES", "[", "$", "this", "->", "getName", "(", ")", "]", ")", ")", "{", "$", "this", "->", "setValue", "(", "$", "_FILES", "[", "$", "this", "->", "getName", "(", ")"...
Short description of method feed @access public @author Joel Bout, <joel.bout@tudor.lu>
[ "Short", "description", "of", "method", "feed" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/elements/xhtml/class.File.php#L43-L50
oat-sa/tao-core
helpers/form/elements/xhtml/class.File.php
tao_helpers_form_elements_xhtml_File.render
public function render() { if (! empty($this->value)) { if (common_Utils::isUri($this->value)) { $referencer = $this->getServiceLocator()->get(FileReferenceSerializer::SERVICE_ID); /** @var File $file */ $file = $referencer->unserialize($this->value); if (!$file->exists()) { $referencer->cleanup($this->value); } } } $returnValue = $this->renderLabel(); $returnValue .= "<input type='hidden' name='MAX_FILE_SIZE' value='" . tao_helpers_form_elements_File::MAX_FILE_SIZE . "' />"; $returnValue .= "<input type='file' name='{$this->name}' id='{$this->name}' "; $returnValue .= $this->renderAttributes(); $returnValue .= " value='{$this->value}' />"; return (string) $returnValue; }
php
public function render() { if (! empty($this->value)) { if (common_Utils::isUri($this->value)) { $referencer = $this->getServiceLocator()->get(FileReferenceSerializer::SERVICE_ID); /** @var File $file */ $file = $referencer->unserialize($this->value); if (!$file->exists()) { $referencer->cleanup($this->value); } } } $returnValue = $this->renderLabel(); $returnValue .= "<input type='hidden' name='MAX_FILE_SIZE' value='" . tao_helpers_form_elements_File::MAX_FILE_SIZE . "' />"; $returnValue .= "<input type='file' name='{$this->name}' id='{$this->name}' "; $returnValue .= $this->renderAttributes(); $returnValue .= " value='{$this->value}' />"; return (string) $returnValue; }
[ "public", "function", "render", "(", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "value", ")", ")", "{", "if", "(", "common_Utils", "::", "isUri", "(", "$", "this", "->", "value", ")", ")", "{", "$", "referencer", "=", "$", "this",...
Short description of method render @access public @author Joel Bout, <joel.bout@tudor.lu> @return string
[ "Short", "description", "of", "method", "render" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/elements/xhtml/class.File.php#L59-L79
oat-sa/tao-core
actions/class.Users.php
tao_actions_Users.index
public function index() { $this->defaultData(); $userLangService = $this->getServiceLocator()->get(UserLanguageServiceInterface::class); $this->setData('user-data-lang-enabled', $userLangService->isDataLanguageEnabled()); $this->setView('user/list.tpl'); }
php
public function index() { $this->defaultData(); $userLangService = $this->getServiceLocator()->get(UserLanguageServiceInterface::class); $this->setData('user-data-lang-enabled', $userLangService->isDataLanguageEnabled()); $this->setView('user/list.tpl'); }
[ "public", "function", "index", "(", ")", "{", "$", "this", "->", "defaultData", "(", ")", ";", "$", "userLangService", "=", "$", "this", "->", "getServiceLocator", "(", ")", "->", "get", "(", "UserLanguageServiceInterface", "::", "class", ")", ";", "$", ...
Show the list of users @return void
[ "Show", "the", "list", "of", "users" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.Users.php#L62-L68
oat-sa/tao-core
actions/class.Users.php
tao_actions_Users.data
public function data() { $userService = $this->getServiceLocator()->get(tao_models_classes_UserService::class); $userLangService = $this->getServiceLocator()->get(UserLanguageServiceInterface::class); $page = $this->getRequestParameter('page'); $limit = $this->getRequestParameter('rows'); $sortBy = $this->getRequestParameter('sortby'); $sortOrder = $this->getRequestParameter('sortorder'); $filterQuery = $this->getRequestParameter('filterquery'); $filterColumns = $this->getRequestParameter('filtercolumns'); $start = $limit * $page - $limit; $fieldsMap = [ 'login' => GenerisRdf::PROPERTY_USER_LOGIN, 'firstname' => GenerisRdf::PROPERTY_USER_FIRSTNAME, 'lastname' => GenerisRdf::PROPERTY_USER_LASTNAME, 'email' => GenerisRdf::PROPERTY_USER_MAIL, 'guiLg' => GenerisRdf::PROPERTY_USER_UILG, 'roles' => GenerisRdf::PROPERTY_USER_ROLES ]; if ($userLangService->isDataLanguageEnabled()) { $fieldsMap['dataLg'] = GenerisRdf::PROPERTY_USER_DEFLG; } // sorting $order = array_key_exists($sortBy, $fieldsMap) ? $fieldsMap[$sortBy] : $fieldsMap['login']; // filtering $filters = [ GenerisRdf::PROPERTY_USER_LOGIN => '*', ]; if ($filterQuery) { if (!$filterColumns) { // if filter columns not set, search by all columns $filterColumns = array_keys($fieldsMap); } $filters = array_flip(array_intersect_key($fieldsMap, array_flip($filterColumns))); array_walk($filters, function (&$row, $key) use($filterQuery) { $row = $filterQuery; }); } $options = array( 'recursive' => true, 'like' => true, 'chaining' => count($filters) > 1 ? 'or' : 'and', 'order' => $order, 'orderdir' => strtoupper($sortOrder), ); // get total user count... $total = $userService->getCountUsers($options, $filters); // get the users using requested paging... $users = $userService->getAllUsers(array_merge($options, [ 'offset' => $start, 'limit' => $limit ]), $filters); $rolesProperty = $this->getProperty(GenerisRdf::PROPERTY_USER_ROLES); $response = new stdClass(); $readonly = []; $index = 0; /** @var core_kernel_classes_Resource $user */ foreach ($users as $user) { $propValues = $user->getPropertiesValues(array_values($fieldsMap)); $roles = $user->getPropertyValues($rolesProperty); $labels = []; foreach ($roles as $uri) { $labels[] = $this->getResource($uri)->getLabel(); } $id = tao_helpers_Uri::encode($user->getUri()); $login = (string)current($propValues[GenerisRdf::PROPERTY_USER_LOGIN]); $firstName = empty($propValues[GenerisRdf::PROPERTY_USER_FIRSTNAME]) ? '' : (string)current($propValues[GenerisRdf::PROPERTY_USER_FIRSTNAME]); $lastName = empty($propValues[GenerisRdf::PROPERTY_USER_LASTNAME]) ? '' : (string)current($propValues[GenerisRdf::PROPERTY_USER_LASTNAME]); $uiRes = empty($propValues[GenerisRdf::PROPERTY_USER_UILG]) ? null : current($propValues[GenerisRdf::PROPERTY_USER_UILG]); if ($userLangService->isDataLanguageEnabled()) { $dataRes = empty($propValues[GenerisRdf::PROPERTY_USER_DEFLG]) ? null : current($propValues[GenerisRdf::PROPERTY_USER_DEFLG]); $response->data[$index]['dataLg'] = is_null($dataRes) ? '' : $dataRes->getLabel(); } $response->data[$index]['id'] = $id; $response->data[$index]['login'] = $login; $response->data[$index]['firstname'] = $firstName; $response->data[$index]['lastname'] = $lastName; $response->data[$index]['email'] = (string)current($propValues[GenerisRdf::PROPERTY_USER_MAIL]); $response->data[$index]['roles'] = implode(', ', $labels); $response->data[$index]['guiLg'] = is_null($uiRes) ? '' : $uiRes->getLabel(); $statusInfo = $this->getUserLocksService()->getStatusDetails($login); $response->data[$index]['lockable'] = $statusInfo['lockable']; $response->data[$index]['locked'] = $statusInfo['locked']; $response->data[$index]['status'] = $statusInfo['status']; if ($user->getUri() == LOCAL_NAMESPACE . TaoOntology::DEFAULT_USER_URI_SUFFIX) { $readonly[$id] = true; } $index++; } $response->page = floor($start / $limit) + 1; $response->total = ceil($total / $limit); $response->records = count($users); $response->readonly = $readonly; $this->returnJson($response, 200); }
php
public function data() { $userService = $this->getServiceLocator()->get(tao_models_classes_UserService::class); $userLangService = $this->getServiceLocator()->get(UserLanguageServiceInterface::class); $page = $this->getRequestParameter('page'); $limit = $this->getRequestParameter('rows'); $sortBy = $this->getRequestParameter('sortby'); $sortOrder = $this->getRequestParameter('sortorder'); $filterQuery = $this->getRequestParameter('filterquery'); $filterColumns = $this->getRequestParameter('filtercolumns'); $start = $limit * $page - $limit; $fieldsMap = [ 'login' => GenerisRdf::PROPERTY_USER_LOGIN, 'firstname' => GenerisRdf::PROPERTY_USER_FIRSTNAME, 'lastname' => GenerisRdf::PROPERTY_USER_LASTNAME, 'email' => GenerisRdf::PROPERTY_USER_MAIL, 'guiLg' => GenerisRdf::PROPERTY_USER_UILG, 'roles' => GenerisRdf::PROPERTY_USER_ROLES ]; if ($userLangService->isDataLanguageEnabled()) { $fieldsMap['dataLg'] = GenerisRdf::PROPERTY_USER_DEFLG; } // sorting $order = array_key_exists($sortBy, $fieldsMap) ? $fieldsMap[$sortBy] : $fieldsMap['login']; // filtering $filters = [ GenerisRdf::PROPERTY_USER_LOGIN => '*', ]; if ($filterQuery) { if (!$filterColumns) { // if filter columns not set, search by all columns $filterColumns = array_keys($fieldsMap); } $filters = array_flip(array_intersect_key($fieldsMap, array_flip($filterColumns))); array_walk($filters, function (&$row, $key) use($filterQuery) { $row = $filterQuery; }); } $options = array( 'recursive' => true, 'like' => true, 'chaining' => count($filters) > 1 ? 'or' : 'and', 'order' => $order, 'orderdir' => strtoupper($sortOrder), ); // get total user count... $total = $userService->getCountUsers($options, $filters); // get the users using requested paging... $users = $userService->getAllUsers(array_merge($options, [ 'offset' => $start, 'limit' => $limit ]), $filters); $rolesProperty = $this->getProperty(GenerisRdf::PROPERTY_USER_ROLES); $response = new stdClass(); $readonly = []; $index = 0; /** @var core_kernel_classes_Resource $user */ foreach ($users as $user) { $propValues = $user->getPropertiesValues(array_values($fieldsMap)); $roles = $user->getPropertyValues($rolesProperty); $labels = []; foreach ($roles as $uri) { $labels[] = $this->getResource($uri)->getLabel(); } $id = tao_helpers_Uri::encode($user->getUri()); $login = (string)current($propValues[GenerisRdf::PROPERTY_USER_LOGIN]); $firstName = empty($propValues[GenerisRdf::PROPERTY_USER_FIRSTNAME]) ? '' : (string)current($propValues[GenerisRdf::PROPERTY_USER_FIRSTNAME]); $lastName = empty($propValues[GenerisRdf::PROPERTY_USER_LASTNAME]) ? '' : (string)current($propValues[GenerisRdf::PROPERTY_USER_LASTNAME]); $uiRes = empty($propValues[GenerisRdf::PROPERTY_USER_UILG]) ? null : current($propValues[GenerisRdf::PROPERTY_USER_UILG]); if ($userLangService->isDataLanguageEnabled()) { $dataRes = empty($propValues[GenerisRdf::PROPERTY_USER_DEFLG]) ? null : current($propValues[GenerisRdf::PROPERTY_USER_DEFLG]); $response->data[$index]['dataLg'] = is_null($dataRes) ? '' : $dataRes->getLabel(); } $response->data[$index]['id'] = $id; $response->data[$index]['login'] = $login; $response->data[$index]['firstname'] = $firstName; $response->data[$index]['lastname'] = $lastName; $response->data[$index]['email'] = (string)current($propValues[GenerisRdf::PROPERTY_USER_MAIL]); $response->data[$index]['roles'] = implode(', ', $labels); $response->data[$index]['guiLg'] = is_null($uiRes) ? '' : $uiRes->getLabel(); $statusInfo = $this->getUserLocksService()->getStatusDetails($login); $response->data[$index]['lockable'] = $statusInfo['lockable']; $response->data[$index]['locked'] = $statusInfo['locked']; $response->data[$index]['status'] = $statusInfo['status']; if ($user->getUri() == LOCAL_NAMESPACE . TaoOntology::DEFAULT_USER_URI_SUFFIX) { $readonly[$id] = true; } $index++; } $response->page = floor($start / $limit) + 1; $response->total = ceil($total / $limit); $response->records = count($users); $response->readonly = $readonly; $this->returnJson($response, 200); }
[ "public", "function", "data", "(", ")", "{", "$", "userService", "=", "$", "this", "->", "getServiceLocator", "(", ")", "->", "get", "(", "tao_models_classes_UserService", "::", "class", ")", ";", "$", "userLangService", "=", "$", "this", "->", "getServiceLo...
Provide the user list data via json @return string|json @throws Exception @throws common_exception_InvalidArgumentType
[ "Provide", "the", "user", "list", "data", "via", "json" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.Users.php#L76-L190
oat-sa/tao-core
actions/class.Users.php
tao_actions_Users.delete
public function delete() { $userService = $this->getServiceLocator()->get(tao_models_classes_UserService::class); // Csrf token validation $tokenService = $this->getServiceLocator()->get(TokenService::SERVICE_ID); $tokenName = $tokenService->getTokenName(); $token = $this->getRequestParameter($tokenName); if (! $tokenService->checkToken($token)) { $this->logWarning('Xsrf validation failed'); $this->returnJson([ 'success' => false, 'message' => 'Not authorized to perform action' ]); return; } else { $tokenService->revokeToken($token); $newToken = $tokenService->createToken(); $this->setCookie($tokenName, $newToken, null, '/'); } $deleted = false; $message = __('An error occurred during user deletion'); if (ApplicationHelper::isDemo()) { $message = __('User deletion not permitted on a demo instance'); } elseif ($this->hasRequestParameter('uri')) { $user = $this->getResource(tao_helpers_Uri::decode($this->getRequestParameter('uri'))); $this->checkUser($user->getUri()); if ($userService->removeUser($user)) { $deleted = true; $message = __('User deleted successfully'); } } $this->returnJson(array( 'success' => $deleted, 'message' => $message )); }
php
public function delete() { $userService = $this->getServiceLocator()->get(tao_models_classes_UserService::class); // Csrf token validation $tokenService = $this->getServiceLocator()->get(TokenService::SERVICE_ID); $tokenName = $tokenService->getTokenName(); $token = $this->getRequestParameter($tokenName); if (! $tokenService->checkToken($token)) { $this->logWarning('Xsrf validation failed'); $this->returnJson([ 'success' => false, 'message' => 'Not authorized to perform action' ]); return; } else { $tokenService->revokeToken($token); $newToken = $tokenService->createToken(); $this->setCookie($tokenName, $newToken, null, '/'); } $deleted = false; $message = __('An error occurred during user deletion'); if (ApplicationHelper::isDemo()) { $message = __('User deletion not permitted on a demo instance'); } elseif ($this->hasRequestParameter('uri')) { $user = $this->getResource(tao_helpers_Uri::decode($this->getRequestParameter('uri'))); $this->checkUser($user->getUri()); if ($userService->removeUser($user)) { $deleted = true; $message = __('User deleted successfully'); } } $this->returnJson(array( 'success' => $deleted, 'message' => $message )); }
[ "public", "function", "delete", "(", ")", "{", "$", "userService", "=", "$", "this", "->", "getServiceLocator", "(", ")", "->", "get", "(", "tao_models_classes_UserService", "::", "class", ")", ";", "// Csrf token validation", "$", "tokenService", "=", "$", "t...
Remove a user The request must contains the user's login to remove @return void @throws Exception @throws common_exception_Error
[ "Remove", "a", "user", "The", "request", "must", "contains", "the", "user", "s", "login", "to", "remove" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.Users.php#L199-L236
oat-sa/tao-core
actions/class.Users.php
tao_actions_Users.add
public function add() { $this->defaultData(); $container = new tao_actions_form_Users($this->getClass(TaoOntology::CLASS_URI_TAO_USER)); $form = $container->getForm(); if ($form->isSubmited()) { if ($form->isValid()) { $values = $form->getValues(); $values[GenerisRdf::PROPERTY_USER_PASSWORD] = core_kernel_users_Service::getPasswordHash()->encrypt($values['password1']); $plainPassword = $values['password1']; unset($values['password1']); unset($values['password2']); $user = $container->getUser(); $binder = new tao_models_classes_dataBinding_GenerisFormDataBinder($container->getUser()); if ($binder->bind($values)) { $this->getEventManager()->trigger(new UserUpdatedEvent( $user, array_merge($values, ['hashForKey' => UserHashForEncryption::hash($plainPassword)])) ); $this->setData('message', __('User added')); $this->setData('exit', true); } } } $this->setData('loginUri', tao_helpers_Uri::encode(GenerisRdf::PROPERTY_USER_LOGIN)); $this->setData('formTitle', __('Add a user')); $this->setData('myForm', $form->render()); $this->setView('user/form.tpl'); }
php
public function add() { $this->defaultData(); $container = new tao_actions_form_Users($this->getClass(TaoOntology::CLASS_URI_TAO_USER)); $form = $container->getForm(); if ($form->isSubmited()) { if ($form->isValid()) { $values = $form->getValues(); $values[GenerisRdf::PROPERTY_USER_PASSWORD] = core_kernel_users_Service::getPasswordHash()->encrypt($values['password1']); $plainPassword = $values['password1']; unset($values['password1']); unset($values['password2']); $user = $container->getUser(); $binder = new tao_models_classes_dataBinding_GenerisFormDataBinder($container->getUser()); if ($binder->bind($values)) { $this->getEventManager()->trigger(new UserUpdatedEvent( $user, array_merge($values, ['hashForKey' => UserHashForEncryption::hash($plainPassword)])) ); $this->setData('message', __('User added')); $this->setData('exit', true); } } } $this->setData('loginUri', tao_helpers_Uri::encode(GenerisRdf::PROPERTY_USER_LOGIN)); $this->setData('formTitle', __('Add a user')); $this->setData('myForm', $form->render()); $this->setView('user/form.tpl'); }
[ "public", "function", "add", "(", ")", "{", "$", "this", "->", "defaultData", "(", ")", ";", "$", "container", "=", "new", "tao_actions_form_Users", "(", "$", "this", "->", "getClass", "(", "TaoOntology", "::", "CLASS_URI_TAO_USER", ")", ")", ";", "$", "...
form to add a user @return void @throws Exception @throws \oat\generis\model\user\PasswordConstraintsException @throws tao_models_classes_dataBinding_GenerisFormDataBindingException
[ "form", "to", "add", "a", "user" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.Users.php#L245-L277
oat-sa/tao-core
actions/class.Users.php
tao_actions_Users.checkLogin
public function checkLogin() { $this->defaultData(); $userService = $this->getServiceLocator()->get(tao_models_classes_UserService::class); if (!$this->isXmlHttpRequest()) { throw new common_exception_BadRequest('wrong request mode'); } $data = array('available' => false); if ($this->hasRequestParameter('login')) { $data['available'] = $userService->loginAvailable($this->getRequestParameter('login')); } $this->returnJson($data); }
php
public function checkLogin() { $this->defaultData(); $userService = $this->getServiceLocator()->get(tao_models_classes_UserService::class); if (!$this->isXmlHttpRequest()) { throw new common_exception_BadRequest('wrong request mode'); } $data = array('available' => false); if ($this->hasRequestParameter('login')) { $data['available'] = $userService->loginAvailable($this->getRequestParameter('login')); } $this->returnJson($data); }
[ "public", "function", "checkLogin", "(", ")", "{", "$", "this", "->", "defaultData", "(", ")", ";", "$", "userService", "=", "$", "this", "->", "getServiceLocator", "(", ")", "->", "get", "(", "tao_models_classes_UserService", "::", "class", ")", ";", "if"...
action used to check if a login can be used @return void @throws Exception @throws common_exception_BadRequest
[ "action", "used", "to", "check", "if", "a", "login", "can", "be", "used" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.Users.php#L317-L331
oat-sa/tao-core
actions/class.Users.php
tao_actions_Users.edit
public function edit() { $this->defaultData(); $userService = $this->getServiceLocator()->get(tao_models_classes_UserService::class); $user = $this->getUserResource(); $types = $user->getTypes(); $myFormContainer = new tao_actions_form_Users(reset($types), $user); $myForm = $myFormContainer->getForm(); if ($myForm->isSubmited()) { if ($myForm->isValid()) { $values = $myForm->getValues(); if (!empty($values['password2']) && !empty($values['password3'])) { $plainPassword = $values['password2']; $values[GenerisRdf::PROPERTY_USER_PASSWORD] = core_kernel_users_Service::getPasswordHash()->encrypt($values['password2']); } unset($values['password2']); unset($values['password3']); if (!preg_match("/[A-Z]{2,4}$/", trim($values[GenerisRdf::PROPERTY_USER_UILG]))) { unset($values[GenerisRdf::PROPERTY_USER_UILG]); } if (!preg_match("/[A-Z]{2,4}$/", trim($values[GenerisRdf::PROPERTY_USER_DEFLG]))) { unset($values[GenerisRdf::PROPERTY_USER_DEFLG]); } $userService->checkCurrentUserAccess($values[GenerisRdf::PROPERTY_USER_ROLES]); // leave roles which are not in the allowed list for current user $oldRoles = $userService->getUserRoles($user); $allowedRoles = $userService->getPermittedRoles($userService->getCurrentUser(), $oldRoles, false); $staticRoles = array_diff($oldRoles, $allowedRoles); $values[GenerisRdf::PROPERTY_USER_ROLES] = array_merge($values[GenerisRdf::PROPERTY_USER_ROLES], $staticRoles); $binder = new tao_models_classes_dataBinding_GenerisFormDataBinder($user); if ($binder->bind($values)) { $data = []; if (isset($plainPassword)){ $data = ['hashForKey' => UserHashForEncryption::hash($plainPassword)]; } $this->getEventManager()->trigger(new UserUpdatedEvent( $user, array_merge($values, $data)) ); $this->setData('message', __('User saved')); } } } $this->setData('formTitle', __('Edit a user')); $this->setData('myForm', $myForm->render()); $this->setView('user/form.tpl'); }
php
public function edit() { $this->defaultData(); $userService = $this->getServiceLocator()->get(tao_models_classes_UserService::class); $user = $this->getUserResource(); $types = $user->getTypes(); $myFormContainer = new tao_actions_form_Users(reset($types), $user); $myForm = $myFormContainer->getForm(); if ($myForm->isSubmited()) { if ($myForm->isValid()) { $values = $myForm->getValues(); if (!empty($values['password2']) && !empty($values['password3'])) { $plainPassword = $values['password2']; $values[GenerisRdf::PROPERTY_USER_PASSWORD] = core_kernel_users_Service::getPasswordHash()->encrypt($values['password2']); } unset($values['password2']); unset($values['password3']); if (!preg_match("/[A-Z]{2,4}$/", trim($values[GenerisRdf::PROPERTY_USER_UILG]))) { unset($values[GenerisRdf::PROPERTY_USER_UILG]); } if (!preg_match("/[A-Z]{2,4}$/", trim($values[GenerisRdf::PROPERTY_USER_DEFLG]))) { unset($values[GenerisRdf::PROPERTY_USER_DEFLG]); } $userService->checkCurrentUserAccess($values[GenerisRdf::PROPERTY_USER_ROLES]); // leave roles which are not in the allowed list for current user $oldRoles = $userService->getUserRoles($user); $allowedRoles = $userService->getPermittedRoles($userService->getCurrentUser(), $oldRoles, false); $staticRoles = array_diff($oldRoles, $allowedRoles); $values[GenerisRdf::PROPERTY_USER_ROLES] = array_merge($values[GenerisRdf::PROPERTY_USER_ROLES], $staticRoles); $binder = new tao_models_classes_dataBinding_GenerisFormDataBinder($user); if ($binder->bind($values)) { $data = []; if (isset($plainPassword)){ $data = ['hashForKey' => UserHashForEncryption::hash($plainPassword)]; } $this->getEventManager()->trigger(new UserUpdatedEvent( $user, array_merge($values, $data)) ); $this->setData('message', __('User saved')); } } } $this->setData('formTitle', __('Edit a user')); $this->setData('myForm', $myForm->render()); $this->setView('user/form.tpl'); }
[ "public", "function", "edit", "(", ")", "{", "$", "this", "->", "defaultData", "(", ")", ";", "$", "userService", "=", "$", "this", "->", "getServiceLocator", "(", ")", "->", "get", "(", "tao_models_classes_UserService", "::", "class", ")", ";", "$", "us...
Form to edit a user User login must be set in parameter @return void @throws Exception @throws \oat\generis\model\user\PasswordConstraintsException @throws common_exception_Error @throws tao_models_classes_dataBinding_GenerisFormDataBindingException
[ "Form", "to", "edit", "a", "user", "User", "login", "must", "be", "set", "in", "parameter" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.Users.php#L342-L397
oat-sa/tao-core
actions/class.Users.php
tao_actions_Users.unlock
public function unlock() { $user = UserHelper::getUser($this->getUserResource()); if ($this->getUserLocksService()->unlockUser($user)) { $this->returnJson(['success' => true, 'message' => __('User %s successfully unlocked', UserHelper::getUserLogin(UserHelper::getUser($user)))]); } else { $this->returnJson(['success' => false, 'message' => __('User %s can not be unlocked', UserHelper::getUserLogin(UserHelper::getUser($user)))]); } }
php
public function unlock() { $user = UserHelper::getUser($this->getUserResource()); if ($this->getUserLocksService()->unlockUser($user)) { $this->returnJson(['success' => true, 'message' => __('User %s successfully unlocked', UserHelper::getUserLogin(UserHelper::getUser($user)))]); } else { $this->returnJson(['success' => false, 'message' => __('User %s can not be unlocked', UserHelper::getUserLogin(UserHelper::getUser($user)))]); } }
[ "public", "function", "unlock", "(", ")", "{", "$", "user", "=", "UserHelper", "::", "getUser", "(", "$", "this", "->", "getUserResource", "(", ")", ")", ";", "if", "(", "$", "this", "->", "getUserLocksService", "(", ")", "->", "unlockUser", "(", "$", ...
Removes all locks from user account @throws Exception
[ "Removes", "all", "locks", "from", "user", "account" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.Users.php#L403-L412
oat-sa/tao-core
actions/class.Users.php
tao_actions_Users.lock
public function lock() { $user = UserHelper::getUser($this->getUserResource()); if ($this->getUserLocksService()->lockUser($user)) { $this->returnJson(['success' => true, 'message' => __('User %s successfully locked', UserHelper::getUserLogin(UserHelper::getUser($user)))]); } else { $this->returnJson(['success' => false, 'message' => __('User %s can not be locked', UserHelper::getUserLogin(UserHelper::getUser($user)))]); } }
php
public function lock() { $user = UserHelper::getUser($this->getUserResource()); if ($this->getUserLocksService()->lockUser($user)) { $this->returnJson(['success' => true, 'message' => __('User %s successfully locked', UserHelper::getUserLogin(UserHelper::getUser($user)))]); } else { $this->returnJson(['success' => false, 'message' => __('User %s can not be locked', UserHelper::getUserLogin(UserHelper::getUser($user)))]); } }
[ "public", "function", "lock", "(", ")", "{", "$", "user", "=", "UserHelper", "::", "getUser", "(", "$", "this", "->", "getUserResource", "(", ")", ")", ";", "if", "(", "$", "this", "->", "getUserLocksService", "(", ")", "->", "lockUser", "(", "$", "u...
Locks user account, he can not login in to the system anymore @throws Exception
[ "Locks", "user", "account", "he", "can", "not", "login", "in", "to", "the", "system", "anymore" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.Users.php#L418-L427
oat-sa/tao-core
helpers/translation/class.TranslationFileReader.php
tao_helpers_translation_TranslationFileReader.getTranslationFile
public function getTranslationFile() { $returnValue = null; if ($this->translationFile != null) { return $this->translationFile; } else { throw new tao_helpers_translation_TranslationException('No TranslationFile to retrieve.'); } return $returnValue; }
php
public function getTranslationFile() { $returnValue = null; if ($this->translationFile != null) { return $this->translationFile; } else { throw new tao_helpers_translation_TranslationException('No TranslationFile to retrieve.'); } return $returnValue; }
[ "public", "function", "getTranslationFile", "(", ")", "{", "$", "returnValue", "=", "null", ";", "if", "(", "$", "this", "->", "translationFile", "!=", "null", ")", "{", "return", "$", "this", "->", "translationFile", ";", "}", "else", "{", "throw", "new...
Gets the TranslationFile instance resulting of the reading of the file. @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @return tao_helpers_translation_TranslationFile
[ "Gets", "the", "TranslationFile", "instance", "resulting", "of", "the", "reading", "of", "the", "file", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/translation/class.TranslationFileReader.php#L94-L108
oat-sa/tao-core
models/classes/export/implementation/AbstractFileExporter.php
AbstractFileExporter.download
protected function download($data, $fileName = null) { if ($fileName === null) { $fileName = time(); } while (ob_get_level() > 0) { ob_end_flush(); } header('Content-Type: ' . $this->contentType); header('Content-Disposition: attachment; fileName="' . $fileName .'"'); header("Content-Length: " . strlen($data)); echo $data; }
php
protected function download($data, $fileName = null) { if ($fileName === null) { $fileName = time(); } while (ob_get_level() > 0) { ob_end_flush(); } header('Content-Type: ' . $this->contentType); header('Content-Disposition: attachment; fileName="' . $fileName .'"'); header("Content-Length: " . strlen($data)); echo $data; }
[ "protected", "function", "download", "(", "$", "data", ",", "$", "fileName", "=", "null", ")", "{", "if", "(", "$", "fileName", "===", "null", ")", "{", "$", "fileName", "=", "time", "(", ")", ";", "}", "while", "(", "ob_get_level", "(", ")", ">", ...
Send exported data to end user @param string $data Data to be exported @param string|null $fileName @return mixed
[ "Send", "exported", "data", "to", "end", "user" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/export/implementation/AbstractFileExporter.php#L64-L79
oat-sa/tao-core
models/classes/service/class.ConstantParameter.php
tao_models_classes_service_ConstantParameter.toOntology
public function toOntology() { $serviceCallClass = new core_kernel_classes_Class(WfEngineOntology::CLASS_URI_ACTUAL_PARAMETER); $resource = $serviceCallClass->createInstanceWithProperties(array( WfEngineOntology::PROPERTY_ACTUAL_PARAMETER_FORMAL_PARAMETER => $this->getDefinition(), WfEngineOntology::PROPERTY_ACTUAL_PARAMETER_CONSTANT_VALUE => $this->value )); return $resource; }
php
public function toOntology() { $serviceCallClass = new core_kernel_classes_Class(WfEngineOntology::CLASS_URI_ACTUAL_PARAMETER); $resource = $serviceCallClass->createInstanceWithProperties(array( WfEngineOntology::PROPERTY_ACTUAL_PARAMETER_FORMAL_PARAMETER => $this->getDefinition(), WfEngineOntology::PROPERTY_ACTUAL_PARAMETER_CONSTANT_VALUE => $this->value )); return $resource; }
[ "public", "function", "toOntology", "(", ")", "{", "$", "serviceCallClass", "=", "new", "core_kernel_classes_Class", "(", "WfEngineOntology", "::", "CLASS_URI_ACTUAL_PARAMETER", ")", ";", "$", "resource", "=", "$", "serviceCallClass", "->", "createInstanceWithProperties...
(non-PHPdoc) @see tao_models_classes_service_Parameter::serialize()
[ "(", "non", "-", "PHPdoc", ")" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/service/class.ConstantParameter.php#L64-L71
oat-sa/tao-core
models/classes/taskQueue/TaskLog/TaskLogFilter.php
TaskLogFilter.addAvailableFilters
public function addAvailableFilters($userId, $archivedAllowed = false, $cancelledAvailable = false) { if (!$archivedAllowed) { $this->neq(TaskLogBrokerInterface::COLUMN_STATUS, TaskLogInterface::STATUS_ARCHIVED); } if (!$cancelledAvailable) { $this->neq(TaskLogBrokerInterface::COLUMN_STATUS, TaskLogInterface::STATUS_CANCELLED); } if ($userId !== TaskLogInterface::SUPER_USER) { $this->eq(TaskLogBrokerInterface::COLUMN_OWNER, $userId); } return $this; }
php
public function addAvailableFilters($userId, $archivedAllowed = false, $cancelledAvailable = false) { if (!$archivedAllowed) { $this->neq(TaskLogBrokerInterface::COLUMN_STATUS, TaskLogInterface::STATUS_ARCHIVED); } if (!$cancelledAvailable) { $this->neq(TaskLogBrokerInterface::COLUMN_STATUS, TaskLogInterface::STATUS_CANCELLED); } if ($userId !== TaskLogInterface::SUPER_USER) { $this->eq(TaskLogBrokerInterface::COLUMN_OWNER, $userId); } return $this; }
[ "public", "function", "addAvailableFilters", "(", "$", "userId", ",", "$", "archivedAllowed", "=", "false", ",", "$", "cancelledAvailable", "=", "false", ")", "{", "if", "(", "!", "$", "archivedAllowed", ")", "{", "$", "this", "->", "neq", "(", "TaskLogBro...
Add a basic filter to query only rows belonging to a given user and not having status ARCHIVED or CANCELLED. @param string $userId @param bool $archivedAllowed @param bool $cancelledAvailable @return $this
[ "Add", "a", "basic", "filter", "to", "query", "only", "rows", "belonging", "to", "a", "given", "user", "and", "not", "having", "status", "ARCHIVED", "or", "CANCELLED", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/taskQueue/TaskLog/TaskLogFilter.php#L201-L216
oat-sa/tao-core
install/utils/class.ChecksHelper.php
tao_install_utils_ChecksHelper.getConfigChecker
public static function getConfigChecker($extensionIds) { $returnValue = new common_configuration_ComponentCollection(); $checkArray = array(); // resolve dependencies foreach (self::getRawChecks($extensionIds) as $c){ $checkArray[] = $c; $comp = common_configuration_ComponentFactory::buildFromArray($c); if (!empty($c['value']['id'])){ $componentArray[$c['value']['id']] = $comp; } $returnValue->addComponent($comp); if (!empty($c['value']['silent']) && $c['value']['silent'] == true){ $returnValue->silent($comp); } } // Deal with the dependencies. foreach ($checkArray as $config){ if (!empty($config['value']['dependsOn']) && is_array($config['value']['dependsOn'])){ foreach ($config['value']['dependsOn'] as $d){ // Find the component it depends on and tell the ComponentCollection. if (!empty($componentArray[$config['value']['id']]) && !empty($componentArray[$d])){ $returnValue->addDependency($componentArray[$config['value']['id']], $componentArray[$d]); } } } } return $returnValue; }
php
public static function getConfigChecker($extensionIds) { $returnValue = new common_configuration_ComponentCollection(); $checkArray = array(); // resolve dependencies foreach (self::getRawChecks($extensionIds) as $c){ $checkArray[] = $c; $comp = common_configuration_ComponentFactory::buildFromArray($c); if (!empty($c['value']['id'])){ $componentArray[$c['value']['id']] = $comp; } $returnValue->addComponent($comp); if (!empty($c['value']['silent']) && $c['value']['silent'] == true){ $returnValue->silent($comp); } } // Deal with the dependencies. foreach ($checkArray as $config){ if (!empty($config['value']['dependsOn']) && is_array($config['value']['dependsOn'])){ foreach ($config['value']['dependsOn'] as $d){ // Find the component it depends on and tell the ComponentCollection. if (!empty($componentArray[$config['value']['id']]) && !empty($componentArray[$d])){ $returnValue->addDependency($componentArray[$config['value']['id']], $componentArray[$d]); } } } } return $returnValue; }
[ "public", "static", "function", "getConfigChecker", "(", "$", "extensionIds", ")", "{", "$", "returnValue", "=", "new", "common_configuration_ComponentCollection", "(", ")", ";", "$", "checkArray", "=", "array", "(", ")", ";", "// resolve dependencies", "foreach", ...
Get the ComponentCollection corresponding to the distribution. It the configuration checks to perform for all extensions involved in the @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param array $extensionIds @return common_configuration_ComponentCollection
[ "Get", "the", "ComponentCollection", "corresponding", "to", "the", "distribution", ".", "It", "the", "configuration", "checks", "to", "perform", "for", "all", "extensions", "involved", "in", "the" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/install/utils/class.ChecksHelper.php#L42-L75
oat-sa/tao-core
models/classes/metadata/writer/ontologyWriter/ListPropertyWriter.php
ListPropertyWriter.format
public function format(array $data) { $value = parent::format($data); foreach ($this->list as $uri => $values) { if (in_array($value, $values)) { return $uri; } } return ''; }
php
public function format(array $data) { $value = parent::format($data); foreach ($this->list as $uri => $values) { if (in_array($value, $values)) { return $uri; } } return ''; }
[ "public", "function", "format", "(", "array", "$", "data", ")", "{", "$", "value", "=", "parent", "::", "format", "(", "$", "data", ")", ";", "foreach", "(", "$", "this", "->", "list", "as", "$", "uri", "=>", "$", "values", ")", "{", "if", "(", ...
Format an array to expected value to be written @param array $data @return int|string @throws MetadataReaderNotFoundException
[ "Format", "an", "array", "to", "expected", "value", "to", "be", "written" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/metadata/writer/ontologyWriter/ListPropertyWriter.php#L77-L86
oat-sa/tao-core
models/classes/textConverter/TextConverterService.php
TextConverterService.get
public function get($key) { $textRegistry = $this->getTextRegistry(); if (is_string($key) && isset($textRegistry[$key])) { return $textRegistry[$key]; } return $key; }
php
public function get($key) { $textRegistry = $this->getTextRegistry(); if (is_string($key) && isset($textRegistry[$key])) { return $textRegistry[$key]; } return $key; }
[ "public", "function", "get", "(", "$", "key", ")", "{", "$", "textRegistry", "=", "$", "this", "->", "getTextRegistry", "(", ")", ";", "if", "(", "is_string", "(", "$", "key", ")", "&&", "isset", "(", "$", "textRegistry", "[", "$", "key", "]", ")",...
Return the associated conversion of the given key @param string $key The text to convert, should be an index of getTextRegistry array @return string
[ "Return", "the", "associated", "conversion", "of", "the", "given", "key" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/textConverter/TextConverterService.php#L40-L47
oat-sa/tao-core
helpers/TreeHelper.php
TreeHelper.getNodesToOpen
public static function getNodesToOpen($uris, core_kernel_classes_Class $rootNode) { // this array is in the form of // URI to test => array of uris that depend on the URI $toTest = array(); foreach($uris as $uri){ $resource = new core_kernel_classes_Resource($uri); foreach ($resource->getTypes() as $type) { $toTest[$type->getUri()] = array(); } } $toOpen = array($rootNode->getUri()); while (!empty($toTest)) { reset($toTest); $classUri = key($toTest); $depends = current($toTest); unset($toTest[$classUri]); if (in_array($classUri, $toOpen)) { $toOpen = array_merge($toOpen, $depends); } else { $class = new core_kernel_classes_Class($classUri); /** @var core_kernel_classes_Class $parent */ foreach ($class->getParentClasses(false) as $parent) { if ($parent->getUri() === OntologyRdfs::RDFS_CLASS) { continue; } if (!isset($toTest[$parent->getUri()])) { $toTest[$parent->getUri()] = array(); } $toTest[$parent->getUri()] = array_merge( $toTest[$parent->getUri()], array($classUri), $depends ); } } } return $toOpen; }
php
public static function getNodesToOpen($uris, core_kernel_classes_Class $rootNode) { // this array is in the form of // URI to test => array of uris that depend on the URI $toTest = array(); foreach($uris as $uri){ $resource = new core_kernel_classes_Resource($uri); foreach ($resource->getTypes() as $type) { $toTest[$type->getUri()] = array(); } } $toOpen = array($rootNode->getUri()); while (!empty($toTest)) { reset($toTest); $classUri = key($toTest); $depends = current($toTest); unset($toTest[$classUri]); if (in_array($classUri, $toOpen)) { $toOpen = array_merge($toOpen, $depends); } else { $class = new core_kernel_classes_Class($classUri); /** @var core_kernel_classes_Class $parent */ foreach ($class->getParentClasses(false) as $parent) { if ($parent->getUri() === OntologyRdfs::RDFS_CLASS) { continue; } if (!isset($toTest[$parent->getUri()])) { $toTest[$parent->getUri()] = array(); } $toTest[$parent->getUri()] = array_merge( $toTest[$parent->getUri()], array($classUri), $depends ); } } } return $toOpen; }
[ "public", "static", "function", "getNodesToOpen", "(", "$", "uris", ",", "core_kernel_classes_Class", "$", "rootNode", ")", "{", "// this array is in the form of", "// URI to test => array of uris that depend on the URI", "$", "toTest", "=", "array", "(", ")", ";", "forea...
Returns the nodes to open in order to display all the listed resources to be visible @param array $uris list of resources to show @param core_kernel_classes_Class $rootNode root node of the tree @return array array of the uris of the nodes to open
[ "Returns", "the", "nodes", "to", "open", "in", "order", "to", "display", "all", "the", "listed", "resources", "to", "be", "visible" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/TreeHelper.php#L43-L80
oat-sa/tao-core
helpers/TreeHelper.php
TreeHelper.buildResourceNode
public static function buildResourceNode(core_kernel_classes_Resource $resource, core_kernel_classes_Class $class, array $extraProperties = []) { $label = $resource->getLabel(); $label = empty($label) ? __('no label') : $label; $extraValues = []; if (!empty($extraProperties)) { foreach ($extraProperties as $key => $value) { $extraValues[$key] = $resource->getOnePropertyValue($class->getProperty($value)); } } $signatureGenerator = ServiceManager::getServiceManager()->get(SignatureGenerator::class); return [ 'data' => _dh($label), 'type' => 'instance', 'attributes' => array_merge([ 'id' => tao_helpers_Uri::encode($resource->getUri()), 'class' => 'node-instance', 'data-uri' => $resource->getUri(), 'data-classUri' => $class->getUri(), 'data-signature' => $signatureGenerator->generate($resource->getUri()), ], $extraValues) ]; }
php
public static function buildResourceNode(core_kernel_classes_Resource $resource, core_kernel_classes_Class $class, array $extraProperties = []) { $label = $resource->getLabel(); $label = empty($label) ? __('no label') : $label; $extraValues = []; if (!empty($extraProperties)) { foreach ($extraProperties as $key => $value) { $extraValues[$key] = $resource->getOnePropertyValue($class->getProperty($value)); } } $signatureGenerator = ServiceManager::getServiceManager()->get(SignatureGenerator::class); return [ 'data' => _dh($label), 'type' => 'instance', 'attributes' => array_merge([ 'id' => tao_helpers_Uri::encode($resource->getUri()), 'class' => 'node-instance', 'data-uri' => $resource->getUri(), 'data-classUri' => $class->getUri(), 'data-signature' => $signatureGenerator->generate($resource->getUri()), ], $extraValues) ]; }
[ "public", "static", "function", "buildResourceNode", "(", "core_kernel_classes_Resource", "$", "resource", ",", "core_kernel_classes_Class", "$", "class", ",", "array", "$", "extraProperties", "=", "[", "]", ")", "{", "$", "label", "=", "$", "resource", "->", "g...
generis tree representation of a resource node @param core_kernel_classes_Resource $resource @param core_kernel_classes_Class $class @param array $extraProperties @return array
[ "generis", "tree", "representation", "of", "a", "resource", "node" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/TreeHelper.php#L90-L116
oat-sa/tao-core
helpers/translation/class.TranslationFile.php
tao_helpers_translation_TranslationFile.getAnnotation
public function getAnnotation($name) { $returnValue = array(); if (isset($this->annotations[$name])) { $returnValue = array( 'name' => $name, 'value' => $this->annotations[$name] ); } else { $returnValue = null; } return (array) $returnValue; }
php
public function getAnnotation($name) { $returnValue = array(); if (isset($this->annotations[$name])) { $returnValue = array( 'name' => $name, 'value' => $this->annotations[$name] ); } else { $returnValue = null; } return (array) $returnValue; }
[ "public", "function", "getAnnotation", "(", "$", "name", ")", "{", "$", "returnValue", "=", "array", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "annotations", "[", "$", "name", "]", ")", ")", "{", "$", "returnValue", "=", "array", "...
Get an annotation for a given annotation name. Returns an associative where keys are 'name' and 'value'. @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param string name @return array
[ "Get", "an", "annotation", "for", "a", "given", "annotation", "name", ".", "Returns", "an", "associative", "where", "keys", "are", "name", "and", "value", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/translation/class.TranslationFile.php#L173-L187
oat-sa/tao-core
helpers/translation/class.TranslationFile.php
tao_helpers_translation_TranslationFile.addTranslationUnit
public function addTranslationUnit(tao_helpers_translation_TranslationUnit $translationUnit) { // If the translation unit exists, we replace the target with the new one if it exists. foreach ($this->getTranslationUnits() as $tu) { if ($tu->getSource() == $translationUnit->getSource()) { // If we are here, it means that this TU is being overriden by // another one having the same source... // // Let's make sure we don't override the existing one with an empty target! if ($translationUnit->getTarget() !== '') { $tu->setTarget($translationUnit->getTarget()); $tu->setAnnotations($translationUnit->getAnnotations()); } return; } } // If we are here, it means that this TU does not exist. $translationUnit->setSourceLanguage($this->getSourceLanguage()); $translationUnit->setTargetLanguage($this->getTargetLanguage()); array_push($this->translationUnits, $translationUnit); }
php
public function addTranslationUnit(tao_helpers_translation_TranslationUnit $translationUnit) { // If the translation unit exists, we replace the target with the new one if it exists. foreach ($this->getTranslationUnits() as $tu) { if ($tu->getSource() == $translationUnit->getSource()) { // If we are here, it means that this TU is being overriden by // another one having the same source... // // Let's make sure we don't override the existing one with an empty target! if ($translationUnit->getTarget() !== '') { $tu->setTarget($translationUnit->getTarget()); $tu->setAnnotations($translationUnit->getAnnotations()); } return; } } // If we are here, it means that this TU does not exist. $translationUnit->setSourceLanguage($this->getSourceLanguage()); $translationUnit->setTargetLanguage($this->getTargetLanguage()); array_push($this->translationUnits, $translationUnit); }
[ "public", "function", "addTranslationUnit", "(", "tao_helpers_translation_TranslationUnit", "$", "translationUnit", ")", "{", "// If the translation unit exists, we replace the target with the new one if it exists.", "foreach", "(", "$", "this", "->", "getTranslationUnits", "(", ")...
Adds a TranslationUnit instance to the file. It is appenned at the end of collection. @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param TranslationUnit translationUnit @return mixed
[ "Adds", "a", "TranslationUnit", "instance", "to", "the", "file", ".", "It", "is", "appenned", "at", "the", "end", "of", "collection", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/translation/class.TranslationFile.php#L304-L328
oat-sa/tao-core
helpers/translation/class.TranslationFile.php
tao_helpers_translation_TranslationFile.removeTranslationUnit
public function removeTranslationUnit(tao_helpers_translation_TranslationUnit $translationUnit) { $tus = $this->getTranslationUnits(); for ($i = 0; $i < count($tus); $i ++) { if ($tus[$i] === $translationUnit) { unset($tus[$i]); break; } } throw new tao_helpers_translation_TranslationException('Cannot remove Translation Unit. Not Found.'); }
php
public function removeTranslationUnit(tao_helpers_translation_TranslationUnit $translationUnit) { $tus = $this->getTranslationUnits(); for ($i = 0; $i < count($tus); $i ++) { if ($tus[$i] === $translationUnit) { unset($tus[$i]); break; } } throw new tao_helpers_translation_TranslationException('Cannot remove Translation Unit. Not Found.'); }
[ "public", "function", "removeTranslationUnit", "(", "tao_helpers_translation_TranslationUnit", "$", "translationUnit", ")", "{", "$", "tus", "=", "$", "this", "->", "getTranslationUnits", "(", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "co...
Removes a given TranslationUnit from the collection of TranslationUnits the file. @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param TranslationUnit translationUnit @return mixed
[ "Removes", "a", "given", "TranslationUnit", "from", "the", "collection", "of", "TranslationUnits", "the", "file", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/translation/class.TranslationFile.php#L339-L350
oat-sa/tao-core
helpers/translation/class.TranslationFile.php
tao_helpers_translation_TranslationFile.hasSameSource
public function hasSameSource(tao_helpers_translation_TranslationUnit $translationUnit) { $returnValue = (bool) false; foreach ($this->getTranslationUnits() as $tu) { if ($tu->hasSameTranslationUnitSource($translationUnit)) { $returnValue = true; break; } } return (bool) $returnValue; }
php
public function hasSameSource(tao_helpers_translation_TranslationUnit $translationUnit) { $returnValue = (bool) false; foreach ($this->getTranslationUnits() as $tu) { if ($tu->hasSameTranslationUnitSource($translationUnit)) { $returnValue = true; break; } } return (bool) $returnValue; }
[ "public", "function", "hasSameSource", "(", "tao_helpers_translation_TranslationUnit", "$", "translationUnit", ")", "{", "$", "returnValue", "=", "(", "bool", ")", "false", ";", "foreach", "(", "$", "this", "->", "getTranslationUnits", "(", ")", "as", "$", "tu",...
Short description of method hasSameSource @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param TranslationUnit translationUnit @return boolean
[ "Short", "description", "of", "method", "hasSameSource" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/translation/class.TranslationFile.php#L397-L409
oat-sa/tao-core
helpers/translation/class.TranslationFile.php
tao_helpers_translation_TranslationFile.hasSameTarget
public function hasSameTarget(tao_helpers_translation_TranslationUnit $translationUnit) { $returnValue = (bool) false; foreach ($this->getTranslationUnits() as $tu) { if ($tu->hasSameTranslationUnitTarget($translationUnit)) { $returnValue = true; break; } } return (bool) $returnValue; }
php
public function hasSameTarget(tao_helpers_translation_TranslationUnit $translationUnit) { $returnValue = (bool) false; foreach ($this->getTranslationUnits() as $tu) { if ($tu->hasSameTranslationUnitTarget($translationUnit)) { $returnValue = true; break; } } return (bool) $returnValue; }
[ "public", "function", "hasSameTarget", "(", "tao_helpers_translation_TranslationUnit", "$", "translationUnit", ")", "{", "$", "returnValue", "=", "(", "bool", ")", "false", ";", "foreach", "(", "$", "this", "->", "getTranslationUnits", "(", ")", "as", "$", "tu",...
Short description of method hasSameTarget @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param TranslationUnit translationUnit @return boolean
[ "Short", "description", "of", "method", "hasSameTarget" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/translation/class.TranslationFile.php#L419-L431
oat-sa/tao-core
helpers/translation/class.TranslationFile.php
tao_helpers_translation_TranslationFile.sortBySource
public function sortBySource($sortingType) { $returnValue = $this->getTranslationUnits(); switch ($sortingType) { case self::SORT_ASC: $cmpFunction = function ($a, $b) { return strcmp($a->getSource(), $b->getSource()); }; break; case self::SORT_ASC_I: $cmpFunction = function ($a, $b) { return strcmp(mb_strtolower($a->getSource(), "UTF-8"), mb_strtolower($b->getSource(), "UTF-8")); }; break; case self::SORT_DESC: $cmpFunction = function ($a, $b) { return - 1 * strcmp($a->getSource(), $b->getSource()); }; break; case self::SORT_DESC_I: $cmpFunction = function ($a, $b) { return - 1 * strcmp(mb_strtolower($a->getSource(), "UTF-8"), mb_strtolower($b->getSource(), "UTF-8")); }; break; default: throw new common_Exception('Unknown sortingType ' . $sortingType); } usort($returnValue, $cmpFunction); return $returnValue; }
php
public function sortBySource($sortingType) { $returnValue = $this->getTranslationUnits(); switch ($sortingType) { case self::SORT_ASC: $cmpFunction = function ($a, $b) { return strcmp($a->getSource(), $b->getSource()); }; break; case self::SORT_ASC_I: $cmpFunction = function ($a, $b) { return strcmp(mb_strtolower($a->getSource(), "UTF-8"), mb_strtolower($b->getSource(), "UTF-8")); }; break; case self::SORT_DESC: $cmpFunction = function ($a, $b) { return - 1 * strcmp($a->getSource(), $b->getSource()); }; break; case self::SORT_DESC_I: $cmpFunction = function ($a, $b) { return - 1 * strcmp(mb_strtolower($a->getSource(), "UTF-8"), mb_strtolower($b->getSource(), "UTF-8")); }; break; default: throw new common_Exception('Unknown sortingType ' . $sortingType); } usort($returnValue, $cmpFunction); return $returnValue; }
[ "public", "function", "sortBySource", "(", "$", "sortingType", ")", "{", "$", "returnValue", "=", "$", "this", "->", "getTranslationUnits", "(", ")", ";", "switch", "(", "$", "sortingType", ")", "{", "case", "self", "::", "SORT_ASC", ":", "$", "cmpFunction...
Sorts and returns the TranslationUnits by Source with a specified sorting @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param int sortingType @return array
[ "Sorts", "and", "returns", "the", "TranslationUnits", "by", "Source", "with", "a", "specified", "sorting" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/translation/class.TranslationFile.php#L441-L470
oat-sa/tao-core
helpers/translation/class.TranslationFile.php
tao_helpers_translation_TranslationFile.getBySource
public function getBySource(tao_helpers_translation_TranslationUnit $translationUnit) { $returnValue = null; foreach ($this->getTranslationUnits() as $tu) { if ($tu->hasSameTranslationUnitSource($translationUnit)) { $returnValue = $tu; break; } } return $returnValue; }
php
public function getBySource(tao_helpers_translation_TranslationUnit $translationUnit) { $returnValue = null; foreach ($this->getTranslationUnits() as $tu) { if ($tu->hasSameTranslationUnitSource($translationUnit)) { $returnValue = $tu; break; } } return $returnValue; }
[ "public", "function", "getBySource", "(", "tao_helpers_translation_TranslationUnit", "$", "translationUnit", ")", "{", "$", "returnValue", "=", "null", ";", "foreach", "(", "$", "this", "->", "getTranslationUnits", "(", ")", "as", "$", "tu", ")", "{", "if", "(...
Short description of method getBySource @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param TranslationUnit translationUnit @return tao_helpers_translation_TranslationUnit
[ "Short", "description", "of", "method", "getBySource" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/translation/class.TranslationFile.php#L497-L509
oat-sa/tao-core
helpers/translation/class.TranslationFile.php
tao_helpers_translation_TranslationFile.getByTarget
public function getByTarget(tao_helpers_translation_TranslationUnit $translationUnit) { $returnValue = null; foreach ($this->getTranslationUnits() as $tu) { if ($tu->hasSameTranslationUnitTarget($translationUnit)) { $returnValue = $tu; break; } } return $returnValue; }
php
public function getByTarget(tao_helpers_translation_TranslationUnit $translationUnit) { $returnValue = null; foreach ($this->getTranslationUnits() as $tu) { if ($tu->hasSameTranslationUnitTarget($translationUnit)) { $returnValue = $tu; break; } } return $returnValue; }
[ "public", "function", "getByTarget", "(", "tao_helpers_translation_TranslationUnit", "$", "translationUnit", ")", "{", "$", "returnValue", "=", "null", ";", "foreach", "(", "$", "this", "->", "getTranslationUnits", "(", ")", "as", "$", "tu", ")", "{", "if", "(...
Short description of method getByTarget @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param TranslationUnit translationUnit @return tao_helpers_translation_TranslationUnit
[ "Short", "description", "of", "method", "getByTarget" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/translation/class.TranslationFile.php#L519-L531
oat-sa/tao-core
actions/form/class.Clazz.php
tao_actions_form_Clazz.getPropertyForm
protected function getPropertyForm($property, $index, $isParentProp, $propData) { $propFormClass = 'tao_actions_form_' . ucfirst(strtolower($this->propertyMode)) . 'Property'; if (!class_exists($propFormClass)) { $propFormClass = 'tao_actions_form_SimpleProperty'; } $propFormContainer = new $propFormClass($this->getClassInstance(), $property, array('index' => $index, 'isParentProperty' => $isParentProp ), $propData); return $propFormContainer->getForm(); }
php
protected function getPropertyForm($property, $index, $isParentProp, $propData) { $propFormClass = 'tao_actions_form_' . ucfirst(strtolower($this->propertyMode)) . 'Property'; if (!class_exists($propFormClass)) { $propFormClass = 'tao_actions_form_SimpleProperty'; } $propFormContainer = new $propFormClass($this->getClassInstance(), $property, array('index' => $index, 'isParentProperty' => $isParentProp ), $propData); return $propFormContainer->getForm(); }
[ "protected", "function", "getPropertyForm", "(", "$", "property", ",", "$", "index", ",", "$", "isParentProp", ",", "$", "propData", ")", "{", "$", "propFormClass", "=", "'tao_actions_form_'", ".", "ucfirst", "(", "strtolower", "(", "$", "this", "->", "prope...
Returns the form for the property, based on the mode @param core_kernel_classes_Property $property @param integer $index @param boolean $isParentProp @param array $propData
[ "Returns", "the", "form", "for", "the", "property", "based", "on", "the", "mode" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/form/class.Clazz.php#L97-L105
oat-sa/tao-core
actions/form/class.Clazz.php
tao_actions_form_Clazz.initForm
protected function initForm() { (isset($this->options['name'])) ? $name = $this->options['name'] : $name = ''; if (empty($name)) { $name = 'form_' . (count(self::$forms) + 1); } unset($this->options['name']); $this->form = tao_helpers_form_FormFactory::getForm($name, $this->options); //add property action in toolbar $actions = tao_helpers_form_FormFactory::getCommonActions(); $propertyElt = tao_helpers_form_FormFactory::getElement('property', 'Free'); $propertyElt->setValue( "<a href='#' class='btn-info property-adder small'><span class='icon-property-add'></span> " . __('Add property') . "</a>" ); $actions[] = $propertyElt; //property mode $propModeELt = tao_helpers_form_FormFactory::getElement('propMode', 'Free'); if($this->propertyMode == 'advanced'){ $propModeELt->setValue("<a href='#' class='btn-info property-mode small property-mode-simple'><span class='icon-property-advanced'></span> ".__('Simple Mode')."</a>"); } else{ $propModeELt->setValue("<a href='#' class='btn-info property-mode small property-mode-advanced'><span class='icon-property-advanced'></span> ".__('Advanced Mode')."</a>"); } $actions[] = $propModeELt; //add a hidden field that states it is a class edition form. $classElt = tao_helpers_form_FormFactory::getElement('tao.forms.class', 'Hidden'); $classElt->setValue('1'); $classElt->addClass('global'); $this->form->addElement($classElt); $this->form->setActions($actions, 'top'); $this->form->setActions($actions, 'bottom'); }
php
protected function initForm() { (isset($this->options['name'])) ? $name = $this->options['name'] : $name = ''; if (empty($name)) { $name = 'form_' . (count(self::$forms) + 1); } unset($this->options['name']); $this->form = tao_helpers_form_FormFactory::getForm($name, $this->options); //add property action in toolbar $actions = tao_helpers_form_FormFactory::getCommonActions(); $propertyElt = tao_helpers_form_FormFactory::getElement('property', 'Free'); $propertyElt->setValue( "<a href='#' class='btn-info property-adder small'><span class='icon-property-add'></span> " . __('Add property') . "</a>" ); $actions[] = $propertyElt; //property mode $propModeELt = tao_helpers_form_FormFactory::getElement('propMode', 'Free'); if($this->propertyMode == 'advanced'){ $propModeELt->setValue("<a href='#' class='btn-info property-mode small property-mode-simple'><span class='icon-property-advanced'></span> ".__('Simple Mode')."</a>"); } else{ $propModeELt->setValue("<a href='#' class='btn-info property-mode small property-mode-advanced'><span class='icon-property-advanced'></span> ".__('Advanced Mode')."</a>"); } $actions[] = $propModeELt; //add a hidden field that states it is a class edition form. $classElt = tao_helpers_form_FormFactory::getElement('tao.forms.class', 'Hidden'); $classElt->setValue('1'); $classElt->addClass('global'); $this->form->addElement($classElt); $this->form->setActions($actions, 'top'); $this->form->setActions($actions, 'bottom'); }
[ "protected", "function", "initForm", "(", ")", "{", "(", "isset", "(", "$", "this", "->", "options", "[", "'name'", "]", ")", ")", "?", "$", "name", "=", "$", "this", "->", "options", "[", "'name'", "]", ":", "$", "name", "=", "''", ";", "if", ...
Initialize the form @access protected @author Bertrand Chevrier, <bertrand.chevrier@tudor.lu> @return mixed
[ "Initialize", "the", "form" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/form/class.Clazz.php#L114-L153
oat-sa/tao-core
actions/form/class.Clazz.php
tao_actions_form_Clazz.initElements
protected function initElements() { $clazz = $this->getClassInstance(); //add a group form for the class edition $elementNames = array(); foreach (tao_helpers_form_GenerisFormFactory::getDefaultProperties() as $property) { //map properties widgets to form elements $element = tao_helpers_form_GenerisFormFactory::elementMap($property); if (!is_null($element)) { //take property values to populate the form $values = $clazz->getPropertyValues($property); if (!$property->isMultiple()) { if (count($values) > 1) { $values = array_slice($values, 0, 1); } } foreach ($values as $value) { if (!is_null($value)) { $element->setValue($value); } } $element->setName('class_' . $element->getName()); //set label validator, read only if ($property->getUri() == OntologyRdfs::RDFS_LABEL) { $readonly = tao_helpers_form_FormFactory::getElement($element->getName(), 'Readonly'); $readonly->setDescription($element->getDescription()); $readonly->setValue($element->getRawValue()); $element = $readonly; } $element->addClass('global'); $this->form->addElement($element); $elementNames[] = $element->getName(); } } //add an hidden elt for the class uri $classUriElt = tao_helpers_form_FormFactory::getElement('classUri', 'Hidden'); $classUriElt->setValue(tao_helpers_Uri::encode($clazz->getUri())); $classUriElt->addClass('global'); $this->form->addElement($classUriElt); $hiddenId = tao_helpers_form_FormFactory::getElement('id', 'Hidden'); $hiddenId->setValue($clazz->getUri()); $hiddenId->addClass('global'); $this->form->addElement($hiddenId); $localNamespace = common_ext_NamespaceManager::singleton()->getLocalNamespace()->getUri(); //class properties edition: add a group form for each property $classProperties = tao_helpers_form_GenerisFormFactory::getClassProperties($clazz, $this->getTopClazz()); $i = 0; $systemProperties = $this->getSystemProperties(); foreach ($classProperties as $classProperty) { $i++; $useEditor = (boolean)preg_match("/^" . preg_quote($localNamespace, '/') . "/", $classProperty->getUri()); $parentProp = true; $domains = $classProperty->getDomain(); foreach ($domains->getIterator() as $domain) { if (array_search($classProperty->getUri(), $systemProperties) !== false || $domain->getUri() == $clazz->getUri() ) { $parentProp = false; //@todo use the getPrivileges method once implemented break; } } if ($useEditor) { $propData = array(); if (isset($this->propertyData[$classProperty->getUri()])) { foreach ($this->propertyData[$classProperty->getUri()] as $key => $value) { $propData[$i.'_'.$key] = $value; } } $propForm = $this->getPropertyForm($classProperty, $i, $parentProp, $propData); //and get its elements and groups $this->form->setElements(array_merge($this->form->getElements(), $propForm->getElements())); $this->form->setGroups(array_merge($this->form->getGroups(), $propForm->getGroups())); unset($propForm); } // read only properties else { $roElement = tao_helpers_form_FormFactory::getElement('roProperty' . $i, 'Free'); $roElement->setValue(__('Cannot be edited')); $this->form->addElement($roElement); $groupTitle = '<span class="property-heading-label">' . _dh($classProperty->getLabel()) . '</span>'; $this->form->createGroup("ro_property_{$i}", $groupTitle, array('roProperty' . $i)); } } }
php
protected function initElements() { $clazz = $this->getClassInstance(); //add a group form for the class edition $elementNames = array(); foreach (tao_helpers_form_GenerisFormFactory::getDefaultProperties() as $property) { //map properties widgets to form elements $element = tao_helpers_form_GenerisFormFactory::elementMap($property); if (!is_null($element)) { //take property values to populate the form $values = $clazz->getPropertyValues($property); if (!$property->isMultiple()) { if (count($values) > 1) { $values = array_slice($values, 0, 1); } } foreach ($values as $value) { if (!is_null($value)) { $element->setValue($value); } } $element->setName('class_' . $element->getName()); //set label validator, read only if ($property->getUri() == OntologyRdfs::RDFS_LABEL) { $readonly = tao_helpers_form_FormFactory::getElement($element->getName(), 'Readonly'); $readonly->setDescription($element->getDescription()); $readonly->setValue($element->getRawValue()); $element = $readonly; } $element->addClass('global'); $this->form->addElement($element); $elementNames[] = $element->getName(); } } //add an hidden elt for the class uri $classUriElt = tao_helpers_form_FormFactory::getElement('classUri', 'Hidden'); $classUriElt->setValue(tao_helpers_Uri::encode($clazz->getUri())); $classUriElt->addClass('global'); $this->form->addElement($classUriElt); $hiddenId = tao_helpers_form_FormFactory::getElement('id', 'Hidden'); $hiddenId->setValue($clazz->getUri()); $hiddenId->addClass('global'); $this->form->addElement($hiddenId); $localNamespace = common_ext_NamespaceManager::singleton()->getLocalNamespace()->getUri(); //class properties edition: add a group form for each property $classProperties = tao_helpers_form_GenerisFormFactory::getClassProperties($clazz, $this->getTopClazz()); $i = 0; $systemProperties = $this->getSystemProperties(); foreach ($classProperties as $classProperty) { $i++; $useEditor = (boolean)preg_match("/^" . preg_quote($localNamespace, '/') . "/", $classProperty->getUri()); $parentProp = true; $domains = $classProperty->getDomain(); foreach ($domains->getIterator() as $domain) { if (array_search($classProperty->getUri(), $systemProperties) !== false || $domain->getUri() == $clazz->getUri() ) { $parentProp = false; //@todo use the getPrivileges method once implemented break; } } if ($useEditor) { $propData = array(); if (isset($this->propertyData[$classProperty->getUri()])) { foreach ($this->propertyData[$classProperty->getUri()] as $key => $value) { $propData[$i.'_'.$key] = $value; } } $propForm = $this->getPropertyForm($classProperty, $i, $parentProp, $propData); //and get its elements and groups $this->form->setElements(array_merge($this->form->getElements(), $propForm->getElements())); $this->form->setGroups(array_merge($this->form->getGroups(), $propForm->getGroups())); unset($propForm); } // read only properties else { $roElement = tao_helpers_form_FormFactory::getElement('roProperty' . $i, 'Free'); $roElement->setValue(__('Cannot be edited')); $this->form->addElement($roElement); $groupTitle = '<span class="property-heading-label">' . _dh($classProperty->getLabel()) . '</span>'; $this->form->createGroup("ro_property_{$i}", $groupTitle, array('roProperty' . $i)); } } }
[ "protected", "function", "initElements", "(", ")", "{", "$", "clazz", "=", "$", "this", "->", "getClassInstance", "(", ")", ";", "//add a group form for the class edition", "$", "elementNames", "=", "array", "(", ")", ";", "foreach", "(", "tao_helpers_form_Generis...
Initialize the form elements @access protected @author Bertrand Chevrier, <bertrand.chevrier@tudor.lu> @return mixed
[ "Initialize", "the", "form", "elements" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/form/class.Clazz.php#L162-L268
oat-sa/tao-core
actions/form/class.Clazz.php
tao_actions_form_Clazz.getSystemProperties
protected function getSystemProperties() { $constants = get_defined_constants(true); $keys = array_filter(array_keys($constants['user']), function ($key) { return strstr($key, 'PROPERTY') !== false; }); return array_intersect_key($constants['user'], array_flip($keys)); }
php
protected function getSystemProperties() { $constants = get_defined_constants(true); $keys = array_filter(array_keys($constants['user']), function ($key) { return strstr($key, 'PROPERTY') !== false; }); return array_intersect_key($constants['user'], array_flip($keys)); }
[ "protected", "function", "getSystemProperties", "(", ")", "{", "$", "constants", "=", "get_defined_constants", "(", "true", ")", ";", "$", "keys", "=", "array_filter", "(", "array_keys", "(", "$", "constants", "[", "'user'", "]", ")", ",", "function", "(", ...
Returns list of all system property classes @return array
[ "Returns", "list", "of", "all", "system", "property", "classes" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/form/class.Clazz.php#L274-L284
oat-sa/tao-core
models/classes/upload/UploadService.php
UploadService.universalizeUpload
public function universalizeUpload($file) { if ((is_string($file) && is_file($file)) || $file instanceof File) { return $file; } return $this->getUploadedFlyFile($file); }
php
public function universalizeUpload($file) { if ((is_string($file) && is_file($file)) || $file instanceof File) { return $file; } return $this->getUploadedFlyFile($file); }
[ "public", "function", "universalizeUpload", "(", "$", "file", ")", "{", "if", "(", "(", "is_string", "(", "$", "file", ")", "&&", "is_file", "(", "$", "file", ")", ")", "||", "$", "file", "instanceof", "File", ")", "{", "return", "$", "file", ";", ...
Detects @param $file @return File|string @deprecated @throws \common_Exception
[ "Detects" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/upload/UploadService.php#L118-L125
oat-sa/tao-core
models/classes/upload/UploadService.php
UploadService.getUploadedFile
public function getUploadedFile($serial) { $file = $this->universalizeUpload($serial); if ($file instanceof File) { $file = $this->getLocalCopy($file); } return $file; }
php
public function getUploadedFile($serial) { $file = $this->universalizeUpload($serial); if ($file instanceof File) { $file = $this->getLocalCopy($file); } return $file; }
[ "public", "function", "getUploadedFile", "(", "$", "serial", ")", "{", "$", "file", "=", "$", "this", "->", "universalizeUpload", "(", "$", "serial", ")", ";", "if", "(", "$", "file", "instanceof", "File", ")", "{", "$", "file", "=", "$", "this", "->...
Either create local copy or use original location for tile Returns absolute path to the file, to be compatible with legacy methods @deprecated @param string|File $serial @return string @throws \common_Exception
[ "Either", "create", "local", "copy", "or", "use", "original", "location", "for", "tile", "Returns", "absolute", "path", "to", "the", "file", "to", "be", "compatible", "with", "legacy", "methods" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/upload/UploadService.php#L135-L142
oat-sa/tao-core
models/classes/upload/UploadService.php
UploadService.getUploadedFlyFile
public function getUploadedFlyFile($serial) { $path = $this->getUserDirectoryHash() . '/'; if (filter_var($serial, FILTER_VALIDATE_URL)) { // Getting the File instance of the file url. $fakeFile = $this->getSerializer()->unserializeFile($serial); // Filesystem hack check. if ($fakeFile->getFileSystemId() !== $this->getUploadFSid()) { throw new \common_exception_NotAcceptable( 'The uploaded file url contains a wrong filesystem id!' . '(Expected: `' . $this->getUploadFSid() . '` Actual: `' . $fakeFile->getFileSystemId() . '`)' ); } $path .= $fakeFile->getBasename(); } else { $path .= $serial; } $realFile = $this->getUploadDir()->getFile($path); if ($realFile->exists()) { return $realFile; } return null; }
php
public function getUploadedFlyFile($serial) { $path = $this->getUserDirectoryHash() . '/'; if (filter_var($serial, FILTER_VALIDATE_URL)) { // Getting the File instance of the file url. $fakeFile = $this->getSerializer()->unserializeFile($serial); // Filesystem hack check. if ($fakeFile->getFileSystemId() !== $this->getUploadFSid()) { throw new \common_exception_NotAcceptable( 'The uploaded file url contains a wrong filesystem id!' . '(Expected: `' . $this->getUploadFSid() . '` Actual: `' . $fakeFile->getFileSystemId() . '`)' ); } $path .= $fakeFile->getBasename(); } else { $path .= $serial; } $realFile = $this->getUploadDir()->getFile($path); if ($realFile->exists()) { return $realFile; } return null; }
[ "public", "function", "getUploadedFlyFile", "(", "$", "serial", ")", "{", "$", "path", "=", "$", "this", "->", "getUserDirectoryHash", "(", ")", ".", "'/'", ";", "if", "(", "filter_var", "(", "$", "serial", ",", "FILTER_VALIDATE_URL", ")", ")", "{", "// ...
@param string $serial @throws \common_exception_NotAcceptable When the uploaded file url contains a wrong system id. @return File
[ "@param", "string", "$serial" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/upload/UploadService.php#L151-L178
oat-sa/tao-core
models/classes/upload/UploadService.php
UploadService.getLocalCopy
private function getLocalCopy(File $file) { $tmpName = \tao_helpers_File::concat([\tao_helpers_File::createTempDir(), $file->getBasename()]); if (($resource = fopen($tmpName, 'wb')) !== false) { stream_copy_to_stream($file->readStream(), $resource); fclose($resource); $this->getServiceLocator()->get(EventManager::CONFIG_ID)->trigger(new UploadLocalCopyCreatedEvent($file, $tmpName)); return $tmpName; } throw new \common_Exception('Impossible to make local file copy at ' . $tmpName); }
php
private function getLocalCopy(File $file) { $tmpName = \tao_helpers_File::concat([\tao_helpers_File::createTempDir(), $file->getBasename()]); if (($resource = fopen($tmpName, 'wb')) !== false) { stream_copy_to_stream($file->readStream(), $resource); fclose($resource); $this->getServiceLocator()->get(EventManager::CONFIG_ID)->trigger(new UploadLocalCopyCreatedEvent($file, $tmpName)); return $tmpName; } throw new \common_Exception('Impossible to make local file copy at ' . $tmpName); }
[ "private", "function", "getLocalCopy", "(", "File", "$", "file", ")", "{", "$", "tmpName", "=", "\\", "tao_helpers_File", "::", "concat", "(", "[", "\\", "tao_helpers_File", "::", "createTempDir", "(", ")", ",", "$", "file", "->", "getBasename", "(", ")", ...
Deprecated, for compatibility with legacy code @param $file @return string @throws \common_Exception
[ "Deprecated", "for", "compatibility", "with", "legacy", "code" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/upload/UploadService.php#L186-L197
oat-sa/tao-core
models/classes/upload/UploadService.php
UploadService.isUploadedFile
public function isUploadedFile($filePath) { // If it's a serialized one. if (filter_var($filePath, FILTER_VALIDATE_URL)) { return true; } // If it's a normal filename. $file = $this->getUploadDir()->getFile($this->getUserDirectoryHash() . '/' . $filePath); if ($file->exists()) { return true; } return false; }
php
public function isUploadedFile($filePath) { // If it's a serialized one. if (filter_var($filePath, FILTER_VALIDATE_URL)) { return true; } // If it's a normal filename. $file = $this->getUploadDir()->getFile($this->getUserDirectoryHash() . '/' . $filePath); if ($file->exists()) { return true; } return false; }
[ "public", "function", "isUploadedFile", "(", "$", "filePath", ")", "{", "// If it's a serialized one.", "if", "(", "filter_var", "(", "$", "filePath", ",", "FILTER_VALIDATE_URL", ")", ")", "{", "return", "true", ";", "}", "// If it's a normal filename.", "$", "fil...
Is the uploaded filename looks as an uploaded file. @param $filePath @return bool
[ "Is", "the", "uploaded", "filename", "looks", "as", "an", "uploaded", "file", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/upload/UploadService.php#L252-L266
oat-sa/tao-core
install/utils/class.MysqlProceduresParser.php
tao_install_utils_MysqlProceduresParser.parse
public function parse(){ $this->setStatements(array()); $file = $this->getFile(); if (!file_exists($file)){ throw new tao_install_utils_SQLParsingException("SQL file '${file}' does not exist."); } else if (!is_readable($file)){ throw new tao_install_utils_SQLParsingException("SQL file '${file}' is not readable."); } else if(!preg_match("/\.sql$/", basename($file))){ throw new tao_install_utils_SQLParsingException("File '${file}' is not a valid SQL file. Extension '.sql' not found."); } $content = @file_get_contents($file); if ($content !== false){ $matches = array(); $patterns = array( 'DROP\s+FUNCTION\s+IF\s+EXISTS\s*\w+\s*;', 'DROP\s+PROCEDURE\s+IF\s+EXISTS\s*\w+\s*;', 'CREATE\s+PROCEDURE\s+\w+\s*\(.*\)\s*(?:(?:NOT\s+){0,1}DETERMINISTIC){0,1}\s*BEGIN\s+(?:.*\s*;\s*)*END\s*;', 'CREATE\s+(DEFINER = \w+\s+)FUNCTION\s+\w+\s*\(.*\)\s*RETURNS\s+(?:.*)\s*(?:(?:NOT\s+){0,1}DETERMINISTIC){0,1}\s*(?:CONTAINS SQL\s+|NO SQL\s+|READS SQL DATA\s+|MODIFIES SQL DATA\s+|SQL SECURITY INVOKER\s+)*\s*BEGIN\s+(?:.*\s*;\s*)*END\s*;'); if (preg_match_all('/' . implode($patterns, '|') . '/i', $content, $matches)){ foreach ($matches[0] as $match){ $this->addStatement($match); } } } else{ throw new tao_install_utils_SQLParsingException("SQL file '${file}' cannot be read. An unknown error occured while reading it."); } }
php
public function parse(){ $this->setStatements(array()); $file = $this->getFile(); if (!file_exists($file)){ throw new tao_install_utils_SQLParsingException("SQL file '${file}' does not exist."); } else if (!is_readable($file)){ throw new tao_install_utils_SQLParsingException("SQL file '${file}' is not readable."); } else if(!preg_match("/\.sql$/", basename($file))){ throw new tao_install_utils_SQLParsingException("File '${file}' is not a valid SQL file. Extension '.sql' not found."); } $content = @file_get_contents($file); if ($content !== false){ $matches = array(); $patterns = array( 'DROP\s+FUNCTION\s+IF\s+EXISTS\s*\w+\s*;', 'DROP\s+PROCEDURE\s+IF\s+EXISTS\s*\w+\s*;', 'CREATE\s+PROCEDURE\s+\w+\s*\(.*\)\s*(?:(?:NOT\s+){0,1}DETERMINISTIC){0,1}\s*BEGIN\s+(?:.*\s*;\s*)*END\s*;', 'CREATE\s+(DEFINER = \w+\s+)FUNCTION\s+\w+\s*\(.*\)\s*RETURNS\s+(?:.*)\s*(?:(?:NOT\s+){0,1}DETERMINISTIC){0,1}\s*(?:CONTAINS SQL\s+|NO SQL\s+|READS SQL DATA\s+|MODIFIES SQL DATA\s+|SQL SECURITY INVOKER\s+)*\s*BEGIN\s+(?:.*\s*;\s*)*END\s*;'); if (preg_match_all('/' . implode($patterns, '|') . '/i', $content, $matches)){ foreach ($matches[0] as $match){ $this->addStatement($match); } } } else{ throw new tao_install_utils_SQLParsingException("SQL file '${file}' cannot be read. An unknown error occured while reading it."); } }
[ "public", "function", "parse", "(", ")", "{", "$", "this", "->", "setStatements", "(", "array", "(", ")", ")", ";", "$", "file", "=", "$", "this", "->", "getFile", "(", ")", ";", "if", "(", "!", "file_exists", "(", "$", "file", ")", ")", "{", "...
Parse a SQL file containing mySQL compliant Procedures or Functions. @return void @throws tao_install_utils_SQLParsingException
[ "Parse", "a", "SQL", "file", "containing", "mySQL", "compliant", "Procedures", "or", "Functions", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/install/utils/class.MysqlProceduresParser.php#L45-L76
oat-sa/tao-core
models/classes/taskQueue/TaskLog/CategorizedStatus.php
CategorizedStatus.createFromString
public static function createFromString($status) { switch ($status) { case TaskLogInterface::STATUS_ENQUEUED: return self::created(); break; case TaskLogInterface::STATUS_DEQUEUED: case TaskLogInterface::STATUS_RUNNING: case TaskLogInterface::STATUS_CHILD_RUNNING: return self::inProgress(); break; case TaskLogInterface::STATUS_COMPLETED: return self::completed(); break; case TaskLogInterface::STATUS_ARCHIVED: return self::archived(); break; case TaskLogInterface::STATUS_CANCELLED: return self::cancelled(); break; case TaskLogInterface::STATUS_FAILED: case TaskLogInterface::STATUS_UNKNOWN: return self::failed(); break; default: throw new \Exception('Invalid status provided'); } }
php
public static function createFromString($status) { switch ($status) { case TaskLogInterface::STATUS_ENQUEUED: return self::created(); break; case TaskLogInterface::STATUS_DEQUEUED: case TaskLogInterface::STATUS_RUNNING: case TaskLogInterface::STATUS_CHILD_RUNNING: return self::inProgress(); break; case TaskLogInterface::STATUS_COMPLETED: return self::completed(); break; case TaskLogInterface::STATUS_ARCHIVED: return self::archived(); break; case TaskLogInterface::STATUS_CANCELLED: return self::cancelled(); break; case TaskLogInterface::STATUS_FAILED: case TaskLogInterface::STATUS_UNKNOWN: return self::failed(); break; default: throw new \Exception('Invalid status provided'); } }
[ "public", "static", "function", "createFromString", "(", "$", "status", ")", "{", "switch", "(", "$", "status", ")", "{", "case", "TaskLogInterface", "::", "STATUS_ENQUEUED", ":", "return", "self", "::", "created", "(", ")", ";", "break", ";", "case", "Tas...
@param string $status @return CategorizedStatus @throws Exception
[ "@param", "string", "$status", "@return", "CategorizedStatus" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/taskQueue/TaskLog/CategorizedStatus.php#L76-L109
oat-sa/tao-core
helpers/form/elements/xhtml/class.AsyncFile.php
tao_helpers_form_elements_xhtml_AsyncFile.feed
public function feed() { common_Logger::t('Evaluating AsyncFile ' . $this->getName(), array( 'TAO')); if (isset($_POST[$this->name])) { $struct = json_decode($_POST[$this->name], true); if ($struct !== false) { $this->setValue($struct); } else { common_Logger::w('Could not unserialise AsyncFile field ' . $this->getName(), array( 'TAO')); } } }
php
public function feed() { common_Logger::t('Evaluating AsyncFile ' . $this->getName(), array( 'TAO')); if (isset($_POST[$this->name])) { $struct = json_decode($_POST[$this->name], true); if ($struct !== false) { $this->setValue($struct); } else { common_Logger::w('Could not unserialise AsyncFile field ' . $this->getName(), array( 'TAO')); } } }
[ "public", "function", "feed", "(", ")", "{", "common_Logger", "::", "t", "(", "'Evaluating AsyncFile '", ".", "$", "this", "->", "getName", "(", ")", ",", "array", "(", "'TAO'", ")", ")", ";", "if", "(", "isset", "(", "$", "_POST", "[", "$", "this", ...
Short description of method feed @access public @author Joel Bout, <joel.bout@tudor.lu>
[ "Short", "description", "of", "method", "feed" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/elements/xhtml/class.AsyncFile.php#L42-L55
oat-sa/tao-core
helpers/form/elements/xhtml/class.AsyncFile.php
tao_helpers_form_elements_xhtml_AsyncFile.render
public function render() { $widgetName = 'Uploader_' . md5($this->name); $returnValue = $this->renderLabel(); $returnValue .= "<input type='hidden' name='{$this->name}' id='{$this->name}' value='' />"; $returnValue .= "<div id='{$widgetName}_container' class='form-elt-container file-uploader'>"; // get the upload max size $fileSize = SystemHelper::getFileUploadLimit(); $mimetypes = array(); // add a client validation foreach ($this->validators as $validator) { // get the valid file extensions if ($validator instanceof tao_helpers_form_validators_FileMimeType) { $options = $validator->getOptions(); if (isset($options['mimetype'])) { $mimetypes = $options['mimetype']; } } // get the max file size if ($validator instanceof tao_helpers_form_validators_FileSize) { $options = $validator->getOptions(); if (isset($options['max'])) { $validatorMax = (int) $options['max']; if ($validatorMax > 0 && $validatorMax < $fileSize) { $fileSize = $validatorMax; } } } } // default value for 'auto' is 'true': $auto = 'true'; if (isset($this->attributes['auto'])) { if (! $this->attributes['auto'] || $this->attributes['auto'] === 'false') { $auto = 'false'; } unset($this->attributes['auto']); } // initialize the Uploader Js component $returnValue .= '<script type="text/javascript"> require([\'jquery\', \'ui/feedback\', \'ui/uploader\'], function($, feedback){ $("#' . $widgetName . '_container").uploader({ uploadUrl: "' . ROOT_URL . 'tao/File/upload", autoUpload: "' . $auto . '" , showResetButton: "' . ! $auto . '" , showUploadButton: "' . ! $auto . '" , fileSelect : function(files, done){ var error = [], files = files.filter(_.isObject),// due to Chrome drag\'n\'drop issue givenLength = files.length, filters = "' . implode(',', $mimetypes) . '".split(",").filter(function(e){return e.length}); if (filters.length){ files = _.filter(files, function(file){ return !file.type || _.contains(filters, file.type.replace(/[\'"]+/g, \'\'));//IE9 doesnt detect type, so lets rely on server validation }); if(files.length !== givenLength){ error.push( "Unauthorized files have been removed"); } } files = _.filter(files, function(file){ return file.size <= ' . $fileSize . '; }); if(files.length !== givenLength && !error.length){ error.push( "Size limit is ' . $fileSize . ' bytes"); } if (error.length){ feedback().error(error.join(",")); } done(files); if ( ' . $auto . ' ){ $(this).uploader("upload"); } } }).on("upload.uploader", function(e, file, result){ if ( result && result.uploaded ){ $("input[name=\'' . $this->getName() . '\']").val(result.data); } }) }); </script>'; $returnValue .= "</div>"; return (string) $returnValue; }
php
public function render() { $widgetName = 'Uploader_' . md5($this->name); $returnValue = $this->renderLabel(); $returnValue .= "<input type='hidden' name='{$this->name}' id='{$this->name}' value='' />"; $returnValue .= "<div id='{$widgetName}_container' class='form-elt-container file-uploader'>"; // get the upload max size $fileSize = SystemHelper::getFileUploadLimit(); $mimetypes = array(); // add a client validation foreach ($this->validators as $validator) { // get the valid file extensions if ($validator instanceof tao_helpers_form_validators_FileMimeType) { $options = $validator->getOptions(); if (isset($options['mimetype'])) { $mimetypes = $options['mimetype']; } } // get the max file size if ($validator instanceof tao_helpers_form_validators_FileSize) { $options = $validator->getOptions(); if (isset($options['max'])) { $validatorMax = (int) $options['max']; if ($validatorMax > 0 && $validatorMax < $fileSize) { $fileSize = $validatorMax; } } } } // default value for 'auto' is 'true': $auto = 'true'; if (isset($this->attributes['auto'])) { if (! $this->attributes['auto'] || $this->attributes['auto'] === 'false') { $auto = 'false'; } unset($this->attributes['auto']); } // initialize the Uploader Js component $returnValue .= '<script type="text/javascript"> require([\'jquery\', \'ui/feedback\', \'ui/uploader\'], function($, feedback){ $("#' . $widgetName . '_container").uploader({ uploadUrl: "' . ROOT_URL . 'tao/File/upload", autoUpload: "' . $auto . '" , showResetButton: "' . ! $auto . '" , showUploadButton: "' . ! $auto . '" , fileSelect : function(files, done){ var error = [], files = files.filter(_.isObject),// due to Chrome drag\'n\'drop issue givenLength = files.length, filters = "' . implode(',', $mimetypes) . '".split(",").filter(function(e){return e.length}); if (filters.length){ files = _.filter(files, function(file){ return !file.type || _.contains(filters, file.type.replace(/[\'"]+/g, \'\'));//IE9 doesnt detect type, so lets rely on server validation }); if(files.length !== givenLength){ error.push( "Unauthorized files have been removed"); } } files = _.filter(files, function(file){ return file.size <= ' . $fileSize . '; }); if(files.length !== givenLength && !error.length){ error.push( "Size limit is ' . $fileSize . ' bytes"); } if (error.length){ feedback().error(error.join(",")); } done(files); if ( ' . $auto . ' ){ $(this).uploader("upload"); } } }).on("upload.uploader", function(e, file, result){ if ( result && result.uploaded ){ $("input[name=\'' . $this->getName() . '\']").val(result.data); } }) }); </script>'; $returnValue .= "</div>"; return (string) $returnValue; }
[ "public", "function", "render", "(", ")", "{", "$", "widgetName", "=", "'Uploader_'", ".", "md5", "(", "$", "this", "->", "name", ")", ";", "$", "returnValue", "=", "$", "this", "->", "renderLabel", "(", ")", ";", "$", "returnValue", ".=", "\"<input ty...
Short description of method render @access public @author Joel Bout, <joel.bout@tudor.lu> @return string
[ "Short", "description", "of", "method", "render" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/elements/xhtml/class.AsyncFile.php#L64-L161
oat-sa/tao-core
models/classes/ClientLibRegistry.php
ClientLibRegistry.register
public function register($id, $fullPath) { /** @var AssetService $assetService */ $assetService = ServiceManager::getServiceManager()->get(AssetService::SERVICE_ID); if (self::getRegistry()->isRegistered($id)) { common_Logger::w('Lib already registered'); } if (substr($fullPath, 0, strlen('../../../')) == '../../../') { $fullPath = ROOT_URL.substr($fullPath, strlen('../../../')); } $found = false; foreach (\common_ext_ExtensionsManager::singleton()->getInstalledExtensions() as $ext) { if (strpos($fullPath, $assetService->getJsBaseWww( $ext->getId() )) === 0) { $found = true; self::getRegistry()->set($id, array( 'extId' => $ext->getId(), 'path' => substr($fullPath, strlen( $assetService->getJsBaseWww($ext->getId()) )) )); break; } } if ($found == false) { throw new \common_exception_Error('Path "'.$fullPath.'" is not a valid asset path in Tao'); } }
php
public function register($id, $fullPath) { /** @var AssetService $assetService */ $assetService = ServiceManager::getServiceManager()->get(AssetService::SERVICE_ID); if (self::getRegistry()->isRegistered($id)) { common_Logger::w('Lib already registered'); } if (substr($fullPath, 0, strlen('../../../')) == '../../../') { $fullPath = ROOT_URL.substr($fullPath, strlen('../../../')); } $found = false; foreach (\common_ext_ExtensionsManager::singleton()->getInstalledExtensions() as $ext) { if (strpos($fullPath, $assetService->getJsBaseWww( $ext->getId() )) === 0) { $found = true; self::getRegistry()->set($id, array( 'extId' => $ext->getId(), 'path' => substr($fullPath, strlen( $assetService->getJsBaseWww($ext->getId()) )) )); break; } } if ($found == false) { throw new \common_exception_Error('Path "'.$fullPath.'" is not a valid asset path in Tao'); } }
[ "public", "function", "register", "(", "$", "id", ",", "$", "fullPath", ")", "{", "/** @var AssetService $assetService */", "$", "assetService", "=", "ServiceManager", "::", "getServiceManager", "(", ")", "->", "get", "(", "AssetService", "::", "SERVICE_ID", ")", ...
Register a new path for given alias, trigger a warning if path already register @author Lionel Lecaque, lionel@taotesting.com @param string $id @param string $fullPath @throws \common_exception_Error
[ "Register", "a", "new", "path", "for", "given", "alias", "trigger", "a", "warning", "if", "path", "already", "register" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/ClientLibRegistry.php#L85-L113
oat-sa/tao-core
models/classes/layout/AmdLoader.php
AmdLoader.getBundleLoader
public function getBundleLoader($bundle, $controller, $params = null){ $attributes = [ 'data-config' => $this->configUrl, 'src' => $bundle, 'data-controller' => $controller ]; if(!is_null($params)){ $attributes['data-params'] = json_encode($params); } return $this->buildScriptTag($attributes); }
php
public function getBundleLoader($bundle, $controller, $params = null){ $attributes = [ 'data-config' => $this->configUrl, 'src' => $bundle, 'data-controller' => $controller ]; if(!is_null($params)){ $attributes['data-params'] = json_encode($params); } return $this->buildScriptTag($attributes); }
[ "public", "function", "getBundleLoader", "(", "$", "bundle", ",", "$", "controller", ",", "$", "params", "=", "null", ")", "{", "$", "attributes", "=", "[", "'data-config'", "=>", "$", "this", "->", "configUrl", ",", "'src'", "=>", "$", "bundle", ",", ...
Get the loader for the bundle mode @param string $bundle the URL of the bundle @param string $controller the controller module id @param array $params additionnal parameters to give to the loader @return the generated script tag
[ "Get", "the", "loader", "for", "the", "bundle", "mode", "@param", "string", "$bundle", "the", "URL", "of", "the", "bundle", "@param", "string", "$controller", "the", "controller", "module", "id", "@param", "array", "$params", "additionnal", "parameters", "to", ...
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/layout/AmdLoader.php#L68-L80
oat-sa/tao-core
models/classes/layout/AmdLoader.php
AmdLoader.getDynamicLoader
public function getDynamicLoader($controller, $params = null){ $attributes = [ 'data-config' => $this->configUrl, 'src' => $this->requireJsUrl, 'data-main' => $this->bootstrapUrl, 'data-controller' => $controller ]; if(!is_null($params)){ $attributes['data-params'] = json_encode($params); } return $this->buildScriptTag($attributes); }
php
public function getDynamicLoader($controller, $params = null){ $attributes = [ 'data-config' => $this->configUrl, 'src' => $this->requireJsUrl, 'data-main' => $this->bootstrapUrl, 'data-controller' => $controller ]; if(!is_null($params)){ $attributes['data-params'] = json_encode($params); } return $this->buildScriptTag($attributes); }
[ "public", "function", "getDynamicLoader", "(", "$", "controller", ",", "$", "params", "=", "null", ")", "{", "$", "attributes", "=", "[", "'data-config'", "=>", "$", "this", "->", "configUrl", ",", "'src'", "=>", "$", "this", "->", "requireJsUrl", ",", "...
Get the loader for the dynamic mode @param string $controller the controller module id @param array $params additionnal parameters to give to the loader @return the generated script tag
[ "Get", "the", "loader", "for", "the", "dynamic", "mode", "@param", "string", "$controller", "the", "controller", "module", "id", "@param", "array", "$params", "additionnal", "parameters", "to", "give", "to", "the", "loader" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/layout/AmdLoader.php#L89-L102
oat-sa/tao-core
models/classes/layout/AmdLoader.php
AmdLoader.buildScriptTag
private function buildScriptTag($attributes){ $amdScript = '<script id="' . self::LOADER_ID . '" '; foreach($attributes as $attr => $value) { $amdScript .= $attr . '="' . \tao_helpers_Display::htmlize($value) . '" '; } return trim($amdScript) . '></script>'; }
php
private function buildScriptTag($attributes){ $amdScript = '<script id="' . self::LOADER_ID . '" '; foreach($attributes as $attr => $value) { $amdScript .= $attr . '="' . \tao_helpers_Display::htmlize($value) . '" '; } return trim($amdScript) . '></script>'; }
[ "private", "function", "buildScriptTag", "(", "$", "attributes", ")", "{", "$", "amdScript", "=", "'<script id=\"'", ".", "self", "::", "LOADER_ID", ".", "'\" '", ";", "foreach", "(", "$", "attributes", "as", "$", "attr", "=>", "$", "value", ")", "{", "$...
Build the script tag @param array $attributes key/val to create tag's attributes @return the generated script tag
[ "Build", "the", "script", "tag", "@param", "array", "$attributes", "key", "/", "val", "to", "create", "tag", "s", "attributes" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/layout/AmdLoader.php#L110-L116
oat-sa/tao-core
helpers/form/validators/class.FileSize.php
tao_helpers_form_validators_FileSize.setOptions
public function setOptions(array $options) { parent::setOptions($options); if ($this->hasOption('min') && $this->hasOption('max') ) { $this->setMessage(__('Invalid file size (minimum %1$s bytes, maximum %2$s bytes)', $this->getOption('min'), $this->getOption('max'))); } elseif ($this->hasOption('max')) { $this->setMessage(__('The uploaded file is too large (maximum %s bytes)', $this->getOption('max'))); $this->setOption('min', 0); } else { throw new common_Exception("Please set 'min' and/or 'max' options!"); } }
php
public function setOptions(array $options) { parent::setOptions($options); if ($this->hasOption('min') && $this->hasOption('max') ) { $this->setMessage(__('Invalid file size (minimum %1$s bytes, maximum %2$s bytes)', $this->getOption('min'), $this->getOption('max'))); } elseif ($this->hasOption('max')) { $this->setMessage(__('The uploaded file is too large (maximum %s bytes)', $this->getOption('max'))); $this->setOption('min', 0); } else { throw new common_Exception("Please set 'min' and/or 'max' options!"); } }
[ "public", "function", "setOptions", "(", "array", "$", "options", ")", "{", "parent", "::", "setOptions", "(", "$", "options", ")", ";", "if", "(", "$", "this", "->", "hasOption", "(", "'min'", ")", "&&", "$", "this", "->", "hasOption", "(", "'max'", ...
--- OPERATIONS ---
[ "---", "OPERATIONS", "---" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/validators/class.FileSize.php#L39-L51
oat-sa/tao-core
helpers/form/validators/class.FileSize.php
tao_helpers_form_validators_FileSize.evaluate
public function evaluate($values) { $returnValue = (bool) false; if(is_array($values)){ if(isset($values['size'])){ if($values['size'] >= $this->getOption('min') && $values['size'] <= $this->getOption('max')){ $returnValue = true; } }else{ $returnValue = true; } }else{ $returnValue = true; } return (bool) $returnValue; }
php
public function evaluate($values) { $returnValue = (bool) false; if(is_array($values)){ if(isset($values['size'])){ if($values['size'] >= $this->getOption('min') && $values['size'] <= $this->getOption('max')){ $returnValue = true; } }else{ $returnValue = true; } }else{ $returnValue = true; } return (bool) $returnValue; }
[ "public", "function", "evaluate", "(", "$", "values", ")", "{", "$", "returnValue", "=", "(", "bool", ")", "false", ";", "if", "(", "is_array", "(", "$", "values", ")", ")", "{", "if", "(", "isset", "(", "$", "values", "[", "'size'", "]", ")", ")...
Short description of method evaluate @access public @author Joel Bout, <joel.bout@tudor.lu> @param values @return boolean
[ "Short", "description", "of", "method", "evaluate" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/validators/class.FileSize.php#L62-L83
oat-sa/tao-core
actions/class.Search.php
tao_actions_Search.searchParams
public function searchParams() { $rawQuery = isset($_POST['query'])?$_POST['query']:''; $this->returnJson(array( 'url' => _url('search'), 'params' => array( 'query' => $rawQuery, 'rootNode' => $this->getRequestParameter('rootNode') ), 'filter' => array(), 'model' => array( OntologyRdfs::RDFS_LABEL => array( 'id' => OntologyRdfs::RDFS_LABEL, 'label' => __('Label'), 'sortable' => false ) ), 'result' => true )); }
php
public function searchParams() { $rawQuery = isset($_POST['query'])?$_POST['query']:''; $this->returnJson(array( 'url' => _url('search'), 'params' => array( 'query' => $rawQuery, 'rootNode' => $this->getRequestParameter('rootNode') ), 'filter' => array(), 'model' => array( OntologyRdfs::RDFS_LABEL => array( 'id' => OntologyRdfs::RDFS_LABEL, 'label' => __('Label'), 'sortable' => false ) ), 'result' => true )); }
[ "public", "function", "searchParams", "(", ")", "{", "$", "rawQuery", "=", "isset", "(", "$", "_POST", "[", "'query'", "]", ")", "?", "$", "_POST", "[", "'query'", "]", ":", "''", ";", "$", "this", "->", "returnJson", "(", "array", "(", "'url'", "=...
Search parameters endpoints. The response provides parameters to create a datatable.
[ "Search", "parameters", "endpoints", ".", "The", "response", "provides", "parameters", "to", "create", "a", "datatable", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.Search.php#L42-L61
oat-sa/tao-core
actions/class.Search.php
tao_actions_Search.search
public function search() { $params = $this->getRequestParameter('params'); $query = $params['query']; $class = $this->getClass($params['rootNode']); $rows = $this->hasRequestParameter('rows') ? (int)$this->getRequestParameter('rows') : null; $page = $this->hasRequestParameter('page') ? (int)$this->getRequestParameter('page') : 1; $startRow = is_null($rows) ? 0 : $rows * ($page - 1); try { $results = []; // if it is an URI if (strpos($query, LOCAL_NAMESPACE) === 0) { $resource = $this->getResource($query); if ($resource->exists() && $resource->isInstanceOf($class)) { $results = new ResultSet([$resource->getUri()], 1); } } // if there is no results based on considering the query as URI if (empty($results)) { $results = $this->getServiceLocator()->get(Search::SERVICE_ID)->query($query, $class->getUri(), $startRow, $rows); } $totalPages = is_null($rows) ? 1 : ceil( $results->getTotalCount() / $rows ); $response = new StdClass(); if(count($results) > 0 ){ foreach($results as $uri) { $instance = $this->getResource($uri); $instanceProperties = array( 'id' => $instance->getUri(), OntologyRdfs::RDFS_LABEL => $instance->getLabel() ); $response->data[] = $instanceProperties; } } $response->success = true; $response->page = empty($response->data) ? 0 : $page; $response->total = $totalPages; $response->records = count($results); $this->returnJson($response, 200); } catch (SyntaxException $e) { $this->returnJson(array( 'success' => false, 'msg' => $e->getUserMessage() )); } }
php
public function search() { $params = $this->getRequestParameter('params'); $query = $params['query']; $class = $this->getClass($params['rootNode']); $rows = $this->hasRequestParameter('rows') ? (int)$this->getRequestParameter('rows') : null; $page = $this->hasRequestParameter('page') ? (int)$this->getRequestParameter('page') : 1; $startRow = is_null($rows) ? 0 : $rows * ($page - 1); try { $results = []; // if it is an URI if (strpos($query, LOCAL_NAMESPACE) === 0) { $resource = $this->getResource($query); if ($resource->exists() && $resource->isInstanceOf($class)) { $results = new ResultSet([$resource->getUri()], 1); } } // if there is no results based on considering the query as URI if (empty($results)) { $results = $this->getServiceLocator()->get(Search::SERVICE_ID)->query($query, $class->getUri(), $startRow, $rows); } $totalPages = is_null($rows) ? 1 : ceil( $results->getTotalCount() / $rows ); $response = new StdClass(); if(count($results) > 0 ){ foreach($results as $uri) { $instance = $this->getResource($uri); $instanceProperties = array( 'id' => $instance->getUri(), OntologyRdfs::RDFS_LABEL => $instance->getLabel() ); $response->data[] = $instanceProperties; } } $response->success = true; $response->page = empty($response->data) ? 0 : $page; $response->total = $totalPages; $response->records = count($results); $this->returnJson($response, 200); } catch (SyntaxException $e) { $this->returnJson(array( 'success' => false, 'msg' => $e->getUserMessage() )); } }
[ "public", "function", "search", "(", ")", "{", "$", "params", "=", "$", "this", "->", "getRequestParameter", "(", "'params'", ")", ";", "$", "query", "=", "$", "params", "[", "'query'", "]", ";", "$", "class", "=", "$", "this", "->", "getClass", "(",...
Search results The search is paginated and initiated by the datatable component.
[ "Search", "results", "The", "search", "is", "paginated", "and", "initiated", "by", "the", "datatable", "component", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.Search.php#L67-L120
oat-sa/tao-core
models/classes/import/service/ImporterFactory.php
ImporterFactory.create
public function create($type) { $typeOptions = $this->getOption(self::OPTION_MAPPERS); $typeOption = isset($typeOptions[$type]) ? $typeOptions[$type] : $this->throwException(); $importerString = isset($typeOption[self::OPTION_MAPPERS_IMPORTER]) ? $typeOption[self::OPTION_MAPPERS_IMPORTER] : $this->throwException(); $importer = $this->buildService($importerString, ImportServiceInterface::class); if (isset($typeOption[self::OPTION_MAPPERS_MAPPER])) { $mapperString = $typeOption[self::OPTION_MAPPERS_MAPPER]; $mapper = $this->buildService($mapperString); } else { $mapper = $this->getDefaultMapper(); } $this->propagate($mapper); $importer->setMapper($mapper); return $importer; }
php
public function create($type) { $typeOptions = $this->getOption(self::OPTION_MAPPERS); $typeOption = isset($typeOptions[$type]) ? $typeOptions[$type] : $this->throwException(); $importerString = isset($typeOption[self::OPTION_MAPPERS_IMPORTER]) ? $typeOption[self::OPTION_MAPPERS_IMPORTER] : $this->throwException(); $importer = $this->buildService($importerString, ImportServiceInterface::class); if (isset($typeOption[self::OPTION_MAPPERS_MAPPER])) { $mapperString = $typeOption[self::OPTION_MAPPERS_MAPPER]; $mapper = $this->buildService($mapperString); } else { $mapper = $this->getDefaultMapper(); } $this->propagate($mapper); $importer->setMapper($mapper); return $importer; }
[ "public", "function", "create", "(", "$", "type", ")", "{", "$", "typeOptions", "=", "$", "this", "->", "getOption", "(", "self", "::", "OPTION_MAPPERS", ")", ";", "$", "typeOption", "=", "isset", "(", "$", "typeOptions", "[", "$", "type", "]", ")", ...
Create an importer User type is defined in a config mapper and is associated to a role @param $type @return ImportServiceInterface @throws \common_exception_NotFound @throws InvalidService @throws InvalidServiceManagerException
[ "Create", "an", "importer" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/import/service/ImporterFactory.php#L39-L57
oat-sa/tao-core
install/utils/class.ModelCreator.php
tao_install_utils_ModelCreator.insertSuperUser
public function insertSuperUser(array $userData){ if (empty($userData['login']) || empty($userData['password'])){ throw new tao_install_utils_Exception("To create a super user you must provide at least a login and a password"); } $superUserOntology = dirname(__FILE__) . "/../ontology/superuser.rdf"; if (!@is_readable($superUserOntology)){ throw new tao_install_utils_Exception("Unable to load ontology : ${superUserOntology}"); } $doc = new DOMDocument(); $doc->load($superUserOntology); foreach ($userData as $key => $value){ $tags = $doc->getElementsByTagNameNS('http://www.tao.lu/Ontologies/generis.rdf#', $key); foreach ($tags as $tag){ $tag->appendChild($doc->createCDATASection($value)); } } return $this->insertLocalModel($doc->saveXML()); }
php
public function insertSuperUser(array $userData){ if (empty($userData['login']) || empty($userData['password'])){ throw new tao_install_utils_Exception("To create a super user you must provide at least a login and a password"); } $superUserOntology = dirname(__FILE__) . "/../ontology/superuser.rdf"; if (!@is_readable($superUserOntology)){ throw new tao_install_utils_Exception("Unable to load ontology : ${superUserOntology}"); } $doc = new DOMDocument(); $doc->load($superUserOntology); foreach ($userData as $key => $value){ $tags = $doc->getElementsByTagNameNS('http://www.tao.lu/Ontologies/generis.rdf#', $key); foreach ($tags as $tag){ $tag->appendChild($doc->createCDATASection($value)); } } return $this->insertLocalModel($doc->saveXML()); }
[ "public", "function", "insertSuperUser", "(", "array", "$", "userData", ")", "{", "if", "(", "empty", "(", "$", "userData", "[", "'login'", "]", ")", "||", "empty", "(", "$", "userData", "[", "'password'", "]", ")", ")", "{", "throw", "new", "tao_insta...
Specifiq method to insert the super user model, by using a template RDF file @param array $userData
[ "Specifiq", "method", "to", "insert", "the", "super", "user", "model", "by", "using", "a", "template", "RDF", "file" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/install/utils/class.ModelCreator.php#L58-L80
oat-sa/tao-core
install/utils/class.ModelCreator.php
tao_install_utils_ModelCreator.insertLocalModelFile
public function insertLocalModelFile($file){ if(!file_exists($file) || !is_readable($file)){ throw new tao_install_utils_Exception("Unable to load ontology : $file"); } return $this->insertLocalModel(file_get_contents($file)); }
php
public function insertLocalModelFile($file){ if(!file_exists($file) || !is_readable($file)){ throw new tao_install_utils_Exception("Unable to load ontology : $file"); } return $this->insertLocalModel(file_get_contents($file)); }
[ "public", "function", "insertLocalModelFile", "(", "$", "file", ")", "{", "if", "(", "!", "file_exists", "(", "$", "file", ")", "||", "!", "is_readable", "(", "$", "file", ")", ")", "{", "throw", "new", "tao_install_utils_Exception", "(", "\"Unable to load o...
Insert a model into the local namespace @throws tao_install_utils_Exception @param string $file the path to the RDF file @return boolean true if inserted
[ "Insert", "a", "model", "into", "the", "local", "namespace" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/install/utils/class.ModelCreator.php#L102-L107
oat-sa/tao-core
install/utils/class.ModelCreator.php
tao_install_utils_ModelCreator.insertLocalModel
public function insertLocalModel($model, $replacements = array()){ $model = str_replace('LOCAL_NAMESPACE#', $this->localNs, $model); $model = str_replace('{ROOT_PATH}', ROOT_PATH, $model); foreach ($replacements as $k => $r){ $model = str_replace($k, $r, $model); } return $this->insertModel($this->localNs, $model); }
php
public function insertLocalModel($model, $replacements = array()){ $model = str_replace('LOCAL_NAMESPACE#', $this->localNs, $model); $model = str_replace('{ROOT_PATH}', ROOT_PATH, $model); foreach ($replacements as $k => $r){ $model = str_replace($k, $r, $model); } return $this->insertModel($this->localNs, $model); }
[ "public", "function", "insertLocalModel", "(", "$", "model", ",", "$", "replacements", "=", "array", "(", ")", ")", "{", "$", "model", "=", "str_replace", "(", "'LOCAL_NAMESPACE#'", ",", "$", "this", "->", "localNs", ",", "$", "model", ")", ";", "$", "...
Insert a model into the local namespace @param string $model the XML data @return boolean true if inserted
[ "Insert", "a", "model", "into", "the", "local", "namespace" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/install/utils/class.ModelCreator.php#L114-L123
oat-sa/tao-core
install/utils/class.ModelCreator.php
tao_install_utils_ModelCreator.insertModelFile
public function insertModelFile($namespace, $file){ if(!file_exists($file) || !is_readable($file)){ throw new tao_install_utils_Exception("Unable to load ontology : $file"); } return $this->insertModel($namespace, file_get_contents($file)); }
php
public function insertModelFile($namespace, $file){ if(!file_exists($file) || !is_readable($file)){ throw new tao_install_utils_Exception("Unable to load ontology : $file"); } return $this->insertModel($namespace, file_get_contents($file)); }
[ "public", "function", "insertModelFile", "(", "$", "namespace", ",", "$", "file", ")", "{", "if", "(", "!", "file_exists", "(", "$", "file", ")", "||", "!", "is_readable", "(", "$", "file", ")", ")", "{", "throw", "new", "tao_install_utils_Exception", "(...
Insert a model @throws tao_install_utils_Exception @param string $file the path to the RDF file @return boolean true if inserted
[ "Insert", "a", "model" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/install/utils/class.ModelCreator.php#L131-L136
oat-sa/tao-core
install/utils/class.ModelCreator.php
tao_install_utils_ModelCreator.insertModel
public function insertModel($namespace, $model){ $returnValue = false; if(!preg_match("/#$/", $namespace)){ $namespace .= '#'; } $modFactory = new core_kernel_api_ModelFactory(); $returnValue = $modFactory->createModel($namespace, $model); return $returnValue; }
php
public function insertModel($namespace, $model){ $returnValue = false; if(!preg_match("/#$/", $namespace)){ $namespace .= '#'; } $modFactory = new core_kernel_api_ModelFactory(); $returnValue = $modFactory->createModel($namespace, $model); return $returnValue; }
[ "public", "function", "insertModel", "(", "$", "namespace", ",", "$", "model", ")", "{", "$", "returnValue", "=", "false", ";", "if", "(", "!", "preg_match", "(", "\"/#$/\"", ",", "$", "namespace", ")", ")", "{", "$", "namespace", ".=", "'#'", ";", "...
Insert a model @param string $model the XML data @return boolean true if inserted
[ "Insert", "a", "model" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/install/utils/class.ModelCreator.php#L143-L156
oat-sa/tao-core
install/utils/class.ModelCreator.php
tao_install_utils_ModelCreator.getLanguageModels
public function getLanguageModels() { $models = array(); $ns = $this->localNs; $extensionPath = dirname(__FILE__) . '/../../../tao'; $localesPath = $extensionPath . '/locales'; if (@is_dir($localesPath) && @is_readable($localesPath)) { $localeDirectories = scandir($localesPath); foreach ($localeDirectories as $localeDir) { $path = $localesPath . '/' . $localeDir; if ($localeDir[0] != '.' && @is_dir($path)){ // Look if the lang.rdf can be read. $languageModelFile = $path . '/lang.rdf'; if (@file_exists($languageModelFile) && @is_readable($languageModelFile)){ // Add this file to the returned values. if (!isset($models[$ns])){ $models[$ns] = array(); } $models[$ns][] = $languageModelFile; } } } return $models; } else{ throw new tao_install_utils_Exception("Cannot read 'locales' directory in extenstion 'tao'."); } }
php
public function getLanguageModels() { $models = array(); $ns = $this->localNs; $extensionPath = dirname(__FILE__) . '/../../../tao'; $localesPath = $extensionPath . '/locales'; if (@is_dir($localesPath) && @is_readable($localesPath)) { $localeDirectories = scandir($localesPath); foreach ($localeDirectories as $localeDir) { $path = $localesPath . '/' . $localeDir; if ($localeDir[0] != '.' && @is_dir($path)){ // Look if the lang.rdf can be read. $languageModelFile = $path . '/lang.rdf'; if (@file_exists($languageModelFile) && @is_readable($languageModelFile)){ // Add this file to the returned values. if (!isset($models[$ns])){ $models[$ns] = array(); } $models[$ns][] = $languageModelFile; } } } return $models; } else{ throw new tao_install_utils_Exception("Cannot read 'locales' directory in extenstion 'tao'."); } }
[ "public", "function", "getLanguageModels", "(", ")", "{", "$", "models", "=", "array", "(", ")", ";", "$", "ns", "=", "$", "this", "->", "localNs", ";", "$", "extensionPath", "=", "dirname", "(", "__FILE__", ")", ".", "'/../../../tao'", ";", "$", "loca...
Convenience method that returns available language descriptions to be inserted in the knowledge base. @return array of ns => files
[ "Convenience", "method", "that", "returns", "available", "language", "descriptions", "to", "be", "inserted", "in", "the", "knowledge", "base", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/install/utils/class.ModelCreator.php#L164-L195
oat-sa/tao-core
models/classes/resources/ListResourceLookup.php
ListResourceLookup.getResources
public function getResources(\core_kernel_classes_Class $rootClass, array $selectedUris = [], array $propertyFilters = [], $offset = 0, $limit = 30) { // Searching by label parameter will utilize fulltext search if (count($propertyFilters) == 1 && isset($propertyFilters[OntologyRdfs::RDFS_LABEL])) { $searchString = current($propertyFilters); return $this->searchByString($searchString, $rootClass, $offset, $limit); } else { return $this->searchByProperties($propertyFilters, $rootClass, $offset, $limit); } }
php
public function getResources(\core_kernel_classes_Class $rootClass, array $selectedUris = [], array $propertyFilters = [], $offset = 0, $limit = 30) { // Searching by label parameter will utilize fulltext search if (count($propertyFilters) == 1 && isset($propertyFilters[OntologyRdfs::RDFS_LABEL])) { $searchString = current($propertyFilters); return $this->searchByString($searchString, $rootClass, $offset, $limit); } else { return $this->searchByProperties($propertyFilters, $rootClass, $offset, $limit); } }
[ "public", "function", "getResources", "(", "\\", "core_kernel_classes_Class", "$", "rootClass", ",", "array", "$", "selectedUris", "=", "[", "]", ",", "array", "$", "propertyFilters", "=", "[", "]", ",", "$", "offset", "=", "0", ",", "$", "limit", "=", "...
Retrieve Resources for the given parameters as a list @param \core_kernel_classes_Class $rootClass the resources class @param array $propertyFilters propUri/propValue to search resources @param string[] $selectedUris the resources to open @param int $offset for paging @param int $limit for paging @return array the resources
[ "Retrieve", "Resources", "for", "the", "given", "parameters", "as", "a", "list" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/resources/ListResourceLookup.php#L50-L59
oat-sa/tao-core
models/classes/resources/ListResourceLookup.php
ListResourceLookup.searchByString
private function searchByString($searchString, $rootClass, $offset, $limit) { /** @var Search $searchService */ $searchService = $this->getServiceLocator()->get(Search::SERVICE_ID); /** @var ResultSet $result */ $result = $searchService->query($searchString, $rootClass, $offset, $limit); $count = $result->getTotalCount(); return $this->format($result, $count, $offset, $limit); }
php
private function searchByString($searchString, $rootClass, $offset, $limit) { /** @var Search $searchService */ $searchService = $this->getServiceLocator()->get(Search::SERVICE_ID); /** @var ResultSet $result */ $result = $searchService->query($searchString, $rootClass, $offset, $limit); $count = $result->getTotalCount(); return $this->format($result, $count, $offset, $limit); }
[ "private", "function", "searchByString", "(", "$", "searchString", ",", "$", "rootClass", ",", "$", "offset", ",", "$", "limit", ")", "{", "/** @var Search $searchService */", "$", "searchService", "=", "$", "this", "->", "getServiceLocator", "(", ")", "->", "...
Search using an advanced search string @param string $searchString @param \core_kernel_classes_Class $rootClass @param int $offset @param int $limit @return array
[ "Search", "using", "an", "advanced", "search", "string" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/resources/ListResourceLookup.php#L69-L77
oat-sa/tao-core
models/classes/resources/ListResourceLookup.php
ListResourceLookup.searchByProperties
private function searchByProperties($propertyFilters, $rootClass, $offset, $limit) { // for searching by properties will be used RDF search $options = [ 'recursive' => true, 'like' => true, 'limit' => $limit, 'offset' => $offset ]; $count = $rootClass->countInstances($propertyFilters, $options); $resources = $rootClass->searchInstances($propertyFilters, $options); return $this->format($resources, $count, $offset, $limit); }
php
private function searchByProperties($propertyFilters, $rootClass, $offset, $limit) { // for searching by properties will be used RDF search $options = [ 'recursive' => true, 'like' => true, 'limit' => $limit, 'offset' => $offset ]; $count = $rootClass->countInstances($propertyFilters, $options); $resources = $rootClass->searchInstances($propertyFilters, $options); return $this->format($resources, $count, $offset, $limit); }
[ "private", "function", "searchByProperties", "(", "$", "propertyFilters", ",", "$", "rootClass", ",", "$", "offset", ",", "$", "limit", ")", "{", "// for searching by properties will be used RDF search", "$", "options", "=", "[", "'recursive'", "=>", "true", ",", ...
Search using properties @param string $searchString @param \core_kernel_classes_Class $rootClass @param int $offset @param int $limit @return array
[ "Search", "using", "properties" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/resources/ListResourceLookup.php#L87-L99
oat-sa/tao-core
models/classes/resources/ListResourceLookup.php
ListResourceLookup.format
private function format($result, $count, $offset, $limit) { $nodes = []; foreach ($result as $item) { $resource = $this->getResource($item); $data = $this->getResourceData($resource); if ($data) { $nodes[] = $data; } } return [ 'total' => $count, 'offset' => $offset, 'limit' => $limit, 'nodes' => $nodes ]; }
php
private function format($result, $count, $offset, $limit) { $nodes = []; foreach ($result as $item) { $resource = $this->getResource($item); $data = $this->getResourceData($resource); if ($data) { $nodes[] = $data; } } return [ 'total' => $count, 'offset' => $offset, 'limit' => $limit, 'nodes' => $nodes ]; }
[ "private", "function", "format", "(", "$", "result", ",", "$", "count", ",", "$", "offset", ",", "$", "limit", ")", "{", "$", "nodes", "=", "[", "]", ";", "foreach", "(", "$", "result", "as", "$", "item", ")", "{", "$", "resource", "=", "$", "t...
Format the results according to the needs of ListLookup @param array $result @param int $count @param int $offset @param int $limit @return array
[ "Format", "the", "results", "according", "to", "the", "needs", "of", "ListLookup" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/resources/ListResourceLookup.php#L109-L125
oat-sa/tao-core
models/classes/resources/ListResourceLookup.php
ListResourceLookup.getResourceData
private function getResourceData($resource) { $data = false; if(!is_null($resource) && $resource->exists()) { $resourceTypes = array_keys($resource->getTypes()); $data = [ 'uri' => $resource->getUri(), 'classUri' => $resourceTypes[0], 'label' => $resource->getLabel(), 'type' => 'instance' ]; } return $data; }
php
private function getResourceData($resource) { $data = false; if(!is_null($resource) && $resource->exists()) { $resourceTypes = array_keys($resource->getTypes()); $data = [ 'uri' => $resource->getUri(), 'classUri' => $resourceTypes[0], 'label' => $resource->getLabel(), 'type' => 'instance' ]; } return $data; }
[ "private", "function", "getResourceData", "(", "$", "resource", ")", "{", "$", "data", "=", "false", ";", "if", "(", "!", "is_null", "(", "$", "resource", ")", "&&", "$", "resource", "->", "exists", "(", ")", ")", "{", "$", "resourceTypes", "=", "arr...
Preparing resource to be used in the ListLookup @param $resource @return array|bool
[ "Preparing", "resource", "to", "be", "used", "in", "the", "ListLookup" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/resources/ListResourceLookup.php#L132-L145
oat-sa/tao-core
models/classes/taskQueue/Task/FileReferenceSerializerAwareTrait.php
FileReferenceSerializerAwareTrait.getReferencedFile
protected function getReferencedFile($serial) { try { $file = $this->getFileReferenceSerializer()->unserialize($serial); if ($file instanceof File && $file->exists()) { return $file; } } catch (\Exception $e) { // do nothing } return null; }
php
protected function getReferencedFile($serial) { try { $file = $this->getFileReferenceSerializer()->unserialize($serial); if ($file instanceof File && $file->exists()) { return $file; } } catch (\Exception $e) { // do nothing } return null; }
[ "protected", "function", "getReferencedFile", "(", "$", "serial", ")", "{", "try", "{", "$", "file", "=", "$", "this", "->", "getFileReferenceSerializer", "(", ")", "->", "unserialize", "(", "$", "serial", ")", ";", "if", "(", "$", "file", "instanceof", ...
Tries to get the referenced file if it exists. @param string $serial @return null|File
[ "Tries", "to", "get", "the", "referenced", "file", "if", "it", "exists", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/taskQueue/Task/FileReferenceSerializerAwareTrait.php#L50-L62
oat-sa/tao-core
actions/class.Export.php
tao_actions_Export.getCurrentExporter
private function getCurrentExporter() { if ($this->hasRequestParameter('exportHandler')) { $exportHandler = $_REQUEST['exportHandler'];//allow method "GET" if (class_exists($exportHandler) && in_array('tao_models_classes_export_ExportHandler', class_implements($exportHandler)) ) { return new $exportHandler(); } else { throw new common_Exception('Unknown or incompatible ExporterHandler: \'' . $exportHandler . '\''); } } else { return current($this->getAvailableExportHandlers()); } }
php
private function getCurrentExporter() { if ($this->hasRequestParameter('exportHandler')) { $exportHandler = $_REQUEST['exportHandler'];//allow method "GET" if (class_exists($exportHandler) && in_array('tao_models_classes_export_ExportHandler', class_implements($exportHandler)) ) { return new $exportHandler(); } else { throw new common_Exception('Unknown or incompatible ExporterHandler: \'' . $exportHandler . '\''); } } else { return current($this->getAvailableExportHandlers()); } }
[ "private", "function", "getCurrentExporter", "(", ")", "{", "if", "(", "$", "this", "->", "hasRequestParameter", "(", "'exportHandler'", ")", ")", "{", "$", "exportHandler", "=", "$", "_REQUEST", "[", "'exportHandler'", "]", ";", "//allow method \"GET\"", "if", ...
Returns the selected ExportHandler @return tao_models_classes_export_ExportHandler @throws common_Exception
[ "Returns", "the", "selected", "ExportHandler" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.Export.php#L176-L190
oat-sa/tao-core
actions/class.SinglePageModule.php
tao_actions_SinglePageModule.composeView
protected function composeView($scope = '', $data = array(), $template = '', $extension = '') { if (!is_array($data)) { $data = []; } if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false) { $this->returnJson([ 'success' => true, 'data' => $data, ]); } else { foreach ($data as $key => $value) { if (is_array($value) || is_object($value)) { $data[$key] = json_encode($value); } } $this->setData('data', $data); $this->setPage($scope, $template, $extension); } }
php
protected function composeView($scope = '', $data = array(), $template = '', $extension = '') { if (!is_array($data)) { $data = []; } if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false) { $this->returnJson([ 'success' => true, 'data' => $data, ]); } else { foreach ($data as $key => $value) { if (is_array($value) || is_object($value)) { $data[$key] = json_encode($value); } } $this->setData('data', $data); $this->setPage($scope, $template, $extension); } }
[ "protected", "function", "composeView", "(", "$", "scope", "=", "''", ",", "$", "data", "=", "array", "(", ")", ",", "$", "template", "=", "''", ",", "$", "extension", "=", "''", ")", "{", "if", "(", "!", "is_array", "(", "$", "data", ")", ")", ...
Main method to render a view using a particular template. Detects whether the client only need JSON content. You still need to set the main view, however it must be set before to call this method as this view may be overridden. @param string [$scope] - A CSS class name that scope the view @param array [$data] - An optional data set to forward to the view @param String [$template] - Defines the path of the view, default to 'pages/index.tpl' @param String [$extension] - Defines the extension that should contain the template @throws \common_exception_Error
[ "Main", "method", "to", "render", "a", "view", "using", "a", "particular", "template", ".", "Detects", "whether", "the", "client", "only", "need", "JSON", "content", ".", "You", "still", "need", "to", "set", "the", "main", "view", "however", "it", "must", ...
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.SinglePageModule.php#L82-L102
oat-sa/tao-core
actions/class.SinglePageModule.php
tao_actions_SinglePageModule.setPage
protected function setPage($scope = '', $template = '', $extension = '') { $template = empty($template) ? 'pages/index.tpl' : $template; $extension = empty($extension) ? \Context::getInstance()->getExtensionName() : $extension; $this->defaultData(); $this->setData('scope', $scope); if ($this->isXmlHttpRequest()) { $this->setView($template, $extension); } else { $this->setData('content-template', [$template, $extension]); $layout = (array)$this->getLayout(); $this->setView($layout[0], isset($layout[1]) ? $layout[1] : null); } }
php
protected function setPage($scope = '', $template = '', $extension = '') { $template = empty($template) ? 'pages/index.tpl' : $template; $extension = empty($extension) ? \Context::getInstance()->getExtensionName() : $extension; $this->defaultData(); $this->setData('scope', $scope); if ($this->isXmlHttpRequest()) { $this->setView($template, $extension); } else { $this->setData('content-template', [$template, $extension]); $layout = (array)$this->getLayout(); $this->setView($layout[0], isset($layout[1]) ? $layout[1] : null); } }
[ "protected", "function", "setPage", "(", "$", "scope", "=", "''", ",", "$", "template", "=", "''", ",", "$", "extension", "=", "''", ")", "{", "$", "template", "=", "empty", "(", "$", "template", ")", "?", "'pages/index.tpl'", ":", "$", "template", "...
Assigns the template to render. @param string [$scope] - A CSS class name that scope the view @param String [$template] - Defines the path of the view, default to 'pages/index.tpl' @param String [$extension] - Defines the extension that should contain the template
[ "Assigns", "the", "template", "to", "render", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.SinglePageModule.php#L110-L126
oat-sa/tao-core
models/classes/cliArgument/argument/implementation/verbose/Info.php
Info.isApplicable
public function isApplicable(array $params) { $this->setOutputColorVisibility($params); return $this->hasParameter($params, '-vvv') || $this->hasParameter($params, '--verbose', 3); }
php
public function isApplicable(array $params) { $this->setOutputColorVisibility($params); return $this->hasParameter($params, '-vvv') || $this->hasParameter($params, '--verbose', 3); }
[ "public", "function", "isApplicable", "(", "array", "$", "params", ")", "{", "$", "this", "->", "setOutputColorVisibility", "(", "$", "params", ")", ";", "return", "$", "this", "->", "hasParameter", "(", "$", "params", ",", "'-vvv'", ")", "||", "$", "thi...
Check if params array contains targeted arguments, Short and Long In case of Long, check is done is following param argument @param array $params @return bool
[ "Check", "if", "params", "array", "contains", "targeted", "arguments", "Short", "and", "Long", "In", "case", "of", "Long", "check", "is", "done", "is", "following", "param", "argument" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/cliArgument/argument/implementation/verbose/Info.php#L34-L39
oat-sa/tao-core
helpers/translation/class.RDFTranslationUnit.php
tao_helpers_translation_RDFTranslationUnit.hasSameTranslationUnitSubject
public function hasSameTranslationUnitSubject( tao_helpers_translation_RDFTranslationUnit $translationUnit) { $returnValue = (bool) false; $returnValue = $this->getSubject() == $translationUnit->getSubject(); return (bool) $returnValue; }
php
public function hasSameTranslationUnitSubject( tao_helpers_translation_RDFTranslationUnit $translationUnit) { $returnValue = (bool) false; $returnValue = $this->getSubject() == $translationUnit->getSubject(); return (bool) $returnValue; }
[ "public", "function", "hasSameTranslationUnitSubject", "(", "tao_helpers_translation_RDFTranslationUnit", "$", "translationUnit", ")", "{", "$", "returnValue", "=", "(", "bool", ")", "false", ";", "$", "returnValue", "=", "$", "this", "->", "getSubject", "(", ")", ...
Checks whether or not a given RDFTranslationUnit has the same subject value as the current instance. @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param RDFTranslationUnit translationUnit @return boolean
[ "Checks", "whether", "or", "not", "a", "given", "RDFTranslationUnit", "has", "the", "same", "subject", "value", "as", "the", "current", "instance", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/translation/class.RDFTranslationUnit.php#L133-L142
oat-sa/tao-core
helpers/translation/class.RDFTranslationUnit.php
tao_helpers_translation_RDFTranslationUnit.hasSameTranslationUnitPredicate
public function hasSameTranslationUnitPredicate( tao_helpers_translation_RDFTranslationUnit $translationUnit) { $returnValue = (bool) false; $returnValue = $this->getPredicate() == $translationUnit->getPredicate(); return (bool) $returnValue; }
php
public function hasSameTranslationUnitPredicate( tao_helpers_translation_RDFTranslationUnit $translationUnit) { $returnValue = (bool) false; $returnValue = $this->getPredicate() == $translationUnit->getPredicate(); return (bool) $returnValue; }
[ "public", "function", "hasSameTranslationUnitPredicate", "(", "tao_helpers_translation_RDFTranslationUnit", "$", "translationUnit", ")", "{", "$", "returnValue", "=", "(", "bool", ")", "false", ";", "$", "returnValue", "=", "$", "this", "->", "getPredicate", "(", ")...
Checks whether or not a given RDFTranslationUnit has the same predicate value as the current instance. @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param RDFTranslationUnit translationUnit @return boolean
[ "Checks", "whether", "or", "not", "a", "given", "RDFTranslationUnit", "has", "the", "same", "predicate", "value", "as", "the", "current", "instance", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/translation/class.RDFTranslationUnit.php#L153-L162
oat-sa/tao-core
helpers/translation/class.RDFTranslationUnit.php
tao_helpers_translation_RDFTranslationUnit.hasSameTranslationUnitSource
public function hasSameTranslationUnitSource( tao_helpers_translation_TranslationUnit $translationUnit) { $returnValue = (bool) false; $returnValue = $this->hasSameTranslationUnitPredicate($translationUnit) && $this->hasSameTranslationUnitSubject($translationUnit) && $this->hasSameTranslationUnitTargetLanguage($translationUnit); return (bool) $returnValue; }
php
public function hasSameTranslationUnitSource( tao_helpers_translation_TranslationUnit $translationUnit) { $returnValue = (bool) false; $returnValue = $this->hasSameTranslationUnitPredicate($translationUnit) && $this->hasSameTranslationUnitSubject($translationUnit) && $this->hasSameTranslationUnitTargetLanguage($translationUnit); return (bool) $returnValue; }
[ "public", "function", "hasSameTranslationUnitSource", "(", "tao_helpers_translation_TranslationUnit", "$", "translationUnit", ")", "{", "$", "returnValue", "=", "(", "bool", ")", "false", ";", "$", "returnValue", "=", "$", "this", "->", "hasSameTranslationUnitPredicate"...
Checks wether or not that the current translation unit has the same than another one. For RDFTranslationUnits, we consider that two units have the same source if their source, subject, predicate and target are identical. @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param TranslationUnit translationUnit A translation unit to compare. @return boolean
[ "Checks", "wether", "or", "not", "that", "the", "current", "translation", "unit", "has", "the", "same", "than", "another", "one", ".", "For", "RDFTranslationUnits", "we", "consider", "that", "two", "units", "have", "the", "same", "source", "if", "their", "so...
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/translation/class.RDFTranslationUnit.php#L175-L186
oat-sa/tao-core
actions/class.RestClass.php
tao_actions_RestClass.getAll
public function getAll() { if ($this->isRequestGet()) { try { $class = $this->getClassParameter(); $classes = $this->getResourceService()->getAllClasses($class); $this->returnSuccess([$classes]); } catch (common_Exception $e) { $this->returnFailure($e); } } else { $this->returnFailure(new common_exception_MethodNotAllowed(__METHOD__ . ' only accepts GET method')); } }
php
public function getAll() { if ($this->isRequestGet()) { try { $class = $this->getClassParameter(); $classes = $this->getResourceService()->getAllClasses($class); $this->returnSuccess([$classes]); } catch (common_Exception $e) { $this->returnFailure($e); } } else { $this->returnFailure(new common_exception_MethodNotAllowed(__METHOD__ . ' only accepts GET method')); } }
[ "public", "function", "getAll", "(", ")", "{", "if", "(", "$", "this", "->", "isRequestGet", "(", ")", ")", "{", "try", "{", "$", "class", "=", "$", "this", "->", "getClassParameter", "(", ")", ";", "$", "classes", "=", "$", "this", "->", "getResou...
Get all the classes that belong to a subclass. @requiresRight classUri READ
[ "Get", "all", "the", "classes", "that", "belong", "to", "a", "subclass", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.RestClass.php#L34-L47
oat-sa/tao-core
models/classes/auth/BasicAuthType.php
BasicAuthType.call
public function call(RequestInterface $request, array $clientOptions = []) { return (new Client($clientOptions))->send($request, ['auth' => $this->getCredentials(), 'verify' => false]); }
php
public function call(RequestInterface $request, array $clientOptions = []) { return (new Client($clientOptions))->send($request, ['auth' => $this->getCredentials(), 'verify' => false]); }
[ "public", "function", "call", "(", "RequestInterface", "$", "request", ",", "array", "$", "clientOptions", "=", "[", "]", ")", "{", "return", "(", "new", "Client", "(", "$", "clientOptions", ")", ")", "->", "send", "(", "$", "request", ",", "[", "'auth...
Call a request through basic client @param RequestInterface $request @param array $clientOptions Http client options @return mixed|\Psr\Http\Message\ResponseInterface @throws \GuzzleHttp\Exception\GuzzleException @throws \common_exception_InvalidArgumentType
[ "Call", "a", "request", "through", "basic", "client" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/auth/BasicAuthType.php#L39-L42
oat-sa/tao-core
models/classes/auth/BasicAuthType.php
BasicAuthType.loadCredentials
protected function loadCredentials() { $instance = $this->getInstance(); if ($instance && $instance->exists()) { $props = $instance->getPropertiesValues([ $this->getProperty(self::PROPERTY_LOGIN), $this->getProperty(self::PROPERTY_PASSWORD) ]); $data = [ self::PROPERTY_LOGIN => (string)current($props[self::PROPERTY_LOGIN]), self::PROPERTY_PASSWORD => (string)current($props[self::PROPERTY_PASSWORD]), ]; } else { $data = [ self::PROPERTY_LOGIN => '', self::PROPERTY_PASSWORD => '', ]; } return $data; }
php
protected function loadCredentials() { $instance = $this->getInstance(); if ($instance && $instance->exists()) { $props = $instance->getPropertiesValues([ $this->getProperty(self::PROPERTY_LOGIN), $this->getProperty(self::PROPERTY_PASSWORD) ]); $data = [ self::PROPERTY_LOGIN => (string)current($props[self::PROPERTY_LOGIN]), self::PROPERTY_PASSWORD => (string)current($props[self::PROPERTY_PASSWORD]), ]; } else { $data = [ self::PROPERTY_LOGIN => '', self::PROPERTY_PASSWORD => '', ]; } return $data; }
[ "protected", "function", "loadCredentials", "(", ")", "{", "$", "instance", "=", "$", "this", "->", "getInstance", "(", ")", ";", "if", "(", "$", "instance", "&&", "$", "instance", "->", "exists", "(", ")", ")", "{", "$", "props", "=", "$", "instance...
Fetch the credentials for the current resource. Contains login and password or with null value if empty @return array @throws \common_exception_InvalidArgumentType
[ "Fetch", "the", "credentials", "for", "the", "current", "resource", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/auth/BasicAuthType.php#L87-L109
oat-sa/tao-core
helpers/form/elements/Model.php
Model.getOptions
public function getOptions() { $options = parent::getOptions(); $statusProperty = new core_kernel_classes_Property(TaoOntology::PROPERTY_ABSTRACT_MODEL_STATUS); $current = $this->getEvaluatedValue(); $options = array(); foreach (parent::getOptions() as $optUri => $optLabel) { $model = new core_kernel_classes_Resource(tao_helpers_Uri::decode($optUri)); $status = $model->getOnePropertyValue($statusProperty); if (!is_null($status)) { $options[$optUri] = $optLabel; } elseif ($model->getUri() == $current) { $options[$optUri] = $optLabel.' ('.(is_null($status) ? __('unknown') : $status->getLabel()).')'; } } return $options; }
php
public function getOptions() { $options = parent::getOptions(); $statusProperty = new core_kernel_classes_Property(TaoOntology::PROPERTY_ABSTRACT_MODEL_STATUS); $current = $this->getEvaluatedValue(); $options = array(); foreach (parent::getOptions() as $optUri => $optLabel) { $model = new core_kernel_classes_Resource(tao_helpers_Uri::decode($optUri)); $status = $model->getOnePropertyValue($statusProperty); if (!is_null($status)) { $options[$optUri] = $optLabel; } elseif ($model->getUri() == $current) { $options[$optUri] = $optLabel.' ('.(is_null($status) ? __('unknown') : $status->getLabel()).')'; } } return $options; }
[ "public", "function", "getOptions", "(", ")", "{", "$", "options", "=", "parent", "::", "getOptions", "(", ")", ";", "$", "statusProperty", "=", "new", "core_kernel_classes_Property", "(", "TaoOntology", "::", "PROPERTY_ABSTRACT_MODEL_STATUS", ")", ";", "$", "cu...
(non-PHPdoc) @see tao_helpers_form_elements_MultipleElement::getOptions()
[ "(", "non", "-", "PHPdoc", ")" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/elements/Model.php#L49-L67
oat-sa/tao-core
models/classes/taskQueue/Worker/OneTimeTask.php
OneTimeTask.run
public function run() { $this->logDebug('Starting Task.'); try{ return $this->processTask($this->task); } catch (\Exception $e) { $this->logError('Error processing task '. $e->getMessage()); } $this->logDebug('Task finished.'); return TaskLogInterface::STATUS_FAILED; }
php
public function run() { $this->logDebug('Starting Task.'); try{ return $this->processTask($this->task); } catch (\Exception $e) { $this->logError('Error processing task '. $e->getMessage()); } $this->logDebug('Task finished.'); return TaskLogInterface::STATUS_FAILED; }
[ "public", "function", "run", "(", ")", "{", "$", "this", "->", "logDebug", "(", "'Starting Task.'", ")", ";", "try", "{", "return", "$", "this", "->", "processTask", "(", "$", "this", "->", "task", ")", ";", "}", "catch", "(", "\\", "Exception", "$",...
Start processing tasks from a given queue @return string
[ "Start", "processing", "tasks", "from", "a", "given", "queue" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/taskQueue/Worker/OneTimeTask.php#L36-L49
oat-sa/tao-core
helpers/form/validators/class.Length.php
tao_helpers_form_validators_Length.evaluate
public function evaluate($values) { $returnValue = (bool) false; $returnValue = true; $values = is_array($values) ? $values : array($values); foreach ($values as $value) { if ($this->hasOption('min') && mb_strlen($value) < $this->getOption('min')) { if ($this->hasOption('allowEmpty') && $this->getOption('allowEmpty') && empty($value)) { continue; } else { $returnValue = false; break; } } if ($this->hasOption('max') && mb_strlen($value) > $this->getOption('max')) { $returnValue = false; break; } } return (bool) $returnValue; }
php
public function evaluate($values) { $returnValue = (bool) false; $returnValue = true; $values = is_array($values) ? $values : array($values); foreach ($values as $value) { if ($this->hasOption('min') && mb_strlen($value) < $this->getOption('min')) { if ($this->hasOption('allowEmpty') && $this->getOption('allowEmpty') && empty($value)) { continue; } else { $returnValue = false; break; } } if ($this->hasOption('max') && mb_strlen($value) > $this->getOption('max')) { $returnValue = false; break; } } return (bool) $returnValue; }
[ "public", "function", "evaluate", "(", "$", "values", ")", "{", "$", "returnValue", "=", "(", "bool", ")", "false", ";", "$", "returnValue", "=", "true", ";", "$", "values", "=", "is_array", "(", "$", "values", ")", "?", "$", "values", ":", "array", ...
Short description of method evaluate @access public @author Joel Bout, <joel.bout@tudor.lu> @param values @return boolean
[ "Short", "description", "of", "method", "evaluate" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/validators/class.Length.php#L59-L84
oat-sa/tao-core
actions/class.Permission.php
tao_actions_Permission.denied
public function denied() { $accepts = explode(',', $this->getRequest()->getHeader('Accept')); if(array_search('application/json', $accepts) !== false || array_search('text/javascript', $accepts) !== false){ $this->returnJson(array( 'error' => __("You do not have the required rights to edit this resource."))); return; } return $this->setView('permission/denied.tpl'); }
php
public function denied() { $accepts = explode(',', $this->getRequest()->getHeader('Accept')); if(array_search('application/json', $accepts) !== false || array_search('text/javascript', $accepts) !== false){ $this->returnJson(array( 'error' => __("You do not have the required rights to edit this resource."))); return; } return $this->setView('permission/denied.tpl'); }
[ "public", "function", "denied", "(", ")", "{", "$", "accepts", "=", "explode", "(", "','", ",", "$", "this", "->", "getRequest", "(", ")", "->", "getHeader", "(", "'Accept'", ")", ")", ";", "if", "(", "array_search", "(", "'application/json'", ",", "$"...
Access to resource id denied
[ "Access", "to", "resource", "id", "denied" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.Permission.php#L33-L41
oat-sa/tao-core
models/classes/service/class.FileStorage.php
tao_models_classes_service_FileStorage.deleteDirectoryById
public function deleteDirectoryById($id) { $public = $id[strlen($id)-1] == '+'; $path = $this->id2path($id); return $this->getServiceLocator()->get(FileSystemService::SERVICE_ID)->getFileSystem($this->getFsId($public))->deleteDir($path); }
php
public function deleteDirectoryById($id) { $public = $id[strlen($id)-1] == '+'; $path = $this->id2path($id); return $this->getServiceLocator()->get(FileSystemService::SERVICE_ID)->getFileSystem($this->getFsId($public))->deleteDir($path); }
[ "public", "function", "deleteDirectoryById", "(", "$", "id", ")", "{", "$", "public", "=", "$", "id", "[", "strlen", "(", "$", "id", ")", "-", "1", "]", "==", "'+'", ";", "$", "path", "=", "$", "this", "->", "id2path", "(", "$", "id", ")", ";",...
Delete directory represented by the $id @param $id @return mixed
[ "Delete", "directory", "represented", "by", "the", "$id" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/service/class.FileStorage.php#L105-L110
oat-sa/tao-core
models/classes/service/class.FileStorage.php
tao_models_classes_service_FileStorage.getStreamHash
private function getStreamHash($stream, $hash = 'md5') { $hc = hash_init($hash); hash_update_stream($hc, $stream); return hash_final($hc); }
php
private function getStreamHash($stream, $hash = 'md5') { $hc = hash_init($hash); hash_update_stream($hc, $stream); return hash_final($hc); }
[ "private", "function", "getStreamHash", "(", "$", "stream", ",", "$", "hash", "=", "'md5'", ")", "{", "$", "hc", "=", "hash_init", "(", "$", "hash", ")", ";", "hash_update_stream", "(", "$", "hc", ",", "$", "stream", ")", ";", "return", "hash_final", ...
Calculates hash for given stream @param $stream @param string $hash @return string
[ "Calculates", "hash", "for", "given", "stream" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/service/class.FileStorage.php#L168-L173
oat-sa/tao-core
models/classes/theme/ThemeServiceAbstract.php
ThemeServiceAbstract.getTheme
public function getTheme() { $themeId = $this->getThemeIdFromThemeDetailsProviders(); if (empty($themeId)) { $themeId = $this->getCurrentThemeId(); } return $this->getThemeById($themeId); }
php
public function getTheme() { $themeId = $this->getThemeIdFromThemeDetailsProviders(); if (empty($themeId)) { $themeId = $this->getCurrentThemeId(); } return $this->getThemeById($themeId); }
[ "public", "function", "getTheme", "(", ")", "{", "$", "themeId", "=", "$", "this", "->", "getThemeIdFromThemeDetailsProviders", "(", ")", ";", "if", "(", "empty", "(", "$", "themeId", ")", ")", "{", "$", "themeId", "=", "$", "this", "->", "getCurrentThem...
@inheritdoc @throws \common_exception_InconsistentData
[ "@inheritdoc" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/theme/ThemeServiceAbstract.php#L33-L41
oat-sa/tao-core
models/classes/theme/ThemeServiceAbstract.php
ThemeServiceAbstract.getThemeIdFromThemeDetailsProviders
protected function getThemeIdFromThemeDetailsProviders() { $providers = $this->getThemeDetailsProviders(); foreach ($providers as $provider) { if ($provider instanceof ThemeDetailsProviderInterface) { $themeId = $provider->getThemeId(); if (!empty($themeId) && $themeId !== ' ') { if ($this->hasTheme($themeId)) { return $themeId; } \common_Logger::i( 'The requested theme ' . $themeId . ' requested by the ' . get_class($provider) . ' provider does not exist!' ); } } } return ''; }
php
protected function getThemeIdFromThemeDetailsProviders() { $providers = $this->getThemeDetailsProviders(); foreach ($providers as $provider) { if ($provider instanceof ThemeDetailsProviderInterface) { $themeId = $provider->getThemeId(); if (!empty($themeId) && $themeId !== ' ') { if ($this->hasTheme($themeId)) { return $themeId; } \common_Logger::i( 'The requested theme ' . $themeId . ' requested by the ' . get_class($provider) . ' provider does not exist!' ); } } } return ''; }
[ "protected", "function", "getThemeIdFromThemeDetailsProviders", "(", ")", "{", "$", "providers", "=", "$", "this", "->", "getThemeDetailsProviders", "(", ")", ";", "foreach", "(", "$", "providers", "as", "$", "provider", ")", "{", "if", "(", "$", "provider", ...
Returns the theme id provided by the themeDetailsProviders. @return string
[ "Returns", "the", "theme", "id", "provided", "by", "the", "themeDetailsProviders", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/theme/ThemeServiceAbstract.php#L95-L115
oat-sa/tao-core
models/classes/theme/ThemeServiceAbstract.php
ThemeServiceAbstract.getUniqueId
protected function getUniqueId(Theme $theme) { $baseId = $theme->getId(); $idNumber = 0; while ($this->hasTheme($baseId . $idNumber)) { $idNumber++; } return $baseId . $idNumber; }
php
protected function getUniqueId(Theme $theme) { $baseId = $theme->getId(); $idNumber = 0; while ($this->hasTheme($baseId . $idNumber)) { $idNumber++; } return $baseId . $idNumber; }
[ "protected", "function", "getUniqueId", "(", "Theme", "$", "theme", ")", "{", "$", "baseId", "=", "$", "theme", "->", "getId", "(", ")", ";", "$", "idNumber", "=", "0", ";", "while", "(", "$", "this", "->", "hasTheme", "(", "$", "baseId", ".", "$",...
Returns the unique identifier. @param Theme $theme @return string
[ "Returns", "the", "unique", "identifier", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/theme/ThemeServiceAbstract.php#L124-L134
oat-sa/tao-core
models/classes/theme/ThemeServiceAbstract.php
ThemeServiceAbstract.isHeadless
public function isHeadless() { if ($this->hasOption(self::OPTION_HEADLESS_PAGE)) { return $this->getOption(self::OPTION_HEADLESS_PAGE); } $isHeadless = $this->getIsHeadLessFromThemeDetailsProviders(); if (empty($isHeadless)) { $isHeadless = false; } return $isHeadless; }
php
public function isHeadless() { if ($this->hasOption(self::OPTION_HEADLESS_PAGE)) { return $this->getOption(self::OPTION_HEADLESS_PAGE); } $isHeadless = $this->getIsHeadLessFromThemeDetailsProviders(); if (empty($isHeadless)) { $isHeadless = false; } return $isHeadless; }
[ "public", "function", "isHeadless", "(", ")", "{", "if", "(", "$", "this", "->", "hasOption", "(", "self", "::", "OPTION_HEADLESS_PAGE", ")", ")", "{", "return", "$", "this", "->", "getOption", "(", "self", "::", "OPTION_HEADLESS_PAGE", ")", ";", "}", "$...
Tells if the page has to be headless: without header and footer. @return bool|mixed
[ "Tells", "if", "the", "page", "has", "to", "be", "headless", ":", "without", "header", "and", "footer", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/theme/ThemeServiceAbstract.php#L141-L153
oat-sa/tao-core
models/classes/theme/ThemeServiceAbstract.php
ThemeServiceAbstract.getIsHeadlessFromThemeDetailsProviders
protected function getIsHeadlessFromThemeDetailsProviders() { $providers = $this->getThemeDetailsProviders(); foreach ($providers as $provider) { if ($provider instanceof ThemeDetailsProviderInterface) { $isHeadless = $provider->isHeadless(); if (!empty($isHeadless)) { return $isHeadless; } } } return false; }
php
protected function getIsHeadlessFromThemeDetailsProviders() { $providers = $this->getThemeDetailsProviders(); foreach ($providers as $provider) { if ($provider instanceof ThemeDetailsProviderInterface) { $isHeadless = $provider->isHeadless(); if (!empty($isHeadless)) { return $isHeadless; } } } return false; }
[ "protected", "function", "getIsHeadlessFromThemeDetailsProviders", "(", ")", "{", "$", "providers", "=", "$", "this", "->", "getThemeDetailsProviders", "(", ")", ";", "foreach", "(", "$", "providers", "as", "$", "provider", ")", "{", "if", "(", "$", "provider"...
Returns the isHeadless details provided by the themeDetailsProviders. @return bool|mixed
[ "Returns", "the", "isHeadless", "details", "provided", "by", "the", "themeDetailsProviders", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/theme/ThemeServiceAbstract.php#L160-L173
oat-sa/tao-core
models/classes/security/SignatureValidator.php
SignatureValidator.checkSignatures
public function checkSignatures(array $list, $signatureFieldName = 'signature', $idFieldName = 'id') { foreach ($list as $item) { $this->checkSignature($item[$signatureFieldName], $item[$idFieldName]); } }
php
public function checkSignatures(array $list, $signatureFieldName = 'signature', $idFieldName = 'id') { foreach ($list as $item) { $this->checkSignature($item[$signatureFieldName], $item[$idFieldName]); } }
[ "public", "function", "checkSignatures", "(", "array", "$", "list", ",", "$", "signatureFieldName", "=", "'signature'", ",", "$", "idFieldName", "=", "'id'", ")", "{", "foreach", "(", "$", "list", "as", "$", "item", ")", "{", "$", "this", "->", "checkSig...
@param array $list @param string $signatureFieldName @param string $idFieldName @throws SecurityException @throws InconsistencyConfigException
[ "@param", "array", "$list", "@param", "string", "$signatureFieldName", "@param", "string", "$idFieldName" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/security/SignatureValidator.php#L35-L40
oat-sa/tao-core
models/classes/security/SignatureValidator.php
SignatureValidator.checkSignature
public function checkSignature($signature, ...$dataToSign) { if (empty($signature)) { throw new SecurityException('Empty signature'); } if (!is_string($signature)) { throw new SecurityException('Signature should be a string'); } if ($signature !== $this->getSignatureGenerator()->generate(...$dataToSign)) { throw new SecurityException('Invalid signature'); } }
php
public function checkSignature($signature, ...$dataToSign) { if (empty($signature)) { throw new SecurityException('Empty signature'); } if (!is_string($signature)) { throw new SecurityException('Signature should be a string'); } if ($signature !== $this->getSignatureGenerator()->generate(...$dataToSign)) { throw new SecurityException('Invalid signature'); } }
[ "public", "function", "checkSignature", "(", "$", "signature", ",", "...", "$", "dataToSign", ")", "{", "if", "(", "empty", "(", "$", "signature", ")", ")", "{", "throw", "new", "SecurityException", "(", "'Empty signature'", ")", ";", "}", "if", "(", "!"...
@param string $signature @param mixed $dataToSign data to be signed @throws SecurityException @throws InconsistencyConfigException
[ "@param", "string", "$signature", "@param", "mixed", "$dataToSign", "data", "to", "be", "signed" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/security/SignatureValidator.php#L49-L62
oat-sa/tao-core
actions/class.RestResource.php
tao_actions_RestResource.create
public function create() { if ($this->isRequestGet()) { try { $this->returnSuccess($this->getForm($this->getClassParameter())->getData()); } catch (common_Exception $e) { $this->returnFailure($e); } } elseif ($this->isRequestPost()) { try { $this->processForm($this->getClassParameter()); } catch (common_Exception $e) { $this->returnFailure($e); } } else { $this->returnFailure(new common_exception_MethodNotAllowed(__METHOD__ . ' only accepts GET or POST method')); } }
php
public function create() { if ($this->isRequestGet()) { try { $this->returnSuccess($this->getForm($this->getClassParameter())->getData()); } catch (common_Exception $e) { $this->returnFailure($e); } } elseif ($this->isRequestPost()) { try { $this->processForm($this->getClassParameter()); } catch (common_Exception $e) { $this->returnFailure($e); } } else { $this->returnFailure(new common_exception_MethodNotAllowed(__METHOD__ . ' only accepts GET or POST method')); } }
[ "public", "function", "create", "(", ")", "{", "if", "(", "$", "this", "->", "isRequestGet", "(", ")", ")", "{", "try", "{", "$", "this", "->", "returnSuccess", "(", "$", "this", "->", "getForm", "(", "$", "this", "->", "getClassParameter", "(", ")",...
Create a resource for class found into http request parameters If http method is GET, return the form data If http method is POST, process form The POST request has to follow this structure: array ( 'propertyUri' => 'value', 'propertyUri1' => 'value1', 'propertyUri2' => 'value2', 'propertyUri3' => array( 'value', 'value2', ) ) @requiresRight classUri WRITE
[ "Create", "a", "resource", "for", "class", "found", "into", "http", "request", "parameters" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.RestResource.php#L56-L73
oat-sa/tao-core
actions/class.RestResource.php
tao_actions_RestResource.edit
public function edit() { if ($this->isRequestGet()) { try { $this->returnSuccess($this->getForm($this->getResourceParameter())->getData()); } catch (common_Exception $e) { $this->returnFailure($e); } } if ($this->isRequestPost()) { try { $this->processForm($this->getResourceParameter()); } catch (common_Exception $e) { $this->returnFailure($e); } } $this->returnFailure(new common_exception_MethodNotAllowed(__METHOD__ . ' only accepts GET or PUT method')); }
php
public function edit() { if ($this->isRequestGet()) { try { $this->returnSuccess($this->getForm($this->getResourceParameter())->getData()); } catch (common_Exception $e) { $this->returnFailure($e); } } if ($this->isRequestPost()) { try { $this->processForm($this->getResourceParameter()); } catch (common_Exception $e) { $this->returnFailure($e); } } $this->returnFailure(new common_exception_MethodNotAllowed(__METHOD__ . ' only accepts GET or PUT method')); }
[ "public", "function", "edit", "(", ")", "{", "if", "(", "$", "this", "->", "isRequestGet", "(", ")", ")", "{", "try", "{", "$", "this", "->", "returnSuccess", "(", "$", "this", "->", "getForm", "(", "$", "this", "->", "getResourceParameter", "(", ")"...
Edit a resource found into http request parameters If http method is GET, return the form data If http method is PUT, process form The PUT request has to follow this structure: array ( 'propertyUri' => 'value', 'propertyUri1' => 'value1', 'propertyUri2' => 'value2', 'propertyUri3' => array( 'value', 'value2', ) ) @requiresRight uri WRITE
[ "Edit", "a", "resource", "found", "into", "http", "request", "parameters" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.RestResource.php#L93-L112
oat-sa/tao-core
actions/class.RestResource.php
tao_actions_RestResource.getAll
public function getAll() { if ($this->isRequestGet()) { try { $format = $this->getRequestParameter('format'); $search = $this->hasRequestParameter('search') ? $this->getRawParameter('search') : ''; $limit = $this->hasRequestParameter('limit') ? $this->getRequestParameter('limit') : 30; $offset = $this->hasRequestParameter('offset') ? $this->getRequestParameter('offset') : 0; $selectedUris = []; if(! empty($search) ){ $decodedSearch = json_decode($search, true); if(is_array($decodedSearch) && count($decodedSearch) > 0){ $search = $decodedSearch; } } if($this->hasRequestParameter('selectedUri')){ $selectedUri = $this->getRequestParameter('selectedUri'); if (!empty($selectedUri)) { $selectedUris = [$selectedUri]; } } $class = $this->getClassParameter(); if ($this->hasRequestParameter('classOnly')) { $resources = $this->getResourceService()->getClasses($class, $format, $selectedUris, $search, $offset, $limit); } else { $resources = $this->getResourceService()->getResources($class, $format, $selectedUris, $search, $offset, $limit); } $user = \common_Session_SessionManager::getSession()->getUser(); if(isset($resources['nodes'])){ $permissions = $this->getResourceService()->getResourcesPermissions($user, $resources['nodes']); } else { $permissions = $this->getResourceService()->getResourcesPermissions($user, $resources); } $this->returnSuccess([ 'resources' => $resources, 'permissions' => $permissions ]); } catch (common_Exception $e) { $this->returnFailure($e); } } }
php
public function getAll() { if ($this->isRequestGet()) { try { $format = $this->getRequestParameter('format'); $search = $this->hasRequestParameter('search') ? $this->getRawParameter('search') : ''; $limit = $this->hasRequestParameter('limit') ? $this->getRequestParameter('limit') : 30; $offset = $this->hasRequestParameter('offset') ? $this->getRequestParameter('offset') : 0; $selectedUris = []; if(! empty($search) ){ $decodedSearch = json_decode($search, true); if(is_array($decodedSearch) && count($decodedSearch) > 0){ $search = $decodedSearch; } } if($this->hasRequestParameter('selectedUri')){ $selectedUri = $this->getRequestParameter('selectedUri'); if (!empty($selectedUri)) { $selectedUris = [$selectedUri]; } } $class = $this->getClassParameter(); if ($this->hasRequestParameter('classOnly')) { $resources = $this->getResourceService()->getClasses($class, $format, $selectedUris, $search, $offset, $limit); } else { $resources = $this->getResourceService()->getResources($class, $format, $selectedUris, $search, $offset, $limit); } $user = \common_Session_SessionManager::getSession()->getUser(); if(isset($resources['nodes'])){ $permissions = $this->getResourceService()->getResourcesPermissions($user, $resources['nodes']); } else { $permissions = $this->getResourceService()->getResourcesPermissions($user, $resources); } $this->returnSuccess([ 'resources' => $resources, 'permissions' => $permissions ]); } catch (common_Exception $e) { $this->returnFailure($e); } } }
[ "public", "function", "getAll", "(", ")", "{", "if", "(", "$", "this", "->", "isRequestGet", "(", ")", ")", "{", "try", "{", "$", "format", "=", "$", "this", "->", "getRequestParameter", "(", "'format'", ")", ";", "$", "search", "=", "$", "this", "...
Get all resources belonging to a given class. The result is paginated and structured based on the given format. The result can be filtered, or target a given selection. @requiresRight classUri READ
[ "Get", "all", "resources", "belonging", "to", "a", "given", "class", ".", "The", "result", "is", "paginated", "and", "structured", "based", "on", "the", "given", "format", ".", "The", "result", "can", "be", "filtered", "or", "target", "a", "given", "select...
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.RestResource.php#L121-L167
oat-sa/tao-core
actions/class.RestResource.php
tao_actions_RestResource.getRequestParameters
public function getRequestParameters() { $parameters = []; if ($this->isRequestPost()) { $input = file_get_contents("php://input"); $arguments = explode('&', $input); foreach ($arguments as $argument) { $argumentSplited = explode('=', $argument); $key = urldecode($argumentSplited[0]); $value = urldecode($argumentSplited[1]); // for multiple values if (strpos($value, ',')) { $value = explode(',', $value); } if (substr($key, -2) == '[]') { $key = substr($key, 0, strlen($key)-2); if (!isset($parameters[$key])) { $parameters[$key] = []; } $parameters[$key][] = $value; } else { $parameters[$key] = $value; } } } else { $parameters = parent::getRequestParameters(); } return $parameters; }
php
public function getRequestParameters() { $parameters = []; if ($this->isRequestPost()) { $input = file_get_contents("php://input"); $arguments = explode('&', $input); foreach ($arguments as $argument) { $argumentSplited = explode('=', $argument); $key = urldecode($argumentSplited[0]); $value = urldecode($argumentSplited[1]); // for multiple values if (strpos($value, ',')) { $value = explode(',', $value); } if (substr($key, -2) == '[]') { $key = substr($key, 0, strlen($key)-2); if (!isset($parameters[$key])) { $parameters[$key] = []; } $parameters[$key][] = $value; } else { $parameters[$key] = $value; } } } else { $parameters = parent::getRequestParameters(); } return $parameters; }
[ "public", "function", "getRequestParameters", "(", ")", "{", "$", "parameters", "=", "[", "]", ";", "if", "(", "$", "this", "->", "isRequestPost", "(", ")", ")", "{", "$", "input", "=", "file_get_contents", "(", "\"php://input\"", ")", ";", "$", "argumen...
Get the request parameters If http method is POST read stream from php://input Otherwise call parent method @return array
[ "Get", "the", "request", "parameters", "If", "http", "method", "is", "POST", "read", "stream", "from", "php", ":", "//", "input", "Otherwise", "call", "parent", "method" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.RestResource.php#L176-L206
oat-sa/tao-core
actions/class.RestResource.php
tao_actions_RestResource.processForm
protected function processForm($instance) { $parameters = $this->getRequestParameters(); $form = $this->getForm($instance)->bind($parameters); $report = $form->validate(); if ($report->containsError()) { $this->returnValidationFailure($report); } else { $resource = $form->save(); $this->returnSuccess(['uri' => $resource->getUri()]); } }
php
protected function processForm($instance) { $parameters = $this->getRequestParameters(); $form = $this->getForm($instance)->bind($parameters); $report = $form->validate(); if ($report->containsError()) { $this->returnValidationFailure($report); } else { $resource = $form->save(); $this->returnSuccess(['uri' => $resource->getUri()]); } }
[ "protected", "function", "processForm", "(", "$", "instance", ")", "{", "$", "parameters", "=", "$", "this", "->", "getRequestParameters", "(", ")", ";", "$", "form", "=", "$", "this", "->", "getForm", "(", "$", "instance", ")", "->", "bind", "(", "$",...
Process the form submission Bind the http data to form, validate, and save @param $instance
[ "Process", "the", "form", "submission", "Bind", "the", "http", "data", "to", "form", "validate", "and", "save" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.RestResource.php#L214-L225
oat-sa/tao-core
actions/class.RestResource.php
tao_actions_RestResource.getResourceParameter
protected function getResourceParameter() { if (! $this->hasRequestParameter(self::RESOURCE_PARAMETER)) { throw new \common_exception_MissingParameter(self::RESOURCE_PARAMETER, __CLASS__); } $uri = $this->getRequestParameter(self::RESOURCE_PARAMETER); if (empty($uri) || !common_Utils::isUri($uri)) { throw new \common_exception_MissingParameter(self::RESOURCE_PARAMETER, __CLASS__); } return $this->getResource($uri); }
php
protected function getResourceParameter() { if (! $this->hasRequestParameter(self::RESOURCE_PARAMETER)) { throw new \common_exception_MissingParameter(self::RESOURCE_PARAMETER, __CLASS__); } $uri = $this->getRequestParameter(self::RESOURCE_PARAMETER); if (empty($uri) || !common_Utils::isUri($uri)) { throw new \common_exception_MissingParameter(self::RESOURCE_PARAMETER, __CLASS__); } return $this->getResource($uri); }
[ "protected", "function", "getResourceParameter", "(", ")", "{", "if", "(", "!", "$", "this", "->", "hasRequestParameter", "(", "self", "::", "RESOURCE_PARAMETER", ")", ")", "{", "throw", "new", "\\", "common_exception_MissingParameter", "(", "self", "::", "RESOU...
Extract the resource from http request The parameter 'uri' must exists and be a valid uri @return core_kernel_classes_Resource @throws common_exception_MissingParameter
[ "Extract", "the", "resource", "from", "http", "request", "The", "parameter", "uri", "must", "exists", "and", "be", "a", "valid", "uri" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.RestResource.php#L246-L258
oat-sa/tao-core
actions/class.RestResource.php
tao_actions_RestResource.getClassParameter
protected function getClassParameter() { if (! $this->hasRequestParameter(self::CLASS_PARAMETER)) { throw new \common_exception_MissingParameter(self::CLASS_PARAMETER, __CLASS__); } $uri = $this->getRequestParameter(self::CLASS_PARAMETER); if (empty($uri) || !common_Utils::isUri($uri)) { throw new \common_exception_MissingParameter(self::CLASS_PARAMETER, __CLASS__); } return $this->getClass($uri); }
php
protected function getClassParameter() { if (! $this->hasRequestParameter(self::CLASS_PARAMETER)) { throw new \common_exception_MissingParameter(self::CLASS_PARAMETER, __CLASS__); } $uri = $this->getRequestParameter(self::CLASS_PARAMETER); if (empty($uri) || !common_Utils::isUri($uri)) { throw new \common_exception_MissingParameter(self::CLASS_PARAMETER, __CLASS__); } return $this->getClass($uri); }
[ "protected", "function", "getClassParameter", "(", ")", "{", "if", "(", "!", "$", "this", "->", "hasRequestParameter", "(", "self", "::", "CLASS_PARAMETER", ")", ")", "{", "throw", "new", "\\", "common_exception_MissingParameter", "(", "self", "::", "CLASS_PARAM...
Extract the class from http request The parameter 'classUri' must exists and be a valid uri @return core_kernel_classes_Class @throws common_exception_MissingParameter
[ "Extract", "the", "class", "from", "http", "request", "The", "parameter", "classUri", "must", "exists", "and", "be", "a", "valid", "uri" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.RestResource.php#L267-L279
oat-sa/tao-core
actions/class.RestResource.php
tao_actions_RestResource.returnValidationFailure
protected function returnValidationFailure(common_report_Report $report, $withMessage=true) { $data = ['data' => []]; /** @var common_report_Report $error */ foreach ($report->getErrors() as $error) { $data['data'][$error->getData()] = $error->getMessage(); } if ($withMessage) { $data['success'] = false; $data['errorCode'] = 400; $data['errorMsg'] = 'Some fields are invalid'; $data['version'] = TAO_VERSION; } $this->returnJson($data, 400); exit(0); }
php
protected function returnValidationFailure(common_report_Report $report, $withMessage=true) { $data = ['data' => []]; /** @var common_report_Report $error */ foreach ($report->getErrors() as $error) { $data['data'][$error->getData()] = $error->getMessage(); } if ($withMessage) { $data['success'] = false; $data['errorCode'] = 400; $data['errorMsg'] = 'Some fields are invalid'; $data['version'] = TAO_VERSION; } $this->returnJson($data, 400); exit(0); }
[ "protected", "function", "returnValidationFailure", "(", "common_report_Report", "$", "report", ",", "$", "withMessage", "=", "true", ")", "{", "$", "data", "=", "[", "'data'", "=>", "[", "]", "]", ";", "/** @var common_report_Report $error */", "foreach", "(", ...
Transform a report to http response with 422 code and report error messages @param common_report_Report $report @param bool $withMessage
[ "Transform", "a", "report", "to", "http", "response", "with", "422", "code", "and", "report", "error", "messages" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.RestResource.php#L287-L304
oat-sa/tao-core
actions/class.RestResource.php
tao_actions_RestResource.returnFailure
protected function returnFailure(Exception $exception, $withMessage=true) { $data = array(); if ($withMessage) { $data['success'] = false; $data['errorCode'] = 500; $data['version'] = TAO_VERSION; if ($exception instanceof common_exception_UserReadableException) { $data['errorMsg'] = $exception->getUserMessage(); } else { $this->logWarning(__CLASS__ . ' : ' . $exception->getMessage()); $data['errorMsg'] = __('Unexpected error. Please contact administrator'); } } $this->returnJson($data, 500); exit(0); }
php
protected function returnFailure(Exception $exception, $withMessage=true) { $data = array(); if ($withMessage) { $data['success'] = false; $data['errorCode'] = 500; $data['version'] = TAO_VERSION; if ($exception instanceof common_exception_UserReadableException) { $data['errorMsg'] = $exception->getUserMessage(); } else { $this->logWarning(__CLASS__ . ' : ' . $exception->getMessage()); $data['errorMsg'] = __('Unexpected error. Please contact administrator'); } } $this->returnJson($data, 500); exit(0); }
[ "protected", "function", "returnFailure", "(", "Exception", "$", "exception", ",", "$", "withMessage", "=", "true", ")", "{", "$", "data", "=", "array", "(", ")", ";", "if", "(", "$", "withMessage", ")", "{", "$", "data", "[", "'success'", "]", "=", ...
Return an error reponse following the given exception An exception handler manages http code, avoid to use returnJson to add unneeded header @param Exception $exception @param bool $withMessage
[ "Return", "an", "error", "reponse", "following", "the", "given", "exception", "An", "exception", "handler", "manages", "http", "code", "avoid", "to", "use", "returnJson", "to", "add", "unneeded", "header" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.RestResource.php#L313-L330