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 | actions/class.ExtensionsManager.php | tao_actions_ExtensionsManager.postInstall | public function postInstall()
{
$this->assertIsDebugMode();
$success = true;
$message = '';
// try to regenerate languages bundles
try {
tao_models_classes_LanguageService::singleton()->generateAll(true);
} catch (common_exception_Error $e) {
$message = $e->getMessage();
$success = false;
}
$this->returnJson(array(
'success' => $success,
'message' => $message
));
} | php | public function postInstall()
{
$this->assertIsDebugMode();
$success = true;
$message = '';
// try to regenerate languages bundles
try {
tao_models_classes_LanguageService::singleton()->generateAll(true);
} catch (common_exception_Error $e) {
$message = $e->getMessage();
$success = false;
}
$this->returnJson(array(
'success' => $success,
'message' => $message
));
} | [
"public",
"function",
"postInstall",
"(",
")",
"{",
"$",
"this",
"->",
"assertIsDebugMode",
"(",
")",
";",
"$",
"success",
"=",
"true",
";",
"$",
"message",
"=",
"''",
";",
"// try to regenerate languages bundles\r",
"try",
"{",
"tao_models_classes_LanguageService... | Once some extensions have been installed, we trigger this action.
@throws common_exception_BadRequest If platform is on production mode | [
"Once",
"some",
"extensions",
"have",
"been",
"installed",
"we",
"trigger",
"this",
"action",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.ExtensionsManager.php#L105-L124 |
oat-sa/tao-core | actions/class.ExtensionsManager.php | tao_actions_ExtensionsManager.disable | public function disable()
{
$this->assertIsDebugMode();
$extId = $this->getRequestParameter('id');
$this->getExtensionManager()->setEnabled($extId, false);
MenuService::flushCache();
$this->returnJson(array(
'success' => true,
'message' => __('Disabled %s', $this->getRequestParameter('id'))
));
} | php | public function disable()
{
$this->assertIsDebugMode();
$extId = $this->getRequestParameter('id');
$this->getExtensionManager()->setEnabled($extId, false);
MenuService::flushCache();
$this->returnJson(array(
'success' => true,
'message' => __('Disabled %s', $this->getRequestParameter('id'))
));
} | [
"public",
"function",
"disable",
"(",
")",
"{",
"$",
"this",
"->",
"assertIsDebugMode",
"(",
")",
";",
"$",
"extId",
"=",
"$",
"this",
"->",
"getRequestParameter",
"(",
"'id'",
")",
";",
"$",
"this",
"->",
"getExtensionManager",
"(",
")",
"->",
"setEnabl... | Disable an extension
@throws common_exception_BadRequest If platform is on production mode
@throws common_exception_Error | [
"Disable",
"an",
"extension"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.ExtensionsManager.php#L132-L143 |
oat-sa/tao-core | actions/class.ExtensionsManager.php | tao_actions_ExtensionsManager.enable | public function enable()
{
$this->assertIsDebugMode();
$extId = $this->getRequestParameter('id');
$this->getExtensionManager()->setEnabled($extId, true);
MenuService::flushCache();
$this->returnJson(array(
'success' => true,
'message' => __('Enabled %s', $this->getRequestParameter('id'))
));
} | php | public function enable()
{
$this->assertIsDebugMode();
$extId = $this->getRequestParameter('id');
$this->getExtensionManager()->setEnabled($extId, true);
MenuService::flushCache();
$this->returnJson(array(
'success' => true,
'message' => __('Enabled %s', $this->getRequestParameter('id'))
));
} | [
"public",
"function",
"enable",
"(",
")",
"{",
"$",
"this",
"->",
"assertIsDebugMode",
"(",
")",
";",
"$",
"extId",
"=",
"$",
"this",
"->",
"getRequestParameter",
"(",
"'id'",
")",
";",
"$",
"this",
"->",
"getExtensionManager",
"(",
")",
"->",
"setEnable... | Enable an extension
@throws common_exception_BadRequest If platform is on production mode
@throws common_exception_Error | [
"Enable",
"an",
"extension"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.ExtensionsManager.php#L151-L162 |
oat-sa/tao-core | actions/class.ExtensionsManager.php | tao_actions_ExtensionsManager.uninstall | public function uninstall()
{
$this->assertIsDebugMode();
try {
$uninstaller = new \tao_install_ExtensionUninstaller($this->getCurrentExtension());
$success = $uninstaller->uninstall();
$message = __('Uninstalled %s', $this->getRequestParameter('id'));
} catch (\common_Exception $e) {
$success = false;
if ($e instanceof \common_exception_UserReadableException) {
$message = $e->getUserMessage();
} else {
$message = __('Uninstall of %s failed', $this->getRequestParameter('id'));
}
}
$this->returnJson(array(
'success' => $success,
'message' => $message
));
} | php | public function uninstall()
{
$this->assertIsDebugMode();
try {
$uninstaller = new \tao_install_ExtensionUninstaller($this->getCurrentExtension());
$success = $uninstaller->uninstall();
$message = __('Uninstalled %s', $this->getRequestParameter('id'));
} catch (\common_Exception $e) {
$success = false;
if ($e instanceof \common_exception_UserReadableException) {
$message = $e->getUserMessage();
} else {
$message = __('Uninstall of %s failed', $this->getRequestParameter('id'));
}
}
$this->returnJson(array(
'success' => $success,
'message' => $message
));
} | [
"public",
"function",
"uninstall",
"(",
")",
"{",
"$",
"this",
"->",
"assertIsDebugMode",
"(",
")",
";",
"try",
"{",
"$",
"uninstaller",
"=",
"new",
"\\",
"tao_install_ExtensionUninstaller",
"(",
"$",
"this",
"->",
"getCurrentExtension",
"(",
")",
")",
";",
... | Uninstall an extension
@throws common_exception_BadRequest If platform is on production mode | [
"Uninstall",
"an",
"extension"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.ExtensionsManager.php#L169-L188 |
oat-sa/tao-core | install/utils/class.System.php | tao_install_utils_System.getInfos | public static function getInfos(){
//subfolder shall be detected as /SUBFLODERS/tao/install/index.php so we remove the "/extension/module/action" part:
$subfolder = $_SERVER['REQUEST_URI'];
$subfolder = preg_replace('/\/(([^\/]*)\/){2}([^\/]*)$/', '', $subfolder);
$subfolder = preg_replace('/^\//', '', $subfolder);
return array(
'folder' => $subfolder,
'host' => $_SERVER['HTTP_HOST'],
'https' => ($_SERVER['SERVER_PORT'] == 443)
);
} | php | public static function getInfos(){
//subfolder shall be detected as /SUBFLODERS/tao/install/index.php so we remove the "/extension/module/action" part:
$subfolder = $_SERVER['REQUEST_URI'];
$subfolder = preg_replace('/\/(([^\/]*)\/){2}([^\/]*)$/', '', $subfolder);
$subfolder = preg_replace('/^\//', '', $subfolder);
return array(
'folder' => $subfolder,
'host' => $_SERVER['HTTP_HOST'],
'https' => ($_SERVER['SERVER_PORT'] == 443)
);
} | [
"public",
"static",
"function",
"getInfos",
"(",
")",
"{",
"//subfolder shall be detected as /SUBFLODERS/tao/install/index.php so we remove the \"/extension/module/action\" part:",
"$",
"subfolder",
"=",
"$",
"_SERVER",
"[",
"'REQUEST_URI'",
"]",
";",
"$",
"subfolder",
"=",
"... | Get informations on the host system.
@return array where key/values are 'folder' as string, 'host' as string, 'https' as boolean. | [
"Get",
"informations",
"on",
"the",
"host",
"system",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/install/utils/class.System.php#L49-L62 |
oat-sa/tao-core | install/utils/class.System.php | tao_install_utils_System.isTAOInstalled | public static function isTAOInstalled($path = '')
{
$path = (empty($path)) ? __DIR__ . '/../../../config' : rtrim($path, '/\\');
$config = "${path}/generis.conf.php";
return file_exists($config);
} | php | public static function isTAOInstalled($path = '')
{
$path = (empty($path)) ? __DIR__ . '/../../../config' : rtrim($path, '/\\');
$config = "${path}/generis.conf.php";
return file_exists($config);
} | [
"public",
"static",
"function",
"isTAOInstalled",
"(",
"$",
"path",
"=",
"''",
")",
"{",
"$",
"path",
"=",
"(",
"empty",
"(",
"$",
"path",
")",
")",
"?",
"__DIR__",
".",
"'/../../../config'",
":",
"rtrim",
"(",
"$",
"path",
",",
"'/\\\\'",
")",
";",
... | Check if TAO is already installed.
@return boolean | [
"Check",
"if",
"TAO",
"is",
"already",
"installed",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/install/utils/class.System.php#L69-L74 |
oat-sa/tao-core | install/utils/class.System.php | tao_install_utils_System.isTAOUpToDate | public static function isTAOUpToDate($path = '')
{
$path = (empty($path)) ? __DIR__ . '/../../../config' : rtrim($path, '/\\');
$generisConf = "${path}/generis.conf.php";
if (!is_readable($generisConf)) {
return false;
}
include_once($generisConf);
$installationConf = "${path}/generis/installation.conf.php";
if (!is_readable($installationConf)) {
return false;
}
$conf = include_once($installationConf);
$extIterator = is_array($conf) ? $conf : $conf->getConfig();
foreach ($extIterator as $extName => $ext) {
$manifestPath = __DIR__ . "/../../../${extName}/manifest.php";
if (!is_readable($manifestPath)) {
return false;
} else {
$manifest = include_once($manifestPath);
if ((!isset($ext["installed"])) || (!isset($manifest["version"])) || ($ext["installed"] !== $manifest["version"])) {
return false;
}
}
}
return true;
} | php | public static function isTAOUpToDate($path = '')
{
$path = (empty($path)) ? __DIR__ . '/../../../config' : rtrim($path, '/\\');
$generisConf = "${path}/generis.conf.php";
if (!is_readable($generisConf)) {
return false;
}
include_once($generisConf);
$installationConf = "${path}/generis/installation.conf.php";
if (!is_readable($installationConf)) {
return false;
}
$conf = include_once($installationConf);
$extIterator = is_array($conf) ? $conf : $conf->getConfig();
foreach ($extIterator as $extName => $ext) {
$manifestPath = __DIR__ . "/../../../${extName}/manifest.php";
if (!is_readable($manifestPath)) {
return false;
} else {
$manifest = include_once($manifestPath);
if ((!isset($ext["installed"])) || (!isset($manifest["version"])) || ($ext["installed"] !== $manifest["version"])) {
return false;
}
}
}
return true;
} | [
"public",
"static",
"function",
"isTAOUpToDate",
"(",
"$",
"path",
"=",
"''",
")",
"{",
"$",
"path",
"=",
"(",
"empty",
"(",
"$",
"path",
")",
")",
"?",
"__DIR__",
".",
"'/../../../config'",
":",
"rtrim",
"(",
"$",
"path",
",",
"'/\\\\'",
")",
";",
... | Check if TAO is already up to date.
@return boolean | [
"Check",
"if",
"TAO",
"is",
"already",
"up",
"to",
"date",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/install/utils/class.System.php#L81-L115 |
oat-sa/tao-core | install/utils/class.System.php | tao_install_utils_System.getAvailableLocales | public static function getAvailableLocales($path){
$locales = @scandir($path);
$returnValue = array();
if ($locales !== false){
foreach ($locales as $l){
if ($l[0] !== '.'){
// We found a locale folder. Does it contain a valid lang.rdf file?
$langFilePath = $path . '/' . $l . '/lang.rdf';
if (is_file($langFilePath) && is_readable($langFilePath)){
try{
$doc = new DOMDocument('1.0', 'UTF-8');
$doc->load($langFilePath);
$xpath = new DOMXPath($doc);
$xpath->registerNamespace('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#');
$xpath->registerNamespace('rdfs', 'http://www.w3.org/2000/01/rdf-schema#');
$expectedUri = 'http://www.tao.lu/Ontologies/TAO.rdf#Lang' . $l;
// Look for an rdf:value equals to the folder name.
$rdfValues = $xpath->query("//rdf:Description[@rdf:about='${expectedUri}']/rdf:value");
if ($rdfValues->length == 1 && $rdfValues->item(0)->nodeValue == $l){
$key = $l;
$rdfsLabels = $xpath->query("//rdf:Description[@rdf:about='${expectedUri}']/rdfs:label[@xml:lang='en-US']");
if ($rdfsLabels->length == 1){
$value = $rdfsLabels->item(0)->nodeValue;
$returnValue[$l] = $value;
}
}
}
catch (DOMException $e){
// Invalid lang.rdf file, we continue to look for other ones.
continue;
}
}
}
}
return $returnValue;
}else{
throw new UnexpectedValueException("Unable to list locales in '${path}'.");
}
} | php | public static function getAvailableLocales($path){
$locales = @scandir($path);
$returnValue = array();
if ($locales !== false){
foreach ($locales as $l){
if ($l[0] !== '.'){
// We found a locale folder. Does it contain a valid lang.rdf file?
$langFilePath = $path . '/' . $l . '/lang.rdf';
if (is_file($langFilePath) && is_readable($langFilePath)){
try{
$doc = new DOMDocument('1.0', 'UTF-8');
$doc->load($langFilePath);
$xpath = new DOMXPath($doc);
$xpath->registerNamespace('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#');
$xpath->registerNamespace('rdfs', 'http://www.w3.org/2000/01/rdf-schema#');
$expectedUri = 'http://www.tao.lu/Ontologies/TAO.rdf#Lang' . $l;
// Look for an rdf:value equals to the folder name.
$rdfValues = $xpath->query("//rdf:Description[@rdf:about='${expectedUri}']/rdf:value");
if ($rdfValues->length == 1 && $rdfValues->item(0)->nodeValue == $l){
$key = $l;
$rdfsLabels = $xpath->query("//rdf:Description[@rdf:about='${expectedUri}']/rdfs:label[@xml:lang='en-US']");
if ($rdfsLabels->length == 1){
$value = $rdfsLabels->item(0)->nodeValue;
$returnValue[$l] = $value;
}
}
}
catch (DOMException $e){
// Invalid lang.rdf file, we continue to look for other ones.
continue;
}
}
}
}
return $returnValue;
}else{
throw new UnexpectedValueException("Unable to list locales in '${path}'.");
}
} | [
"public",
"static",
"function",
"getAvailableLocales",
"(",
"$",
"path",
")",
"{",
"$",
"locales",
"=",
"@",
"scandir",
"(",
"$",
"path",
")",
";",
"$",
"returnValue",
"=",
"array",
"(",
")",
";",
"if",
"(",
"$",
"locales",
"!==",
"false",
")",
"{",
... | Returns the availables locales (languages or cultures) of the tao platform
on the basis of a particular locale folder e.g. the /locales folder of the tao
meta-extension.
A locale will be included in the resulting array only if a valid 'lang.rdf'
file is found.
@param string $path The location of the /locales folder to inspect.
@return array An array of strings where keys are the language code and values the language label.
@throws UnexpectedValueException | [
"Returns",
"the",
"availables",
"locales",
"(",
"languages",
"or",
"cultures",
")",
"of",
"the",
"tao",
"platform",
"on",
"the",
"basis",
"of",
"a",
"particular",
"locale",
"folder",
"e",
".",
"g",
".",
"the",
"/",
"locales",
"folder",
"of",
"the",
"tao"... | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/install/utils/class.System.php#L129-L171 |
oat-sa/tao-core | install/utils/class.SimpleSQLParser.php | tao_install_utils_SimpleSQLParser.parse | public function parse(){
$this->setStatements(array());
//common file checks
$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.");
}
if ($handler = fopen($file, "r")){
//parse file and get only usefull lines
$ch = "";
while (!feof ($handler)){
$line = utf8_decode(fgets($handler));
if (isset($line[0]) && ($line[0] != '#') && ($line[0] != '-')){
$ch = $ch.$line;
}
}
//explode and execute
$requests = explode(";", $ch);
try{
foreach($requests as $index => $request){
$requestTrim = trim($request);
if(!empty($requestTrim)){
$this->addStatement($request);
}
}
}
catch(Exception $e){
throw new tao_install_utils_SQLParsingException("Error executing query #$index : $request . ".$e->getMessage());
}
fclose($handler);
}
} | php | public function parse(){
$this->setStatements(array());
//common file checks
$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.");
}
if ($handler = fopen($file, "r")){
//parse file and get only usefull lines
$ch = "";
while (!feof ($handler)){
$line = utf8_decode(fgets($handler));
if (isset($line[0]) && ($line[0] != '#') && ($line[0] != '-')){
$ch = $ch.$line;
}
}
//explode and execute
$requests = explode(";", $ch);
try{
foreach($requests as $index => $request){
$requestTrim = trim($request);
if(!empty($requestTrim)){
$this->addStatement($request);
}
}
}
catch(Exception $e){
throw new tao_install_utils_SQLParsingException("Error executing query #$index : $request . ".$e->getMessage());
}
fclose($handler);
}
} | [
"public",
"function",
"parse",
"(",
")",
"{",
"$",
"this",
"->",
"setStatements",
"(",
"array",
"(",
")",
")",
";",
"//common file checks\r",
"$",
"file",
"=",
"$",
"this",
"->",
"getFile",
"(",
")",
";",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"fil... | Parses a SQL file containing simple statements.
@return void
@throws tao_install_utils_SQLParsingException | [
"Parses",
"a",
"SQL",
"file",
"containing",
"simple",
"statements",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/install/utils/class.SimpleSQLParser.php#L40-L83 |
oat-sa/tao-core | models/classes/mvc/error/ResponseAbstract.php | ResponseAbstract.chooseRenderer | protected function chooseRenderer(array $accept) {
$renderClass = 'none';
foreach ($accept as $mimeType) {
switch (trim(strtolower($mimeType))) {
case 'text/html' :
case 'application/xhtml+xml':
case '*/*':
$renderClass = 'html';
break 2;
case 'application/json' :
case 'text/json' :
$renderClass = 'json';
break 2;
}
}
if(tao_helpers_Request::isAjax()) {
$renderClass = 'ajax';
}
$className = __NAMESPACE__ . '\\' . $this->rendererClassList[$renderClass];
$renderer = new $className();
return $renderer->setServiceLocator($this->getServiceLocator());
} | php | protected function chooseRenderer(array $accept) {
$renderClass = 'none';
foreach ($accept as $mimeType) {
switch (trim(strtolower($mimeType))) {
case 'text/html' :
case 'application/xhtml+xml':
case '*/*':
$renderClass = 'html';
break 2;
case 'application/json' :
case 'text/json' :
$renderClass = 'json';
break 2;
}
}
if(tao_helpers_Request::isAjax()) {
$renderClass = 'ajax';
}
$className = __NAMESPACE__ . '\\' . $this->rendererClassList[$renderClass];
$renderer = new $className();
return $renderer->setServiceLocator($this->getServiceLocator());
} | [
"protected",
"function",
"chooseRenderer",
"(",
"array",
"$",
"accept",
")",
"{",
"$",
"renderClass",
"=",
"'none'",
";",
"foreach",
"(",
"$",
"accept",
"as",
"$",
"mimeType",
")",
"{",
"switch",
"(",
"trim",
"(",
"strtolower",
"(",
"$",
"mimeType",
")",... | search rendering method in function of request accept header
@param array $accept
@return ResponseAbstract | [
"search",
"rendering",
"method",
"in",
"function",
"of",
"request",
"accept",
"header"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/mvc/error/ResponseAbstract.php#L70-L97 |
oat-sa/tao-core | models/classes/mvc/error/ResponseAbstract.php | ResponseAbstract.sendHeaders | protected function sendHeaders() {
$context = Context::getInstance();
$context->getResponse()->setContentHeader($this->contentType);
header(HTTPToolkit::statusCodeHeader($this->httpCode));
return $this;
} | php | protected function sendHeaders() {
$context = Context::getInstance();
$context->getResponse()->setContentHeader($this->contentType);
header(HTTPToolkit::statusCodeHeader($this->httpCode));
return $this;
} | [
"protected",
"function",
"sendHeaders",
"(",
")",
"{",
"$",
"context",
"=",
"Context",
"::",
"getInstance",
"(",
")",
";",
"$",
"context",
"->",
"getResponse",
"(",
")",
"->",
"setContentHeader",
"(",
"$",
"this",
"->",
"contentType",
")",
";",
"header",
... | send headers
@return $this | [
"send",
"headers"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/mvc/error/ResponseAbstract.php#L102-L107 |
oat-sa/tao-core | actions/class.CommonModule.php | tao_actions_CommonModule.hasAccess | protected function hasAccess($controllerClass, $action, $parameters = [])
{
$user = $this->getSession()->getUser();
return AclProxy::hasAccess($user, $controllerClass, $action, $parameters);
} | php | protected function hasAccess($controllerClass, $action, $parameters = [])
{
$user = $this->getSession()->getUser();
return AclProxy::hasAccess($user, $controllerClass, $action, $parameters);
} | [
"protected",
"function",
"hasAccess",
"(",
"$",
"controllerClass",
",",
"$",
"action",
",",
"$",
"parameters",
"=",
"[",
"]",
")",
"{",
"$",
"user",
"=",
"$",
"this",
"->",
"getSession",
"(",
")",
"->",
"getUser",
"(",
")",
";",
"return",
"AclProxy",
... | Whenever or not the current user has access to a specific action
using functional and data access control
@param string $controllerClass
@param string $action
@param array $parameters
@return boolean
@throws common_exception_Error | [
"Whenever",
"or",
"not",
"the",
"current",
"user",
"has",
"access",
"to",
"a",
"specific",
"action",
"using",
"functional",
"and",
"data",
"access",
"control"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.CommonModule.php#L94-L98 |
oat-sa/tao-core | actions/class.CommonModule.php | tao_actions_CommonModule.defaultData | protected function defaultData()
{
$context = Context::getInstance();
$this->setData('extension', $context->getExtensionName());
$this->setData('module', $context->getModuleName());
$this->setData('action', $context->getActionName());
if ($this->hasRequestParameter('uri')) {
// inform the client of new classUri
$this->setData('uri', $this->getRequestParameter('uri'));
}
if ($this->hasRequestParameter('classUri')) {
// inform the client of new classUri
$this->setData('uri', $this->getRequestParameter('classUri'));
}
if ($this->getRequestParameter('message')) {
$this->setData('message', $this->getRequestParameter('message'));
}
if ($this->getRequestParameter('errorMessage')) {
$this->setData('errorMessage', $this->getRequestParameter('errorMessage'));
}
$this->setData('client_timeout', $this->getClientTimeout());
$this->setData('client_config_url', $this->getClientConfigUrl());
} | php | protected function defaultData()
{
$context = Context::getInstance();
$this->setData('extension', $context->getExtensionName());
$this->setData('module', $context->getModuleName());
$this->setData('action', $context->getActionName());
if ($this->hasRequestParameter('uri')) {
// inform the client of new classUri
$this->setData('uri', $this->getRequestParameter('uri'));
}
if ($this->hasRequestParameter('classUri')) {
// inform the client of new classUri
$this->setData('uri', $this->getRequestParameter('classUri'));
}
if ($this->getRequestParameter('message')) {
$this->setData('message', $this->getRequestParameter('message'));
}
if ($this->getRequestParameter('errorMessage')) {
$this->setData('errorMessage', $this->getRequestParameter('errorMessage'));
}
$this->setData('client_timeout', $this->getClientTimeout());
$this->setData('client_config_url', $this->getClientConfigUrl());
} | [
"protected",
"function",
"defaultData",
"(",
")",
"{",
"$",
"context",
"=",
"Context",
"::",
"getInstance",
"(",
")",
";",
"$",
"this",
"->",
"setData",
"(",
"'extension'",
",",
"$",
"context",
"->",
"getExtensionName",
"(",
")",
")",
";",
"$",
"this",
... | Retrieve the data from the url and make the base initialization
@return void
@throws common_ext_ExtensionException | [
"Retrieve",
"the",
"data",
"from",
"the",
"url",
"and",
"make",
"the",
"base",
"initialization"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.CommonModule.php#L119-L146 |
oat-sa/tao-core | actions/class.CommonModule.php | tao_actions_CommonModule.returnError | protected function returnError($description, $returnLink = true, $httpStatus = null)
{
if ($this->isXmlHttpRequest()) {
$this->logWarning('Called '.__FUNCTION__.' in an unsupported AJAX context');
throw new common_Exception($description);
}
$this->setData('message', $description);
$this->setData('returnLink', $returnLink);
if($httpStatus !== null && file_exists(Template::getTemplate("error/error${httpStatus}.tpl"))){
$this->setView("error/error${httpStatus}.tpl", 'tao');
} else {
$this->setView('error/user_error.tpl', 'tao');
}
} | php | protected function returnError($description, $returnLink = true, $httpStatus = null)
{
if ($this->isXmlHttpRequest()) {
$this->logWarning('Called '.__FUNCTION__.' in an unsupported AJAX context');
throw new common_Exception($description);
}
$this->setData('message', $description);
$this->setData('returnLink', $returnLink);
if($httpStatus !== null && file_exists(Template::getTemplate("error/error${httpStatus}.tpl"))){
$this->setView("error/error${httpStatus}.tpl", 'tao');
} else {
$this->setView('error/user_error.tpl', 'tao');
}
} | [
"protected",
"function",
"returnError",
"(",
"$",
"description",
",",
"$",
"returnLink",
"=",
"true",
",",
"$",
"httpStatus",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isXmlHttpRequest",
"(",
")",
")",
"{",
"$",
"this",
"->",
"logWarning",
... | Function to return an user readable error
Does not work with ajax Requests yet
@param string $description error to show
@param boolean $returnLink whenever or not to add a return link
@param int $httpStatus
@throws common_Exception | [
"Function",
"to",
"return",
"an",
"user",
"readable",
"error",
"Does",
"not",
"work",
"with",
"ajax",
"Requests",
"yet"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.CommonModule.php#L157-L172 |
oat-sa/tao-core | actions/class.CommonModule.php | tao_actions_CommonModule.getTemplatePath | protected static function getTemplatePath($identifier, $extensionID = null)
{
if ($extensionID === true) {
$extensionID = 'tao';
common_Logger::d('Deprecated use of setView() using a boolean');
}
if($extensionID === null) {
$extensionID = Context::getInstance()->getExtensionName();
}
$ext = common_ext_ExtensionsManager::singleton()->getExtensionById($extensionID);
return $ext->getConstant('DIR_VIEWS').'templates'.DIRECTORY_SEPARATOR.$identifier;
} | php | protected static function getTemplatePath($identifier, $extensionID = null)
{
if ($extensionID === true) {
$extensionID = 'tao';
common_Logger::d('Deprecated use of setView() using a boolean');
}
if($extensionID === null) {
$extensionID = Context::getInstance()->getExtensionName();
}
$ext = common_ext_ExtensionsManager::singleton()->getExtensionById($extensionID);
return $ext->getConstant('DIR_VIEWS').'templates'.DIRECTORY_SEPARATOR.$identifier;
} | [
"protected",
"static",
"function",
"getTemplatePath",
"(",
"$",
"identifier",
",",
"$",
"extensionID",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"extensionID",
"===",
"true",
")",
"{",
"$",
"extensionID",
"=",
"'tao'",
";",
"common_Logger",
"::",
"d",
"(",
... | Returns the absolute path to the specified template
@param string $identifier
@param string $extensionID
@return string
@throws common_exception_Error
@throws common_ext_ExtensionException | [
"Returns",
"the",
"absolute",
"path",
"to",
"the",
"specified",
"template"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.CommonModule.php#L183-L194 |
oat-sa/tao-core | actions/class.CommonModule.php | tao_actions_CommonModule.getClientTimeout | protected function getClientTimeout()
{
$ext = $this->getServiceManager()->get(common_ext_ExtensionsManager::SERVICE_ID)->getExtensionById('tao');
$config = $ext->getConfig('js');
if($config !== null && isset($config['timeout'])){
return (int)$config['timeout'];
}
return 30;
} | php | protected function getClientTimeout()
{
$ext = $this->getServiceManager()->get(common_ext_ExtensionsManager::SERVICE_ID)->getExtensionById('tao');
$config = $ext->getConfig('js');
if($config !== null && isset($config['timeout'])){
return (int)$config['timeout'];
}
return 30;
} | [
"protected",
"function",
"getClientTimeout",
"(",
")",
"{",
"$",
"ext",
"=",
"$",
"this",
"->",
"getServiceManager",
"(",
")",
"->",
"get",
"(",
"common_ext_ExtensionsManager",
"::",
"SERVICE_ID",
")",
"->",
"getExtensionById",
"(",
"'tao'",
")",
";",
"$",
"... | Get the client timeout value from the config.
@return int the timeout value in seconds
@throws common_ext_ExtensionException | [
"Get",
"the",
"client",
"timeout",
"value",
"from",
"the",
"config",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.CommonModule.php#L213-L221 |
oat-sa/tao-core | actions/class.CommonModule.php | tao_actions_CommonModule.returnJson | protected function returnJson($data, $httpStatus = 200)
{
header(HTTPToolkit::statusCodeHeader($httpStatus));
Context::getInstance()->getResponse()->setContentHeader('application/json');
$this->response = $this->getPsrResponse()->withBody(stream_for(json_encode($data)));
} | php | protected function returnJson($data, $httpStatus = 200)
{
header(HTTPToolkit::statusCodeHeader($httpStatus));
Context::getInstance()->getResponse()->setContentHeader('application/json');
$this->response = $this->getPsrResponse()->withBody(stream_for(json_encode($data)));
} | [
"protected",
"function",
"returnJson",
"(",
"$",
"data",
",",
"$",
"httpStatus",
"=",
"200",
")",
"{",
"header",
"(",
"HTTPToolkit",
"::",
"statusCodeHeader",
"(",
"$",
"httpStatus",
")",
")",
";",
"Context",
"::",
"getInstance",
"(",
")",
"->",
"getRespon... | Return json response.
@param array|\JsonSerializable $data
@param int $httpStatus | [
"Return",
"json",
"response",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.CommonModule.php#L229-L234 |
oat-sa/tao-core | actions/class.CommonModule.php | tao_actions_CommonModule.returnReport | protected function returnReport(common_report_Report $report)
{
$data = $report->getData();
$successes = $report->getSuccesses();
// if report has no data, try to get it from the sub report
while ($data === null && count($successes) > 0) {
$firstSubReport = current($successes);
$data = $firstSubReport->getData();
$successes = $firstSubReport->getSuccesses();
}
if ($data !== null && $data instanceof core_kernel_classes_Resource) {
$this->setData('selectNode', tao_helpers_Uri::encode($data->getUri()));
}
$this->setData('report', $report);
$this->setView('report.tpl', 'tao');
} | php | protected function returnReport(common_report_Report $report)
{
$data = $report->getData();
$successes = $report->getSuccesses();
// if report has no data, try to get it from the sub report
while ($data === null && count($successes) > 0) {
$firstSubReport = current($successes);
$data = $firstSubReport->getData();
$successes = $firstSubReport->getSuccesses();
}
if ($data !== null && $data instanceof core_kernel_classes_Resource) {
$this->setData('selectNode', tao_helpers_Uri::encode($data->getUri()));
}
$this->setData('report', $report);
$this->setView('report.tpl', 'tao');
} | [
"protected",
"function",
"returnReport",
"(",
"common_report_Report",
"$",
"report",
")",
"{",
"$",
"data",
"=",
"$",
"report",
"->",
"getData",
"(",
")",
";",
"$",
"successes",
"=",
"$",
"report",
"->",
"getSuccesses",
"(",
")",
";",
"// if report has no da... | Returns a report
@param common_report_Report $report | [
"Returns",
"a",
"report"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.CommonModule.php#L241-L258 |
oat-sa/tao-core | actions/class.CommonModule.php | tao_actions_CommonModule.getServiceManager | protected function getServiceManager()
{
try {
$serviceManager = $this->getOriginalServiceManager();
} catch (InvalidServiceManagerException $e) {
$serviceManager = ServiceManager::getServiceManager();
}
return $serviceManager;
} | php | protected function getServiceManager()
{
try {
$serviceManager = $this->getOriginalServiceManager();
} catch (InvalidServiceManagerException $e) {
$serviceManager = ServiceManager::getServiceManager();
}
return $serviceManager;
} | [
"protected",
"function",
"getServiceManager",
"(",
")",
"{",
"try",
"{",
"$",
"serviceManager",
"=",
"$",
"this",
"->",
"getOriginalServiceManager",
"(",
")",
";",
"}",
"catch",
"(",
"InvalidServiceManagerException",
"$",
"e",
")",
"{",
"$",
"serviceManager",
... | Get the service Manager
@deprecated Use $this->propagate or $this->registerService to access ServiceManager functionalities
@deprecated To get the service dependencies manager, use $this->getServiceLocator
@return ServiceManager | [
"Get",
"the",
"service",
"Manager"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.CommonModule.php#L279-L287 |
oat-sa/tao-core | models/classes/mvc/Bootstrap.php | Bootstrap.start | public function start()
{
if(!self::$isStarted){
$this->session();
$this->setDefaultTimezone();
$this->registerErrorhandler();
self::$isStarted = true;
}
} | php | public function start()
{
if(!self::$isStarted){
$this->session();
$this->setDefaultTimezone();
$this->registerErrorhandler();
self::$isStarted = true;
}
} | [
"public",
"function",
"start",
"(",
")",
"{",
"if",
"(",
"!",
"self",
"::",
"$",
"isStarted",
")",
"{",
"$",
"this",
"->",
"session",
"(",
")",
";",
"$",
"this",
"->",
"setDefaultTimezone",
"(",
")",
";",
"$",
"this",
"->",
"registerErrorhandler",
"(... | Start all the services:
1. Start the session
2. Update the include path
3. Include the global helpers
4. Connect the current user to the generis API
5. Initialize the internationalization
6. Check the application' state | [
"Start",
"all",
"the",
"services",
":",
"1",
".",
"Start",
"the",
"session",
"2",
".",
"Update",
"the",
"include",
"path",
"3",
".",
"Include",
"the",
"global",
"helpers",
"4",
".",
"Connect",
"the",
"current",
"user",
"to",
"the",
"generis",
"API",
"5... | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/mvc/Bootstrap.php#L151-L159 |
oat-sa/tao-core | models/classes/mvc/Bootstrap.php | Bootstrap.dispatch | public function dispatch()
{
if(!self::$isDispatched){
if (PHP_SAPI == 'cli') {
$this->dispatchCli();
} else {
$this->dispatchHttp();
}
self::$isDispatched = true;
}
} | php | public function dispatch()
{
if(!self::$isDispatched){
if (PHP_SAPI == 'cli') {
$this->dispatchCli();
} else {
$this->dispatchHttp();
}
self::$isDispatched = true;
}
} | [
"public",
"function",
"dispatch",
"(",
")",
"{",
"if",
"(",
"!",
"self",
"::",
"$",
"isDispatched",
")",
"{",
"if",
"(",
"PHP_SAPI",
"==",
"'cli'",
")",
"{",
"$",
"this",
"->",
"dispatchCli",
"(",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"d... | Dispatch the current http request into the control loop:
1. Load the ressources
2. Start the MVC Loop from the ClearFW
manage Exception: | [
"Dispatch",
"the",
"current",
"http",
"request",
"into",
"the",
"control",
"loop",
":",
"1",
".",
"Load",
"the",
"ressources",
"2",
".",
"Start",
"the",
"MVC",
"Loop",
"from",
"the",
"ClearFW",
"manage",
"Exception",
":"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/mvc/Bootstrap.php#L231-L241 |
oat-sa/tao-core | models/classes/mvc/Bootstrap.php | Bootstrap.catchError | protected function catchError(Exception $exception)
{
$exceptionInterpreterService = $this->getServiceLocator()->get(ExceptionInterpreterService::SERVICE_ID);
$interpretor = $exceptionInterpreterService->getExceptionInterpreter($exception);
$interpretor->getResponse()->send();
} | php | protected function catchError(Exception $exception)
{
$exceptionInterpreterService = $this->getServiceLocator()->get(ExceptionInterpreterService::SERVICE_ID);
$interpretor = $exceptionInterpreterService->getExceptionInterpreter($exception);
$interpretor->getResponse()->send();
} | [
"protected",
"function",
"catchError",
"(",
"Exception",
"$",
"exception",
")",
"{",
"$",
"exceptionInterpreterService",
"=",
"$",
"this",
"->",
"getServiceLocator",
"(",
")",
"->",
"get",
"(",
"ExceptionInterpreterService",
"::",
"SERVICE_ID",
")",
";",
"$",
"i... | Catch any errors
return a http response in function of client accepted mime type
@param Exception $exception | [
"Catch",
"any",
"errors",
"return",
"a",
"http",
"response",
"in",
"function",
"of",
"client",
"accepted",
"mime",
"type"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/mvc/Bootstrap.php#L249-L254 |
oat-sa/tao-core | models/classes/mvc/Bootstrap.php | Bootstrap.session | protected function session()
{
if (tao_helpers_Context::check('APP_MODE')) {
// Set a specific ID to the session.
$request = new \Request();
if ($request->hasParameter('session_id')) {
session_id($request->getParameter('session_id'));
}
}
// set the session cookie to HTTP only.
$this->configureSessionHandler();
$sessionParams = session_get_cookie_params();
$cookieDomain = ((true == tao_helpers_Uri::isValidAsCookieDomain(ROOT_URL)) ? tao_helpers_Uri::getDomain(ROOT_URL) : $sessionParams['domain']);
$isSecureFlag = \common_http_Request::isHttps();
session_set_cookie_params($sessionParams['lifetime'], tao_helpers_Uri::getPath(ROOT_URL), $cookieDomain, $isSecureFlag, TRUE);
session_name(GENERIS_SESSION_NAME);
if (isset($_COOKIE[GENERIS_SESSION_NAME])) {
// Resume the session
session_start();
//cookie keep alive, if lifetime is not 0
if ($sessionParams['lifetime'] !== 0) {
$expiryTime = $sessionParams['lifetime'] + time();
setcookie(session_name(), session_id(), $expiryTime, tao_helpers_Uri::getPath(ROOT_URL), $cookieDomain, $isSecureFlag, true);
}
}
} | php | protected function session()
{
if (tao_helpers_Context::check('APP_MODE')) {
// Set a specific ID to the session.
$request = new \Request();
if ($request->hasParameter('session_id')) {
session_id($request->getParameter('session_id'));
}
}
// set the session cookie to HTTP only.
$this->configureSessionHandler();
$sessionParams = session_get_cookie_params();
$cookieDomain = ((true == tao_helpers_Uri::isValidAsCookieDomain(ROOT_URL)) ? tao_helpers_Uri::getDomain(ROOT_URL) : $sessionParams['domain']);
$isSecureFlag = \common_http_Request::isHttps();
session_set_cookie_params($sessionParams['lifetime'], tao_helpers_Uri::getPath(ROOT_URL), $cookieDomain, $isSecureFlag, TRUE);
session_name(GENERIS_SESSION_NAME);
if (isset($_COOKIE[GENERIS_SESSION_NAME])) {
// Resume the session
session_start();
//cookie keep alive, if lifetime is not 0
if ($sessionParams['lifetime'] !== 0) {
$expiryTime = $sessionParams['lifetime'] + time();
setcookie(session_name(), session_id(), $expiryTime, tao_helpers_Uri::getPath(ROOT_URL), $cookieDomain, $isSecureFlag, true);
}
}
} | [
"protected",
"function",
"session",
"(",
")",
"{",
"if",
"(",
"tao_helpers_Context",
"::",
"check",
"(",
"'APP_MODE'",
")",
")",
"{",
"// Set a specific ID to the session.",
"$",
"request",
"=",
"new",
"\\",
"Request",
"(",
")",
";",
"if",
"(",
"$",
"request... | Start the session | [
"Start",
"the",
"session"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/mvc/Bootstrap.php#L259-L290 |
oat-sa/tao-core | models/classes/mvc/Bootstrap.php | Bootstrap.mvc | protected function mvc()
{
$request = ServerRequest::fromGlobals();
$response = new Response();
$frontController = $this->propagate(new TaoFrontController());
$frontController($request, $response);
} | php | protected function mvc()
{
$request = ServerRequest::fromGlobals();
$response = new Response();
$frontController = $this->propagate(new TaoFrontController());
$frontController($request, $response);
} | [
"protected",
"function",
"mvc",
"(",
")",
"{",
"$",
"request",
"=",
"ServerRequest",
"::",
"fromGlobals",
"(",
")",
";",
"$",
"response",
"=",
"new",
"Response",
"(",
")",
";",
"$",
"frontController",
"=",
"$",
"this",
"->",
"propagate",
"(",
"new",
"T... | Start the MVC Loop from the ClearFW
@throws \ActionEnforcingException in case of wrong module or action
@throws \tao_models_classes_UserException when a request try to acces a protected area | [
"Start",
"the",
"MVC",
"Loop",
"from",
"the",
"ClearFW"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/mvc/Bootstrap.php#L330-L336 |
oat-sa/tao-core | models/classes/mvc/Bootstrap.php | Bootstrap.scripts | protected function scripts()
{
$assetService = $this->getServiceLocator()->get(AssetService::SERVICE_ID);
$cssFiles = [
$assetService->getAsset('css/layout.css', 'tao'),
$assetService->getAsset('css/tao-main-style.css', 'tao'),
$assetService->getAsset('css/tao-3.css', 'tao')
];
//stylesheets to load
\tao_helpers_Scriptloader::addCssFiles($cssFiles);
if(\common_session_SessionManager::isAnonymous()) {
\tao_helpers_Scriptloader::addCssFile(
$assetService->getAsset('css/portal.css', 'tao')
);
}
} | php | protected function scripts()
{
$assetService = $this->getServiceLocator()->get(AssetService::SERVICE_ID);
$cssFiles = [
$assetService->getAsset('css/layout.css', 'tao'),
$assetService->getAsset('css/tao-main-style.css', 'tao'),
$assetService->getAsset('css/tao-3.css', 'tao')
];
//stylesheets to load
\tao_helpers_Scriptloader::addCssFiles($cssFiles);
if(\common_session_SessionManager::isAnonymous()) {
\tao_helpers_Scriptloader::addCssFile(
$assetService->getAsset('css/portal.css', 'tao')
);
}
} | [
"protected",
"function",
"scripts",
"(",
")",
"{",
"$",
"assetService",
"=",
"$",
"this",
"->",
"getServiceLocator",
"(",
")",
"->",
"get",
"(",
"AssetService",
"::",
"SERVICE_ID",
")",
";",
"$",
"cssFiles",
"=",
"[",
"$",
"assetService",
"->",
"getAsset",... | Load external resources for the current context
@see \tao_helpers_Scriptloader | [
"Load",
"external",
"resources",
"for",
"the",
"current",
"context"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/mvc/Bootstrap.php#L342-L359 |
oat-sa/tao-core | helpers/class.Icon.php | tao_helpers_Icon.buildIcon | protected static function buildIcon($icon, $options=array()){
$options['class'] = !empty($options['class']) ? $options['class'] . ' ' . $icon : $icon;
$element = !empty($options['element']) ? $options['element'] : 'span';
unset($options['element']);
$retVal = '<' . $element . ' ';
foreach($options as $key => $value) {
$retVal .= $key . '="' . $value . '"';
}
$retVal .= '></' . $element . '>';
return $retVal;
} | php | protected static function buildIcon($icon, $options=array()){
$options['class'] = !empty($options['class']) ? $options['class'] . ' ' . $icon : $icon;
$element = !empty($options['element']) ? $options['element'] : 'span';
unset($options['element']);
$retVal = '<' . $element . ' ';
foreach($options as $key => $value) {
$retVal .= $key . '="' . $value . '"';
}
$retVal .= '></' . $element . '>';
return $retVal;
} | [
"protected",
"static",
"function",
"buildIcon",
"(",
"$",
"icon",
",",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"$",
"options",
"[",
"'class'",
"]",
"=",
"!",
"empty",
"(",
"$",
"options",
"[",
"'class'",
"]",
")",
"?",
"$",
"options",
"["... | This function builds the actual HTML element and is used by all other functions.
The doc for $options is the applicable for all other functions.
@param string $icon name of the icon to display
@param array $options (optional) hashtable with HTML attributes, also allows to set element="almostAnyHtmlElement"
@param string HTML element with icon | [
"This",
"function",
"builds",
"the",
"actual",
"HTML",
"element",
"and",
"is",
"used",
"by",
"all",
"other",
"functions",
".",
"The",
"doc",
"for",
"$options",
"is",
"the",
"applicable",
"for",
"all",
"other",
"functions",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/class.Icon.php#L44-L54 |
oat-sa/tao-core | actions/form/class.RestUserForm.php | tao_actions_form_RestUserForm.getData | public function getData()
{
$properties = $this->formProperties;
foreach ($properties as $index => $property) {
if ($this->doesExist() && $property['uri'] == 'http://www.tao.lu/Ontologies/generis.rdf#login') {
$properties[$index]['widget'] = 'http://www.tao.lu/datatypes/WidgetDefinitions.rdf#Readonly';
break;
}
}
if ($this->doesExist()) {
foreach ($properties as $key => $property) {
if ($property['uri'] == GenerisRdf::PROPERTY_USER_PASSWORD && isset($property['value'])) {
$properties[$key]['value'] = '';
break;
}
}
}
return [
self::PROPERTIES => $properties,
self::RANGES => $this->ranges,
];
} | php | public function getData()
{
$properties = $this->formProperties;
foreach ($properties as $index => $property) {
if ($this->doesExist() && $property['uri'] == 'http://www.tao.lu/Ontologies/generis.rdf#login') {
$properties[$index]['widget'] = 'http://www.tao.lu/datatypes/WidgetDefinitions.rdf#Readonly';
break;
}
}
if ($this->doesExist()) {
foreach ($properties as $key => $property) {
if ($property['uri'] == GenerisRdf::PROPERTY_USER_PASSWORD && isset($property['value'])) {
$properties[$key]['value'] = '';
break;
}
}
}
return [
self::PROPERTIES => $properties,
self::RANGES => $this->ranges,
];
} | [
"public",
"function",
"getData",
"(",
")",
"{",
"$",
"properties",
"=",
"$",
"this",
"->",
"formProperties",
";",
"foreach",
"(",
"$",
"properties",
"as",
"$",
"index",
"=>",
"$",
"property",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"doesExist",
"(",
... | Get the form data.
Set readOnly to login in case of edition.
Add password and password confirmation with different label depending creation or edition
@return array | [
"Get",
"the",
"form",
"data",
".",
"Set",
"readOnly",
"to",
"login",
"in",
"case",
"of",
"edition",
".",
"Add",
"password",
"and",
"password",
"confirmation",
"with",
"different",
"label",
"depending",
"creation",
"or",
"edition"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/form/class.RestUserForm.php#L47-L71 |
oat-sa/tao-core | actions/form/class.RestUserForm.php | tao_actions_form_RestUserForm.validate | public function validate()
{
$report = parent::validate();
$password = null;
foreach ($this->formProperties as $key => $property) {
if ($property['uri'] == GenerisRdf::PROPERTY_USER_PASSWORD && !empty($this->formProperties[$key]['formValue'])) {
$password = $this->formProperties[$key]['formValue'];
break;
}
}
if ($this->isNew() || ($this->doesExist() && !is_null($password))) {
try {
$this->validatePassword($password);
$this->changePassword = true;
} catch (common_exception_ValidationFailed $e) {
$subReport = common_report_Report::createFailure($e->getMessage());
$subReport->setData(GenerisRdf::PROPERTY_USER_PASSWORD);
$report->add($subReport);
}
}
// Validate new login availability
if ($this->isNew()) {
foreach($this->formProperties as $property) {
if ( $property['uri'] == 'http://www.tao.lu/Ontologies/generis.rdf#login') {
if ( empty($property['formValue']) ) {
$subReport = common_report_Report::createFailure(__('Login is empty.'));
} else if ( ! $this->isLoginAvailable($property['formValue']) ) {
$subReport = common_report_Report::createFailure(__('Login is already in use.'));
}
if ( isset($subReport) ) {
$subReport->setData($property['uri']);
$report->add($subReport);
}
}
}
}
return $report;
} | php | public function validate()
{
$report = parent::validate();
$password = null;
foreach ($this->formProperties as $key => $property) {
if ($property['uri'] == GenerisRdf::PROPERTY_USER_PASSWORD && !empty($this->formProperties[$key]['formValue'])) {
$password = $this->formProperties[$key]['formValue'];
break;
}
}
if ($this->isNew() || ($this->doesExist() && !is_null($password))) {
try {
$this->validatePassword($password);
$this->changePassword = true;
} catch (common_exception_ValidationFailed $e) {
$subReport = common_report_Report::createFailure($e->getMessage());
$subReport->setData(GenerisRdf::PROPERTY_USER_PASSWORD);
$report->add($subReport);
}
}
// Validate new login availability
if ($this->isNew()) {
foreach($this->formProperties as $property) {
if ( $property['uri'] == 'http://www.tao.lu/Ontologies/generis.rdf#login') {
if ( empty($property['formValue']) ) {
$subReport = common_report_Report::createFailure(__('Login is empty.'));
} else if ( ! $this->isLoginAvailable($property['formValue']) ) {
$subReport = common_report_Report::createFailure(__('Login is already in use.'));
}
if ( isset($subReport) ) {
$subReport->setData($property['uri']);
$report->add($subReport);
}
}
}
}
return $report;
} | [
"public",
"function",
"validate",
"(",
")",
"{",
"$",
"report",
"=",
"parent",
"::",
"validate",
"(",
")",
";",
"$",
"password",
"=",
"null",
";",
"foreach",
"(",
"$",
"this",
"->",
"formProperties",
"as",
"$",
"key",
"=>",
"$",
"property",
")",
"{",... | Validate the form against the property validators.
In case of range, check if value belong to associated ranges list
@return common_report_Report | [
"Validate",
"the",
"form",
"against",
"the",
"property",
"validators",
".",
"In",
"case",
"of",
"range",
"check",
"if",
"value",
"belong",
"to",
"associated",
"ranges",
"list"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/form/class.RestUserForm.php#L79-L121 |
oat-sa/tao-core | actions/form/class.RestUserForm.php | tao_actions_form_RestUserForm.getPropertyValidators | protected function getPropertyValidators(core_kernel_classes_Property $property)
{
$validators = parent::getPropertyValidators($property);
$notEmptyProperties = [
GenerisRdf::PROPERTY_USER_UILG,
GenerisRdf::PROPERTY_USER_ROLES,
OntologyRdfs::RDFS_LABEL,
];
if ($this->isNew()) {
$notEmptyProperties[] = GenerisRdf::PROPERTY_USER_PASSWORD;
$notEmptyProperties[] = 'http://www.tao.lu/Ontologies/generis.rdf#login';
}
if (in_array($property->getUri(), $notEmptyProperties)) {
$validators[] = 'notEmpty';
}
return $validators;
} | php | protected function getPropertyValidators(core_kernel_classes_Property $property)
{
$validators = parent::getPropertyValidators($property);
$notEmptyProperties = [
GenerisRdf::PROPERTY_USER_UILG,
GenerisRdf::PROPERTY_USER_ROLES,
OntologyRdfs::RDFS_LABEL,
];
if ($this->isNew()) {
$notEmptyProperties[] = GenerisRdf::PROPERTY_USER_PASSWORD;
$notEmptyProperties[] = 'http://www.tao.lu/Ontologies/generis.rdf#login';
}
if (in_array($property->getUri(), $notEmptyProperties)) {
$validators[] = 'notEmpty';
}
return $validators;
} | [
"protected",
"function",
"getPropertyValidators",
"(",
"core_kernel_classes_Property",
"$",
"property",
")",
"{",
"$",
"validators",
"=",
"parent",
"::",
"getPropertyValidators",
"(",
"$",
"property",
")",
";",
"$",
"notEmptyProperties",
"=",
"[",
"GenerisRdf",
"::"... | Get validators of a property.
Add not empty validator to user to languages and roles properties
@param core_kernel_classes_Property $property
@return array | [
"Get",
"validators",
"of",
"a",
"property",
".",
"Add",
"not",
"empty",
"validator",
"to",
"user",
"to",
"languages",
"and",
"roles",
"properties"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/form/class.RestUserForm.php#L130-L150 |
oat-sa/tao-core | actions/form/class.RestUserForm.php | tao_actions_form_RestUserForm.validatePassword | protected function validatePassword($password)
{
if (!(new tao_helpers_form_validators_NotEmpty())->evaluate($password)) {
throw new common_exception_ValidationFailed(GenerisRdf::PROPERTY_USER_PASSWORD, __('Password is empty.'));
}
/** @var ValidatorInterface $validator */
foreach (PasswordConstraintsService::singleton()->getValidators() as $validator) {
if (!$validator->evaluate($password)) {
throw new common_exception_ValidationFailed(GenerisRdf::PROPERTY_USER_PASSWORD, $validator->getMessage());
}
}
} | php | protected function validatePassword($password)
{
if (!(new tao_helpers_form_validators_NotEmpty())->evaluate($password)) {
throw new common_exception_ValidationFailed(GenerisRdf::PROPERTY_USER_PASSWORD, __('Password is empty.'));
}
/** @var ValidatorInterface $validator */
foreach (PasswordConstraintsService::singleton()->getValidators() as $validator) {
if (!$validator->evaluate($password)) {
throw new common_exception_ValidationFailed(GenerisRdf::PROPERTY_USER_PASSWORD, $validator->getMessage());
}
}
} | [
"protected",
"function",
"validatePassword",
"(",
"$",
"password",
")",
"{",
"if",
"(",
"!",
"(",
"new",
"tao_helpers_form_validators_NotEmpty",
"(",
")",
")",
"->",
"evaluate",
"(",
"$",
"password",
")",
")",
"{",
"throw",
"new",
"common_exception_ValidationFai... | Validate password by evaluate it against PasswordConstraintService and NotEmpty validators
@param $password
@throws common_exception_ValidationFailed If invalid | [
"Validate",
"password",
"by",
"evaluate",
"it",
"against",
"PasswordConstraintService",
"and",
"NotEmpty",
"validators"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/form/class.RestUserForm.php#L158-L170 |
oat-sa/tao-core | actions/form/class.RestUserForm.php | tao_actions_form_RestUserForm.prepareValuesToSave | protected function prepareValuesToSave()
{
$values = parent::prepareValuesToSave();
if ($this->changePassword) {
$password = null;
foreach ($this->formProperties as $key => $property) {
if ($property['uri'] == GenerisRdf::PROPERTY_USER_PASSWORD && isset($this->formProperties[$key]['formValue'])) {
$password = $this->formProperties[$key]['formValue'];
break;
}
}
$values[GenerisRdf::PROPERTY_USER_PASSWORD] = core_kernel_users_Service::getPasswordHash()->encrypt($password);
}
return $values;
} | php | protected function prepareValuesToSave()
{
$values = parent::prepareValuesToSave();
if ($this->changePassword) {
$password = null;
foreach ($this->formProperties as $key => $property) {
if ($property['uri'] == GenerisRdf::PROPERTY_USER_PASSWORD && isset($this->formProperties[$key]['formValue'])) {
$password = $this->formProperties[$key]['formValue'];
break;
}
}
$values[GenerisRdf::PROPERTY_USER_PASSWORD] = core_kernel_users_Service::getPasswordHash()->encrypt($password);
}
return $values;
} | [
"protected",
"function",
"prepareValuesToSave",
"(",
")",
"{",
"$",
"values",
"=",
"parent",
"::",
"prepareValuesToSave",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"changePassword",
")",
"{",
"$",
"password",
"=",
"null",
";",
"foreach",
"(",
"$",
"th... | Prepare form properties values to be saved.
Remove form fields for password and create a new one with encrypted value.
@return array | [
"Prepare",
"form",
"properties",
"values",
"to",
"be",
"saved",
".",
"Remove",
"form",
"fields",
"for",
"password",
"and",
"create",
"a",
"new",
"one",
"with",
"encrypted",
"value",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/form/class.RestUserForm.php#L178-L194 |
oat-sa/tao-core | helpers/class.Duration.php | tao_helpers_Duration.timetoDuration | public static function timetoDuration($time)
{
$duration = 'PT';
$regexp = "/^([0-9]{2}):([0-9]{2}):([0-9]{2})(\.[0-9]{1,6})?$/";
if (preg_match($regexp, $time, $matches)) {
$duration .= intval($matches[1]) . 'H' . intval($matches[2]) . 'M';
$duration .= isset($matches[4])
? intval($matches[3]) . $matches[4] . 'S'
: intval($matches[3]) . 'S';
} else {
$duration .= '0S';
}
return $duration;
} | php | public static function timetoDuration($time)
{
$duration = 'PT';
$regexp = "/^([0-9]{2}):([0-9]{2}):([0-9]{2})(\.[0-9]{1,6})?$/";
if (preg_match($regexp, $time, $matches)) {
$duration .= intval($matches[1]) . 'H' . intval($matches[2]) . 'M';
$duration .= isset($matches[4])
? intval($matches[3]) . $matches[4] . 'S'
: intval($matches[3]) . 'S';
} else {
$duration .= '0S';
}
return $duration;
} | [
"public",
"static",
"function",
"timetoDuration",
"(",
"$",
"time",
")",
"{",
"$",
"duration",
"=",
"'PT'",
";",
"$",
"regexp",
"=",
"\"/^([0-9]{2}):([0-9]{2}):([0-9]{2})(\\.[0-9]{1,6})?$/\"",
";",
"if",
"(",
"preg_match",
"(",
"$",
"regexp",
",",
"$",
"time",
... | Converts a time string to an ISO8601 duration
@param string $time as hh:mm:ss.micros
@return string the ISO duration | [
"Converts",
"a",
"time",
"string",
"to",
"an",
"ISO8601",
"duration"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/class.Duration.php#L38-L54 |
oat-sa/tao-core | helpers/class.Duration.php | tao_helpers_Duration.intervalToTime | public static function intervalToTime(DateInterval $interval)
{
$time = null;
if (!is_null($interval)) {
$format = property_exists(get_class($interval), 'u') ? '%H:%I:%S.%U' : '%H:%I:%S';
$time = $interval->format($format);
}
return $time;
} | php | public static function intervalToTime(DateInterval $interval)
{
$time = null;
if (!is_null($interval)) {
$format = property_exists(get_class($interval), 'u') ? '%H:%I:%S.%U' : '%H:%I:%S';
$time = $interval->format($format);
}
return $time;
} | [
"public",
"static",
"function",
"intervalToTime",
"(",
"DateInterval",
"$",
"interval",
")",
"{",
"$",
"time",
"=",
"null",
";",
"if",
"(",
"!",
"is_null",
"(",
"$",
"interval",
")",
")",
"{",
"$",
"format",
"=",
"property_exists",
"(",
"get_class",
"(",... | Converts an interval to a time
@param DateInterval $interval
@return string time hh:mm:ss | [
"Converts",
"an",
"interval",
"to",
"a",
"time"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/class.Duration.php#L61-L71 |
oat-sa/tao-core | helpers/class.Duration.php | tao_helpers_Duration.durationToTime | public static function durationToTime($duration)
{
$time = null;
try {
$interval = preg_match('/(\.[0-9]{1,6}S)$/', $duration)
? new DateIntervalMS($duration)
: new DateInterval($duration);
$time = self::intervalToTime($interval);
} catch (Exception $e) {
common_Logger::e($e->getMessage());
}
return $time;
} | php | public static function durationToTime($duration)
{
$time = null;
try {
$interval = preg_match('/(\.[0-9]{1,6}S)$/', $duration)
? new DateIntervalMS($duration)
: new DateInterval($duration);
$time = self::intervalToTime($interval);
} catch (Exception $e) {
common_Logger::e($e->getMessage());
}
return $time;
} | [
"public",
"static",
"function",
"durationToTime",
"(",
"$",
"duration",
")",
"{",
"$",
"time",
"=",
"null",
";",
"try",
"{",
"$",
"interval",
"=",
"preg_match",
"(",
"'/(\\.[0-9]{1,6}S)$/'",
",",
"$",
"duration",
")",
"?",
"new",
"DateIntervalMS",
"(",
"$"... | Converts a duration to a time
@param string $duration the ISO duration
@return string time hh:mm:ss.micros | [
"Converts",
"a",
"duration",
"to",
"a",
"time"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/class.Duration.php#L78-L92 |
oat-sa/tao-core | models/classes/search/index/OntologyIndex.php | OntologyIndex.getOneCached | private function getOneCached($propertyUri)
{
if (is_null($this->cached)) {
$props = array(static::PROPERTY_INDEX_IDENTIFIER, static::PROPERTY_INDEX_TOKENIZER, static::PROPERTY_INDEX_FUZZY_MATCHING, static::PROPERTY_DEFAULT_SEARCH);
$this->cached = $this->getPropertiesValues($props);
}
return empty($this->cached[$propertyUri]) ? null : reset($this->cached[$propertyUri]);
} | php | private function getOneCached($propertyUri)
{
if (is_null($this->cached)) {
$props = array(static::PROPERTY_INDEX_IDENTIFIER, static::PROPERTY_INDEX_TOKENIZER, static::PROPERTY_INDEX_FUZZY_MATCHING, static::PROPERTY_DEFAULT_SEARCH);
$this->cached = $this->getPropertiesValues($props);
}
return empty($this->cached[$propertyUri]) ? null : reset($this->cached[$propertyUri]);
} | [
"private",
"function",
"getOneCached",
"(",
"$",
"propertyUri",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"cached",
")",
")",
"{",
"$",
"props",
"=",
"array",
"(",
"static",
"::",
"PROPERTY_INDEX_IDENTIFIER",
",",
"static",
"::",
"PROPERTY_IN... | Preload all the index properties and return the
property requested
@param string $propertyUri
@return Ambigous <NULL, mixed> | [
"Preload",
"all",
"the",
"index",
"properties",
"and",
"return",
"the",
"property",
"requested"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/search/index/OntologyIndex.php#L45-L52 |
oat-sa/tao-core | models/classes/search/index/OntologyIndex.php | OntologyIndex.isFuzzyMatching | public function isFuzzyMatching()
{
$res = $this->getOneCached(static::PROPERTY_INDEX_FUZZY_MATCHING);
return !is_null($res) && is_object($res) && $res->getUri() == GenerisRdf::GENERIS_TRUE;
} | php | public function isFuzzyMatching()
{
$res = $this->getOneCached(static::PROPERTY_INDEX_FUZZY_MATCHING);
return !is_null($res) && is_object($res) && $res->getUri() == GenerisRdf::GENERIS_TRUE;
} | [
"public",
"function",
"isFuzzyMatching",
"(",
")",
"{",
"$",
"res",
"=",
"$",
"this",
"->",
"getOneCached",
"(",
"static",
"::",
"PROPERTY_INDEX_FUZZY_MATCHING",
")",
";",
"return",
"!",
"is_null",
"(",
"$",
"res",
")",
"&&",
"is_object",
"(",
"$",
"res",
... | Should the string matching be fuzzy
defaults to false if no information present
@return boolean | [
"Should",
"the",
"string",
"matching",
"be",
"fuzzy",
"defaults",
"to",
"false",
"if",
"no",
"information",
"present"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/search/index/OntologyIndex.php#L79-L83 |
oat-sa/tao-core | models/classes/search/index/OntologyIndex.php | OntologyIndex.isDefaultSearchable | public function isDefaultSearchable()
{
$res = $this->getOneCached(static::PROPERTY_DEFAULT_SEARCH);
return !is_null($res) && is_object($res) && $res->getUri() == GenerisRdf::GENERIS_TRUE;
} | php | public function isDefaultSearchable()
{
$res = $this->getOneCached(static::PROPERTY_DEFAULT_SEARCH);
return !is_null($res) && is_object($res) && $res->getUri() == GenerisRdf::GENERIS_TRUE;
} | [
"public",
"function",
"isDefaultSearchable",
"(",
")",
"{",
"$",
"res",
"=",
"$",
"this",
"->",
"getOneCached",
"(",
"static",
"::",
"PROPERTY_DEFAULT_SEARCH",
")",
";",
"return",
"!",
"is_null",
"(",
"$",
"res",
")",
"&&",
"is_object",
"(",
"$",
"res",
... | Should the property be used by default if no index key is specified
defaults to false if no information present
@return boolean | [
"Should",
"the",
"property",
"be",
"used",
"by",
"default",
"if",
"no",
"index",
"key",
"is",
"specified",
"defaults",
"to",
"false",
"if",
"no",
"information",
"present"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/search/index/OntologyIndex.php#L91-L95 |
oat-sa/tao-core | helpers/class.I18n.php | tao_helpers_I18n.init | public static function init(common_ext_Extension $extension, $langCode)
{
// if the langCode is empty do nothing
if (empty($langCode)){
throw new Exception("Language is not defined");
}
//init the ClearFw l10n tools
$translations = tao_models_classes_LanguageService::singleton()->getServerBundle($langCode);
l10n::init($translations);
$serviceManager = \oat\oatbox\service\ServiceManager::getServiceManager();
$extraPoService = $serviceManager->get(\oat\tao\model\i18n\ExtraPoService::SERVICE_ID);
$extraPoCount = $extraPoService->requirePos();
} | php | public static function init(common_ext_Extension $extension, $langCode)
{
// if the langCode is empty do nothing
if (empty($langCode)){
throw new Exception("Language is not defined");
}
//init the ClearFw l10n tools
$translations = tao_models_classes_LanguageService::singleton()->getServerBundle($langCode);
l10n::init($translations);
$serviceManager = \oat\oatbox\service\ServiceManager::getServiceManager();
$extraPoService = $serviceManager->get(\oat\tao\model\i18n\ExtraPoService::SERVICE_ID);
$extraPoCount = $extraPoService->requirePos();
} | [
"public",
"static",
"function",
"init",
"(",
"common_ext_Extension",
"$",
"extension",
",",
"$",
"langCode",
")",
"{",
"// if the langCode is empty do nothing",
"if",
"(",
"empty",
"(",
"$",
"langCode",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"Languag... | Load the translation strings
@access public
@author Jerome Bogaerts, <jerome.bogaerts@tudor.lu>
@param common_ext_Extension $extension
@param string langCode
@return mixed | [
"Load",
"the",
"translation",
"strings"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/class.I18n.php#L59-L73 |
oat-sa/tao-core | helpers/class.I18n.php | tao_helpers_I18n.getLangResourceByCode | public static function getLangResourceByCode($code)
{
$langs = self::getAvailableLangs();
return isset($langs[$code]) ? new core_kernel_classes_Resource($langs[$code]['uri']) : null;
} | php | public static function getLangResourceByCode($code)
{
$langs = self::getAvailableLangs();
return isset($langs[$code]) ? new core_kernel_classes_Resource($langs[$code]['uri']) : null;
} | [
"public",
"static",
"function",
"getLangResourceByCode",
"(",
"$",
"code",
")",
"{",
"$",
"langs",
"=",
"self",
"::",
"getAvailableLangs",
"(",
")",
";",
"return",
"isset",
"(",
"$",
"langs",
"[",
"$",
"code",
"]",
")",
"?",
"new",
"core_kernel_classes_Res... | Returns the code of a resource
@access public
@author Jerome Bogaerts, <jerome.bogaerts@tudor.lu>
@param string code
@return core_kernel_classes_Resource | [
"Returns",
"the",
"code",
"of",
"a",
"resource"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/class.I18n.php#L94-L98 |
oat-sa/tao-core | helpers/class.I18n.php | tao_helpers_I18n.getAvailableLangs | private static function getAvailableLangs()
{
//get it into the api only once
if(count(self::$availableLangs) == 0){
try {
self::$availableLangs = common_cache_FileCache::singleton()->get(self::AVAILABLE_LANGS_CACHEKEY);
} catch (common_cache_NotFoundException $e) {
$langClass = new core_kernel_classes_Class(tao_models_classes_LanguageService::CLASS_URI_LANGUAGES);
$valueProperty = new core_kernel_classes_Property(OntologyRdf::RDF_VALUE);
foreach($langClass->getInstances() as $lang){
$values = $lang->getPropertiesValues(array(
OntologyRdf::RDF_VALUE,
tao_models_classes_LanguageService::PROPERTY_LANGUAGE_USAGES,
tao_models_classes_LanguageService::PROPERTY_LANGUAGE_ORIENTATION
));
if (count($values[OntologyRdf::RDF_VALUE]) != 1) {
throw new common_exception_InconsistentData('Error with value of language '.$lang->getUri());
}
$value = current($values[OntologyRdf::RDF_VALUE])->__toString();
$usages = array();
foreach ($values[tao_models_classes_LanguageService::PROPERTY_LANGUAGE_USAGES] as $usage) {
$usages[] = $usage->getUri();
}
if (count($values[tao_models_classes_LanguageService::PROPERTY_LANGUAGE_ORIENTATION]) != 1) {
common_Logger::w('Error with orientation of language '.$lang->getUri());
$orientation = tao_models_classes_LanguageService::INSTANCE_ORIENTATION_LTR;
} else {
$orientation = current($values[tao_models_classes_LanguageService::PROPERTY_LANGUAGE_ORIENTATION ])->getUri();
}
self::$availableLangs[$value] = array(
'uri' => $lang->getUri(),
tao_models_classes_LanguageService::PROPERTY_LANGUAGE_USAGES => $usages,
tao_models_classes_LanguageService::PROPERTY_LANGUAGE_ORIENTATION => $orientation
);
}
common_cache_FileCache::singleton()->put(self::$availableLangs, self::AVAILABLE_LANGS_CACHEKEY);
}
}
return self::$availableLangs;
} | php | private static function getAvailableLangs()
{
//get it into the api only once
if(count(self::$availableLangs) == 0){
try {
self::$availableLangs = common_cache_FileCache::singleton()->get(self::AVAILABLE_LANGS_CACHEKEY);
} catch (common_cache_NotFoundException $e) {
$langClass = new core_kernel_classes_Class(tao_models_classes_LanguageService::CLASS_URI_LANGUAGES);
$valueProperty = new core_kernel_classes_Property(OntologyRdf::RDF_VALUE);
foreach($langClass->getInstances() as $lang){
$values = $lang->getPropertiesValues(array(
OntologyRdf::RDF_VALUE,
tao_models_classes_LanguageService::PROPERTY_LANGUAGE_USAGES,
tao_models_classes_LanguageService::PROPERTY_LANGUAGE_ORIENTATION
));
if (count($values[OntologyRdf::RDF_VALUE]) != 1) {
throw new common_exception_InconsistentData('Error with value of language '.$lang->getUri());
}
$value = current($values[OntologyRdf::RDF_VALUE])->__toString();
$usages = array();
foreach ($values[tao_models_classes_LanguageService::PROPERTY_LANGUAGE_USAGES] as $usage) {
$usages[] = $usage->getUri();
}
if (count($values[tao_models_classes_LanguageService::PROPERTY_LANGUAGE_ORIENTATION]) != 1) {
common_Logger::w('Error with orientation of language '.$lang->getUri());
$orientation = tao_models_classes_LanguageService::INSTANCE_ORIENTATION_LTR;
} else {
$orientation = current($values[tao_models_classes_LanguageService::PROPERTY_LANGUAGE_ORIENTATION ])->getUri();
}
self::$availableLangs[$value] = array(
'uri' => $lang->getUri(),
tao_models_classes_LanguageService::PROPERTY_LANGUAGE_USAGES => $usages,
tao_models_classes_LanguageService::PROPERTY_LANGUAGE_ORIENTATION => $orientation
);
}
common_cache_FileCache::singleton()->put(self::$availableLangs, self::AVAILABLE_LANGS_CACHEKEY);
}
}
return self::$availableLangs;
} | [
"private",
"static",
"function",
"getAvailableLangs",
"(",
")",
"{",
"//get it into the api only once ",
"if",
"(",
"count",
"(",
"self",
"::",
"$",
"availableLangs",
")",
"==",
"0",
")",
"{",
"try",
"{",
"self",
"::",
"$",
"availableLangs",
"=",
"common_cache... | This method returns the languages available in TAO.
@access public
@author Jerome Bogaerts, <jerome.bogaerts@tudor.lu>
@param boolean langName If set to true, an associative array where keys are language codes and values are language labels. If set to false (default), a simple array of language codes is returned.
@return array
@throws common_exception_InconsistentData | [
"This",
"method",
"returns",
"the",
"languages",
"available",
"in",
"TAO",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/class.I18n.php#L121-L161 |
oat-sa/tao-core | helpers/class.I18n.php | tao_helpers_I18n.getAvailableLangsByUsage | public static function getAvailableLangsByUsage( core_kernel_classes_Resource $usage)
{
$returnValue = array();
foreach (self::getAvailableLangs() as $code => $langData) {
if (in_array($usage->getUri(), $langData[tao_models_classes_LanguageService::PROPERTY_LANGUAGE_USAGES])) {
$lang = new core_kernel_classes_Resource($langData['uri']);
$returnValue[$code] = $lang->getLabel();
}
}
return $returnValue;
} | php | public static function getAvailableLangsByUsage( core_kernel_classes_Resource $usage)
{
$returnValue = array();
foreach (self::getAvailableLangs() as $code => $langData) {
if (in_array($usage->getUri(), $langData[tao_models_classes_LanguageService::PROPERTY_LANGUAGE_USAGES])) {
$lang = new core_kernel_classes_Resource($langData['uri']);
$returnValue[$code] = $lang->getLabel();
}
}
return $returnValue;
} | [
"public",
"static",
"function",
"getAvailableLangsByUsage",
"(",
"core_kernel_classes_Resource",
"$",
"usage",
")",
"{",
"$",
"returnValue",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"self",
"::",
"getAvailableLangs",
"(",
")",
"as",
"$",
"code",
"=>",
"$",... | Get available languages from the knownledge base depending on a specific usage.
By default, TAO considers two built-in usages:
* GUI Language ('http://www.tao.lu/Ontologies/TAO.rdf#LanguageUsageGUI')
* Data Language ('http://www.tao.lu/Ontologies/TAO.rdf#LanguageUsageData')
@author Jérôme Bogaerts <jerome@taotesting.com>
@param core_kernel_classes_Resource $usage Resource usage An instance of tao:LanguagesUsages from the knowledge base.
@return array An associative array of core_kernel_classes_Resource objects index by language code. | [
"Get",
"available",
"languages",
"from",
"the",
"knownledge",
"base",
"depending",
"on",
"a",
"specific",
"usage",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/class.I18n.php#L175-L186 |
oat-sa/tao-core | helpers/translation/class.StructureExtractor.php | tao_helpers_translation_StructureExtractor.extract | public function extract()
{
$translationUnits = array();
foreach ($this->getPaths() as $file) {
$xml = new \SimpleXMLElement($file, null, true);
if ($xml instanceof SimpleXMLElement){
// look up for "name" attributes of structure elements.
$nodes = $xml->xpath("//structure[@name]|//section[@name]");
foreach ($nodes as $node) {
if (isset($node['name'])) {
$nodeName = (string)$node['name'];
$newTranslationUnit = new tao_helpers_translation_POTranslationUnit();
$newTranslationUnit->setSource($nodeName);
$newTranslationUnit->addFlag('tao-public');
$translationUnits[$nodeName] = $newTranslationUnit;
}
}
// look up for "name" attributes of action elements.
$nodes = $xml->xpath("//action[@name]|//tree[@name]");
foreach ($nodes as $node) {
if (isset($node['name'])) {
$nodeName = (string)$node['name'];
$newTranslationUnit = new tao_helpers_translation_POTranslationUnit();
$newTranslationUnit->setSource($nodeName);
$newTranslationUnit->addFlag('tao-public');
$translationUnits[$nodeName] = $newTranslationUnit;
}
}
// look up for "description" elements.
$nodes = $xml->xpath("//description");
foreach ($nodes as $node) {
if ((string)$node != '') {
$newTranslationUnit = new tao_helpers_translation_POTranslationUnit();
$newTranslationUnit->setSource((string)$node);
$newTranslationUnit->addFlag('tao-public');
$translationUnits[(string)$node] = $newTranslationUnit;
}
}
// look up for "action" elements inside a toolbar
$nodes = $xml->xpath("//toolbar/toolbaraction");
foreach ($nodes as $node) {
$nodeValue = (string)$node;
if (trim($nodeValue) != '' && !array_key_exists($nodeValue, $translationUnits)){
$newTranslationUnit = new tao_helpers_translation_POTranslationUnit();
$newTranslationUnit->setSource($nodeValue);
$newTranslationUnit->addFlag('tao-public');
$translationUnits[$nodeValue] = $newTranslationUnit;
}
}
// look up for the "title" attr of an "action" element inside a toolbar
$nodes = $xml->xpath("//toolbar/toolbaraction[@title]");
foreach ($nodes as $node) {
if (isset($node['title'])) {
$nodeTitle = (string)$node['title'];
$newTranslationUnit = new tao_helpers_translation_POTranslationUnit();
$newTranslationUnit->setSource($nodeTitle);
$newTranslationUnit->addFlag('tao-public');
$translationUnits[$nodeTitle] = $newTranslationUnit;
}
}
// look up for the "entrypoint" elements
$nodes = $xml->xpath("//entrypoint");
foreach ($nodes as $node) {
if (isset($node['title'])) {
$nodeTitle = (string)$node['title'];
$newTranslationUnit = new tao_helpers_translation_POTranslationUnit();
$newTranslationUnit->setSource($nodeTitle);
$newTranslationUnit->addFlag('tao-public');
$translationUnits[$nodeTitle] = $newTranslationUnit;
}
if (isset($node['label'])) {
$nodeLabel = (string)$node['label'];
$newTranslationUnit = new tao_helpers_translation_POTranslationUnit();
$newTranslationUnit->setSource($nodeLabel);
$newTranslationUnit->addFlag('tao-public');
$translationUnits[$nodeTitle] = $newTranslationUnit;
}
}
}
}
$this->setTranslationUnits(array_values($translationUnits));
} | php | public function extract()
{
$translationUnits = array();
foreach ($this->getPaths() as $file) {
$xml = new \SimpleXMLElement($file, null, true);
if ($xml instanceof SimpleXMLElement){
// look up for "name" attributes of structure elements.
$nodes = $xml->xpath("//structure[@name]|//section[@name]");
foreach ($nodes as $node) {
if (isset($node['name'])) {
$nodeName = (string)$node['name'];
$newTranslationUnit = new tao_helpers_translation_POTranslationUnit();
$newTranslationUnit->setSource($nodeName);
$newTranslationUnit->addFlag('tao-public');
$translationUnits[$nodeName] = $newTranslationUnit;
}
}
// look up for "name" attributes of action elements.
$nodes = $xml->xpath("//action[@name]|//tree[@name]");
foreach ($nodes as $node) {
if (isset($node['name'])) {
$nodeName = (string)$node['name'];
$newTranslationUnit = new tao_helpers_translation_POTranslationUnit();
$newTranslationUnit->setSource($nodeName);
$newTranslationUnit->addFlag('tao-public');
$translationUnits[$nodeName] = $newTranslationUnit;
}
}
// look up for "description" elements.
$nodes = $xml->xpath("//description");
foreach ($nodes as $node) {
if ((string)$node != '') {
$newTranslationUnit = new tao_helpers_translation_POTranslationUnit();
$newTranslationUnit->setSource((string)$node);
$newTranslationUnit->addFlag('tao-public');
$translationUnits[(string)$node] = $newTranslationUnit;
}
}
// look up for "action" elements inside a toolbar
$nodes = $xml->xpath("//toolbar/toolbaraction");
foreach ($nodes as $node) {
$nodeValue = (string)$node;
if (trim($nodeValue) != '' && !array_key_exists($nodeValue, $translationUnits)){
$newTranslationUnit = new tao_helpers_translation_POTranslationUnit();
$newTranslationUnit->setSource($nodeValue);
$newTranslationUnit->addFlag('tao-public');
$translationUnits[$nodeValue] = $newTranslationUnit;
}
}
// look up for the "title" attr of an "action" element inside a toolbar
$nodes = $xml->xpath("//toolbar/toolbaraction[@title]");
foreach ($nodes as $node) {
if (isset($node['title'])) {
$nodeTitle = (string)$node['title'];
$newTranslationUnit = new tao_helpers_translation_POTranslationUnit();
$newTranslationUnit->setSource($nodeTitle);
$newTranslationUnit->addFlag('tao-public');
$translationUnits[$nodeTitle] = $newTranslationUnit;
}
}
// look up for the "entrypoint" elements
$nodes = $xml->xpath("//entrypoint");
foreach ($nodes as $node) {
if (isset($node['title'])) {
$nodeTitle = (string)$node['title'];
$newTranslationUnit = new tao_helpers_translation_POTranslationUnit();
$newTranslationUnit->setSource($nodeTitle);
$newTranslationUnit->addFlag('tao-public');
$translationUnits[$nodeTitle] = $newTranslationUnit;
}
if (isset($node['label'])) {
$nodeLabel = (string)$node['label'];
$newTranslationUnit = new tao_helpers_translation_POTranslationUnit();
$newTranslationUnit->setSource($nodeLabel);
$newTranslationUnit->addFlag('tao-public');
$translationUnits[$nodeTitle] = $newTranslationUnit;
}
}
}
}
$this->setTranslationUnits(array_values($translationUnits));
} | [
"public",
"function",
"extract",
"(",
")",
"{",
"$",
"translationUnits",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"getPaths",
"(",
")",
"as",
"$",
"file",
")",
"{",
"$",
"xml",
"=",
"new",
"\\",
"SimpleXMLElement",
"(",
"$",
... | Extracts the translation units from a structures.xml file.
Translation Units can be retrieved after extraction by calling the getTranslationUnits
method.
@access public
@author Jerome Bogaerts <jerome@taotesting.com>
@throws tao_helpers_translation_TranslationException If an error occurs. | [
"Extracts",
"the",
"translation",
"units",
"from",
"a",
"structures",
".",
"xml",
"file",
".",
"Translation",
"Units",
"can",
"be",
"retrieved",
"after",
"extraction",
"by",
"calling",
"the",
"getTranslationUnits",
"method",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/translation/class.StructureExtractor.php#L46-L134 |
oat-sa/tao-core | models/classes/import/class.RdfImporter.php | tao_models_classes_import_RdfImporter.flatImport | protected function flatImport($content, core_kernel_classes_Class $class)
{
$report = common_report_Report::createSuccess(__('Data imported successfully'));
$graph = new EasyRdf_Graph();
$graph->parse($content);
// keep type property
$map = [
OntologyRdf::RDF_PROPERTY => OntologyRdf::RDF_PROPERTY
];
foreach ($graph->resources() as $resource) {
$map[$resource->getUri()] = common_Utils::getNewUri();
}
$format = EasyRdf_Format::getFormat('php');
$data = $graph->serialise($format);
foreach ($data as $subjectUri => $propertiesValues) {
$resource = new core_kernel_classes_Resource($map[$subjectUri]);
$subreport = $this->importProperties($resource, $propertiesValues, $map, $class);
$report->add($subreport);
}
return $report;
} | php | protected function flatImport($content, core_kernel_classes_Class $class)
{
$report = common_report_Report::createSuccess(__('Data imported successfully'));
$graph = new EasyRdf_Graph();
$graph->parse($content);
// keep type property
$map = [
OntologyRdf::RDF_PROPERTY => OntologyRdf::RDF_PROPERTY
];
foreach ($graph->resources() as $resource) {
$map[$resource->getUri()] = common_Utils::getNewUri();
}
$format = EasyRdf_Format::getFormat('php');
$data = $graph->serialise($format);
foreach ($data as $subjectUri => $propertiesValues) {
$resource = new core_kernel_classes_Resource($map[$subjectUri]);
$subreport = $this->importProperties($resource, $propertiesValues, $map, $class);
$report->add($subreport);
}
return $report;
} | [
"protected",
"function",
"flatImport",
"(",
"$",
"content",
",",
"core_kernel_classes_Class",
"$",
"class",
")",
"{",
"$",
"report",
"=",
"common_report_Report",
"::",
"createSuccess",
"(",
"__",
"(",
"'Data imported successfully'",
")",
")",
";",
"$",
"graph",
... | Imports the rdf file into the selected class
@param string $content
@param core_kernel_classes_Class $class
@return common_report_Report | [
"Imports",
"the",
"rdf",
"file",
"into",
"the",
"selected",
"class"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/import/class.RdfImporter.php#L100-L126 |
oat-sa/tao-core | models/classes/import/class.RdfImporter.php | tao_models_classes_import_RdfImporter.importProperties | protected function importProperties(core_kernel_classes_Resource $resource, $propertiesValues, $map, $class)
{
if (isset($propertiesValues[OntologyRdf::RDF_TYPE])) {
// assuming single Type
if (count($propertiesValues[OntologyRdf::RDF_TYPE]) > 1) {
return new common_report_Report(common_report_Report::TYPE_ERROR, __('Resource not imported due to multiple types'));
} else {
foreach ($propertiesValues[OntologyRdf::RDF_TYPE] as $k => $v) {
$classType = isset($map[$v['value']])
? new core_kernel_classes_Class($map[$v['value']])
: $class;
//$resource->setType($classType);
$classType->createInstance(null, null, $resource->getUri());
}
}
unset($propertiesValues[OntologyRdf::RDF_TYPE]);
}
if (isset($propertiesValues[OntologyRdfs::RDFS_SUBCLASSOF])) {
$resource = new core_kernel_classes_Class($resource);
// assuming single subclass
if (isset($propertiesValues[OntologyRdf::RDF_TYPE]) && count($propertiesValues[OntologyRdf::RDF_TYPE]) > 1) {
return new common_report_Report(common_report_Report::TYPE_ERROR, __('Resource not imported due to multiple super classes'));
}
foreach ($propertiesValues[OntologyRdfs::RDFS_SUBCLASSOF] as $k => $v) {
$classSup = isset($map[$v['value']])
? new core_kernel_classes_Class($map[$v['value']])
: $class;
$resource->setSubClassOf($classSup);
}
unset($propertiesValues[OntologyRdfs::RDFS_SUBCLASSOF]);
}
foreach ($propertiesValues as $prop => $values) {
$property = new core_kernel_classes_Property(isset($map[$prop]) ? $map[$prop] : $prop);
foreach ($values as $k => $v) {
$value = isset($map[$v['value']]) ? $map[$v['value']] : $v['value'];
if (isset($v['lang'])) {
$resource->setPropertyValueByLg($property, $value, $v['lang']);
} else {
$resource->setPropertyValue($property, $value);
}
}
}
$msg = $resource instanceof core_kernel_classes_Class
? __('Successfully imported class "%s"', $resource->getLabel())
: __('Successfully imported "%s"', $resource->getLabel());
return new common_report_Report(common_report_Report::TYPE_SUCCESS, $msg, $resource);
} | php | protected function importProperties(core_kernel_classes_Resource $resource, $propertiesValues, $map, $class)
{
if (isset($propertiesValues[OntologyRdf::RDF_TYPE])) {
// assuming single Type
if (count($propertiesValues[OntologyRdf::RDF_TYPE]) > 1) {
return new common_report_Report(common_report_Report::TYPE_ERROR, __('Resource not imported due to multiple types'));
} else {
foreach ($propertiesValues[OntologyRdf::RDF_TYPE] as $k => $v) {
$classType = isset($map[$v['value']])
? new core_kernel_classes_Class($map[$v['value']])
: $class;
//$resource->setType($classType);
$classType->createInstance(null, null, $resource->getUri());
}
}
unset($propertiesValues[OntologyRdf::RDF_TYPE]);
}
if (isset($propertiesValues[OntologyRdfs::RDFS_SUBCLASSOF])) {
$resource = new core_kernel_classes_Class($resource);
// assuming single subclass
if (isset($propertiesValues[OntologyRdf::RDF_TYPE]) && count($propertiesValues[OntologyRdf::RDF_TYPE]) > 1) {
return new common_report_Report(common_report_Report::TYPE_ERROR, __('Resource not imported due to multiple super classes'));
}
foreach ($propertiesValues[OntologyRdfs::RDFS_SUBCLASSOF] as $k => $v) {
$classSup = isset($map[$v['value']])
? new core_kernel_classes_Class($map[$v['value']])
: $class;
$resource->setSubClassOf($classSup);
}
unset($propertiesValues[OntologyRdfs::RDFS_SUBCLASSOF]);
}
foreach ($propertiesValues as $prop => $values) {
$property = new core_kernel_classes_Property(isset($map[$prop]) ? $map[$prop] : $prop);
foreach ($values as $k => $v) {
$value = isset($map[$v['value']]) ? $map[$v['value']] : $v['value'];
if (isset($v['lang'])) {
$resource->setPropertyValueByLg($property, $value, $v['lang']);
} else {
$resource->setPropertyValue($property, $value);
}
}
}
$msg = $resource instanceof core_kernel_classes_Class
? __('Successfully imported class "%s"', $resource->getLabel())
: __('Successfully imported "%s"', $resource->getLabel());
return new common_report_Report(common_report_Report::TYPE_SUCCESS, $msg, $resource);
} | [
"protected",
"function",
"importProperties",
"(",
"core_kernel_classes_Resource",
"$",
"resource",
",",
"$",
"propertiesValues",
",",
"$",
"map",
",",
"$",
"class",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"propertiesValues",
"[",
"OntologyRdf",
"::",
"RDF_TYPE",... | Import the properties of the resource
@param core_kernel_classes_Resource $resource
@param array $propertiesValues
@param array $map
@param core_kernel_classes_Class $class
@return common_report_Report | [
"Import",
"the",
"properties",
"of",
"the",
"resource"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/import/class.RdfImporter.php#L137-L186 |
oat-sa/tao-core | actions/form/class.Import.php | tao_actions_form_Import.initForm | public function initForm()
{
$this->form = tao_helpers_form_FormFactory::getForm('import');
$this->form->setActions(is_null($this->subForm) ? array() : $this->subForm->getActions('top'), 'top');
$this->form->setActions(is_null($this->subForm) ? array() : $this->subForm->getActions('bottom'), 'bottom');
} | php | public function initForm()
{
$this->form = tao_helpers_form_FormFactory::getForm('import');
$this->form->setActions(is_null($this->subForm) ? array() : $this->subForm->getActions('top'), 'top');
$this->form->setActions(is_null($this->subForm) ? array() : $this->subForm->getActions('bottom'), 'bottom');
} | [
"public",
"function",
"initForm",
"(",
")",
"{",
"$",
"this",
"->",
"form",
"=",
"tao_helpers_form_FormFactory",
"::",
"getForm",
"(",
"'import'",
")",
";",
"$",
"this",
"->",
"form",
"->",
"setActions",
"(",
"is_null",
"(",
"$",
"this",
"->",
"subForm",
... | inits the import form
@access public
@author Joel Bout, <joel.bout@tudor.lu>
@return mixed | [
"inits",
"the",
"import",
"form"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/form/class.Import.php#L74-L81 |
oat-sa/tao-core | actions/form/class.Import.php | tao_actions_form_Import.initElements | public function initElements()
{
//create the element to select the import format
$formatElt = tao_helpers_form_FormFactory::getElement('importHandler', 'Radiobox');
$formatElt->setDescription(__('Choose import format'));
$formatElt->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty')); // should never happen anyway
$importHandlerOptions= array();
foreach ($this->importHandlers as $importHandler) {
$importHandlerOptions[get_class($importHandler)] = $importHandler->getLabel();
}
$formatElt->setOptions($importHandlerOptions);
$classUriElt = tao_helpers_form_FormFactory::getElement('classUri', 'Hidden');
// $classUriElt->setValue($class->getUri());
$this->form->addElement($classUriElt);
$classUriElt = tao_helpers_form_FormFactory::getElement('id', 'Hidden');
$this->form->addElement($classUriElt);
$this->form->addElement($formatElt);
if (!is_null($this->subForm)) {
// load dynamically the method regarding the selected format
$this->form->setElements(array_merge($this->form->getElements(), $this->subForm->getElements()));
foreach ($this->subForm->getGroups() as $key => $group) {
$this->form->createGroup($key,$group['title'],$group['elements'],$group['options']);
}
}
} | php | public function initElements()
{
//create the element to select the import format
$formatElt = tao_helpers_form_FormFactory::getElement('importHandler', 'Radiobox');
$formatElt->setDescription(__('Choose import format'));
$formatElt->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty')); // should never happen anyway
$importHandlerOptions= array();
foreach ($this->importHandlers as $importHandler) {
$importHandlerOptions[get_class($importHandler)] = $importHandler->getLabel();
}
$formatElt->setOptions($importHandlerOptions);
$classUriElt = tao_helpers_form_FormFactory::getElement('classUri', 'Hidden');
// $classUriElt->setValue($class->getUri());
$this->form->addElement($classUriElt);
$classUriElt = tao_helpers_form_FormFactory::getElement('id', 'Hidden');
$this->form->addElement($classUriElt);
$this->form->addElement($formatElt);
if (!is_null($this->subForm)) {
// load dynamically the method regarding the selected format
$this->form->setElements(array_merge($this->form->getElements(), $this->subForm->getElements()));
foreach ($this->subForm->getGroups() as $key => $group) {
$this->form->createGroup($key,$group['title'],$group['elements'],$group['options']);
}
}
} | [
"public",
"function",
"initElements",
"(",
")",
"{",
"//create the element to select the import format",
"$",
"formatElt",
"=",
"tao_helpers_form_FormFactory",
"::",
"getElement",
"(",
"'importHandler'",
",",
"'Radiobox'",
")",
";",
"$",
"formatElt",
"->",
"setDescription... | Inits the element to select the importhandler
and takes over the elements of the import form
@access public
@author Joel Bout, <joel.bout@tudor.lu>
@return mixed | [
"Inits",
"the",
"element",
"to",
"select",
"the",
"importhandler",
"and",
"takes",
"over",
"the",
"elements",
"of",
"the",
"import",
"form"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/form/class.Import.php#L91-L120 |
oat-sa/tao-core | models/classes/clientConfig/ClientConfigService.php | ClientConfigService.getExtendedConfig | public function getExtendedConfig() {
$config = array();
foreach ($this->getOption(self::OPTION_CONFIG_SOURCES) as $key => $source) {
$config[$key] = $source->getConfig();
}
return $config;
} | php | public function getExtendedConfig() {
$config = array();
foreach ($this->getOption(self::OPTION_CONFIG_SOURCES) as $key => $source) {
$config[$key] = $source->getConfig();
}
return $config;
} | [
"public",
"function",
"getExtendedConfig",
"(",
")",
"{",
"$",
"config",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"getOption",
"(",
"self",
"::",
"OPTION_CONFIG_SOURCES",
")",
"as",
"$",
"key",
"=>",
"$",
"source",
")",
"{",
"$",... | Returns an array of json serialisable content
to be send to the client json encoded
@return array | [
"Returns",
"an",
"array",
"of",
"json",
"serialisable",
"content",
"to",
"be",
"send",
"to",
"the",
"client",
"json",
"encoded"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/clientConfig/ClientConfigService.php#L39-L45 |
oat-sa/tao-core | models/classes/clientConfig/ClientConfigService.php | ClientConfigService.setClientConfig | public function setClientConfig($id, ClientConfig $configSource) {
$sources = $this->hasOption(self::OPTION_CONFIG_SOURCES)
? $this->getOption(self::OPTION_CONFIG_SOURCES)
: array()
;
$sources[$id] = $configSource;
$this->setOption(self::OPTION_CONFIG_SOURCES, $sources);
} | php | public function setClientConfig($id, ClientConfig $configSource) {
$sources = $this->hasOption(self::OPTION_CONFIG_SOURCES)
? $this->getOption(self::OPTION_CONFIG_SOURCES)
: array()
;
$sources[$id] = $configSource;
$this->setOption(self::OPTION_CONFIG_SOURCES, $sources);
} | [
"public",
"function",
"setClientConfig",
"(",
"$",
"id",
",",
"ClientConfig",
"$",
"configSource",
")",
"{",
"$",
"sources",
"=",
"$",
"this",
"->",
"hasOption",
"(",
"self",
"::",
"OPTION_CONFIG_SOURCES",
")",
"?",
"$",
"this",
"->",
"getOption",
"(",
"se... | Either adds or overrides an existing client config
@param string $id
@param ClientConfig $configSource | [
"Either",
"adds",
"or",
"overrides",
"an",
"existing",
"client",
"config"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/clientConfig/ClientConfigService.php#L53-L60 |
oat-sa/tao-core | models/classes/state/StateMigration.php | StateMigration.archive | public function archive($userId, $callId)
{
/** @var StateStorage $stateStorage */
$stateStorage = $this->getServiceManager()->get(StateStorage::SERVICE_ID);
$state = $stateStorage->get($userId, $callId);
return (!is_null($state)) ? $this->getFileSystem()->write($this->generateSerial($userId, $callId), $state) : false;
} | php | public function archive($userId, $callId)
{
/** @var StateStorage $stateStorage */
$stateStorage = $this->getServiceManager()->get(StateStorage::SERVICE_ID);
$state = $stateStorage->get($userId, $callId);
return (!is_null($state)) ? $this->getFileSystem()->write($this->generateSerial($userId, $callId), $state) : false;
} | [
"public",
"function",
"archive",
"(",
"$",
"userId",
",",
"$",
"callId",
")",
"{",
"/** @var StateStorage $stateStorage */",
"$",
"stateStorage",
"=",
"$",
"this",
"->",
"getServiceManager",
"(",
")",
"->",
"get",
"(",
"StateStorage",
"::",
"SERVICE_ID",
")",
... | Store the state of the service call
@param string $userId
@param string $callId
@return boolean | [
"Store",
"the",
"state",
"of",
"the",
"service",
"call"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/state/StateMigration.php#L62-L71 |
oat-sa/tao-core | helpers/CssHandler.php | CssHandler.cssToArray | public static function cssToArray($css){
if(!$css) {
return array();
}
$css = str_replace(' /* Do not edit */', '', $css);
$oldCssArr = explode("\n", $css);
$newCssArr = array();
foreach($oldCssArr as $line) {
if(false === strpos($line, '{')) {
continue;
}
preg_match('~(?P<selector>[^{]+)(\{)(?P<rules>[^}]+)\}~', $line, $matches);
foreach($matches as $key => &$match){
if(is_numeric($key)) {
continue;
}
$match = trim($match);
if($key === 'rules') {
$ruleSet = array_filter(array_map('trim', explode(';', $match)));
$match = array();
foreach($ruleSet as $rule) {
$rule = array_map('trim', explode(':', $rule));
$match[$rule[0]] = $rule[1];
}
}
}
$newCssArr[$matches['selector']] = $matches['rules'];
}
return $newCssArr;
} | php | public static function cssToArray($css){
if(!$css) {
return array();
}
$css = str_replace(' /* Do not edit */', '', $css);
$oldCssArr = explode("\n", $css);
$newCssArr = array();
foreach($oldCssArr as $line) {
if(false === strpos($line, '{')) {
continue;
}
preg_match('~(?P<selector>[^{]+)(\{)(?P<rules>[^}]+)\}~', $line, $matches);
foreach($matches as $key => &$match){
if(is_numeric($key)) {
continue;
}
$match = trim($match);
if($key === 'rules') {
$ruleSet = array_filter(array_map('trim', explode(';', $match)));
$match = array();
foreach($ruleSet as $rule) {
$rule = array_map('trim', explode(':', $rule));
$match[$rule[0]] = $rule[1];
}
}
}
$newCssArr[$matches['selector']] = $matches['rules'];
}
return $newCssArr;
} | [
"public",
"static",
"function",
"cssToArray",
"(",
"$",
"css",
")",
"{",
"if",
"(",
"!",
"$",
"css",
")",
"{",
"return",
"array",
"(",
")",
";",
"}",
"$",
"css",
"=",
"str_replace",
"(",
"' /* Do not edit */'",
",",
"''",
",",
"$",
"css",
")",
";",... | Convert incoming CSS to CSS array
This CSS must have the format generated by the online editor
@param $css
@return mixed | [
"Convert",
"incoming",
"CSS",
"to",
"CSS",
"array",
"This",
"CSS",
"must",
"have",
"the",
"format",
"generated",
"by",
"the",
"online",
"editor"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/CssHandler.php#L34-L66 |
oat-sa/tao-core | helpers/CssHandler.php | CssHandler.arrayToCss | public static function arrayToCss($array, $compressed = true){
$css = '';
$break = '';
$space = '';
if(!$compressed){
$break = "\n\t";
$space = " ";
}
// rebuild CSS
foreach($array as $key1 => $value1){
$css .= $key1 . $space . '{';
foreach($value1 as $key2 => $value2){
// in the case that the code is embedded in a media query
if(is_array($value2)){
foreach($value2 as $value3){
$css .= $break . $key2 . $space . '{';
foreach($value3 as $mProp){
$css .= $break . $mProp . ':' . $value3 . ';';
}
$css .= ($compressed)?'}':"\n}\n";
}
}
// regular selectors
else{
$css .= $break . $key2 . ':' . $value2 . ';';
}
}
$css .= ($compressed)?'}':"\n}\n";
}
return $css;
} | php | public static function arrayToCss($array, $compressed = true){
$css = '';
$break = '';
$space = '';
if(!$compressed){
$break = "\n\t";
$space = " ";
}
// rebuild CSS
foreach($array as $key1 => $value1){
$css .= $key1 . $space . '{';
foreach($value1 as $key2 => $value2){
// in the case that the code is embedded in a media query
if(is_array($value2)){
foreach($value2 as $value3){
$css .= $break . $key2 . $space . '{';
foreach($value3 as $mProp){
$css .= $break . $mProp . ':' . $value3 . ';';
}
$css .= ($compressed)?'}':"\n}\n";
}
}
// regular selectors
else{
$css .= $break . $key2 . ':' . $value2 . ';';
}
}
$css .= ($compressed)?'}':"\n}\n";
}
return $css;
} | [
"public",
"static",
"function",
"arrayToCss",
"(",
"$",
"array",
",",
"$",
"compressed",
"=",
"true",
")",
"{",
"$",
"css",
"=",
"''",
";",
"$",
"break",
"=",
"''",
";",
"$",
"space",
"=",
"''",
";",
"if",
"(",
"!",
"$",
"compressed",
")",
"{",
... | Convert incoming CSS array to proper CSS
@param $array
@param $compressed boolean add break lines or not
@return string | [
"Convert",
"incoming",
"CSS",
"array",
"to",
"proper",
"CSS"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/CssHandler.php#L75-L107 |
oat-sa/tao-core | helpers/form/validators/class.NotEmpty.php | tao_helpers_form_validators_NotEmpty.evaluate | public function evaluate($values)
{
$returnValue = (bool) false;
if (is_string($values)){
$values = trim($values);
}
$isScalar = is_bool($values) || is_int($values) || is_float($values);
if( $isScalar === true ){
$returnValue = true;
} elseif( is_array($values) ) {
$returnValue = (count($values) >= 1);
} else {
$returnValue = !empty($values);
}
return (bool) $returnValue;
} | php | public function evaluate($values)
{
$returnValue = (bool) false;
if (is_string($values)){
$values = trim($values);
}
$isScalar = is_bool($values) || is_int($values) || is_float($values);
if( $isScalar === true ){
$returnValue = true;
} elseif( is_array($values) ) {
$returnValue = (count($values) >= 1);
} else {
$returnValue = !empty($values);
}
return (bool) $returnValue;
} | [
"public",
"function",
"evaluate",
"(",
"$",
"values",
")",
"{",
"$",
"returnValue",
"=",
"(",
"bool",
")",
"false",
";",
"if",
"(",
"is_string",
"(",
"$",
"values",
")",
")",
"{",
"$",
"values",
"=",
"trim",
"(",
"$",
"values",
")",
";",
"}",
"$"... | 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.NotEmpty.php#L48-L67 |
oat-sa/tao-core | helpers/form/validators/XsrfTokenValidator.php | XsrfTokenValidator.evaluate | public function evaluate($values)
{
$tokenService = $this->getServiceManager()->get(TokenService::SERVICE_ID);
if($tokenService->checkToken($values)){
$tokenService->revokeToken($values);
return true;
}
\common_Logger::e('Attempt to post a form with the incorrect token');
throw new \common_exception_Unauthorized('Invalid token '. $values);
} | php | public function evaluate($values)
{
$tokenService = $this->getServiceManager()->get(TokenService::SERVICE_ID);
if($tokenService->checkToken($values)){
$tokenService->revokeToken($values);
return true;
}
\common_Logger::e('Attempt to post a form with the incorrect token');
throw new \common_exception_Unauthorized('Invalid token '. $values);
} | [
"public",
"function",
"evaluate",
"(",
"$",
"values",
")",
"{",
"$",
"tokenService",
"=",
"$",
"this",
"->",
"getServiceManager",
"(",
")",
"->",
"get",
"(",
"TokenService",
"::",
"SERVICE_ID",
")",
";",
"if",
"(",
"$",
"tokenService",
"->",
"checkToken",
... | Validate an active XSRF token.
@param string $values should be the token
@return boolean true only if valid
@throws \common_exception_Unauthorized if the token is not valid | [
"Validate",
"an",
"active",
"XSRF",
"token",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/validators/XsrfTokenValidator.php#L41-L52 |
oat-sa/tao-core | models/classes/media/MediaService.php | MediaService.getMediaSources | protected function getMediaSources()
{
if (is_null($this->mediaSources)) {
$this->mediaSources = array();
$tao = \common_ext_ExtensionsManager::singleton()->getExtensionById('tao');
$sources = $tao->getConfig(self::CONFIG_KEY);
$sources = is_array($sources) ? $sources : array();
foreach($sources as $mediaSourceId => $mediaSource){
$this->mediaSources[$mediaSourceId] = is_object($mediaSource)
? $mediaSource
: new $mediaSource(array());
}
}
return $this->mediaSources;
} | php | protected function getMediaSources()
{
if (is_null($this->mediaSources)) {
$this->mediaSources = array();
$tao = \common_ext_ExtensionsManager::singleton()->getExtensionById('tao');
$sources = $tao->getConfig(self::CONFIG_KEY);
$sources = is_array($sources) ? $sources : array();
foreach($sources as $mediaSourceId => $mediaSource){
$this->mediaSources[$mediaSourceId] = is_object($mediaSource)
? $mediaSource
: new $mediaSource(array());
}
}
return $this->mediaSources;
} | [
"protected",
"function",
"getMediaSources",
"(",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"mediaSources",
")",
")",
"{",
"$",
"this",
"->",
"mediaSources",
"=",
"array",
"(",
")",
";",
"$",
"tao",
"=",
"\\",
"common_ext_ExtensionsManager",
... | Return all configured media sources
@return MediaBrowser | [
"Return",
"all",
"configured",
"media",
"sources"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/media/MediaService.php#L61-L77 |
oat-sa/tao-core | models/classes/media/MediaService.php | MediaService.getMediaSource | public function getMediaSource($mediaSourceId)
{
$sources = $this->getMediaSources();
if (!isset($sources[$mediaSourceId])) {
throw new \common_Exception('Media Sources Configuration for source '.$mediaSourceId.' not found');
}
return $sources[$mediaSourceId];
} | php | public function getMediaSource($mediaSourceId)
{
$sources = $this->getMediaSources();
if (!isset($sources[$mediaSourceId])) {
throw new \common_Exception('Media Sources Configuration for source '.$mediaSourceId.' not found');
}
return $sources[$mediaSourceId];
} | [
"public",
"function",
"getMediaSource",
"(",
"$",
"mediaSourceId",
")",
"{",
"$",
"sources",
"=",
"$",
"this",
"->",
"getMediaSources",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"sources",
"[",
"$",
"mediaSourceId",
"]",
")",
")",
"{",
"throw",... | Returns the media source specified by $mediaSourceId
@param string $mediaSourceId
@throws \common_Exception
@return MediaBrowser | [
"Returns",
"the",
"media",
"source",
"specified",
"by",
"$mediaSourceId"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/media/MediaService.php#L86-L93 |
oat-sa/tao-core | models/classes/media/MediaService.php | MediaService.getBrowsableSources | public function getBrowsableSources()
{
$returnValue = array();
foreach ($this->getMediaSources() as $id => $source) {
if ($source instanceof MediaBrowser) {
$returnValue[$id] = $source;
}
}
return $returnValue;
} | php | public function getBrowsableSources()
{
$returnValue = array();
foreach ($this->getMediaSources() as $id => $source) {
if ($source instanceof MediaBrowser) {
$returnValue[$id] = $source;
}
}
return $returnValue;
} | [
"public",
"function",
"getBrowsableSources",
"(",
")",
"{",
"$",
"returnValue",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"getMediaSources",
"(",
")",
"as",
"$",
"id",
"=>",
"$",
"source",
")",
"{",
"if",
"(",
"$",
"source",
"in... | Returns all media sources that are browsable
@return MediaBrowser[] | [
"Returns",
"all",
"media",
"sources",
"that",
"are",
"browsable"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/media/MediaService.php#L100-L109 |
oat-sa/tao-core | models/classes/media/MediaService.php | MediaService.getWritableSources | public function getWritableSources()
{
$returnValue = array();
foreach ($this->getMediaSources() as $id => $source) {
if ($source instanceof MediaManagement) {
$returnValue[$id] = $source;
}
}
return $returnValue;
} | php | public function getWritableSources()
{
$returnValue = array();
foreach ($this->getMediaSources() as $id => $source) {
if ($source instanceof MediaManagement) {
$returnValue[$id] = $source;
}
}
return $returnValue;
} | [
"public",
"function",
"getWritableSources",
"(",
")",
"{",
"$",
"returnValue",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"getMediaSources",
"(",
")",
"as",
"$",
"id",
"=>",
"$",
"source",
")",
"{",
"if",
"(",
"$",
"source",
"ins... | Returns all media sources that can write
@return MediaManagement[] | [
"Returns",
"all",
"media",
"sources",
"that",
"can",
"write"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/media/MediaService.php#L116-L125 |
oat-sa/tao-core | models/classes/media/MediaService.php | MediaService.addMediaSource | public function addMediaSource(MediaBrowser $source)
{
// ensure loaded
$this->getMediaSources();
// only mediaSource called 'mediamanager' supported
$this->mediaSources['mediamanager'] = $source;
$tao = \common_ext_ExtensionsManager::singleton()->getExtensionById('tao');
return $tao->setConfig(self::CONFIG_KEY, $this->mediaSources);
} | php | public function addMediaSource(MediaBrowser $source)
{
// ensure loaded
$this->getMediaSources();
// only mediaSource called 'mediamanager' supported
$this->mediaSources['mediamanager'] = $source;
$tao = \common_ext_ExtensionsManager::singleton()->getExtensionById('tao');
return $tao->setConfig(self::CONFIG_KEY, $this->mediaSources);
} | [
"public",
"function",
"addMediaSource",
"(",
"MediaBrowser",
"$",
"source",
")",
"{",
"// ensure loaded",
"$",
"this",
"->",
"getMediaSources",
"(",
")",
";",
"// only mediaSource called 'mediamanager' supported",
"$",
"this",
"->",
"mediaSources",
"[",
"'mediamanager'"... | Adds a media source to Tao
WARNING: Will always add the mediasource as 'mediamanager' as other
identifiers are not supported by js widget
@param MediaBrowser $source
@return boolean | [
"Adds",
"a",
"media",
"source",
"to",
"Tao"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/media/MediaService.php#L136-L144 |
oat-sa/tao-core | models/classes/media/MediaService.php | MediaService.removeMediaSource | public function removeMediaSource($sourceId)
{
// ensure loaded
$this->getMediaSources();
unset($this->mediaSources[$sourceId]);
$tao = \common_ext_ExtensionsManager::singleton()->getExtensionById('tao');
return $tao->setConfig(self::CONFIG_KEY, $this->mediaSources);
} | php | public function removeMediaSource($sourceId)
{
// ensure loaded
$this->getMediaSources();
unset($this->mediaSources[$sourceId]);
$tao = \common_ext_ExtensionsManager::singleton()->getExtensionById('tao');
return $tao->setConfig(self::CONFIG_KEY, $this->mediaSources);
} | [
"public",
"function",
"removeMediaSource",
"(",
"$",
"sourceId",
")",
"{",
"// ensure loaded",
"$",
"this",
"->",
"getMediaSources",
"(",
")",
";",
"unset",
"(",
"$",
"this",
"->",
"mediaSources",
"[",
"$",
"sourceId",
"]",
")",
";",
"$",
"tao",
"=",
"\\... | Removes a media source for tao
@param string $sourceId
@return boolean | [
"Removes",
"a",
"media",
"source",
"for",
"tao"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/media/MediaService.php#L152-L159 |
oat-sa/tao-core | models/classes/taskQueue/Queue/Broker/AbstractQueueBroker.php | AbstractQueueBroker.unserializeTask | protected function unserializeTask($taskJSON, $idForDeletion, array $logContext = [])
{
/** @var TaskSerializerService $taskSerializer */
$taskSerializer = $this->getServiceLocator()->get(TaskSerializerService::SERVICE_ID);
try {
return $taskSerializer->deserialize($taskJSON);
} catch (\Exception $e) {
$this->doDelete($idForDeletion, $logContext);
return null;
}
} | php | protected function unserializeTask($taskJSON, $idForDeletion, array $logContext = [])
{
/** @var TaskSerializerService $taskSerializer */
$taskSerializer = $this->getServiceLocator()->get(TaskSerializerService::SERVICE_ID);
try {
return $taskSerializer->deserialize($taskJSON);
} catch (\Exception $e) {
$this->doDelete($idForDeletion, $logContext);
return null;
}
} | [
"protected",
"function",
"unserializeTask",
"(",
"$",
"taskJSON",
",",
"$",
"idForDeletion",
",",
"array",
"$",
"logContext",
"=",
"[",
"]",
")",
"{",
"/** @var TaskSerializerService $taskSerializer */",
"$",
"taskSerializer",
"=",
"$",
"this",
"->",
"getServiceLoca... | Unserialize the given task JSON.
If the json is not valid, it deletes the task straight away without processing it.
@param string $taskJSON
@param string $idForDeletion An identification of the given task
@param array $logContext
@return null|TaskInterface | [
"Unserialize",
"the",
"given",
"task",
"JSON",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/taskQueue/Queue/Broker/AbstractQueueBroker.php#L127-L142 |
oat-sa/tao-core | install/utils/class.ConfigWriter.php | tao_install_utils_ConfigWriter.createConfig | public function createConfig()
{
//common checks
if(!is_writable(dirname($this->file))){
throw new tao_install_utils_Exception('Unable to create configuration file. Please set write permission to : '.dirname($this->file));
}
if(file_exists($this->file) && !is_writable($this->file)){
throw new tao_install_utils_Exception('Unable to create the configuration file. Please set the write permissions to : '.$this->file);
}
if(!is_readable($this->sample)){
throw new tao_install_utils_Exception('Unable to read the sample configuration. Please set the read permissions to : '.$this->sample);
}
if(!copy($this->sample, $this->file)){
throw new tao_install_utils_Exception('Unable to copy the sample configuration to : '.$this->file);
}
} | php | public function createConfig()
{
//common checks
if(!is_writable(dirname($this->file))){
throw new tao_install_utils_Exception('Unable to create configuration file. Please set write permission to : '.dirname($this->file));
}
if(file_exists($this->file) && !is_writable($this->file)){
throw new tao_install_utils_Exception('Unable to create the configuration file. Please set the write permissions to : '.$this->file);
}
if(!is_readable($this->sample)){
throw new tao_install_utils_Exception('Unable to read the sample configuration. Please set the read permissions to : '.$this->sample);
}
if(!copy($this->sample, $this->file)){
throw new tao_install_utils_Exception('Unable to copy the sample configuration to : '.$this->file);
}
} | [
"public",
"function",
"createConfig",
"(",
")",
"{",
"//common checks",
"if",
"(",
"!",
"is_writable",
"(",
"dirname",
"(",
"$",
"this",
"->",
"file",
")",
")",
")",
"{",
"throw",
"new",
"tao_install_utils_Exception",
"(",
"'Unable to create configuration file. Pl... | Create the config file from the sample
@throws tao_install_utils_Exception | [
"Create",
"the",
"config",
"file",
"from",
"the",
"sample"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/install/utils/class.ConfigWriter.php#L64-L81 |
oat-sa/tao-core | install/utils/class.ConfigWriter.php | tao_install_utils_ConfigWriter.writeConstants | public function writeConstants(array $constants)
{
//common checks
if(!file_exists($this->file)){
throw new tao_install_utils_Exception("Unable to write constants: $this->file don't exists!");
}
if(!is_readable($this->file) || !is_writable($this->file)){
throw new tao_install_utils_Exception("Unable to write constants: $this->file must have read and write permissions!");
}
$content = file_get_contents($this->file);
if(!empty($content)){
foreach($constants as $name => $val){
if(is_string($val)){
$val = addslashes((string)$val);
$content = preg_replace('/(\''.$name.'\')(.*?)$/ms','$1,\''.addslashes($val).'\');',$content);
}
else if(is_bool($val)){
($val === true) ? $val = 'true' : $val = 'false';
$content = preg_replace('/(\''.$name.'\')(.*?)$/ms','$1, '.$val.');',$content);
}
else if(is_numeric($val)){
$content = preg_replace('/(\''.$name.'\')(.*?)$/ms','$1, '.$val.');',$content);
}
}
file_put_contents($this->file, $content);
}
} | php | public function writeConstants(array $constants)
{
//common checks
if(!file_exists($this->file)){
throw new tao_install_utils_Exception("Unable to write constants: $this->file don't exists!");
}
if(!is_readable($this->file) || !is_writable($this->file)){
throw new tao_install_utils_Exception("Unable to write constants: $this->file must have read and write permissions!");
}
$content = file_get_contents($this->file);
if(!empty($content)){
foreach($constants as $name => $val){
if(is_string($val)){
$val = addslashes((string)$val);
$content = preg_replace('/(\''.$name.'\')(.*?)$/ms','$1,\''.addslashes($val).'\');',$content);
}
else if(is_bool($val)){
($val === true) ? $val = 'true' : $val = 'false';
$content = preg_replace('/(\''.$name.'\')(.*?)$/ms','$1, '.$val.');',$content);
}
else if(is_numeric($val)){
$content = preg_replace('/(\''.$name.'\')(.*?)$/ms','$1, '.$val.');',$content);
}
}
file_put_contents($this->file, $content);
}
} | [
"public",
"function",
"writeConstants",
"(",
"array",
"$",
"constants",
")",
"{",
"//common checks",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"this",
"->",
"file",
")",
")",
"{",
"throw",
"new",
"tao_install_utils_Exception",
"(",
"\"Unable to write constants: $th... | Write the constants into the config file
@param array $constants the list of constants to write (the key is the name of the constant)
@throws tao_install_utils_Exception | [
"Write",
"the",
"constants",
"into",
"the",
"config",
"file"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/install/utils/class.ConfigWriter.php#L88-L117 |
oat-sa/tao-core | install/utils/class.ConfigWriter.php | tao_install_utils_ConfigWriter.writeJsVariable | public function writeJsVariable(array $variables, $lineBeginWith = "var")
{
//common checks
if(!file_exists($this->file)){
throw new tao_install_utils_Exception("Unable to write variables: $this->file don't exists!");
}
if(!is_readable($this->file) || !is_writable($this->file)){
throw new tao_install_utils_Exception("Unable to write variables: $this->file must have read and write permissions!");
}
$lines = file($this->file);
if($lines !== false){
$data = file_get_contents($this->file);
$changes = 0;
foreach($lines as $line){
foreach($variables as $key => $value){
if(is_string($value)){
$value = "'$value'";
}
else if(is_bool($value)){
($value === true) ? $value = 'true' : $value = 'false';
}
if(preg_match("/^\s?$lineBeginWith\s?$key\s?=\s?/i", trim($line))){
$data = str_replace(trim($line), "$lineBeginWith $key = $value;", $data);
$changes++;
}
}
}
if($changes > 0){
file_put_contents($this->file, $data);
}
}
} | php | public function writeJsVariable(array $variables, $lineBeginWith = "var")
{
//common checks
if(!file_exists($this->file)){
throw new tao_install_utils_Exception("Unable to write variables: $this->file don't exists!");
}
if(!is_readable($this->file) || !is_writable($this->file)){
throw new tao_install_utils_Exception("Unable to write variables: $this->file must have read and write permissions!");
}
$lines = file($this->file);
if($lines !== false){
$data = file_get_contents($this->file);
$changes = 0;
foreach($lines as $line){
foreach($variables as $key => $value){
if(is_string($value)){
$value = "'$value'";
}
else if(is_bool($value)){
($value === true) ? $value = 'true' : $value = 'false';
}
if(preg_match("/^\s?$lineBeginWith\s?$key\s?=\s?/i", trim($line))){
$data = str_replace(trim($line), "$lineBeginWith $key = $value;", $data);
$changes++;
}
}
}
if($changes > 0){
file_put_contents($this->file, $data);
}
}
} | [
"public",
"function",
"writeJsVariable",
"(",
"array",
"$",
"variables",
",",
"$",
"lineBeginWith",
"=",
"\"var\"",
")",
"{",
"//common checks",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"this",
"->",
"file",
")",
")",
"{",
"throw",
"new",
"tao_install_utils_... | Write the constants into a Javascript config file
@param array $variables the list of variables to write (the key is the name of the var)
@throws tao_install_utils_Exception | [
"Write",
"the",
"constants",
"into",
"a",
"Javascript",
"config",
"file"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/install/utils/class.ConfigWriter.php#L124-L157 |
oat-sa/tao-core | actions/class.TaskQueueWebApi.php | tao_actions_TaskQueueWebApi.download | public function download()
{
try{
$this->checkIfTaskIdExists();
$taskLogEntity = $this->getTaskLogService()->getByIdAndUser(
$this->getRequestParameter(self::PARAMETER_TASK_ID),
$this->getSessionUserUri()
);
if (!$taskLogEntity->getStatus()->isCompleted()) {
throw new \common_Exception('Task "'. $taskLogEntity->getId() .'" is not downloadable.');
}
$fileNameOrSerial = $taskLogEntity->getFileNameFromReport();
if (empty($fileNameOrSerial)) {
throw new \common_Exception('Filename not found in report.');
}
// first try to get a referenced file is it is a serial
$file = $this->getReferencedFile($fileNameOrSerial);
// if no file let's try the task queue storage
if (is_null($file)) {
$file = $this->getQueueStorageFile($fileNameOrSerial);
}
if (!$file) {
throw new \common_exception_NotFound('File not found.');
}
header('Set-Cookie: fileDownload=true');
setcookie('fileDownload', 'true', 0, '/');
header('Content-Disposition: attachment; filename="' . $file->getBasename() . '"');
header('Content-Type: ' . $file->getMimeType());
\tao_helpers_Http::returnStream($file->readPsrStream());
exit();
} catch (\Exception $e) {
return $this->returnJson([
'success' => false,
'errorMsg' => $e instanceof \common_exception_UserReadableException ? $e->getUserMessage() : $e->getMessage(),
'errorCode' => $e->getCode(),
]);
}
} | php | public function download()
{
try{
$this->checkIfTaskIdExists();
$taskLogEntity = $this->getTaskLogService()->getByIdAndUser(
$this->getRequestParameter(self::PARAMETER_TASK_ID),
$this->getSessionUserUri()
);
if (!$taskLogEntity->getStatus()->isCompleted()) {
throw new \common_Exception('Task "'. $taskLogEntity->getId() .'" is not downloadable.');
}
$fileNameOrSerial = $taskLogEntity->getFileNameFromReport();
if (empty($fileNameOrSerial)) {
throw new \common_Exception('Filename not found in report.');
}
// first try to get a referenced file is it is a serial
$file = $this->getReferencedFile($fileNameOrSerial);
// if no file let's try the task queue storage
if (is_null($file)) {
$file = $this->getQueueStorageFile($fileNameOrSerial);
}
if (!$file) {
throw new \common_exception_NotFound('File not found.');
}
header('Set-Cookie: fileDownload=true');
setcookie('fileDownload', 'true', 0, '/');
header('Content-Disposition: attachment; filename="' . $file->getBasename() . '"');
header('Content-Type: ' . $file->getMimeType());
\tao_helpers_Http::returnStream($file->readPsrStream());
exit();
} catch (\Exception $e) {
return $this->returnJson([
'success' => false,
'errorMsg' => $e instanceof \common_exception_UserReadableException ? $e->getUserMessage() : $e->getMessage(),
'errorCode' => $e->getCode(),
]);
}
} | [
"public",
"function",
"download",
"(",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"checkIfTaskIdExists",
"(",
")",
";",
"$",
"taskLogEntity",
"=",
"$",
"this",
"->",
"getTaskLogService",
"(",
")",
"->",
"getByIdAndUser",
"(",
"$",
"this",
"->",
"getRequestPa... | Download the file created by task. | [
"Download",
"the",
"file",
"created",
"by",
"task",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.TaskQueueWebApi.php#L196-L242 |
oat-sa/tao-core | models/classes/requiredAction/implementation/RequiredActionRedirect.php | RequiredActionRedirect.execute | public function execute(array $params = [])
{
$context = \Context::getInstance();
$excludedRoutes = $this->getExcludedRoutes();
$currentRoute = [
'extension' => $context->getExtensionName(),
'module' => $context->getModuleName(),
'action' => $context->getActionName(),
];
if (!in_array($currentRoute, $excludedRoutes)) {
$currentUrl = \common_http_Request::currentRequest()->getUrl();
$url = $this->url . (parse_url($this->url, PHP_URL_QUERY) ? '&' : '?') . 'return_url=' . urlencode($currentUrl);
$flowController = new FlowController();
$flowController->redirect($url);
}
} | php | public function execute(array $params = [])
{
$context = \Context::getInstance();
$excludedRoutes = $this->getExcludedRoutes();
$currentRoute = [
'extension' => $context->getExtensionName(),
'module' => $context->getModuleName(),
'action' => $context->getActionName(),
];
if (!in_array($currentRoute, $excludedRoutes)) {
$currentUrl = \common_http_Request::currentRequest()->getUrl();
$url = $this->url . (parse_url($this->url, PHP_URL_QUERY) ? '&' : '?') . 'return_url=' . urlencode($currentUrl);
$flowController = new FlowController();
$flowController->redirect($url);
}
} | [
"public",
"function",
"execute",
"(",
"array",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"$",
"context",
"=",
"\\",
"Context",
"::",
"getInstance",
"(",
")",
";",
"$",
"excludedRoutes",
"=",
"$",
"this",
"->",
"getExcludedRoutes",
"(",
")",
";",
"$",
"... | @deprecated use \oat\tao\model\requiredAction\implementation\RequiredActionRedirectUrlPart instead
Execute an action
@param array $params
@return mixed | [
"@deprecated",
"use",
"\\",
"oat",
"\\",
"tao",
"\\",
"model",
"\\",
"requiredAction",
"\\",
"implementation",
"\\",
"RequiredActionRedirectUrlPart",
"instead"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/requiredAction/implementation/RequiredActionRedirect.php#L76-L93 |
oat-sa/tao-core | models/classes/requiredAction/implementation/RequiredActionRedirect.php | RequiredActionRedirect.getExcludedRoutes | private function getExcludedRoutes()
{
$result = $this->excludedRoutes;
$resolver = new \Resolver($this->url);
$result[] = [
'extension' => $resolver->getExtensionFromURL(),
'module' => $resolver->getModule(),
'action' => $resolver->getAction(),
];
return $result;
} | php | private function getExcludedRoutes()
{
$result = $this->excludedRoutes;
$resolver = new \Resolver($this->url);
$result[] = [
'extension' => $resolver->getExtensionFromURL(),
'module' => $resolver->getModule(),
'action' => $resolver->getAction(),
];
return $result;
} | [
"private",
"function",
"getExcludedRoutes",
"(",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"excludedRoutes",
";",
"$",
"resolver",
"=",
"new",
"\\",
"Resolver",
"(",
"$",
"this",
"->",
"url",
")",
";",
"$",
"result",
"[",
"]",
"=",
"[",
"'exte... | Some actions should not be redirected (such as retrieving requireJs config)
@return array | [
"Some",
"actions",
"should",
"not",
"be",
"redirected",
"(",
"such",
"as",
"retrieving",
"requireJs",
"config",
")"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/requiredAction/implementation/RequiredActionRedirect.php#L124-L136 |
oat-sa/tao-core | helpers/form/xhtml/class.Form.php | tao_helpers_form_xhtml_Form.getValues | public function getValues($groupName = '')
{
$returnValue = array();
foreach($this->elements as $element){
if (!empty($this->systemElements) && in_array($element->getName(), $this->systemElements)) {
continue;
}
if(empty($groupName)
|| !isset($this->groups[$groupName])
|| in_array($element->getName(), $this->groups[$groupName]['elements'])) {
$returnValue[tao_helpers_Uri::decode($element->getName())] = $element->getEvaluatedValue();
}
}
return (array) $returnValue;
} | php | public function getValues($groupName = '')
{
$returnValue = array();
foreach($this->elements as $element){
if (!empty($this->systemElements) && in_array($element->getName(), $this->systemElements)) {
continue;
}
if(empty($groupName)
|| !isset($this->groups[$groupName])
|| in_array($element->getName(), $this->groups[$groupName]['elements'])) {
$returnValue[tao_helpers_Uri::decode($element->getName())] = $element->getEvaluatedValue();
}
}
return (array) $returnValue;
} | [
"public",
"function",
"getValues",
"(",
"$",
"groupName",
"=",
"''",
")",
"{",
"$",
"returnValue",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"elements",
"as",
"$",
"element",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this"... | Short description of method getValues
@access public
@author Bertrand Chevrier, <bertrand.chevrier@tudor.lu>
@param string $groupName
@param array $filterProperties List of properties which values are unneeded and must be filtered
@return array | [
"Short",
"description",
"of",
"method",
"getValues"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/xhtml/class.Form.php#L49-L67 |
oat-sa/tao-core | helpers/form/xhtml/class.Form.php | tao_helpers_form_xhtml_Form.evaluate | public function evaluate()
{
$this->initElements();
if(isset($_POST["{$this->name}_sent"])){
$this->submited = true;
//set posted values
foreach($this->elements as $id => $element){
$this->elements[$id]->feed();
}
$this->validate();
}
} | php | public function evaluate()
{
$this->initElements();
if(isset($_POST["{$this->name}_sent"])){
$this->submited = true;
//set posted values
foreach($this->elements as $id => $element){
$this->elements[$id]->feed();
}
$this->validate();
}
} | [
"public",
"function",
"evaluate",
"(",
")",
"{",
"$",
"this",
"->",
"initElements",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"_POST",
"[",
"\"{$this->name}_sent\"",
"]",
")",
")",
"{",
"$",
"this",
"->",
"submited",
"=",
"true",
";",
"//set posted ... | Short description of method evaluate
@access public
@author Bertrand Chevrier, <bertrand.chevrier@tudor.lu>
@return mixed | [
"Short",
"description",
"of",
"method",
"evaluate"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/xhtml/class.Form.php#L76-L96 |
oat-sa/tao-core | helpers/form/xhtml/class.Form.php | tao_helpers_form_xhtml_Form.render | public function render()
{
$returnValue = (string) '';
(strpos($_SERVER['REQUEST_URI'], '?') > 0) ? $action = substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?')) : $action = $_SERVER['REQUEST_URI'];
// Defensive code, prevent double leading slashes issue.
if (substr($action, 0, 2) == '//'){
$action = substr($action, 1);
}
$returnValue .= "<div class='xhtml_form'>\n";
$returnValue .= "<form method='post' id='{$this->name}' name='{$this->name}' action='$action' ";
if($this->hasFileUpload()){
$returnValue .= "enctype='multipart/form-data' ";
}
$returnValue .= ">\n";
$returnValue .= "<input type='hidden' class='global' name='{$this->name}_sent' value='1' />\n";
//$returnValue .= $this->renderActions('top');
if(!empty($this->error)){
$returnValue .= '<div class="xhtml_form_error">'.$this->error.'</div>';
}
$returnValue .= $this->renderElements();
$returnValue .= $this->renderActions('bottom');
$returnValue .= "</form>\n";
$returnValue .= "</div>\n";
return (string) $returnValue;
} | php | public function render()
{
$returnValue = (string) '';
(strpos($_SERVER['REQUEST_URI'], '?') > 0) ? $action = substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?')) : $action = $_SERVER['REQUEST_URI'];
// Defensive code, prevent double leading slashes issue.
if (substr($action, 0, 2) == '//'){
$action = substr($action, 1);
}
$returnValue .= "<div class='xhtml_form'>\n";
$returnValue .= "<form method='post' id='{$this->name}' name='{$this->name}' action='$action' ";
if($this->hasFileUpload()){
$returnValue .= "enctype='multipart/form-data' ";
}
$returnValue .= ">\n";
$returnValue .= "<input type='hidden' class='global' name='{$this->name}_sent' value='1' />\n";
//$returnValue .= $this->renderActions('top');
if(!empty($this->error)){
$returnValue .= '<div class="xhtml_form_error">'.$this->error.'</div>';
}
$returnValue .= $this->renderElements();
$returnValue .= $this->renderActions('bottom');
$returnValue .= "</form>\n";
$returnValue .= "</div>\n";
return (string) $returnValue;
} | [
"public",
"function",
"render",
"(",
")",
"{",
"$",
"returnValue",
"=",
"(",
"string",
")",
"''",
";",
"(",
"strpos",
"(",
"$",
"_SERVER",
"[",
"'REQUEST_URI'",
"]",
",",
"'?'",
")",
">",
"0",
")",
"?",
"$",
"action",
"=",
"substr",
"(",
"$",
"_S... | Short description of method render
@access public
@author Bertrand Chevrier, <bertrand.chevrier@tudor.lu>
@return string | [
"Short",
"description",
"of",
"method",
"render"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/xhtml/class.Form.php#L105-L145 |
oat-sa/tao-core | helpers/form/xhtml/class.Form.php | tao_helpers_form_xhtml_Form.validate | protected function validate()
{
$returnValue = (bool) false;
$this->valid = true;
foreach($this->elements as $element){
if(!$element->validate()){
$this->valid = false;
}
}
return (bool) $returnValue;
} | php | protected function validate()
{
$returnValue = (bool) false;
$this->valid = true;
foreach($this->elements as $element){
if(!$element->validate()){
$this->valid = false;
}
}
return (bool) $returnValue;
} | [
"protected",
"function",
"validate",
"(",
")",
"{",
"$",
"returnValue",
"=",
"(",
"bool",
")",
"false",
";",
"$",
"this",
"->",
"valid",
"=",
"true",
";",
"foreach",
"(",
"$",
"this",
"->",
"elements",
"as",
"$",
"element",
")",
"{",
"if",
"(",
"!"... | Short description of method validate
@access protected
@author Bertrand Chevrier, <bertrand.chevrier@tudor.lu>
@return boolean | [
"Short",
"description",
"of",
"method",
"validate"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/xhtml/class.Form.php#L154-L171 |
oat-sa/tao-core | helpers/class.Xml.php | tao_helpers_Xml.array_to_xml | private static function array_to_xml($data = array(), &$xml_data) {
foreach($data as $key => $value) {
if(is_array($value) or (is_object($value))) {
if(!is_numeric($key)){
$subnode = $xml_data->addChild("$key");
self::array_to_xml($value, $subnode);
}
else{
$subnode = $xml_data->addChild("element");
self::array_to_xml($value, $subnode);
}
}
else {
if (is_bool($value)) {$value = $value ? "true" : "false";}
$xml_data->addChild("$key","$value");
}
}
} | php | private static function array_to_xml($data = array(), &$xml_data) {
foreach($data as $key => $value) {
if(is_array($value) or (is_object($value))) {
if(!is_numeric($key)){
$subnode = $xml_data->addChild("$key");
self::array_to_xml($value, $subnode);
}
else{
$subnode = $xml_data->addChild("element");
self::array_to_xml($value, $subnode);
}
}
else {
if (is_bool($value)) {$value = $value ? "true" : "false";}
$xml_data->addChild("$key","$value");
}
}
} | [
"private",
"static",
"function",
"array_to_xml",
"(",
"$",
"data",
"=",
"array",
"(",
")",
",",
"&",
"$",
"xml_data",
")",
"{",
"foreach",
"(",
"$",
"data",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"value",
... | function defination to convert array to xml | [
"function",
"defination",
"to",
"convert",
"array",
"to",
"xml"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/class.Xml.php#L21-L39 |
oat-sa/tao-core | models/classes/media/TaoMediaResolver.php | TaoMediaResolver.resolve | public function resolve($url)
{
$urlParts = parse_url($url);
if (isset($urlParts['scheme']) && $urlParts['scheme'] === MediaService::SCHEME_NAME && isset($urlParts['host'])) {
$mediaService = new MediaService();
$mediaSource = $mediaService->getMediaSource($urlParts['host']);
$mediaId = (isset($urlParts['path'])) ? trim($urlParts['path'], '/') : '';
return new MediaAsset($mediaSource, $mediaId);
} elseif (isset($urlParts['scheme']) && in_array($urlParts['scheme'], array('http','https'))) {
return new MediaAsset(new HttpSource(), $url);
} else {
throw new TaoMediaException('Cannot resolve '.$url);
}
} | php | public function resolve($url)
{
$urlParts = parse_url($url);
if (isset($urlParts['scheme']) && $urlParts['scheme'] === MediaService::SCHEME_NAME && isset($urlParts['host'])) {
$mediaService = new MediaService();
$mediaSource = $mediaService->getMediaSource($urlParts['host']);
$mediaId = (isset($urlParts['path'])) ? trim($urlParts['path'], '/') : '';
return new MediaAsset($mediaSource, $mediaId);
} elseif (isset($urlParts['scheme']) && in_array($urlParts['scheme'], array('http','https'))) {
return new MediaAsset(new HttpSource(), $url);
} else {
throw new TaoMediaException('Cannot resolve '.$url);
}
} | [
"public",
"function",
"resolve",
"(",
"$",
"url",
")",
"{",
"$",
"urlParts",
"=",
"parse_url",
"(",
"$",
"url",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"urlParts",
"[",
"'scheme'",
"]",
")",
"&&",
"$",
"urlParts",
"[",
"'scheme'",
"]",
"===",
"Medi... | Resolve a taomedia url to a media asset
@param string $url
@throws \Exception
@return \oat\tao\model\media\MediaAsset | [
"Resolve",
"a",
"taomedia",
"url",
"to",
"a",
"media",
"asset"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/media/TaoMediaResolver.php#L37-L50 |
oat-sa/tao-core | actions/form/class.CspHeader.php | tao_actions_form_CspHeader.setFormData | private function setFormData()
{
$postData = $this->getPostData();
$currentSetting = $this->getSettings();
$listSettings = [];
if ($currentSetting === 'list') {
$listSettings = $this->getListSettings();
}
if ($currentSetting && !isset($postData[self::SOURCE_RADIO_NAME])) {
$this->sourceElement->setValue($currentSetting);
}
if (!empty($listSettings) && !isset($postData[self::SOURCE_LIST_NAME])) {
$this->sourceDomainsElement->setValue(implode("\n", $listSettings));
}
if (isset($postData[self::SOURCE_RADIO_NAME]) && array_key_exists($postData[self::SOURCE_RADIO_NAME], $this->getSourceOptions())) {
$this->sourceElement->setValue($postData[self::SOURCE_RADIO_NAME]);
}
if (isset($postData[self::SOURCE_LIST_NAME])) {
$this->sourceDomainsElement->setValue($postData[self::SOURCE_LIST_NAME]);
}
} | php | private function setFormData()
{
$postData = $this->getPostData();
$currentSetting = $this->getSettings();
$listSettings = [];
if ($currentSetting === 'list') {
$listSettings = $this->getListSettings();
}
if ($currentSetting && !isset($postData[self::SOURCE_RADIO_NAME])) {
$this->sourceElement->setValue($currentSetting);
}
if (!empty($listSettings) && !isset($postData[self::SOURCE_LIST_NAME])) {
$this->sourceDomainsElement->setValue(implode("\n", $listSettings));
}
if (isset($postData[self::SOURCE_RADIO_NAME]) && array_key_exists($postData[self::SOURCE_RADIO_NAME], $this->getSourceOptions())) {
$this->sourceElement->setValue($postData[self::SOURCE_RADIO_NAME]);
}
if (isset($postData[self::SOURCE_LIST_NAME])) {
$this->sourceDomainsElement->setValue($postData[self::SOURCE_LIST_NAME]);
}
} | [
"private",
"function",
"setFormData",
"(",
")",
"{",
"$",
"postData",
"=",
"$",
"this",
"->",
"getPostData",
"(",
")",
";",
"$",
"currentSetting",
"=",
"$",
"this",
"->",
"getSettings",
"(",
")",
";",
"$",
"listSettings",
"=",
"[",
"]",
";",
"if",
"(... | Set the form data based on the available data | [
"Set",
"the",
"form",
"data",
"based",
"on",
"the",
"available",
"data"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/form/class.CspHeader.php#L111-L136 |
oat-sa/tao-core | actions/form/class.CspHeader.php | tao_actions_form_CspHeader.setValidation | private function setValidation()
{
$this->sourceDomainsElement->addValidator(new CspHeaderValidator(['sourceElement' => $this->sourceElement]));
$this->sourceElement->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty'));
} | php | private function setValidation()
{
$this->sourceDomainsElement->addValidator(new CspHeaderValidator(['sourceElement' => $this->sourceElement]));
$this->sourceElement->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty'));
} | [
"private",
"function",
"setValidation",
"(",
")",
"{",
"$",
"this",
"->",
"sourceDomainsElement",
"->",
"addValidator",
"(",
"new",
"CspHeaderValidator",
"(",
"[",
"'sourceElement'",
"=>",
"$",
"this",
"->",
"sourceElement",
"]",
")",
")",
";",
"$",
"this",
... | Set the validation needed for the form elements. | [
"Set",
"the",
"validation",
"needed",
"for",
"the",
"form",
"elements",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/form/class.CspHeader.php#L141-L145 |
oat-sa/tao-core | actions/form/class.CspHeader.php | tao_actions_form_CspHeader.getSettings | private function getSettings()
{
$settingsStorage = $this->getSettingsStorage();
if (!$settingsStorage->exists(CspHeaderSettingsInterface::CSP_HEADER_SETTING)) {
return '';
}
return $settingsStorage->get(CspHeaderSettingsInterface::CSP_HEADER_SETTING);
} | php | private function getSettings()
{
$settingsStorage = $this->getSettingsStorage();
if (!$settingsStorage->exists(CspHeaderSettingsInterface::CSP_HEADER_SETTING)) {
return '';
}
return $settingsStorage->get(CspHeaderSettingsInterface::CSP_HEADER_SETTING);
} | [
"private",
"function",
"getSettings",
"(",
")",
"{",
"$",
"settingsStorage",
"=",
"$",
"this",
"->",
"getSettingsStorage",
"(",
")",
";",
"if",
"(",
"!",
"$",
"settingsStorage",
"->",
"exists",
"(",
"CspHeaderSettingsInterface",
"::",
"CSP_HEADER_SETTING",
")",
... | Get the current settings | [
"Get",
"the",
"current",
"settings"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/form/class.CspHeader.php#L150-L158 |
oat-sa/tao-core | actions/form/class.CspHeader.php | tao_actions_form_CspHeader.getListSettings | private function getListSettings()
{
$settingsStorage = $this->getSettingsStorage();
if (!$settingsStorage->exists(CspHeaderSettingsInterface::CSP_HEADER_LIST)) {
return [];
}
return json_decode($settingsStorage->get(CspHeaderSettingsInterface::CSP_HEADER_LIST));
} | php | private function getListSettings()
{
$settingsStorage = $this->getSettingsStorage();
if (!$settingsStorage->exists(CspHeaderSettingsInterface::CSP_HEADER_LIST)) {
return [];
}
return json_decode($settingsStorage->get(CspHeaderSettingsInterface::CSP_HEADER_LIST));
} | [
"private",
"function",
"getListSettings",
"(",
")",
"{",
"$",
"settingsStorage",
"=",
"$",
"this",
"->",
"getSettingsStorage",
"(",
")",
";",
"if",
"(",
"!",
"$",
"settingsStorage",
"->",
"exists",
"(",
"CspHeaderSettingsInterface",
"::",
"CSP_HEADER_LIST",
")",... | Get the current list settings | [
"Get",
"the",
"current",
"list",
"settings"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/form/class.CspHeader.php#L163-L171 |
oat-sa/tao-core | actions/form/class.CspHeader.php | tao_actions_form_CspHeader.saveSettings | public function saveSettings()
{
$formValues = $this->getForm()->getValues();
$settingStorage = $this->getSettingsStorage();
$configValue = $formValues[self::SOURCE_RADIO_NAME];
if ($configValue === 'list') {
$sources = trim(str_replace("\r", '', $formValues[self::SOURCE_LIST_NAME]));
$sources = explode("\n", $sources);
$settingStorage->set(CspHeaderSettingsInterface::CSP_HEADER_LIST, json_encode($sources));
}
$settingStorage->set(CspHeaderSettingsInterface::CSP_HEADER_SETTING, $configValue);
} | php | public function saveSettings()
{
$formValues = $this->getForm()->getValues();
$settingStorage = $this->getSettingsStorage();
$configValue = $formValues[self::SOURCE_RADIO_NAME];
if ($configValue === 'list') {
$sources = trim(str_replace("\r", '', $formValues[self::SOURCE_LIST_NAME]));
$sources = explode("\n", $sources);
$settingStorage->set(CspHeaderSettingsInterface::CSP_HEADER_LIST, json_encode($sources));
}
$settingStorage->set(CspHeaderSettingsInterface::CSP_HEADER_SETTING, $configValue);
} | [
"public",
"function",
"saveSettings",
"(",
")",
"{",
"$",
"formValues",
"=",
"$",
"this",
"->",
"getForm",
"(",
")",
"->",
"getValues",
"(",
")",
";",
"$",
"settingStorage",
"=",
"$",
"this",
"->",
"getSettingsStorage",
"(",
")",
";",
"$",
"configValue",... | Stores the settings based on the form values. | [
"Stores",
"the",
"settings",
"based",
"on",
"the",
"form",
"values",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/form/class.CspHeader.php#L176-L189 |
oat-sa/tao-core | models/classes/GenerisTreeFactory.php | GenerisTreeFactory.classToNode | private function classToNode(core_kernel_classes_Class $class, core_kernel_classes_Class $parent = null) {
$returnValue = $this->buildClassNode($class, $parent);
// allow the class to be opened if it contains either instances or subclasses
$subclasses = $this->getSubClasses($class);
if($this->showResources) {
$options = array_merge(['recursive' => false], $this->optionsFilter);
$queryBuilder = $this->getQueryBuilder($class, $this->propertyFilter, $options);
$search = $this->getSearchService();
$search->setLanguage($queryBuilder, \common_session_SessionManager::getSession()->getDataLanguage());
$instancesCount = $search->getGateway()->count($queryBuilder);
if ($instancesCount > 0 || count($subclasses) > 0) {
if (in_array($class->getUri(), $this->openNodes)) {
$returnValue['state'] = 'open';
$returnValue['children'] = $this->buildChildNodes($class, $subclasses);
} else {
$returnValue['state'] = 'closed';
}
// only show the resources count if we allow resources to be viewed
$returnValue['count'] = $instancesCount;
}
} else {
if(count($subclasses) > 0) {
if (in_array($class->getUri(), $this->openNodes)) {
$returnValue['state'] = 'open';
$returnValue['children'] = $this->buildChildNodes($class, $subclasses);
} else {
$returnValue['state'] = 'closed';
}
$returnValue['count'] = 0;
}
}
return $returnValue;
} | php | private function classToNode(core_kernel_classes_Class $class, core_kernel_classes_Class $parent = null) {
$returnValue = $this->buildClassNode($class, $parent);
// allow the class to be opened if it contains either instances or subclasses
$subclasses = $this->getSubClasses($class);
if($this->showResources) {
$options = array_merge(['recursive' => false], $this->optionsFilter);
$queryBuilder = $this->getQueryBuilder($class, $this->propertyFilter, $options);
$search = $this->getSearchService();
$search->setLanguage($queryBuilder, \common_session_SessionManager::getSession()->getDataLanguage());
$instancesCount = $search->getGateway()->count($queryBuilder);
if ($instancesCount > 0 || count($subclasses) > 0) {
if (in_array($class->getUri(), $this->openNodes)) {
$returnValue['state'] = 'open';
$returnValue['children'] = $this->buildChildNodes($class, $subclasses);
} else {
$returnValue['state'] = 'closed';
}
// only show the resources count if we allow resources to be viewed
$returnValue['count'] = $instancesCount;
}
} else {
if(count($subclasses) > 0) {
if (in_array($class->getUri(), $this->openNodes)) {
$returnValue['state'] = 'open';
$returnValue['children'] = $this->buildChildNodes($class, $subclasses);
} else {
$returnValue['state'] = 'closed';
}
$returnValue['count'] = 0;
}
}
return $returnValue;
} | [
"private",
"function",
"classToNode",
"(",
"core_kernel_classes_Class",
"$",
"class",
",",
"core_kernel_classes_Class",
"$",
"parent",
"=",
"null",
")",
"{",
"$",
"returnValue",
"=",
"$",
"this",
"->",
"buildClassNode",
"(",
"$",
"class",
",",
"$",
"parent",
"... | Builds a class node including it's content
@param core_kernel_classes_Class $class
@param core_kernel_classes_Class $parent
@return array
@throws | [
"Builds",
"a",
"class",
"node",
"including",
"it",
"s",
"content"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/GenerisTreeFactory.php#L134-L171 |
oat-sa/tao-core | models/classes/GenerisTreeFactory.php | GenerisTreeFactory.buildChildNodes | private function buildChildNodes(core_kernel_classes_Class $class, $subclasses)
{
$children = [];
// subclasses
foreach ($subclasses as $subclass) {
$children[] = $this->classToNode($subclass, $class);
}
// resources
if ($this->showResources) {
$limit = $this->limit;
if (in_array($class->getUri(), $this->browsableTypes)) {
$limit = 0;
}
$options = array_merge([
'limit' => $limit,
'offset' => $this->offset,
'recursive' => false,
'order' => [OntologyRdfs::RDFS_LABEL => 'asc'],
], $this->optionsFilter);
$queryBuilder = $this->getQueryBuilder($class, $this->propertyFilter, $options);
$search = $this->getSearchService();
$search->setLanguage($queryBuilder, \common_session_SessionManager::getSession()->getDataLanguage());
$searchResult = $search->getGateway()->search($queryBuilder);
foreach ($searchResult as $instance){
$children[] = TreeHelper::buildResourceNode($instance, $class, $this->extraProperties);
}
}
return $children;
} | php | private function buildChildNodes(core_kernel_classes_Class $class, $subclasses)
{
$children = [];
// subclasses
foreach ($subclasses as $subclass) {
$children[] = $this->classToNode($subclass, $class);
}
// resources
if ($this->showResources) {
$limit = $this->limit;
if (in_array($class->getUri(), $this->browsableTypes)) {
$limit = 0;
}
$options = array_merge([
'limit' => $limit,
'offset' => $this->offset,
'recursive' => false,
'order' => [OntologyRdfs::RDFS_LABEL => 'asc'],
], $this->optionsFilter);
$queryBuilder = $this->getQueryBuilder($class, $this->propertyFilter, $options);
$search = $this->getSearchService();
$search->setLanguage($queryBuilder, \common_session_SessionManager::getSession()->getDataLanguage());
$searchResult = $search->getGateway()->search($queryBuilder);
foreach ($searchResult as $instance){
$children[] = TreeHelper::buildResourceNode($instance, $class, $this->extraProperties);
}
}
return $children;
} | [
"private",
"function",
"buildChildNodes",
"(",
"core_kernel_classes_Class",
"$",
"class",
",",
"$",
"subclasses",
")",
"{",
"$",
"children",
"=",
"[",
"]",
";",
"// subclasses",
"foreach",
"(",
"$",
"subclasses",
"as",
"$",
"subclass",
")",
"{",
"$",
"childr... | Builds the content of a class node including it's content
@param core_kernel_classes_Class $class
@param core_kernel_classes_Class[] $subclasses
@return array
@throws | [
"Builds",
"the",
"content",
"of",
"a",
"class",
"node",
"including",
"it",
"s",
"content"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/GenerisTreeFactory.php#L181-L213 |
oat-sa/tao-core | models/classes/GenerisTreeFactory.php | GenerisTreeFactory.buildClassNode | private function buildClassNode(core_kernel_classes_Class $class, core_kernel_classes_Class $parent = null)
{
$label = $class->getLabel();
$label = empty($label) ? __('no label') : $label;
return array(
'data' => _dh($label),
'type' => 'class',
'attributes' => array(
'id' => tao_helpers_Uri::encode($class->getUri()),
'class' => 'node-class',
'data-uri' => $class->getUri(),
'data-classUri' => is_null($parent) ? null : $parent->getUri(),
'data-signature' => $this->getSignatureGenerator()->generate($class->getUri()),
)
);
} | php | private function buildClassNode(core_kernel_classes_Class $class, core_kernel_classes_Class $parent = null)
{
$label = $class->getLabel();
$label = empty($label) ? __('no label') : $label;
return array(
'data' => _dh($label),
'type' => 'class',
'attributes' => array(
'id' => tao_helpers_Uri::encode($class->getUri()),
'class' => 'node-class',
'data-uri' => $class->getUri(),
'data-classUri' => is_null($parent) ? null : $parent->getUri(),
'data-signature' => $this->getSignatureGenerator()->generate($class->getUri()),
)
);
} | [
"private",
"function",
"buildClassNode",
"(",
"core_kernel_classes_Class",
"$",
"class",
",",
"core_kernel_classes_Class",
"$",
"parent",
"=",
"null",
")",
"{",
"$",
"label",
"=",
"$",
"class",
"->",
"getLabel",
"(",
")",
";",
"$",
"label",
"=",
"empty",
"("... | generis tree representation of a class node
without it's content
@param core_kernel_classes_Class $class
@param core_kernel_classes_Class $parent
@return array | [
"generis",
"tree",
"representation",
"of",
"a",
"class",
"node",
"without",
"it",
"s",
"content"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/GenerisTreeFactory.php#L224-L240 |
oat-sa/tao-core | models/classes/taskQueue/QueueDispatcher.php | QueueDispatcher.getDefaultQueue | public function getDefaultQueue()
{
return $this->hasOption(self::OPTION_DEFAULT_QUEUE) && $this->getOption(self::OPTION_DEFAULT_QUEUE)
? $this->getQueue($this->getOption(self::OPTION_DEFAULT_QUEUE))
: $this->getFirstQueue();
} | php | public function getDefaultQueue()
{
return $this->hasOption(self::OPTION_DEFAULT_QUEUE) && $this->getOption(self::OPTION_DEFAULT_QUEUE)
? $this->getQueue($this->getOption(self::OPTION_DEFAULT_QUEUE))
: $this->getFirstQueue();
} | [
"public",
"function",
"getDefaultQueue",
"(",
")",
"{",
"return",
"$",
"this",
"->",
"hasOption",
"(",
"self",
"::",
"OPTION_DEFAULT_QUEUE",
")",
"&&",
"$",
"this",
"->",
"getOption",
"(",
"self",
"::",
"OPTION_DEFAULT_QUEUE",
")",
"?",
"$",
"this",
"->",
... | Return the first queue as a default one.
Maybe, later we need other logic the determine the default queue.
@return QueueInterface | [
"Return",
"the",
"first",
"queue",
"as",
"a",
"default",
"one",
".",
"Maybe",
"later",
"we",
"need",
"other",
"logic",
"the",
"determine",
"the",
"default",
"queue",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/taskQueue/QueueDispatcher.php#L233-L238 |
oat-sa/tao-core | models/classes/taskQueue/QueueDispatcher.php | QueueDispatcher.dequeue | public function dequeue()
{
// if there is only one queue defined, let's use that
if(count($this->getQueues()) === 1) {
return $this->getFirstQueue()->dequeue();
}
// default: getting a task using the current task selector strategy
return $this->selectorStrategy->pickNextTask($this->getQueues());
} | php | public function dequeue()
{
// if there is only one queue defined, let's use that
if(count($this->getQueues()) === 1) {
return $this->getFirstQueue()->dequeue();
}
// default: getting a task using the current task selector strategy
return $this->selectorStrategy->pickNextTask($this->getQueues());
} | [
"public",
"function",
"dequeue",
"(",
")",
"{",
"// if there is only one queue defined, let's use that",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"getQueues",
"(",
")",
")",
"===",
"1",
")",
"{",
"return",
"$",
"this",
"->",
"getFirstQueue",
"(",
")",
"->... | Receive a task from a specified queue or from a queue selected by a predefined strategy
@inheritdoc | [
"Receive",
"a",
"task",
"from",
"a",
"specified",
"queue",
"or",
"from",
"a",
"queue",
"selected",
"by",
"a",
"predefined",
"strategy"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/taskQueue/QueueDispatcher.php#L344-L353 |
oat-sa/tao-core | models/classes/taskQueue/QueueDispatcher.php | QueueDispatcher.count | public function count()
{
$counts = array_map(function(QueueInterface $queue) {
return $queue->count();
}, $this->getQueues());
return array_sum($counts);
} | php | public function count()
{
$counts = array_map(function(QueueInterface $queue) {
return $queue->count();
}, $this->getQueues());
return array_sum($counts);
} | [
"public",
"function",
"count",
"(",
")",
"{",
"$",
"counts",
"=",
"array_map",
"(",
"function",
"(",
"QueueInterface",
"$",
"queue",
")",
"{",
"return",
"$",
"queue",
"->",
"count",
"(",
")",
";",
"}",
",",
"$",
"this",
"->",
"getQueues",
"(",
")",
... | Count of messages in all queues.
@return int | [
"Count",
"of",
"messages",
"in",
"all",
"queues",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/taskQueue/QueueDispatcher.php#L368-L375 |
oat-sa/tao-core | models/classes/taskQueue/TaskLogActionTrait.php | TaskLogActionTrait.returnTaskJson | protected function returnTaskJson(TaskInterface $task, array $extraData = [])
{
return $this->returnJson([
'success' => true,
'data' => [
'extra' => $extraData,
'task' => $this->getTaskLogReturnData($task->getId())
]
]);
} | php | protected function returnTaskJson(TaskInterface $task, array $extraData = [])
{
return $this->returnJson([
'success' => true,
'data' => [
'extra' => $extraData,
'task' => $this->getTaskLogReturnData($task->getId())
]
]);
} | [
"protected",
"function",
"returnTaskJson",
"(",
"TaskInterface",
"$",
"task",
",",
"array",
"$",
"extraData",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"returnJson",
"(",
"[",
"'success'",
"=>",
"true",
",",
"'data'",
"=>",
"[",
"'extra'",
"=... | Returns task data in a specific data structure required by the front-end component.
@param TaskInterface $task
@param array $extraData
@return mixed | [
"Returns",
"task",
"data",
"in",
"a",
"specific",
"data",
"structure",
"required",
"by",
"the",
"front",
"-",
"end",
"component",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/taskQueue/TaskLogActionTrait.php#L103-L112 |
oat-sa/tao-core | helpers/class.File.php | tao_helpers_File.securityCheck | public static function securityCheck($path, $traversalSafe = false)
{
$returnValue = true;
//security check: detect directory traversal (deny the ../)
if($traversalSafe){
if(preg_match("/\.\.\//", $path)){
$returnValue = false;
common_Logger::w('directory traversal detected in ' . $path);
}
}
//security check: detect the null byte poison by finding the null char injection
if($returnValue){
for($i = 0; $i < strlen($path); $i++){
if(ord($path[$i]) === 0){
$returnValue = false;
common_Logger::w('null char injection detected in ' . $path);
break;
}
}
}
return (bool) $returnValue;
} | php | public static function securityCheck($path, $traversalSafe = false)
{
$returnValue = true;
//security check: detect directory traversal (deny the ../)
if($traversalSafe){
if(preg_match("/\.\.\//", $path)){
$returnValue = false;
common_Logger::w('directory traversal detected in ' . $path);
}
}
//security check: detect the null byte poison by finding the null char injection
if($returnValue){
for($i = 0; $i < strlen($path); $i++){
if(ord($path[$i]) === 0){
$returnValue = false;
common_Logger::w('null char injection detected in ' . $path);
break;
}
}
}
return (bool) $returnValue;
} | [
"public",
"static",
"function",
"securityCheck",
"(",
"$",
"path",
",",
"$",
"traversalSafe",
"=",
"false",
")",
"{",
"$",
"returnValue",
"=",
"true",
";",
"//security check: detect directory traversal (deny the ../)",
"if",
"(",
"$",
"traversalSafe",
")",
"{",
"i... | Check if the path in parameter can be securly used into the application.
(check the cross directory injection, the null byte injection, etc.)
Use it when the path may be build from a user variable
@author Lionel Lecaque, <lionel@taotesting.com>
@param string $path The path to check.
@param boolean $traversalSafe (optional, default is false) Check if the path is traversal safe.
@return boolean States if the path is secure or not. | [
"Check",
"if",
"the",
"path",
"in",
"parameter",
"can",
"be",
"securly",
"used",
"into",
"the",
"application",
".",
"(",
"check",
"the",
"cross",
"directory",
"injection",
"the",
"null",
"byte",
"injection",
"etc",
".",
")",
"Use",
"it",
"when",
"the",
"... | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/class.File.php#L43-L67 |
oat-sa/tao-core | helpers/class.File.php | tao_helpers_File.concat | public static function concat($paths)
{
$returnValue = (string) '';
foreach ($paths as $path){
if (!preg_match("/\/$/", $returnValue) && !preg_match("/^\//", $path) && !empty($returnValue)){
$returnValue .= '/';
}
$returnValue .= $path;
}
$returnValue = str_replace('//', '/', $returnValue);
return (string) $returnValue;
} | php | public static function concat($paths)
{
$returnValue = (string) '';
foreach ($paths as $path){
if (!preg_match("/\/$/", $returnValue) && !preg_match("/^\//", $path) && !empty($returnValue)){
$returnValue .= '/';
}
$returnValue .= $path;
}
$returnValue = str_replace('//', '/', $returnValue);
return (string) $returnValue;
} | [
"public",
"static",
"function",
"concat",
"(",
"$",
"paths",
")",
"{",
"$",
"returnValue",
"=",
"(",
"string",
")",
"''",
";",
"foreach",
"(",
"$",
"paths",
"as",
"$",
"path",
")",
"{",
"if",
"(",
"!",
"preg_match",
"(",
"\"/\\/$/\"",
",",
"$",
"re... | Use this method to cleanly concat components of a path. It will remove extra slashes/backslashes.
@author Lionel Lecaque, <lionel@taotesting.com>
@param array $paths The path components to concatenate.
@return string The concatenated path. | [
"Use",
"this",
"method",
"to",
"cleanly",
"concat",
"components",
"of",
"a",
"path",
".",
"It",
"will",
"remove",
"extra",
"slashes",
"/",
"backslashes",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/class.File.php#L76-L89 |
oat-sa/tao-core | helpers/class.File.php | tao_helpers_File.remove | public static function remove($path, $recursive = false)
{
$returnValue = (bool) false;
if ($recursive) {
$returnValue = helpers_File::remove($path);
} elseif (is_file($path)) {
$returnValue = @unlink($path);
}
// else fail silently
return (bool) $returnValue;
} | php | public static function remove($path, $recursive = false)
{
$returnValue = (bool) false;
if ($recursive) {
$returnValue = helpers_File::remove($path);
} elseif (is_file($path)) {
$returnValue = @unlink($path);
}
// else fail silently
return (bool) $returnValue;
} | [
"public",
"static",
"function",
"remove",
"(",
"$",
"path",
",",
"$",
"recursive",
"=",
"false",
")",
"{",
"$",
"returnValue",
"=",
"(",
"bool",
")",
"false",
";",
"if",
"(",
"$",
"recursive",
")",
"{",
"$",
"returnValue",
"=",
"helpers_File",
"::",
... | Remove a file. If the recursive parameter is set to true, the target file
can be a directory that contains data.
@author Lionel Lecaque, <lionel@taotesting.com>
@param string $path The path to the file you want to remove.
@param boolean $recursive (optional, default is false) Remove file content recursively (only if the path points to a directory).
@return boolean Return true if the file is correctly removed, false otherwise. | [
"Remove",
"a",
"file",
".",
"If",
"the",
"recursive",
"parameter",
"is",
"set",
"to",
"true",
"the",
"target",
"file",
"can",
"be",
"a",
"directory",
"that",
"contains",
"data",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/class.File.php#L100-L112 |
oat-sa/tao-core | helpers/class.File.php | tao_helpers_File.move | public static function move($source, $destination)
{
$returnValue = (bool) false;
if(is_dir($source)){
if(!file_exists($destination)){
mkdir($destination, 0777, true);
}
$error = false;
foreach(scandir($source) as $file){
if($file != '.' && $file != '..'){
if(is_dir($source.'/'.$file)){
if(!self::move($source.'/'.$file, $destination.'/'.$file, true)){
$error = true;
}
}
else{
if(!self::copy($source.'/'.$file, $destination.'/'.$file, true)){
$error = true;
}
}
}
}
if(!$error){
$returnValue = true;
}
self::remove($source, true);
}
else{
if(file_exists($source) && file_exists($destination)){
$returnValue = rename($source, $destination);
}
else{
if(self::copy($source, $destination, true)){
$returnValue = self::remove($source);
}
}
}
return (bool) $returnValue;
} | php | public static function move($source, $destination)
{
$returnValue = (bool) false;
if(is_dir($source)){
if(!file_exists($destination)){
mkdir($destination, 0777, true);
}
$error = false;
foreach(scandir($source) as $file){
if($file != '.' && $file != '..'){
if(is_dir($source.'/'.$file)){
if(!self::move($source.'/'.$file, $destination.'/'.$file, true)){
$error = true;
}
}
else{
if(!self::copy($source.'/'.$file, $destination.'/'.$file, true)){
$error = true;
}
}
}
}
if(!$error){
$returnValue = true;
}
self::remove($source, true);
}
else{
if(file_exists($source) && file_exists($destination)){
$returnValue = rename($source, $destination);
}
else{
if(self::copy($source, $destination, true)){
$returnValue = self::remove($source);
}
}
}
return (bool) $returnValue;
} | [
"public",
"static",
"function",
"move",
"(",
"$",
"source",
",",
"$",
"destination",
")",
"{",
"$",
"returnValue",
"=",
"(",
"bool",
")",
"false",
";",
"if",
"(",
"is_dir",
"(",
"$",
"source",
")",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",... | Move file from source to destination.
@author Lionel Lecaque, <lionel@taotesting.com>
@param string $source A path to the source file.
@param string $destination A path to the destination file.
@return boolean Returns true if the file was successfully moved, false otherwise. | [
"Move",
"file",
"from",
"source",
"to",
"destination",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/class.File.php#L122-L162 |
oat-sa/tao-core | helpers/class.File.php | tao_helpers_File.getExtention | public static function getExtention($mimeType)
{
$returnValue = (string) '';
foreach(self::getMimeTypeList() as $key => $value){
if($value == trim($mimeType)){
$returnValue = $key;
break;
}
}
return (string) $returnValue;
} | php | public static function getExtention($mimeType)
{
$returnValue = (string) '';
foreach(self::getMimeTypeList() as $key => $value){
if($value == trim($mimeType)){
$returnValue = $key;
break;
}
}
return (string) $returnValue;
} | [
"public",
"static",
"function",
"getExtention",
"(",
"$",
"mimeType",
")",
"{",
"$",
"returnValue",
"=",
"(",
"string",
")",
"''",
";",
"foreach",
"(",
"self",
"::",
"getMimeTypeList",
"(",
")",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"... | Retrieve file extensions usually associated to a given mime-type.
@author Lionel Lecaque, <lionel@taotesting.com>
@param string $mimeType A mime-type which is recognized by the platform.
@return string The extension usually associated to the mime-type. If it could not be retrieved, an empty string is returned. | [
"Retrieve",
"file",
"extensions",
"usually",
"associated",
"to",
"a",
"given",
"mime",
"-",
"type",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/class.File.php#L254-L266 |
oat-sa/tao-core | helpers/class.File.php | tao_helpers_File.getFileExtention | public static function getFileExtention($path)
{
$ext = pathinfo($path, PATHINFO_EXTENSION);
if($ext === ''){
$splitedPath = explode('.', $path);
$ext = end($splitedPath);
}
return $ext;
} | php | public static function getFileExtention($path)
{
$ext = pathinfo($path, PATHINFO_EXTENSION);
if($ext === ''){
$splitedPath = explode('.', $path);
$ext = end($splitedPath);
}
return $ext;
} | [
"public",
"static",
"function",
"getFileExtention",
"(",
"$",
"path",
")",
"{",
"$",
"ext",
"=",
"pathinfo",
"(",
"$",
"path",
",",
"PATHINFO_EXTENSION",
")",
";",
"if",
"(",
"$",
"ext",
"===",
"''",
")",
"{",
"$",
"splitedPath",
"=",
"explode",
"(",
... | Retrieve file extensions of a file
@param string $path the path of the file we want to get the extension
@return string The extension of the parameter file | [
"Retrieve",
"file",
"extensions",
"of",
"a",
"file"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/class.File.php#L275-L286 |
oat-sa/tao-core | helpers/class.File.php | tao_helpers_File.getMimeType | public static function getMimeType($path, $ext = false)
{
$mime_types = self::getMimeTypeList();
if (false == $ext){
$ext = pathinfo($path, PATHINFO_EXTENSION);
if (array_key_exists($ext, $mime_types)) {
$mimetype = $mime_types[$ext];
}
else {
$mimetype = '';
}
if (!in_array($ext, array('css', 'ogg', 'mp3'))) {
if (file_exists($path)) {
if (function_exists('finfo_open')) {
$finfo = finfo_open(FILEINFO_MIME);
$mimetype = finfo_file($finfo, $path);
finfo_close($finfo);
}
else if (function_exists('mime_content_type')) {
$mimetype = mime_content_type($path);
}
if (!empty($mimetype)) {
if (preg_match("/; charset/", $mimetype)) {
$mimetypeInfos = explode(';', $mimetype);
$mimetype = $mimetypeInfos[0];
}
}
}
}
}
else{
// find out the mime-type from the extension of the file.
$ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
if (array_key_exists($ext, $mime_types)){
$mimetype = $mime_types[$ext];
}
}
// If no mime-type found ...
if (empty($mimetype)) {
$mimetype = 'application/octet-stream';
}
return (string) $mimetype;
} | php | public static function getMimeType($path, $ext = false)
{
$mime_types = self::getMimeTypeList();
if (false == $ext){
$ext = pathinfo($path, PATHINFO_EXTENSION);
if (array_key_exists($ext, $mime_types)) {
$mimetype = $mime_types[$ext];
}
else {
$mimetype = '';
}
if (!in_array($ext, array('css', 'ogg', 'mp3'))) {
if (file_exists($path)) {
if (function_exists('finfo_open')) {
$finfo = finfo_open(FILEINFO_MIME);
$mimetype = finfo_file($finfo, $path);
finfo_close($finfo);
}
else if (function_exists('mime_content_type')) {
$mimetype = mime_content_type($path);
}
if (!empty($mimetype)) {
if (preg_match("/; charset/", $mimetype)) {
$mimetypeInfos = explode(';', $mimetype);
$mimetype = $mimetypeInfos[0];
}
}
}
}
}
else{
// find out the mime-type from the extension of the file.
$ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
if (array_key_exists($ext, $mime_types)){
$mimetype = $mime_types[$ext];
}
}
// If no mime-type found ...
if (empty($mimetype)) {
$mimetype = 'application/octet-stream';
}
return (string) $mimetype;
} | [
"public",
"static",
"function",
"getMimeType",
"(",
"$",
"path",
",",
"$",
"ext",
"=",
"false",
")",
"{",
"$",
"mime_types",
"=",
"self",
"::",
"getMimeTypeList",
"(",
")",
";",
"if",
"(",
"false",
"==",
"$",
"ext",
")",
"{",
"$",
"ext",
"=",
"path... | Get the mime-type of the file in parameter.
different methods are used regarding the configuration of the server.
@author Lionel Lecaque, <lionel@taotesting.com>
@param string $path
@param boolean $ext If set to true, the extension of the file will be used to retrieve the mime-type. If now extension can be found, 'text/plain' is returned by the method.
@return string The associated mime-type. | [
"Get",
"the",
"mime",
"-",
"type",
"of",
"the",
"file",
"in",
"parameter",
".",
"different",
"methods",
"are",
"used",
"regarding",
"the",
"configuration",
"of",
"the",
"server",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/class.File.php#L297-L344 |
oat-sa/tao-core | helpers/class.File.php | tao_helpers_File.createTempDir | public static function createTempDir()
{
do {
$folder = sys_get_temp_dir().DIRECTORY_SEPARATOR."tmp".mt_rand().DIRECTORY_SEPARATOR;
} while (file_exists($folder));
mkdir($folder);
return $folder;
} | php | public static function createTempDir()
{
do {
$folder = sys_get_temp_dir().DIRECTORY_SEPARATOR."tmp".mt_rand().DIRECTORY_SEPARATOR;
} while (file_exists($folder));
mkdir($folder);
return $folder;
} | [
"public",
"static",
"function",
"createTempDir",
"(",
")",
"{",
"do",
"{",
"$",
"folder",
"=",
"sys_get_temp_dir",
"(",
")",
".",
"DIRECTORY_SEPARATOR",
".",
"\"tmp\"",
".",
"mt_rand",
"(",
")",
".",
"DIRECTORY_SEPARATOR",
";",
"}",
"while",
"(",
"file_exist... | creates a directory in the system's temp dir.
@author Lionel Lecaque, <lionel@taotesting.com>
@return string The path to the created folder. | [
"creates",
"a",
"directory",
"in",
"the",
"system",
"s",
"temp",
"dir",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/class.File.php#L352-L359 |
oat-sa/tao-core | helpers/class.File.php | tao_helpers_File.delTree | public static function delTree($directory)
{
$files = array_diff(scandir($directory), array('.','..'));
foreach ($files as $file) {
$abspath = $directory.DIRECTORY_SEPARATOR.$file;
if (is_dir($abspath)) {
self::delTree($abspath);
} else {
unlink($abspath);
}
}
return rmdir($directory);
} | php | public static function delTree($directory)
{
$files = array_diff(scandir($directory), array('.','..'));
foreach ($files as $file) {
$abspath = $directory.DIRECTORY_SEPARATOR.$file;
if (is_dir($abspath)) {
self::delTree($abspath);
} else {
unlink($abspath);
}
}
return rmdir($directory);
} | [
"public",
"static",
"function",
"delTree",
"(",
"$",
"directory",
")",
"{",
"$",
"files",
"=",
"array_diff",
"(",
"scandir",
"(",
"$",
"directory",
")",
",",
"array",
"(",
"'.'",
",",
"'..'",
")",
")",
";",
"foreach",
"(",
"$",
"files",
"as",
"$",
... | deletes a directory and its content.
@author Lionel Lecaque, <lionel@taotesting.com>
@param string directory absolute path of the directory
@return boolean true if the directory and its content were deleted, false otherwise. | [
"deletes",
"a",
"directory",
"and",
"its",
"content",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/class.File.php#L368-L382 |
oat-sa/tao-core | helpers/class.File.php | tao_helpers_File.createZip | public static function createZip($src, $withEmptyDir = false) {
$zipArchive = new \ZipArchive();
$path = self::createTempDir().'file.zip';
if ($zipArchive->open($path, \ZipArchive::CREATE)!==TRUE) {
throw new common_Exception('Unable to create zipfile '.$path);
}
self::addFilesToZip($zipArchive, $src, DIRECTORY_SEPARATOR, $withEmptyDir);
$zipArchive->close();
return $path;
} | php | public static function createZip($src, $withEmptyDir = false) {
$zipArchive = new \ZipArchive();
$path = self::createTempDir().'file.zip';
if ($zipArchive->open($path, \ZipArchive::CREATE)!==TRUE) {
throw new common_Exception('Unable to create zipfile '.$path);
}
self::addFilesToZip($zipArchive, $src, DIRECTORY_SEPARATOR, $withEmptyDir);
$zipArchive->close();
return $path;
} | [
"public",
"static",
"function",
"createZip",
"(",
"$",
"src",
",",
"$",
"withEmptyDir",
"=",
"false",
")",
"{",
"$",
"zipArchive",
"=",
"new",
"\\",
"ZipArchive",
"(",
")",
";",
"$",
"path",
"=",
"self",
"::",
"createTempDir",
"(",
")",
".",
"'file.zip... | Create a zip of a directory or file
@param string $src path to the files to zip
@param bool $withEmptyDir
@return string path to the zip file
@throws common_Exception if unable to create the zip | [
"Create",
"a",
"zip",
"of",
"a",
"directory",
"or",
"file"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/class.File.php#L417-L426 |
oat-sa/tao-core | helpers/class.File.php | tao_helpers_File.addFilesToZip | public static function addFilesToZip(ZipArchive $zipArchive, $src, $dest, $withEmptyDir = false) {
$returnValue = null;
$done = 0;
if ($src instanceof \Psr\Http\Message\StreamInterface) {
if ($zipArchive->addFromString(ltrim($dest, "/\\"), $src->getContents())) {
$done++;
}
} elseif (is_resource($src)) {
fseek($src, 0);
$content = stream_get_contents($src);
if ($zipArchive->addFromString(ltrim($dest, "/\\"), $content)) {
$done++;
}
} elseif (is_dir($src)) {
// Go deeper in folder hierarchy !
$src = rtrim($src, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$dest = rtrim($dest, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
if ($withEmptyDir) {
$zipArchive->addEmptyDir($dest);
}
// Recursively copy.
$content = scandir($src);
foreach ($content as $file) {
// avoid . , .. , .svn etc ...
if (!preg_match("/^\./", $file)) {
$done += self::addFilesToZip($zipArchive, $src . $file, $dest . $file, $withEmptyDir);
}
}
} else {
// Simply copy the file. Beware of leading slashes
if ($zipArchive->addFile($src, ltrim($dest, DIRECTORY_SEPARATOR))) {
$done++;
}
}
$returnValue = $done;
return $returnValue;
} | php | public static function addFilesToZip(ZipArchive $zipArchive, $src, $dest, $withEmptyDir = false) {
$returnValue = null;
$done = 0;
if ($src instanceof \Psr\Http\Message\StreamInterface) {
if ($zipArchive->addFromString(ltrim($dest, "/\\"), $src->getContents())) {
$done++;
}
} elseif (is_resource($src)) {
fseek($src, 0);
$content = stream_get_contents($src);
if ($zipArchive->addFromString(ltrim($dest, "/\\"), $content)) {
$done++;
}
} elseif (is_dir($src)) {
// Go deeper in folder hierarchy !
$src = rtrim($src, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$dest = rtrim($dest, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
if ($withEmptyDir) {
$zipArchive->addEmptyDir($dest);
}
// Recursively copy.
$content = scandir($src);
foreach ($content as $file) {
// avoid . , .. , .svn etc ...
if (!preg_match("/^\./", $file)) {
$done += self::addFilesToZip($zipArchive, $src . $file, $dest . $file, $withEmptyDir);
}
}
} else {
// Simply copy the file. Beware of leading slashes
if ($zipArchive->addFile($src, ltrim($dest, DIRECTORY_SEPARATOR))) {
$done++;
}
}
$returnValue = $done;
return $returnValue;
} | [
"public",
"static",
"function",
"addFilesToZip",
"(",
"ZipArchive",
"$",
"zipArchive",
",",
"$",
"src",
",",
"$",
"dest",
",",
"$",
"withEmptyDir",
"=",
"false",
")",
"{",
"$",
"returnValue",
"=",
"null",
";",
"$",
"done",
"=",
"0",
";",
"if",
"(",
"... | Add files or folders (and their content) to the Zip Archive that will contain all the files to the current export session.
For instance, if you want to copy the file 'taoItems/data/i123/item.xml' as 'myitem.xml' to your archive call addFile('path_to_item_location/item.xml', 'myitem.xml').
As a result, you will get a file entry in the final ZIP archive at '/i123/myitem.xml'.
@param ZipArchive $zipArchive the archive to add to
@param string $src | StreamInterface The path to the source file or folder to copy into the ZIP Archive.
@param $dest
@param bool $withEmptyDir
@return integer The amount of files that were transfered from TAO to the ZIP archive within the method call. | [
"Add",
"files",
"or",
"folders",
"(",
"and",
"their",
"content",
")",
"to",
"the",
"Zip",
"Archive",
"that",
"will",
"contain",
"all",
"the",
"files",
"to",
"the",
"current",
"export",
"session",
".",
"For",
"instance",
"if",
"you",
"want",
"to",
"copy",... | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/class.File.php#L439-L482 |
oat-sa/tao-core | helpers/class.File.php | tao_helpers_File.renameInZip | public static function renameInZip(ZipArchive $zipArchive, $oldname, $newname)
{
$i = 0;
$renameCount = 0;
while (($entryName = $zipArchive->getNameIndex($i)) || ($statIndex = $zipArchive->statIndex($i,ZipArchive::FL_UNCHANGED))) {
if ($entryName) {
$newEntryName = str_replace($oldname, $newname, $entryName);
if ($zipArchive->renameIndex($i, $newEntryName)) {
$renameCount++;
}
}
$i++;
}
return $renameCount;
} | php | public static function renameInZip(ZipArchive $zipArchive, $oldname, $newname)
{
$i = 0;
$renameCount = 0;
while (($entryName = $zipArchive->getNameIndex($i)) || ($statIndex = $zipArchive->statIndex($i,ZipArchive::FL_UNCHANGED))) {
if ($entryName) {
$newEntryName = str_replace($oldname, $newname, $entryName);
if ($zipArchive->renameIndex($i, $newEntryName)) {
$renameCount++;
}
}
$i++;
}
return $renameCount;
} | [
"public",
"static",
"function",
"renameInZip",
"(",
"ZipArchive",
"$",
"zipArchive",
",",
"$",
"oldname",
",",
"$",
"newname",
")",
"{",
"$",
"i",
"=",
"0",
";",
"$",
"renameCount",
"=",
"0",
";",
"while",
"(",
"(",
"$",
"entryName",
"=",
"$",
"zipAr... | Rename in Zip
Rename an item in a ZIP archive. Works for files and directories.
In case of renaming directories, the return value of this method will be the amount of files
affected by the directory renaming.
@param ZipArchive $zipArchive An open ZipArchive object.
@param string $oldname
@param string $newname
@return int The amount of renamed entries. | [
"Rename",
"in",
"Zip"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/class.File.php#L497-L514 |
oat-sa/tao-core | helpers/class.File.php | tao_helpers_File.checkWhetherArchiveIsBomb | public static function checkWhetherArchiveIsBomb(\ZipArchive $archive, $minCompressionRatioToBeBomb = 200)
{
if (!$archive->filename) {
throw new common_Exception('ZIP archive should be opened before checking for a ZIP bomb');
}
$contentSize = 0;
for ($fileIndex = 0; $fileIndex < $archive->numFiles; $fileIndex++) {
$stats = $archive->statIndex($fileIndex);
$contentSize += $stats['size'];
}
$archiveFileSize = filesize($archive->filename);
return $archiveFileSize * $minCompressionRatioToBeBomb < $contentSize;
} | php | public static function checkWhetherArchiveIsBomb(\ZipArchive $archive, $minCompressionRatioToBeBomb = 200)
{
if (!$archive->filename) {
throw new common_Exception('ZIP archive should be opened before checking for a ZIP bomb');
}
$contentSize = 0;
for ($fileIndex = 0; $fileIndex < $archive->numFiles; $fileIndex++) {
$stats = $archive->statIndex($fileIndex);
$contentSize += $stats['size'];
}
$archiveFileSize = filesize($archive->filename);
return $archiveFileSize * $minCompressionRatioToBeBomb < $contentSize;
} | [
"public",
"static",
"function",
"checkWhetherArchiveIsBomb",
"(",
"\\",
"ZipArchive",
"$",
"archive",
",",
"$",
"minCompressionRatioToBeBomb",
"=",
"200",
")",
"{",
"if",
"(",
"!",
"$",
"archive",
"->",
"filename",
")",
"{",
"throw",
"new",
"common_Exception",
... | Helps prevent decompression attacks.
Since this method checks archive file size, it needs filename property to be set,
so ZipArchive object should be already opened.
@param \ZipArchive $archive
@param int $minCompressionRatioToBeBomb archive content size / archive size
@return bool
@throws common_Exception
@link https://en.wikipedia.org/wiki/Zip_bomb | [
"Helps",
"prevent",
"decompression",
"attacks",
".",
"Since",
"this",
"method",
"checks",
"archive",
"file",
"size",
"it",
"needs",
"filename",
"property",
"to",
"be",
"set",
"so",
"ZipArchive",
"object",
"should",
"be",
"already",
"opened",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/class.File.php#L528-L543 |
oat-sa/tao-core | helpers/class.File.php | tao_helpers_File.excludeFromZip | public static function excludeFromZip(ZipArchive $zipArchive, $pattern)
{
$i = 0;
$exclusionCount = 0;
while (($entryName = $zipArchive->getNameIndex($i)) || ($statIndex = $zipArchive->statIndex($i,ZipArchive::FL_UNCHANGED))) {
if ($entryName) {
// Not previously removed index.
if (preg_match($pattern, $entryName) === 1 && $zipArchive->deleteIndex($i)) {
$exclusionCount++;
}
}
$i++;
}
return $exclusionCount;
} | php | public static function excludeFromZip(ZipArchive $zipArchive, $pattern)
{
$i = 0;
$exclusionCount = 0;
while (($entryName = $zipArchive->getNameIndex($i)) || ($statIndex = $zipArchive->statIndex($i,ZipArchive::FL_UNCHANGED))) {
if ($entryName) {
// Not previously removed index.
if (preg_match($pattern, $entryName) === 1 && $zipArchive->deleteIndex($i)) {
$exclusionCount++;
}
}
$i++;
}
return $exclusionCount;
} | [
"public",
"static",
"function",
"excludeFromZip",
"(",
"ZipArchive",
"$",
"zipArchive",
",",
"$",
"pattern",
")",
"{",
"$",
"i",
"=",
"0",
";",
"$",
"exclusionCount",
"=",
"0",
";",
"while",
"(",
"(",
"$",
"entryName",
"=",
"$",
"zipArchive",
"->",
"ge... | Exclude from Zip
Exclude entries matching $pattern from a ZIP Archive.
@param ZipArchive $zipArchive An open ZipArchive object.
@param string $pattern A PCRE pattern.
@return int The amount of excluded entries. | [
"Exclude",
"from",
"Zip"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/class.File.php#L554-L571 |
oat-sa/tao-core | helpers/class.File.php | tao_helpers_File.getAllZipNames | public static function getAllZipNames(ZipArchive $zipArchive)
{
$i = 0;
$entries = [];
while (($entryName = $zipArchive->getNameIndex($i)) || ($statIndex = $zipArchive->statIndex($i,ZipArchive::FL_UNCHANGED))) {
if ($entryName) {
$entries[] = $entryName;
}
$i++;
}
return $entries;
} | php | public static function getAllZipNames(ZipArchive $zipArchive)
{
$i = 0;
$entries = [];
while (($entryName = $zipArchive->getNameIndex($i)) || ($statIndex = $zipArchive->statIndex($i,ZipArchive::FL_UNCHANGED))) {
if ($entryName) {
$entries[] = $entryName;
}
$i++;
}
return $entries;
} | [
"public",
"static",
"function",
"getAllZipNames",
"(",
"ZipArchive",
"$",
"zipArchive",
")",
"{",
"$",
"i",
"=",
"0",
";",
"$",
"entries",
"=",
"[",
"]",
";",
"while",
"(",
"(",
"$",
"entryName",
"=",
"$",
"zipArchive",
"->",
"getNameIndex",
"(",
"$",
... | Get All Zip Names
Retrieve all ZIP name entries in a ZIP archive. In others words, all the paths in the
archive having an entry.
@param ZipArchive $zipArchive An open ZipArchive object.
@return array An array of strings. | [
"Get",
"All",
"Zip",
"Names"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/class.File.php#L582-L596 |
oat-sa/tao-core | helpers/class.File.php | tao_helpers_File.getPathFromUrl | public static function getPathFromUrl($url) {
if (substr($url, 0, strlen(ROOT_URL)) != ROOT_URL) {
throw new common_Exception($url.' does not lie within the tao instalation path');
}
$subUrl = substr($url, strlen(ROOT_URL));
$parts = array();
foreach (explode('/', $subUrl) as $directory) {
$parts[] = urldecode($directory);
}
$path = ROOT_PATH.implode(DIRECTORY_SEPARATOR, $parts);
if (self::securityCheck($path)) {
return $path;
} else {
throw new common_Exception($url.' is not secure');
}
} | php | public static function getPathFromUrl($url) {
if (substr($url, 0, strlen(ROOT_URL)) != ROOT_URL) {
throw new common_Exception($url.' does not lie within the tao instalation path');
}
$subUrl = substr($url, strlen(ROOT_URL));
$parts = array();
foreach (explode('/', $subUrl) as $directory) {
$parts[] = urldecode($directory);
}
$path = ROOT_PATH.implode(DIRECTORY_SEPARATOR, $parts);
if (self::securityCheck($path)) {
return $path;
} else {
throw new common_Exception($url.' is not secure');
}
} | [
"public",
"static",
"function",
"getPathFromUrl",
"(",
"$",
"url",
")",
"{",
"if",
"(",
"substr",
"(",
"$",
"url",
",",
"0",
",",
"strlen",
"(",
"ROOT_URL",
")",
")",
"!=",
"ROOT_URL",
")",
"{",
"throw",
"new",
"common_Exception",
"(",
"$",
"url",
".... | Gets the local path to a publicly available resource
no verification if the file should be accessible
@param string $url
@throws common_Exception
@return string | [
"Gets",
"the",
"local",
"path",
"to",
"a",
"publicly",
"available",
"resource",
"no",
"verification",
"if",
"the",
"file",
"should",
"be",
"accessible"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/class.File.php#L606-L621 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.