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/form/class.Instance.php | tao_actions_form_Instance.initElements | protected function initElements()
{
$clazz = $this->getClazz();
$instance = $this->getInstance();
$guiOrderProperty = new core_kernel_classes_Property(TaoOntology::PROPERTY_GUI_ORDER);
//get the list of properties to set in the form
$propertyCandidates = tao_helpers_form_GenerisFormFactory::getDefaultProperties();
$classProperties = tao_helpers_form_GenerisFormFactory::getClassProperties($clazz, $this->getTopClazz());
$propertyCandidates = array_merge($propertyCandidates, $classProperties);
$additionalProperties = (isset($this->options['additionalProperties']) && is_array($this->options['additionalProperties']))?$this->options['additionalProperties']:array();
if(!empty($additionalProperties)){
$propertyCandidates = array_merge($propertyCandidates, $additionalProperties);
}
$excludedProperties = (isset($this->options['excludedProperties']) && is_array($this->options['excludedProperties']))?$this->options['excludedProperties']:array();
$editedProperties = array();
foreach($propertyCandidates as $property){
if(!isset($editedProperties[$property->getUri()]) && !in_array($property->getUri(), $excludedProperties)){
$editedProperties[$property->getUri()] = $property;
}
}
$finalElements = array();
foreach($editedProperties as $property){
$property->feed();
$widget = $property->getWidget();
if($widget == null || $widget instanceof core_kernel_classes_Literal) {
continue;
}
//map properties widgets to form elments
$element = tao_helpers_form_GenerisFormFactory::elementMap($property);
if(!is_null($element)){
//take instance values to populate the form
if(!is_null($instance)){
$values = $instance->getPropertyValuesCollection($property);
foreach($values->getIterator() as $value){
if(!is_null($value)){
if($value instanceof core_kernel_classes_Resource){
if($element instanceof tao_helpers_form_elements_Readonly){
$element->setValue($value->getLabel());
}else if ($element instanceof tao_helpers_form_elements_xhtml_ReadonlyLiteral){
$element->setValue((string)$value);
} else {
$element->setValue($value->getUri());
}
}
if($value instanceof core_kernel_classes_Literal){
$element->setValue((string)$value);
}
}
}
}
// don't show empty labels
if($element instanceof tao_helpers_form_elements_Label && strlen($element->getRawValue()) == 0) {
continue;
}
//set file element validator:
if($element instanceof tao_helpers_form_elements_AsyncFile){
}
if ($property->getUri() == OntologyRdfs::RDFS_LABEL){
// Label will not be a TAO Property. However, it should
// be always first.
array_splice($finalElements, 0, 0, array(array($element, 1)));
}
else if (count($guiOrderPropertyValues = $property->getPropertyValues($guiOrderProperty))){
// get position of this property if it has one.
$position = intval($guiOrderPropertyValues[0]);
// insert the element at the right place.
$i = 0;
while ($i < count($finalElements) && ($position >= $finalElements[$i][1] && $finalElements[$i][1] !== null)){
$i++;
}
array_splice($finalElements, $i, 0, array(array($element, $position)));
}
else{
// Unordered properties will go at the end of the form.
$finalElements[] = array($element, null);
}
}
}
// Add elements related to class properties to the form.
foreach ($finalElements as $element){
$this->form->addElement($element[0]);
}
//add an hidden elt for the class uri
$classUriElt = tao_helpers_form_FormFactory::getElement('classUri', 'Hidden');
$classUriElt->setValue(tao_helpers_Uri::encode($clazz->getUri()));
$this->form->addElement($classUriElt, true);
if(!is_null($instance)){
//add an hidden elt for the instance Uri
$instanceUriElt = tao_helpers_form_FormFactory::getElement('uri', 'Hidden');
$instanceUriElt->setValue(tao_helpers_Uri::encode($instance->getUri()));
$this->form->addElement($instanceUriElt, true);
$hiddenId = tao_helpers_form_FormFactory::getElement('id', 'Hidden');
$hiddenId->setValue($instance->getUri());
$this->form->addElement($hiddenId, true);
}
} | php | protected function initElements()
{
$clazz = $this->getClazz();
$instance = $this->getInstance();
$guiOrderProperty = new core_kernel_classes_Property(TaoOntology::PROPERTY_GUI_ORDER);
//get the list of properties to set in the form
$propertyCandidates = tao_helpers_form_GenerisFormFactory::getDefaultProperties();
$classProperties = tao_helpers_form_GenerisFormFactory::getClassProperties($clazz, $this->getTopClazz());
$propertyCandidates = array_merge($propertyCandidates, $classProperties);
$additionalProperties = (isset($this->options['additionalProperties']) && is_array($this->options['additionalProperties']))?$this->options['additionalProperties']:array();
if(!empty($additionalProperties)){
$propertyCandidates = array_merge($propertyCandidates, $additionalProperties);
}
$excludedProperties = (isset($this->options['excludedProperties']) && is_array($this->options['excludedProperties']))?$this->options['excludedProperties']:array();
$editedProperties = array();
foreach($propertyCandidates as $property){
if(!isset($editedProperties[$property->getUri()]) && !in_array($property->getUri(), $excludedProperties)){
$editedProperties[$property->getUri()] = $property;
}
}
$finalElements = array();
foreach($editedProperties as $property){
$property->feed();
$widget = $property->getWidget();
if($widget == null || $widget instanceof core_kernel_classes_Literal) {
continue;
}
//map properties widgets to form elments
$element = tao_helpers_form_GenerisFormFactory::elementMap($property);
if(!is_null($element)){
//take instance values to populate the form
if(!is_null($instance)){
$values = $instance->getPropertyValuesCollection($property);
foreach($values->getIterator() as $value){
if(!is_null($value)){
if($value instanceof core_kernel_classes_Resource){
if($element instanceof tao_helpers_form_elements_Readonly){
$element->setValue($value->getLabel());
}else if ($element instanceof tao_helpers_form_elements_xhtml_ReadonlyLiteral){
$element->setValue((string)$value);
} else {
$element->setValue($value->getUri());
}
}
if($value instanceof core_kernel_classes_Literal){
$element->setValue((string)$value);
}
}
}
}
// don't show empty labels
if($element instanceof tao_helpers_form_elements_Label && strlen($element->getRawValue()) == 0) {
continue;
}
//set file element validator:
if($element instanceof tao_helpers_form_elements_AsyncFile){
}
if ($property->getUri() == OntologyRdfs::RDFS_LABEL){
// Label will not be a TAO Property. However, it should
// be always first.
array_splice($finalElements, 0, 0, array(array($element, 1)));
}
else if (count($guiOrderPropertyValues = $property->getPropertyValues($guiOrderProperty))){
// get position of this property if it has one.
$position = intval($guiOrderPropertyValues[0]);
// insert the element at the right place.
$i = 0;
while ($i < count($finalElements) && ($position >= $finalElements[$i][1] && $finalElements[$i][1] !== null)){
$i++;
}
array_splice($finalElements, $i, 0, array(array($element, $position)));
}
else{
// Unordered properties will go at the end of the form.
$finalElements[] = array($element, null);
}
}
}
// Add elements related to class properties to the form.
foreach ($finalElements as $element){
$this->form->addElement($element[0]);
}
//add an hidden elt for the class uri
$classUriElt = tao_helpers_form_FormFactory::getElement('classUri', 'Hidden');
$classUriElt->setValue(tao_helpers_Uri::encode($clazz->getUri()));
$this->form->addElement($classUriElt, true);
if(!is_null($instance)){
//add an hidden elt for the instance Uri
$instanceUriElt = tao_helpers_form_FormFactory::getElement('uri', 'Hidden');
$instanceUriElt->setValue(tao_helpers_Uri::encode($instance->getUri()));
$this->form->addElement($instanceUriElt, true);
$hiddenId = tao_helpers_form_FormFactory::getElement('id', 'Hidden');
$hiddenId->setValue($instance->getUri());
$this->form->addElement($hiddenId, true);
}
} | [
"protected",
"function",
"initElements",
"(",
")",
"{",
"$",
"clazz",
"=",
"$",
"this",
"->",
"getClazz",
"(",
")",
";",
"$",
"instance",
"=",
"$",
"this",
"->",
"getInstance",
"(",
")",
";",
"$",
"guiOrderProperty",
"=",
"new",
"core_kernel_classes_Proper... | Initialize the form elements
@access protected
@author Bertrand Chevrier, <bertrand.chevrier@tudor.lu>
@return mixed | [
"Initialize",
"the",
"form",
"elements"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/form/class.Instance.php#L81-L196 |
oat-sa/tao-core | actions/form/class.IndexProperty.php | tao_actions_form_IndexProperty.initElements | protected function initElements()
{
$elementNames = array();
//index part
$indexProperty = $this->getIndex();
$indexUri = tao_helpers_Uri::encode($indexProperty->getUri());
//get and add Label (Text)
$label = (!is_null($indexProperty))?$indexProperty->getLabel():'';
$propIndexElt = tao_helpers_form_FormFactory::getElement("index_".$this->prefix."_".tao_helpers_Uri::encode(OntologyRdfs::RDFS_LABEL), 'Textbox');
$propIndexElt->setDescription(__('Label'));
$propIndexElt->addAttribute('class', 'index');
$propIndexElt->addAttribute('data-related-index', $indexUri);
$propIndexElt->setValue($label);
$this->form->addElement($propIndexElt);
$elementNames[] = $propIndexElt->getName();
//get and add Fuzzy matching (Radiobox)
$fuzzyMatching = (!is_null($indexProperty))?($indexProperty->isFuzzyMatching())?GenerisRdf::GENERIS_TRUE:GenerisRdf::GENERIS_FALSE:'';
$options = array(
tao_helpers_Uri::encode(GenerisRdf::GENERIS_TRUE) => __('True'),
tao_helpers_Uri::encode(GenerisRdf::GENERIS_FALSE) => __('False')
);
$propIndexElt = tao_helpers_form_FormFactory::getElement($this->prefix."_".tao_helpers_Uri::encode(OntologyIndex::PROPERTY_INDEX_FUZZY_MATCHING), 'Radiobox');
$propIndexElt->setOptions($options);
$propIndexElt->setDescription(__('Fuzzy Matching'));
$propIndexElt->addAttribute('class', 'index');
$propIndexElt->addAttribute('data-related-index', $indexUri);
$propIndexElt->setValue(tao_helpers_Uri::encode($fuzzyMatching));
$propIndexElt->addValidator(new tao_helpers_form_validators_NotEmpty());
$this->form->addElement($propIndexElt);
$elementNames[] = $propIndexElt->getName();
//get and add identifier (Text)
$identifier = (!is_null($indexProperty))?$indexProperty->getIdentifier():'';
$propIndexElt = tao_helpers_form_FormFactory::getElement($this->prefix."_".tao_helpers_Uri::encode(OntologyIndex::PROPERTY_INDEX_IDENTIFIER), 'Textbox');
$propIndexElt->setDescription(__('Identifier'));
$propIndexElt->addAttribute('class', 'index');
$propIndexElt->addAttribute('data-related-index', $indexUri);
$propIndexElt->setValue($identifier);
$propIndexElt->addValidator(new tao_helpers_form_validators_IndexIdentifier());
$this->form->addElement($propIndexElt);
$elementNames[] = $propIndexElt->getName();
//get and add Default search
$defaultSearch = (!is_null($indexProperty))?($indexProperty->isDefaultSearchable())?GenerisRdf::GENERIS_TRUE:GenerisRdf::GENERIS_FALSE:'';
$options = array(
tao_helpers_Uri::encode(GenerisRdf::GENERIS_TRUE) => __('True'),
tao_helpers_Uri::encode(GenerisRdf::GENERIS_FALSE) => __('False')
);
$propIndexElt = tao_helpers_form_FormFactory::getElement($this->prefix."_".tao_helpers_Uri::encode(OntologyIndex::PROPERTY_DEFAULT_SEARCH), 'Radiobox');
$propIndexElt->setOptions($options);
$propIndexElt->setDescription(__('Default search'));
$propIndexElt->addAttribute('class', 'index');
$propIndexElt->addAttribute('data-related-index', $indexUri);
$propIndexElt->setValue(tao_helpers_Uri::encode($defaultSearch));
$propIndexElt->addValidator(new tao_helpers_form_validators_NotEmpty());
$this->form->addElement($propIndexElt);
$elementNames[] = $propIndexElt->getName();
//get and add Tokenizer (Combobox)
$tokenizerRange = new \core_kernel_classes_Class('http://www.tao.lu/Ontologies/TAO.rdf#Tokenizer');
$options = array();
/** @var core_kernel_classes_Resource $value */
foreach($tokenizerRange->getInstances() as $value){
$options[tao_helpers_Uri::encode($value->getUri())] = $value->getLabel();
}
$tokenizer = (!is_null($indexProperty))?$indexProperty->getOnePropertyValue(new \core_kernel_classes_Property(OntologyIndex::PROPERTY_INDEX_TOKENIZER)):null;
$tokenizer = (get_class($tokenizer) === 'core_kernel_classes_Resource')?$tokenizer->getUri():'';
$propIndexElt = tao_helpers_form_FormFactory::getElement($this->prefix."_".tao_helpers_Uri::encode(OntologyIndex::PROPERTY_INDEX_TOKENIZER), 'Combobox');
$propIndexElt->setDescription(__('Tokenizer'));
$propIndexElt->addAttribute('class', 'index');
$propIndexElt->addAttribute('data-related-index', $indexUri);
$propIndexElt->setOptions($options);
$propIndexElt->setValue(tao_helpers_Uri::encode($tokenizer));
$propIndexElt->addValidator(new tao_helpers_form_validators_NotEmpty());
$this->form->addElement($propIndexElt);
$elementNames[] = $propIndexElt->getName();
$removeIndexElt = tao_helpers_form_FormFactory::getElement("index_{$indexUri}_remove", 'Free');
$removeIndexElt->setValue(
"<a href='#' id='{$indexUri}' class='btn-error index-remover small' data-index='".$indexProperty->getUri()."'><span class='icon-remove'></span> " . __(
'remove index'
) . "</a>"
);
$this->form->addElement($removeIndexElt);
$elementNames[] = $removeIndexElt;
$separatorIndexElt = tao_helpers_form_FormFactory::getElement("index_".$this->prefix."_separator", 'Free');
$separatorIndexElt->setValue(
"<hr class='index' data-related-index='{$indexUri}'>"
);
$this->form->addElement($separatorIndexElt);
$elementNames[] = $separatorIndexElt;
} | php | protected function initElements()
{
$elementNames = array();
//index part
$indexProperty = $this->getIndex();
$indexUri = tao_helpers_Uri::encode($indexProperty->getUri());
//get and add Label (Text)
$label = (!is_null($indexProperty))?$indexProperty->getLabel():'';
$propIndexElt = tao_helpers_form_FormFactory::getElement("index_".$this->prefix."_".tao_helpers_Uri::encode(OntologyRdfs::RDFS_LABEL), 'Textbox');
$propIndexElt->setDescription(__('Label'));
$propIndexElt->addAttribute('class', 'index');
$propIndexElt->addAttribute('data-related-index', $indexUri);
$propIndexElt->setValue($label);
$this->form->addElement($propIndexElt);
$elementNames[] = $propIndexElt->getName();
//get and add Fuzzy matching (Radiobox)
$fuzzyMatching = (!is_null($indexProperty))?($indexProperty->isFuzzyMatching())?GenerisRdf::GENERIS_TRUE:GenerisRdf::GENERIS_FALSE:'';
$options = array(
tao_helpers_Uri::encode(GenerisRdf::GENERIS_TRUE) => __('True'),
tao_helpers_Uri::encode(GenerisRdf::GENERIS_FALSE) => __('False')
);
$propIndexElt = tao_helpers_form_FormFactory::getElement($this->prefix."_".tao_helpers_Uri::encode(OntologyIndex::PROPERTY_INDEX_FUZZY_MATCHING), 'Radiobox');
$propIndexElt->setOptions($options);
$propIndexElt->setDescription(__('Fuzzy Matching'));
$propIndexElt->addAttribute('class', 'index');
$propIndexElt->addAttribute('data-related-index', $indexUri);
$propIndexElt->setValue(tao_helpers_Uri::encode($fuzzyMatching));
$propIndexElt->addValidator(new tao_helpers_form_validators_NotEmpty());
$this->form->addElement($propIndexElt);
$elementNames[] = $propIndexElt->getName();
//get and add identifier (Text)
$identifier = (!is_null($indexProperty))?$indexProperty->getIdentifier():'';
$propIndexElt = tao_helpers_form_FormFactory::getElement($this->prefix."_".tao_helpers_Uri::encode(OntologyIndex::PROPERTY_INDEX_IDENTIFIER), 'Textbox');
$propIndexElt->setDescription(__('Identifier'));
$propIndexElt->addAttribute('class', 'index');
$propIndexElt->addAttribute('data-related-index', $indexUri);
$propIndexElt->setValue($identifier);
$propIndexElt->addValidator(new tao_helpers_form_validators_IndexIdentifier());
$this->form->addElement($propIndexElt);
$elementNames[] = $propIndexElt->getName();
//get and add Default search
$defaultSearch = (!is_null($indexProperty))?($indexProperty->isDefaultSearchable())?GenerisRdf::GENERIS_TRUE:GenerisRdf::GENERIS_FALSE:'';
$options = array(
tao_helpers_Uri::encode(GenerisRdf::GENERIS_TRUE) => __('True'),
tao_helpers_Uri::encode(GenerisRdf::GENERIS_FALSE) => __('False')
);
$propIndexElt = tao_helpers_form_FormFactory::getElement($this->prefix."_".tao_helpers_Uri::encode(OntologyIndex::PROPERTY_DEFAULT_SEARCH), 'Radiobox');
$propIndexElt->setOptions($options);
$propIndexElt->setDescription(__('Default search'));
$propIndexElt->addAttribute('class', 'index');
$propIndexElt->addAttribute('data-related-index', $indexUri);
$propIndexElt->setValue(tao_helpers_Uri::encode($defaultSearch));
$propIndexElt->addValidator(new tao_helpers_form_validators_NotEmpty());
$this->form->addElement($propIndexElt);
$elementNames[] = $propIndexElt->getName();
//get and add Tokenizer (Combobox)
$tokenizerRange = new \core_kernel_classes_Class('http://www.tao.lu/Ontologies/TAO.rdf#Tokenizer');
$options = array();
/** @var core_kernel_classes_Resource $value */
foreach($tokenizerRange->getInstances() as $value){
$options[tao_helpers_Uri::encode($value->getUri())] = $value->getLabel();
}
$tokenizer = (!is_null($indexProperty))?$indexProperty->getOnePropertyValue(new \core_kernel_classes_Property(OntologyIndex::PROPERTY_INDEX_TOKENIZER)):null;
$tokenizer = (get_class($tokenizer) === 'core_kernel_classes_Resource')?$tokenizer->getUri():'';
$propIndexElt = tao_helpers_form_FormFactory::getElement($this->prefix."_".tao_helpers_Uri::encode(OntologyIndex::PROPERTY_INDEX_TOKENIZER), 'Combobox');
$propIndexElt->setDescription(__('Tokenizer'));
$propIndexElt->addAttribute('class', 'index');
$propIndexElt->addAttribute('data-related-index', $indexUri);
$propIndexElt->setOptions($options);
$propIndexElt->setValue(tao_helpers_Uri::encode($tokenizer));
$propIndexElt->addValidator(new tao_helpers_form_validators_NotEmpty());
$this->form->addElement($propIndexElt);
$elementNames[] = $propIndexElt->getName();
$removeIndexElt = tao_helpers_form_FormFactory::getElement("index_{$indexUri}_remove", 'Free');
$removeIndexElt->setValue(
"<a href='#' id='{$indexUri}' class='btn-error index-remover small' data-index='".$indexProperty->getUri()."'><span class='icon-remove'></span> " . __(
'remove index'
) . "</a>"
);
$this->form->addElement($removeIndexElt);
$elementNames[] = $removeIndexElt;
$separatorIndexElt = tao_helpers_form_FormFactory::getElement("index_".$this->prefix."_separator", 'Free');
$separatorIndexElt->setValue(
"<hr class='index' data-related-index='{$indexUri}'>"
);
$this->form->addElement($separatorIndexElt);
$elementNames[] = $separatorIndexElt;
} | [
"protected",
"function",
"initElements",
"(",
")",
"{",
"$",
"elementNames",
"=",
"array",
"(",
")",
";",
"//index part",
"$",
"indexProperty",
"=",
"$",
"this",
"->",
"getIndex",
"(",
")",
";",
"$",
"indexUri",
"=",
"tao_helpers_Uri",
"::",
"encode",
"(",... | Initialize the form elements
@access protected
@author Bertrand Chevrier, <bertrand.chevrier@tudor.lu>
@return mixed | [
"Initialize",
"the",
"form",
"elements"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/form/class.IndexProperty.php#L78-L177 |
oat-sa/tao-core | models/classes/import/class.CsvUploadForm.php | tao_models_classes_import_CsvUploadForm.initElements | public function initElements()
{
//create file upload form box
$fileElt = tao_helpers_form_FormFactory::getElement('source', 'AsyncFile');
$fileElt->setDescription(__("Add a CSV file"));
if(isset($_POST['import_sent_csv'])){
$fileElt->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty'));
}
else{
$fileElt->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty', array('message' => '')));
}
$fileElt->addValidators(array(
tao_helpers_form_FormFactory::getValidator('FileMimeType',
array(
'mimetype' => array(
'text/plain',
'text/csv',
'text/comma-separated-values',
'text/anytext',
'application/csv',
'application/txt',
'application/csv-tab-delimited-table',
'application/excel',
'application/vnd.ms-excel',
'application/vnd.msexcel',
),
'extension' => array('csv', 'txt')
)),
tao_helpers_form_FormFactory::getValidator('FileSize',
array('max' => SystemHelper::getFileUploadLimit()))
));
$this->form->addElement($fileElt);
$this->form->createGroup('file', __('Import Metadata from CSV file'), array('source'));
$csvSentElt = tao_helpers_form_FormFactory::getElement('import_sent_csv', 'Hidden');
$csvSentElt->setValue(1);
$this->form->addElement($csvSentElt);
// options
$optDelimiter = tao_helpers_form_FormFactory::getElement(tao_helpers_data_CsvFile::FIELD_DELIMITER, 'Textbox');
$optDelimiter->setDescription(__("Field delimiter"));
$optDelimiter->setValue(';');
$optDelimiter->addAttribute("size", 6);
$optDelimiter->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty'));
$this->form->addElement($optDelimiter);
$optEncloser = tao_helpers_form_FormFactory::getElement(tao_helpers_data_CsvFile::FIELD_ENCLOSER, 'Textbox');
$optEncloser->setDescription(__("Field encloser"));
$optEncloser->setValue('"');
$optEncloser->addAttribute("size", 6);
$optEncloser->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty'));
$this->form->addElement($optEncloser);
/*
$optMulti = tao_helpers_form_FormFactory::getElement(tao_helpers_data_CsvFile::MULTI_VALUES_DELIMITER, 'Textbox');
$optMulti->setDescription(__("Multiple values delimiter"));
$optMulti->setValue('|');
$optMulti->addAttribute("size", 6);
$optMulti->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty'));
$this->form->addElement($optMulti);
*/
if (isset($this->options[static::IS_OPTION_FIRST_COLUMN_ENABLE])){
if ($this->options[static::IS_OPTION_FIRST_COLUMN_ENABLE] === true){
$optFirstColumn = $this->addFirstColumnElement();
}
}else{
//backwards compatible
$optFirstColumn = $this->addFirstColumnElement();
}
$opts = [$optDelimiter, $optEncloser];
if (isset($optFirstColumn)){
$opts[] = $optFirstColumn;
}
$this->form->createGroup('options', __('CSV Options'),$opts);
} | php | public function initElements()
{
//create file upload form box
$fileElt = tao_helpers_form_FormFactory::getElement('source', 'AsyncFile');
$fileElt->setDescription(__("Add a CSV file"));
if(isset($_POST['import_sent_csv'])){
$fileElt->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty'));
}
else{
$fileElt->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty', array('message' => '')));
}
$fileElt->addValidators(array(
tao_helpers_form_FormFactory::getValidator('FileMimeType',
array(
'mimetype' => array(
'text/plain',
'text/csv',
'text/comma-separated-values',
'text/anytext',
'application/csv',
'application/txt',
'application/csv-tab-delimited-table',
'application/excel',
'application/vnd.ms-excel',
'application/vnd.msexcel',
),
'extension' => array('csv', 'txt')
)),
tao_helpers_form_FormFactory::getValidator('FileSize',
array('max' => SystemHelper::getFileUploadLimit()))
));
$this->form->addElement($fileElt);
$this->form->createGroup('file', __('Import Metadata from CSV file'), array('source'));
$csvSentElt = tao_helpers_form_FormFactory::getElement('import_sent_csv', 'Hidden');
$csvSentElt->setValue(1);
$this->form->addElement($csvSentElt);
// options
$optDelimiter = tao_helpers_form_FormFactory::getElement(tao_helpers_data_CsvFile::FIELD_DELIMITER, 'Textbox');
$optDelimiter->setDescription(__("Field delimiter"));
$optDelimiter->setValue(';');
$optDelimiter->addAttribute("size", 6);
$optDelimiter->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty'));
$this->form->addElement($optDelimiter);
$optEncloser = tao_helpers_form_FormFactory::getElement(tao_helpers_data_CsvFile::FIELD_ENCLOSER, 'Textbox');
$optEncloser->setDescription(__("Field encloser"));
$optEncloser->setValue('"');
$optEncloser->addAttribute("size", 6);
$optEncloser->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty'));
$this->form->addElement($optEncloser);
/*
$optMulti = tao_helpers_form_FormFactory::getElement(tao_helpers_data_CsvFile::MULTI_VALUES_DELIMITER, 'Textbox');
$optMulti->setDescription(__("Multiple values delimiter"));
$optMulti->setValue('|');
$optMulti->addAttribute("size", 6);
$optMulti->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty'));
$this->form->addElement($optMulti);
*/
if (isset($this->options[static::IS_OPTION_FIRST_COLUMN_ENABLE])){
if ($this->options[static::IS_OPTION_FIRST_COLUMN_ENABLE] === true){
$optFirstColumn = $this->addFirstColumnElement();
}
}else{
//backwards compatible
$optFirstColumn = $this->addFirstColumnElement();
}
$opts = [$optDelimiter, $optEncloser];
if (isset($optFirstColumn)){
$opts[] = $optFirstColumn;
}
$this->form->createGroup('options', __('CSV Options'),$opts);
} | [
"public",
"function",
"initElements",
"(",
")",
"{",
"//create file upload form box",
"$",
"fileElt",
"=",
"tao_helpers_form_FormFactory",
"::",
"getElement",
"(",
"'source'",
",",
"'AsyncFile'",
")",
";",
"$",
"fileElt",
"->",
"setDescription",
"(",
"__",
"(",
"\... | overriden
@access public
@author Joel Bout, <joel.bout@tudor.lu>
@return mixed | [
"overriden"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/import/class.CsvUploadForm.php#L67-L146 |
oat-sa/tao-core | models/classes/requiredAction/implementation/RequiredActionService.php | RequiredActionService.attachAction | public function attachAction(RequiredActionInterface $action)
{
$actions = $this->getRequiredActions();
$actions[] = $action;
$this->setOption(self::OPTION_REQUIRED_ACTIONS, $actions);
} | php | public function attachAction(RequiredActionInterface $action)
{
$actions = $this->getRequiredActions();
$actions[] = $action;
$this->setOption(self::OPTION_REQUIRED_ACTIONS, $actions);
} | [
"public",
"function",
"attachAction",
"(",
"RequiredActionInterface",
"$",
"action",
")",
"{",
"$",
"actions",
"=",
"$",
"this",
"->",
"getRequiredActions",
"(",
")",
";",
"$",
"actions",
"[",
"]",
"=",
"$",
"action",
";",
"$",
"this",
"->",
"setOption",
... | Attach new action
@param RequiredActionInterface $action | [
"Attach",
"new",
"action"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/requiredAction/implementation/RequiredActionService.php#L55-L60 |
oat-sa/tao-core | models/classes/requiredAction/implementation/RequiredActionService.php | RequiredActionService.detachAction | public function detachAction($name)
{
$actions = $this->getRequiredActions();
foreach ($actions as $key => $action) {
if ($action->getName() === $name) {
unset($actions[$key]);
}
}
$this->setOption(self::OPTION_REQUIRED_ACTIONS, $actions);
} | php | public function detachAction($name)
{
$actions = $this->getRequiredActions();
foreach ($actions as $key => $action) {
if ($action->getName() === $name) {
unset($actions[$key]);
}
}
$this->setOption(self::OPTION_REQUIRED_ACTIONS, $actions);
} | [
"public",
"function",
"detachAction",
"(",
"$",
"name",
")",
"{",
"$",
"actions",
"=",
"$",
"this",
"->",
"getRequiredActions",
"(",
")",
";",
"foreach",
"(",
"$",
"actions",
"as",
"$",
"key",
"=>",
"$",
"action",
")",
"{",
"if",
"(",
"$",
"action",
... | Detach old action by name
@param string $name name of action | [
"Detach",
"old",
"action",
"by",
"name"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/requiredAction/implementation/RequiredActionService.php#L66-L77 |
oat-sa/tao-core | models/classes/requiredAction/implementation/RequiredActionService.php | RequiredActionService.getRequiredAction | public function getRequiredAction($name)
{
$result = null;
$actions = $this->getOption(self::OPTION_REQUIRED_ACTIONS);
foreach ($actions as $action) {
if ($action->getName() === $name) {
$result = $action;
break;
}
}
return $result;
} | php | public function getRequiredAction($name)
{
$result = null;
$actions = $this->getOption(self::OPTION_REQUIRED_ACTIONS);
foreach ($actions as $action) {
if ($action->getName() === $name) {
$result = $action;
break;
}
}
return $result;
} | [
"public",
"function",
"getRequiredAction",
"(",
"$",
"name",
")",
"{",
"$",
"result",
"=",
"null",
";",
"$",
"actions",
"=",
"$",
"this",
"->",
"getOption",
"(",
"self",
"::",
"OPTION_REQUIRED_ACTIONS",
")",
";",
"foreach",
"(",
"$",
"actions",
"as",
"$"... | Get required action by name
@param string $name name of action
@return RequiredActionInterface array of required action instances | [
"Get",
"required",
"action",
"by",
"name"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/requiredAction/implementation/RequiredActionService.php#L84-L95 |
oat-sa/tao-core | models/classes/requiredAction/implementation/RequiredActionService.php | RequiredActionService.getActionToBePerformed | public function getActionToBePerformed($names = [], Event $contextEvent = null)
{
$result = null;
if (empty($names)) {
$actionsToCheck = $this->getRequiredActions();
} else {
$actionsToCheck = [];
foreach ($names as $name) {
$actionsToCheck[] = $this->getRequiredAction($name);
}
}
/** @var RequiredActionInterface $requiredAction */
foreach ($actionsToCheck as $requiredAction) {
if ($requiredAction->mustBeExecuted($contextEvent)) {
$result = $requiredAction;
break;
}
}
return $result;
} | php | public function getActionToBePerformed($names = [], Event $contextEvent = null)
{
$result = null;
if (empty($names)) {
$actionsToCheck = $this->getRequiredActions();
} else {
$actionsToCheck = [];
foreach ($names as $name) {
$actionsToCheck[] = $this->getRequiredAction($name);
}
}
/** @var RequiredActionInterface $requiredAction */
foreach ($actionsToCheck as $requiredAction) {
if ($requiredAction->mustBeExecuted($contextEvent)) {
$result = $requiredAction;
break;
}
}
return $result;
} | [
"public",
"function",
"getActionToBePerformed",
"(",
"$",
"names",
"=",
"[",
"]",
",",
"Event",
"$",
"contextEvent",
"=",
"null",
")",
"{",
"$",
"result",
"=",
"null",
";",
"if",
"(",
"empty",
"(",
"$",
"names",
")",
")",
"{",
"$",
"actionsToCheck",
... | Get first action which should be executed (one of action's rules return true).
@param string[] array of action names which should be checked. If array is empty all action will be checked.
@param Event $contextEvent
@return null|RequiredActionInterface | [
"Get",
"first",
"action",
"which",
"should",
"be",
"executed",
"(",
"one",
"of",
"action",
"s",
"rules",
"return",
"true",
")",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/requiredAction/implementation/RequiredActionService.php#L103-L122 |
oat-sa/tao-core | models/classes/requiredAction/implementation/RequiredActionService.php | RequiredActionService.checkRequiredActions | public static function checkRequiredActions(Event $event = null)
{
/** @var RequiredActionService $service */
$service = ServiceManager::getServiceManager()->get(self::CONFIG_ID);
$action = $service->getActionToBePerformed([], $event);
if ($action !== null) {
$action->execute([], $event);
}
} | php | public static function checkRequiredActions(Event $event = null)
{
/** @var RequiredActionService $service */
$service = ServiceManager::getServiceManager()->get(self::CONFIG_ID);
$action = $service->getActionToBePerformed([], $event);
if ($action !== null) {
$action->execute([], $event);
}
} | [
"public",
"static",
"function",
"checkRequiredActions",
"(",
"Event",
"$",
"event",
"=",
"null",
")",
"{",
"/** @var RequiredActionService $service */",
"$",
"service",
"=",
"ServiceManager",
"::",
"getServiceManager",
"(",
")",
"->",
"get",
"(",
"self",
"::",
"CO... | Check if any action must be executed and execute first of them.
@param Event $event | [
"Check",
"if",
"any",
"action",
"must",
"be",
"executed",
"and",
"execute",
"first",
"of",
"them",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/requiredAction/implementation/RequiredActionService.php#L128-L136 |
oat-sa/tao-core | helpers/TaoCe.php | TaoCe.isFirstTimeInTao | public static function isFirstTimeInTao() {
$firstTime = common_session_SessionManager::getSession()->getUserPropertyValues(TaoOntology::PROPERTY_USER_FIRST_TIME);
//for compatibility purpose we assume previous users are veterans
return in_array(GenerisRdf::GENERIS_TRUE, $firstTime);
} | php | public static function isFirstTimeInTao() {
$firstTime = common_session_SessionManager::getSession()->getUserPropertyValues(TaoOntology::PROPERTY_USER_FIRST_TIME);
//for compatibility purpose we assume previous users are veterans
return in_array(GenerisRdf::GENERIS_TRUE, $firstTime);
} | [
"public",
"static",
"function",
"isFirstTimeInTao",
"(",
")",
"{",
"$",
"firstTime",
"=",
"common_session_SessionManager",
"::",
"getSession",
"(",
")",
"->",
"getUserPropertyValues",
"(",
"TaoOntology",
"::",
"PROPERTY_USER_FIRST_TIME",
")",
";",
"//for compatibility p... | Check whether the current user has already been connected to the TAO backend.
@return boolean true if this is the first time | [
"Check",
"whether",
"the",
"current",
"user",
"has",
"already",
"been",
"connected",
"to",
"the",
"TAO",
"backend",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/TaoCe.php#L45-L50 |
oat-sa/tao-core | helpers/TaoCe.php | TaoCe.becomeVeteran | public static function becomeVeteran() {
$success = false;
$userUri = common_session_SessionManager::getSession()->getUserUri();
if (!empty($userUri)) {
$user = new \core_kernel_classes_Resource($userUri);
if ($user->exists()) {
// user in ontology
$success = $user->editPropertyValues(
new core_kernel_classes_Property(TaoOntology::PROPERTY_USER_FIRST_TIME),
new core_kernel_classes_Resource(GenerisRdf::GENERIS_FALSE)
);
} // else we fail;
}
return $success;
} | php | public static function becomeVeteran() {
$success = false;
$userUri = common_session_SessionManager::getSession()->getUserUri();
if (!empty($userUri)) {
$user = new \core_kernel_classes_Resource($userUri);
if ($user->exists()) {
// user in ontology
$success = $user->editPropertyValues(
new core_kernel_classes_Property(TaoOntology::PROPERTY_USER_FIRST_TIME),
new core_kernel_classes_Resource(GenerisRdf::GENERIS_FALSE)
);
} // else we fail;
}
return $success;
} | [
"public",
"static",
"function",
"becomeVeteran",
"(",
")",
"{",
"$",
"success",
"=",
"false",
";",
"$",
"userUri",
"=",
"common_session_SessionManager",
"::",
"getSession",
"(",
")",
"->",
"getUserUri",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"... | The user knows TAO, he's now a veteran, the TaoOntology::PROPERTY_USER_FIRST_TIME property can be false (except if $notYet is true).
@param core_kernel_classes_Resource $user a user or the current user if null/not set
@param boolean $notYet our veteran want to be still considered as a noob... | [
"The",
"user",
"knows",
"TAO",
"he",
"s",
"now",
"a",
"veteran",
"the",
"TaoOntology",
"::",
"PROPERTY_USER_FIRST_TIME",
"property",
"can",
"be",
"false",
"(",
"except",
"if",
"$notYet",
"is",
"true",
")",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/TaoCe.php#L58-L73 |
oat-sa/tao-core | helpers/TaoCe.php | TaoCe.getLastVisitedUrl | public static function getLastVisitedUrl() {
$urls = common_session_SessionManager::getSession()->getUserPropertyValues(TaoOntology::PROPERTY_USER_LAST_EXTENSION);
if (!empty($urls)) {
$lastUrl = current($urls);
return ROOT_URL.$lastUrl;
} else {
return null;
}
} | php | public static function getLastVisitedUrl() {
$urls = common_session_SessionManager::getSession()->getUserPropertyValues(TaoOntology::PROPERTY_USER_LAST_EXTENSION);
if (!empty($urls)) {
$lastUrl = current($urls);
return ROOT_URL.$lastUrl;
} else {
return null;
}
} | [
"public",
"static",
"function",
"getLastVisitedUrl",
"(",
")",
"{",
"$",
"urls",
"=",
"common_session_SessionManager",
"::",
"getSession",
"(",
")",
"->",
"getUserPropertyValues",
"(",
"TaoOntology",
"::",
"PROPERTY_USER_LAST_EXTENSION",
")",
";",
"if",
"(",
"!",
... | Get the URL of the last visited extension
@param core_kernel_classes_Resource $user a user or the current user if null/not set (optional)
@return string the url or null | [
"Get",
"the",
"URL",
"of",
"the",
"last",
"visited",
"extension"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/TaoCe.php#L81-L89 |
oat-sa/tao-core | helpers/TaoCe.php | TaoCe.setLastVisitedUrl | public static function setLastVisitedUrl($url){
if(empty($url)){
throw new common_Exception('Cannot register an empty URL for the last visited extension');
}
$success = false;
$userUri = common_session_SessionManager::getSession()->getUserUri();
if (!empty($userUri)) {
$user = new \core_kernel_classes_Resource($userUri);
$user = new core_kernel_classes_Resource($userUri);
if ($user->exists()) {
// user in ontology
//clean up what's stored
$url = str_replace(ROOT_URL, '', $url);
$success = $user->editPropertyValues(new core_kernel_classes_Property(TaoOntology::PROPERTY_USER_LAST_EXTENSION), $url);
} // else we fail;
}
return $success;
} | php | public static function setLastVisitedUrl($url){
if(empty($url)){
throw new common_Exception('Cannot register an empty URL for the last visited extension');
}
$success = false;
$userUri = common_session_SessionManager::getSession()->getUserUri();
if (!empty($userUri)) {
$user = new \core_kernel_classes_Resource($userUri);
$user = new core_kernel_classes_Resource($userUri);
if ($user->exists()) {
// user in ontology
//clean up what's stored
$url = str_replace(ROOT_URL, '', $url);
$success = $user->editPropertyValues(new core_kernel_classes_Property(TaoOntology::PROPERTY_USER_LAST_EXTENSION), $url);
} // else we fail;
}
return $success;
} | [
"public",
"static",
"function",
"setLastVisitedUrl",
"(",
"$",
"url",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"url",
")",
")",
"{",
"throw",
"new",
"common_Exception",
"(",
"'Cannot register an empty URL for the last visited extension'",
")",
";",
"}",
"$",
"suc... | Set the URL of the last visited extension to a user.
@param string $url a non empty URL where the user was the last time
@param core_kernel_classes_Resource $user a user or the current user if null/not set (optional)
@throws common_Exception | [
"Set",
"the",
"URL",
"of",
"the",
"last",
"visited",
"extension",
"to",
"a",
"user",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/TaoCe.php#L97-L116 |
oat-sa/tao-core | helpers/translation/class.POUtils.php | tao_helpers_translation_POUtils.sanitize | public static function sanitize($string, $reverse = false)
{
$returnValue = (string) '';
if ($reverse) {
$smap = array('"', "\n", "\t", "\r");
$rmap = array('\\"', '\\n"' . "\n" . '"', '\\t', '\\r');
$returnValue = (string) str_replace($smap, $rmap, $string);
} else {
$smap = array('/"\s+"/', '/\\\\n/', '/\\\\r/', '/\\\\t/', '/\\\"/');
$rmap = array('', "\n", "\r", "\t", '"');
$returnValue = (string) preg_replace($smap, $rmap, $string);
}
return (string) $returnValue;
} | php | public static function sanitize($string, $reverse = false)
{
$returnValue = (string) '';
if ($reverse) {
$smap = array('"', "\n", "\t", "\r");
$rmap = array('\\"', '\\n"' . "\n" . '"', '\\t', '\\r');
$returnValue = (string) str_replace($smap, $rmap, $string);
} else {
$smap = array('/"\s+"/', '/\\\\n/', '/\\\\r/', '/\\\\t/', '/\\\"/');
$rmap = array('', "\n", "\r", "\t", '"');
$returnValue = (string) preg_replace($smap, $rmap, $string);
}
return (string) $returnValue;
} | [
"public",
"static",
"function",
"sanitize",
"(",
"$",
"string",
",",
"$",
"reverse",
"=",
"false",
")",
"{",
"$",
"returnValue",
"=",
"(",
"string",
")",
"''",
";",
"if",
"(",
"$",
"reverse",
")",
"{",
"$",
"smap",
"=",
"array",
"(",
"'\"'",
",",
... | Short description of method sanitize
@access public
@author Jerome Bogaerts, <jerome.bogaerts@tudor.lu>
@param string string
@param boolean reverse
@return string | [
"Short",
"description",
"of",
"method",
"sanitize"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/translation/class.POUtils.php#L51-L68 |
oat-sa/tao-core | helpers/translation/class.POUtils.php | tao_helpers_translation_POUtils.unserializeAnnotations | public static function unserializeAnnotations($annotations)
{
$returnValue = array();
$matches = array();
$encoding = self::getApplicationHelper()->getDefaultEncoding();
if (preg_match_all('/(#[\.\:,\|]{0,1}\s+(?:[^\\n]*))/', $annotations, $matches) !== false){
if (isset($matches[1]) && count($matches[1]) > 0){
foreach ($matches[1] as $match){
$match = trim($match);
$matchLen = mb_strlen($match, $encoding);
$annotationId = null;
$annotationValue = null;
switch (mb_substr($match, 1, 1, $encoding)){
case "\t":
case ' ':
// Translator comment.
$annotationId = tao_helpers_translation_POTranslationUnit::TRANSLATOR_COMMENTS;
$annotationValue = mb_substr($match, 2, $matchLen - 2, $encoding);
break;
case '.':
$annotationId = tao_helpers_translation_POTranslationUnit::EXTRACTED_COMMENTS;
$annotationValue = mb_substr($match, 3, $matchLen - 3, $encoding);
break;
case ':':
$annotationId = tao_helpers_translation_POTranslationUnit::REFERENCE;
$annotationValue = mb_substr($match, 3, $matchLen - 3, $encoding);
break;
case ',':
$annotationId = tao_helpers_translation_POTranslationUnit::FLAGS;
$annotationValue = mb_substr($match, 3, $matchLen - 3, $encoding);
break;
case '|':
if (($pos = mb_strpos($match, 'msgid_plural', 0, $encoding)) !== false){
$pos += mb_strlen('msgid_plural', $encoding) + 1;
$annotationId = tao_helpers_translation_POTranslationUnit::PREVIOUS_MSGID_PLURAL;
$annotationValue = mb_substr($match, $pos, $matchLen - $pos, $encoding);
}
else if(($pos = mb_strpos($match, 'msgid', 0, $encoding)) !== false){
$pos += mb_strlen('msgid', $encoding) + 1;
$annotationId = tao_helpers_translation_POTranslationUnit::PREVIOUS_MSGID;
$annotationValue = mb_substr($match, $pos, $matchLen - $pos, $encoding);
}
else if(($pos = mb_strpos($match, 'msgctxt', 0, $encoding)) !== false){
$pos += mb_strlen('msgctxt', $encoding) + 1;
$annotationId = tao_helpers_translation_POTranslationUnit::PREVIOUS_MSGCTXT;
$annotationValue = mb_substr($match, $pos, $matchLen - $pos, $encoding);
}
break;
}
if ($annotationId != null && $annotationValue != null){
if (!isset($returnValue[$annotationId])){
$returnValue[$annotationId] = $annotationValue;
}
else{
$returnValue[$annotationId] .= "\n${annotationValue}";
}
}
}
}
}
else{
throw new tao_helpers_translation_TranslationException("An error occured while unserializing annotations '${annotations}'.");
}
return (array) $returnValue;
} | php | public static function unserializeAnnotations($annotations)
{
$returnValue = array();
$matches = array();
$encoding = self::getApplicationHelper()->getDefaultEncoding();
if (preg_match_all('/(#[\.\:,\|]{0,1}\s+(?:[^\\n]*))/', $annotations, $matches) !== false){
if (isset($matches[1]) && count($matches[1]) > 0){
foreach ($matches[1] as $match){
$match = trim($match);
$matchLen = mb_strlen($match, $encoding);
$annotationId = null;
$annotationValue = null;
switch (mb_substr($match, 1, 1, $encoding)){
case "\t":
case ' ':
// Translator comment.
$annotationId = tao_helpers_translation_POTranslationUnit::TRANSLATOR_COMMENTS;
$annotationValue = mb_substr($match, 2, $matchLen - 2, $encoding);
break;
case '.':
$annotationId = tao_helpers_translation_POTranslationUnit::EXTRACTED_COMMENTS;
$annotationValue = mb_substr($match, 3, $matchLen - 3, $encoding);
break;
case ':':
$annotationId = tao_helpers_translation_POTranslationUnit::REFERENCE;
$annotationValue = mb_substr($match, 3, $matchLen - 3, $encoding);
break;
case ',':
$annotationId = tao_helpers_translation_POTranslationUnit::FLAGS;
$annotationValue = mb_substr($match, 3, $matchLen - 3, $encoding);
break;
case '|':
if (($pos = mb_strpos($match, 'msgid_plural', 0, $encoding)) !== false){
$pos += mb_strlen('msgid_plural', $encoding) + 1;
$annotationId = tao_helpers_translation_POTranslationUnit::PREVIOUS_MSGID_PLURAL;
$annotationValue = mb_substr($match, $pos, $matchLen - $pos, $encoding);
}
else if(($pos = mb_strpos($match, 'msgid', 0, $encoding)) !== false){
$pos += mb_strlen('msgid', $encoding) + 1;
$annotationId = tao_helpers_translation_POTranslationUnit::PREVIOUS_MSGID;
$annotationValue = mb_substr($match, $pos, $matchLen - $pos, $encoding);
}
else if(($pos = mb_strpos($match, 'msgctxt', 0, $encoding)) !== false){
$pos += mb_strlen('msgctxt', $encoding) + 1;
$annotationId = tao_helpers_translation_POTranslationUnit::PREVIOUS_MSGCTXT;
$annotationValue = mb_substr($match, $pos, $matchLen - $pos, $encoding);
}
break;
}
if ($annotationId != null && $annotationValue != null){
if (!isset($returnValue[$annotationId])){
$returnValue[$annotationId] = $annotationValue;
}
else{
$returnValue[$annotationId] .= "\n${annotationValue}";
}
}
}
}
}
else{
throw new tao_helpers_translation_TranslationException("An error occured while unserializing annotations '${annotations}'.");
}
return (array) $returnValue;
} | [
"public",
"static",
"function",
"unserializeAnnotations",
"(",
"$",
"annotations",
")",
"{",
"$",
"returnValue",
"=",
"array",
"(",
")",
";",
"$",
"matches",
"=",
"array",
"(",
")",
";",
"$",
"encoding",
"=",
"self",
"::",
"getApplicationHelper",
"(",
")",... | Unserialize PO message comments.
@access public
@author Jerome Bogaerts, <jerome.bogaerts@tudor.lu>
@param string annotations The PO message comments.
@return array | [
"Unserialize",
"PO",
"message",
"comments",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/translation/class.POUtils.php#L78-L154 |
oat-sa/tao-core | helpers/translation/class.POUtils.php | tao_helpers_translation_POUtils.serializeAnnotations | public static function serializeAnnotations($annotations)
{
$returnValue = (string) '';
// Buffer will contain each line of the serialized PO comment block.
$buffer = array();
foreach ($annotations as $name => $value){
$prefix = null;
switch ($name){
case tao_helpers_translation_POTranslationUnit::TRANSLATOR_COMMENTS:
$prefix = '#';
break;
case tao_helpers_translation_POTranslationUnit::EXTRACTED_COMMENTS:
$prefix = '#.';
break;
case tao_helpers_translation_POTranslationUnit::REFERENCE:
$prefix = '#:';
break;
case tao_helpers_translation_POTranslationUnit::FLAGS:
$prefix = '#,';
break;
case tao_helpers_translation_POTranslationUnit::PREVIOUS_MSGID:
case tao_helpers_translation_POTranslationUnit::PREVIOUS_MSGID_PLURAL:
case tao_helpers_translation_POTranslationUnit::PREVIOUS_MSGCTXT:
$prefix = '#|';
break;
}
if ($prefix !== null){
// We have a PO compliant annotation that we have to serialize.
foreach(explode("\n", $value) as $v){
$buffer[] = "${prefix} ${v}";
}
}
}
// Glue the annotation lines in a single PO comment block.
$returnValue = implode("\n", $buffer);
return (string) $returnValue;
} | php | public static function serializeAnnotations($annotations)
{
$returnValue = (string) '';
// Buffer will contain each line of the serialized PO comment block.
$buffer = array();
foreach ($annotations as $name => $value){
$prefix = null;
switch ($name){
case tao_helpers_translation_POTranslationUnit::TRANSLATOR_COMMENTS:
$prefix = '#';
break;
case tao_helpers_translation_POTranslationUnit::EXTRACTED_COMMENTS:
$prefix = '#.';
break;
case tao_helpers_translation_POTranslationUnit::REFERENCE:
$prefix = '#:';
break;
case tao_helpers_translation_POTranslationUnit::FLAGS:
$prefix = '#,';
break;
case tao_helpers_translation_POTranslationUnit::PREVIOUS_MSGID:
case tao_helpers_translation_POTranslationUnit::PREVIOUS_MSGID_PLURAL:
case tao_helpers_translation_POTranslationUnit::PREVIOUS_MSGCTXT:
$prefix = '#|';
break;
}
if ($prefix !== null){
// We have a PO compliant annotation that we have to serialize.
foreach(explode("\n", $value) as $v){
$buffer[] = "${prefix} ${v}";
}
}
}
// Glue the annotation lines in a single PO comment block.
$returnValue = implode("\n", $buffer);
return (string) $returnValue;
} | [
"public",
"static",
"function",
"serializeAnnotations",
"(",
"$",
"annotations",
")",
"{",
"$",
"returnValue",
"=",
"(",
"string",
")",
"''",
";",
"// Buffer will contain each line of the serialized PO comment block.",
"$",
"buffer",
"=",
"array",
"(",
")",
";",
"fo... | Serialize an array of annotations in a PO compliant comments format.
@access public
@author Jerome Bogaerts, <jerome.bogaerts@tudor.lu>
@param array annotations An array of annotations where keys are annotation identifiers and values are annotation values.
@return string | [
"Serialize",
"an",
"array",
"of",
"annotations",
"in",
"a",
"PO",
"compliant",
"comments",
"format",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/translation/class.POUtils.php#L164-L212 |
oat-sa/tao-core | helpers/translation/class.POUtils.php | tao_helpers_translation_POUtils.addFlag | public static function addFlag($comment, $flag)
{
$returnValue = (string) '';
$returnValue = $comment;
$flag = trim($flag);
$encoding = self::getApplicationHelper()->getDefaultEncoding();
if (mb_strpos($returnValue, $flag, 0, $encoding) === false){
$returnValue .= ((mb_strlen($returnValue, $encoding) > 0) ? " ${flag}" : $flag);
}
return (string) $returnValue;
} | php | public static function addFlag($comment, $flag)
{
$returnValue = (string) '';
$returnValue = $comment;
$flag = trim($flag);
$encoding = self::getApplicationHelper()->getDefaultEncoding();
if (mb_strpos($returnValue, $flag, 0, $encoding) === false){
$returnValue .= ((mb_strlen($returnValue, $encoding) > 0) ? " ${flag}" : $flag);
}
return (string) $returnValue;
} | [
"public",
"static",
"function",
"addFlag",
"(",
"$",
"comment",
",",
"$",
"flag",
")",
"{",
"$",
"returnValue",
"=",
"(",
"string",
")",
"''",
";",
"$",
"returnValue",
"=",
"$",
"comment",
";",
"$",
"flag",
"=",
"trim",
"(",
"$",
"flag",
")",
";",
... | Append a flag to an existing PO comment flag value.
@access public
@author Jerome Bogaerts, <jerome.bogaerts@tudor.lu>
@param string comment A PO flag comment value in which you have to add the new flag.
@param string flag The flag to add to the existing $comment.
@return string | [
"Append",
"a",
"flag",
"to",
"an",
"existing",
"PO",
"comment",
"flag",
"value",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/translation/class.POUtils.php#L223-L237 |
oat-sa/tao-core | helpers/form/validators/class.FileMimeType.php | tao_helpers_form_validators_FileMimeType.evaluate | public function evaluate($values)
{
$returnValue = false;
$mimeType = '';
if (is_array($values)) {
/** @var UploadService $uploadService */
$uploadService = ServiceManager::getServiceManager()->get(UploadService::SERVICE_ID);
if ($uploadService->isUploadedFile($values['uploaded_file'])) {
$file = $uploadService->getUploadedFlyFile($values['uploaded_file']);
$mimeType = $file->getMimeType();
} elseif (file_exists($values['uploaded_file'])) {
common_Logger::w('Deprecated use of uploaded_file');
$mimeType = tao_helpers_File::getMimeType($values['uploaded_file']);
}
if (!empty($mimeType) ) {
common_Logger::d($mimeType);
if (in_array($mimeType, $this->getOption('mimetype'))) {
$returnValue = true;
} else {
$this->setMessage(__('%1$s expected but %2$s detected', implode(', ', $this->getOption('mimetype')), $mimeType));
}
} else {
common_Logger::i('mimetype empty');
}
}
return $returnValue;
} | php | public function evaluate($values)
{
$returnValue = false;
$mimeType = '';
if (is_array($values)) {
/** @var UploadService $uploadService */
$uploadService = ServiceManager::getServiceManager()->get(UploadService::SERVICE_ID);
if ($uploadService->isUploadedFile($values['uploaded_file'])) {
$file = $uploadService->getUploadedFlyFile($values['uploaded_file']);
$mimeType = $file->getMimeType();
} elseif (file_exists($values['uploaded_file'])) {
common_Logger::w('Deprecated use of uploaded_file');
$mimeType = tao_helpers_File::getMimeType($values['uploaded_file']);
}
if (!empty($mimeType) ) {
common_Logger::d($mimeType);
if (in_array($mimeType, $this->getOption('mimetype'))) {
$returnValue = true;
} else {
$this->setMessage(__('%1$s expected but %2$s detected', implode(', ', $this->getOption('mimetype')), $mimeType));
}
} else {
common_Logger::i('mimetype empty');
}
}
return $returnValue;
} | [
"public",
"function",
"evaluate",
"(",
"$",
"values",
")",
"{",
"$",
"returnValue",
"=",
"false",
";",
"$",
"mimeType",
"=",
"''",
";",
"if",
"(",
"is_array",
"(",
"$",
"values",
")",
")",
"{",
"/** @var UploadService $uploadService */",
"$",
"uploadService"... | Short description of method evaluate
@access public
@author Joel Bout, <joel.bout@tudor.lu>
@param $values
@return boolean
@throws \oat\oatbox\service\ServiceNotFoundException
@throws \common_Exception | [
"Short",
"description",
"of",
"method",
"evaluate"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/validators/class.FileMimeType.php#L61-L92 |
oat-sa/tao-core | actions/class.Import.php | tao_actions_Import.index | public function index()
{
$importer = $this->getCurrentImporter();
$this->propagate($importer);
$formContainer = new tao_actions_form_Import(
$importer,
$this->getAvailableImportHandlers(),
$this->getCurrentClass()
);
$importForm = $formContainer->getForm();
if ($importForm->isSubmited() && $importForm->isValid()) {
/** @var QueueDispatcher $queueDispatcher */
$queueDispatcher = $this->getServiceLocator()->get(QueueDispatcher::SERVICE_ID);
$task = $queueDispatcher->createTask(
new ImportByHandler(),
[
ImportByHandler::PARAM_IMPORT_HANDLER => get_class($importer),
ImportByHandler::PARAM_FORM_VALUES => $importer instanceof TaskParameterProviderInterface ? $importer->getTaskParameters($importForm) : [],
ImportByHandler::PARAM_PARENT_CLASS => $this->getCurrentClass()->getUri(),
ImportByHandler::PARAM_OWNER => \common_session_SessionManager::getSession()->getUser()->getIdentifier(),
],
__('Import a %s into "%s"', $importer->getLabel(), $this->getCurrentClass()->getLabel()));
return $this->returnTaskJson($task);
}
$context = Context::getInstance();
$this->setData('import_extension', $context->getExtensionName());
$this->setData('import_module', $context->getModuleName());
$this->setData('import_action', $context->getActionName());
$this->setData('myForm', $importForm->render());
$this->setData('formTitle', __('Import '));
$this->setView('form/import.tpl', 'tao');
} | php | public function index()
{
$importer = $this->getCurrentImporter();
$this->propagate($importer);
$formContainer = new tao_actions_form_Import(
$importer,
$this->getAvailableImportHandlers(),
$this->getCurrentClass()
);
$importForm = $formContainer->getForm();
if ($importForm->isSubmited() && $importForm->isValid()) {
/** @var QueueDispatcher $queueDispatcher */
$queueDispatcher = $this->getServiceLocator()->get(QueueDispatcher::SERVICE_ID);
$task = $queueDispatcher->createTask(
new ImportByHandler(),
[
ImportByHandler::PARAM_IMPORT_HANDLER => get_class($importer),
ImportByHandler::PARAM_FORM_VALUES => $importer instanceof TaskParameterProviderInterface ? $importer->getTaskParameters($importForm) : [],
ImportByHandler::PARAM_PARENT_CLASS => $this->getCurrentClass()->getUri(),
ImportByHandler::PARAM_OWNER => \common_session_SessionManager::getSession()->getUser()->getIdentifier(),
],
__('Import a %s into "%s"', $importer->getLabel(), $this->getCurrentClass()->getLabel()));
return $this->returnTaskJson($task);
}
$context = Context::getInstance();
$this->setData('import_extension', $context->getExtensionName());
$this->setData('import_module', $context->getModuleName());
$this->setData('import_action', $context->getActionName());
$this->setData('myForm', $importForm->render());
$this->setData('formTitle', __('Import '));
$this->setView('form/import.tpl', 'tao');
} | [
"public",
"function",
"index",
"(",
")",
"{",
"$",
"importer",
"=",
"$",
"this",
"->",
"getCurrentImporter",
"(",
")",
";",
"$",
"this",
"->",
"propagate",
"(",
"$",
"importer",
")",
";",
"$",
"formContainer",
"=",
"new",
"tao_actions_form_Import",
"(",
... | initialize the classUri and execute the upload action
@requiresRight id WRITE | [
"initialize",
"the",
"classUri",
"and",
"execute",
"the",
"upload",
"action"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.Import.php#L61-L99 |
oat-sa/tao-core | actions/class.Import.php | tao_actions_Import.getCurrentImporter | protected function getCurrentImporter()
{
$handlers = $this->getAvailableImportHandlers();
if ($this->hasRequestParameter('importHandler')) {
foreach ($handlers as $importHandler) {
if (get_class($importHandler) == $_POST['importHandler']) {
return $importHandler;
}
}
}
$availableImportHandlers = $this->getAvailableImportHandlers();
$currentImporter = reset($availableImportHandlers);
return $currentImporter;
} | php | protected function getCurrentImporter()
{
$handlers = $this->getAvailableImportHandlers();
if ($this->hasRequestParameter('importHandler')) {
foreach ($handlers as $importHandler) {
if (get_class($importHandler) == $_POST['importHandler']) {
return $importHandler;
}
}
}
$availableImportHandlers = $this->getAvailableImportHandlers();
$currentImporter = reset($availableImportHandlers);
return $currentImporter;
} | [
"protected",
"function",
"getCurrentImporter",
"(",
")",
"{",
"$",
"handlers",
"=",
"$",
"this",
"->",
"getAvailableImportHandlers",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"hasRequestParameter",
"(",
"'importHandler'",
")",
")",
"{",
"foreach",
"(",
"$... | Returns the currently selected import handler
or the import handler to use by default
@return tao_models_classes_import_ImportHandler | [
"Returns",
"the",
"currently",
"selected",
"import",
"handler",
"or",
"the",
"import",
"handler",
"to",
"use",
"by",
"default"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.Import.php#L107-L123 |
oat-sa/tao-core | actions/class.Import.php | tao_actions_Import.getAvailableImportHandlers | protected function getAvailableImportHandlers()
{
if (empty($this->availableHandlers)) {
$this->availableHandlers = [
new tao_models_classes_import_RdfImporter(),
new tao_models_classes_import_CsvImporter()
];
}
return $this->availableHandlers;
} | php | protected function getAvailableImportHandlers()
{
if (empty($this->availableHandlers)) {
$this->availableHandlers = [
new tao_models_classes_import_RdfImporter(),
new tao_models_classes_import_CsvImporter()
];
}
return $this->availableHandlers;
} | [
"protected",
"function",
"getAvailableImportHandlers",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"availableHandlers",
")",
")",
"{",
"$",
"this",
"->",
"availableHandlers",
"=",
"[",
"new",
"tao_models_classes_import_RdfImporter",
"(",
")",
",",... | Gets the available import handlers for this module
Should be overwritten by extensions that want to provide additional ImportHandlers
@return tao_models_classes_import_ImportHandler[] | [
"Gets",
"the",
"available",
"import",
"handlers",
"for",
"this",
"module",
"Should",
"be",
"overwritten",
"by",
"extensions",
"that",
"want",
"to",
"provide",
"additional",
"ImportHandlers"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.Import.php#L131-L141 |
oat-sa/tao-core | helpers/form/elements/xhtml/class.Label.php | tao_helpers_form_elements_xhtml_Label.render | public function render()
{
$returnValue = (string) '';
if (isset($this->attributes['class'])) {
$classes = explode(' ', $this->attributes['class']);
if (! isset($this->attributes['no-format'])) {
if (! in_array('form-elt-info', $classes)) {
$classes[] = 'form-elt-info';
}
}
if (! in_array('form-elt-container', $classes)) {
$classes[] = 'form-elt-container';
}
$this->attributes['class'] = implode(' ', $classes);
} else {
if (isset($this->attributes['no-format'])) {
$this->attributes['class'] = 'form-elt-container';
} else {
$this->attributes['class'] = 'form-elt-info form-elt-container';
}
}
unset($this->attributes['no-format']);
$returnValue .= "<span class='form_desc'>";
if (! empty($this->description)) {
$returnValue .= _dh($this->getDescription());
}
$returnValue .= "</span>";
$returnValue .= "<span ";
$returnValue .= $this->renderAttributes();
$returnValue .= " >";
$returnValue .= isset($this->attributes['htmlentities']) && ! $this->attributes['htmlentities'] ? $this->value : _dh($this->value);
$returnValue .= "</span>";
return (string) $returnValue;
} | php | public function render()
{
$returnValue = (string) '';
if (isset($this->attributes['class'])) {
$classes = explode(' ', $this->attributes['class']);
if (! isset($this->attributes['no-format'])) {
if (! in_array('form-elt-info', $classes)) {
$classes[] = 'form-elt-info';
}
}
if (! in_array('form-elt-container', $classes)) {
$classes[] = 'form-elt-container';
}
$this->attributes['class'] = implode(' ', $classes);
} else {
if (isset($this->attributes['no-format'])) {
$this->attributes['class'] = 'form-elt-container';
} else {
$this->attributes['class'] = 'form-elt-info form-elt-container';
}
}
unset($this->attributes['no-format']);
$returnValue .= "<span class='form_desc'>";
if (! empty($this->description)) {
$returnValue .= _dh($this->getDescription());
}
$returnValue .= "</span>";
$returnValue .= "<span ";
$returnValue .= $this->renderAttributes();
$returnValue .= " >";
$returnValue .= isset($this->attributes['htmlentities']) && ! $this->attributes['htmlentities'] ? $this->value : _dh($this->value);
$returnValue .= "</span>";
return (string) $returnValue;
} | [
"public",
"function",
"render",
"(",
")",
"{",
"$",
"returnValue",
"=",
"(",
"string",
")",
"''",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"attributes",
"[",
"'class'",
"]",
")",
")",
"{",
"$",
"classes",
"=",
"explode",
"(",
"' '",
",",
... | 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/elements/xhtml/class.Label.php#L37-L73 |
oat-sa/tao-core | actions/form/class.Generis.php | tao_actions_form_Generis.getTopClazz | public function getTopClazz()
{
$returnValue = null;
if(!is_null($this->topClazz)){
$returnValue = $this->topClazz;
}
else{
$returnValue = new core_kernel_classes_Class(self::DEFAULT_TOP_CLASS);
}
return $returnValue;
} | php | public function getTopClazz()
{
$returnValue = null;
if(!is_null($this->topClazz)){
$returnValue = $this->topClazz;
}
else{
$returnValue = new core_kernel_classes_Class(self::DEFAULT_TOP_CLASS);
}
return $returnValue;
} | [
"public",
"function",
"getTopClazz",
"(",
")",
"{",
"$",
"returnValue",
"=",
"null",
";",
"if",
"(",
"!",
"is_null",
"(",
"$",
"this",
"->",
"topClazz",
")",
")",
"{",
"$",
"returnValue",
"=",
"$",
"this",
"->",
"topClazz",
";",
"}",
"else",
"{",
"... | get the current top level class (the defined or the default)
@access public
@author Bertrand Chevrier, <bertrand.chevrier@tudor.lu>
@return core_kernel_classes_Class | [
"get",
"the",
"current",
"top",
"level",
"class",
"(",
"the",
"defined",
"or",
"the",
"default",
")"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/form/class.Generis.php#L147-L163 |
oat-sa/tao-core | models/classes/accessControl/func/AclProxy.php | AclProxy.setImplementation | public static function setImplementation(FuncAccessControl $implementation) {
self::$implementation = $implementation;
ServiceManager::getServiceManager()->register(self::SERVICE_ID, $implementation);
} | php | public static function setImplementation(FuncAccessControl $implementation) {
self::$implementation = $implementation;
ServiceManager::getServiceManager()->register(self::SERVICE_ID, $implementation);
} | [
"public",
"static",
"function",
"setImplementation",
"(",
"FuncAccessControl",
"$",
"implementation",
")",
"{",
"self",
"::",
"$",
"implementation",
"=",
"$",
"implementation",
";",
"ServiceManager",
"::",
"getServiceManager",
"(",
")",
"->",
"register",
"(",
"sel... | Change the implementation of the access control permanently
@param FuncAccessControl $implementation | [
"Change",
"the",
"implementation",
"of",
"the",
"access",
"control",
"permanently"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/accessControl/func/AclProxy.php#L64-L67 |
oat-sa/tao-core | models/classes/accessControl/func/AclProxy.php | AclProxy.hasAccess | public function hasAccess(User $user, $controller, $action, $parameters) {
return self::accessPossible($user, $controller, $action);
} | php | public function hasAccess(User $user, $controller, $action, $parameters) {
return self::accessPossible($user, $controller, $action);
} | [
"public",
"function",
"hasAccess",
"(",
"User",
"$",
"user",
",",
"$",
"controller",
",",
"$",
"action",
",",
"$",
"parameters",
")",
"{",
"return",
"self",
"::",
"accessPossible",
"(",
"$",
"user",
",",
"$",
"controller",
",",
"$",
"action",
")",
";",... | (non-PHPdoc)
@see \oat\tao\model\accessControl\AccessControl::hasAccess() | [
"(",
"non",
"-",
"PHPdoc",
")"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/accessControl/func/AclProxy.php#L73-L75 |
oat-sa/tao-core | models/classes/accessControl/func/AclProxy.php | AclProxy.accessPossible | public static function accessPossible(User $user, $controller, $action) {
return self::getImplementation()->accessPossible($user, $controller, $action);
} | php | public static function accessPossible(User $user, $controller, $action) {
return self::getImplementation()->accessPossible($user, $controller, $action);
} | [
"public",
"static",
"function",
"accessPossible",
"(",
"User",
"$",
"user",
",",
"$",
"controller",
",",
"$",
"action",
")",
"{",
"return",
"self",
"::",
"getImplementation",
"(",
")",
"->",
"accessPossible",
"(",
"$",
"user",
",",
"$",
"controller",
",",
... | (non-PHPdoc)
@see \oat\tao\model\accessControl\func\FuncAccessControl::accessPossible() | [
"(",
"non",
"-",
"PHPdoc",
")"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/accessControl/func/AclProxy.php#L81-L83 |
oat-sa/tao-core | models/classes/accessControl/func/implementation/SimpleAccess.php | SimpleAccess.accessPossible | public function accessPossible(User $user, $controller, $action) {
$isUser = false;
foreach ($user->getRoles() as $role) {
if ($role == TaoRoles::BASE_USER) {
$isUser = true;
break;
}
}
return $isUser || $this->inWhiteList($controller, $action);
} | php | public function accessPossible(User $user, $controller, $action) {
$isUser = false;
foreach ($user->getRoles() as $role) {
if ($role == TaoRoles::BASE_USER) {
$isUser = true;
break;
}
}
return $isUser || $this->inWhiteList($controller, $action);
} | [
"public",
"function",
"accessPossible",
"(",
"User",
"$",
"user",
",",
"$",
"controller",
",",
"$",
"action",
")",
"{",
"$",
"isUser",
"=",
"false",
";",
"foreach",
"(",
"$",
"user",
"->",
"getRoles",
"(",
")",
"as",
"$",
"role",
")",
"{",
"if",
"(... | (non-PHPdoc)
@see \oat\tao\model\accessControl\func\FuncAccessControl::accessPossible() | [
"(",
"non",
"-",
"PHPdoc",
")"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/accessControl/func/implementation/SimpleAccess.php#L70-L79 |
oat-sa/tao-core | models/classes/taskQueue/Task/FilesystemAwareTrait.php | FilesystemAwareTrait.saveFileToStorage | protected function saveFileToStorage($localFilePath, $newFileName = null)
{
if (is_array($localFilePath) && isset($localFilePath['path'])) {
$localFilePath = $localFilePath['path'];
}
if (!is_string($localFilePath) || !file_exists($localFilePath)) {
return '';
}
if (null === $newFileName) {
$newFileName = basename($localFilePath);
}
// saving the file under the storage
$file = $this->getQueueStorage()->getFile($newFileName);
$stream = fopen($localFilePath, 'r');
$file->put($stream);
fclose($stream);
// delete the local file
@unlink($localFilePath);
return $newFileName;
} | php | protected function saveFileToStorage($localFilePath, $newFileName = null)
{
if (is_array($localFilePath) && isset($localFilePath['path'])) {
$localFilePath = $localFilePath['path'];
}
if (!is_string($localFilePath) || !file_exists($localFilePath)) {
return '';
}
if (null === $newFileName) {
$newFileName = basename($localFilePath);
}
// saving the file under the storage
$file = $this->getQueueStorage()->getFile($newFileName);
$stream = fopen($localFilePath, 'r');
$file->put($stream);
fclose($stream);
// delete the local file
@unlink($localFilePath);
return $newFileName;
} | [
"protected",
"function",
"saveFileToStorage",
"(",
"$",
"localFilePath",
",",
"$",
"newFileName",
"=",
"null",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"localFilePath",
")",
"&&",
"isset",
"(",
"$",
"localFilePath",
"[",
"'path'",
"]",
")",
")",
"{",
"... | Copies a locally stored file under filesystem of task queue storage for later use like:
- user downloading an export file
- saving a file for importing it later
@param string|array $localFilePath The file path or an array containing 'path' key
@param string|null $newFileName New name of the file under task queue filesystem
@return string File name (prefix) of the filesystem file
@throws \common_Exception | [
"Copies",
"a",
"locally",
"stored",
"file",
"under",
"filesystem",
"of",
"task",
"queue",
"storage",
"for",
"later",
"use",
"like",
":",
"-",
"user",
"downloading",
"an",
"export",
"file",
"-",
"saving",
"a",
"file",
"for",
"importing",
"it",
"later"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/taskQueue/Task/FilesystemAwareTrait.php#L51-L75 |
oat-sa/tao-core | models/classes/taskQueue/Task/FilesystemAwareTrait.php | FilesystemAwareTrait.saveStringToStorage | protected function saveStringToStorage($string, $fileName)
{
$file = $this->getQueueStorage()->getFile($fileName);
$file->write((string) $string);
return $file->getPrefix();
} | php | protected function saveStringToStorage($string, $fileName)
{
$file = $this->getQueueStorage()->getFile($fileName);
$file->write((string) $string);
return $file->getPrefix();
} | [
"protected",
"function",
"saveStringToStorage",
"(",
"$",
"string",
",",
"$",
"fileName",
")",
"{",
"$",
"file",
"=",
"$",
"this",
"->",
"getQueueStorage",
"(",
")",
"->",
"getFile",
"(",
"$",
"fileName",
")",
";",
"$",
"file",
"->",
"write",
"(",
"(",... | Writes arbitrary string data into a filesystem file under task queue storage.
@param string $string
@param string $fileName
@return string
@throws \League\Flysystem\FileExistsException
@throws \common_Exception | [
"Writes",
"arbitrary",
"string",
"data",
"into",
"a",
"filesystem",
"file",
"under",
"task",
"queue",
"storage",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/taskQueue/Task/FilesystemAwareTrait.php#L87-L94 |
oat-sa/tao-core | models/classes/taskQueue/Task/FilesystemAwareTrait.php | FilesystemAwareTrait.deleteQueueStorageFile | protected function deleteQueueStorageFile(EntityInterface $taskLogEntity)
{
if ($filename = $taskLogEntity->getFileNameFromReport()) {
$file = $this->getQueueStorage()
->getFile($filename);
if($file->exists()) {
$file->delete();
}
}
return false;
} | php | protected function deleteQueueStorageFile(EntityInterface $taskLogEntity)
{
if ($filename = $taskLogEntity->getFileNameFromReport()) {
$file = $this->getQueueStorage()
->getFile($filename);
if($file->exists()) {
$file->delete();
}
}
return false;
} | [
"protected",
"function",
"deleteQueueStorageFile",
"(",
"EntityInterface",
"$",
"taskLogEntity",
")",
"{",
"if",
"(",
"$",
"filename",
"=",
"$",
"taskLogEntity",
"->",
"getFileNameFromReport",
"(",
")",
")",
"{",
"$",
"file",
"=",
"$",
"this",
"->",
"getQueueS... | Deletes a filesystem file stored under task queue storage
@param EntityInterface $taskLogEntity
@return bool | [
"Deletes",
"a",
"filesystem",
"file",
"stored",
"under",
"task",
"queue",
"storage"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/taskQueue/Task/FilesystemAwareTrait.php#L111-L123 |
oat-sa/tao-core | models/classes/taskQueue/Task/FilesystemAwareTrait.php | FilesystemAwareTrait.getQueueStorageFile | protected function getQueueStorageFile($fileName)
{
$file = $this->getQueueStorage()->getFile($fileName);
if ($file->exists()) {
return $file;
}
return null;
} | php | protected function getQueueStorageFile($fileName)
{
$file = $this->getQueueStorage()->getFile($fileName);
if ($file->exists()) {
return $file;
}
return null;
} | [
"protected",
"function",
"getQueueStorageFile",
"(",
"$",
"fileName",
")",
"{",
"$",
"file",
"=",
"$",
"this",
"->",
"getQueueStorage",
"(",
")",
"->",
"getFile",
"(",
"$",
"fileName",
")",
";",
"if",
"(",
"$",
"file",
"->",
"exists",
"(",
")",
")",
... | Tries to get the file if it exists.
@param string $fileName
@return null|File | [
"Tries",
"to",
"get",
"the",
"file",
"if",
"it",
"exists",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/taskQueue/Task/FilesystemAwareTrait.php#L146-L155 |
oat-sa/tao-core | scripts/tools/AbstractIndexedCsv.php | AbstractIndexedCsv.beforeProcess | protected function beforeProcess()
{
// -- Deal with file handling.
$sourceFp = @fopen($this->getSource(), 'r');
$destinationFp = @fopen($this->getDestination(), 'w');
if ($sourceFp === false) {
return new Report(
Report::TYPE_ERROR,
"Source file '" . $this->getSource() . "' could not be open."
);
} else {
$this->setSourceFp($sourceFp);
}
if ($destinationFp === false) {
return new Report(
Report::TYPE_ERROR,
"Destination file '" . $this->getDestination() . "' could not be open."
);
} else {
$this->setDestinationFp($destinationFp);
return new Report(
Report::TYPE_SUCCESS,
"Source and destination files open."
);
}
} | php | protected function beforeProcess()
{
// -- Deal with file handling.
$sourceFp = @fopen($this->getSource(), 'r');
$destinationFp = @fopen($this->getDestination(), 'w');
if ($sourceFp === false) {
return new Report(
Report::TYPE_ERROR,
"Source file '" . $this->getSource() . "' could not be open."
);
} else {
$this->setSourceFp($sourceFp);
}
if ($destinationFp === false) {
return new Report(
Report::TYPE_ERROR,
"Destination file '" . $this->getDestination() . "' could not be open."
);
} else {
$this->setDestinationFp($destinationFp);
return new Report(
Report::TYPE_SUCCESS,
"Source and destination files open."
);
}
} | [
"protected",
"function",
"beforeProcess",
"(",
")",
"{",
"// -- Deal with file handling.",
"$",
"sourceFp",
"=",
"@",
"fopen",
"(",
"$",
"this",
"->",
"getSource",
"(",
")",
",",
"'r'",
")",
";",
"$",
"destinationFp",
"=",
"@",
"fopen",
"(",
"$",
"this",
... | Behaviour to be triggered at the beginning of the script.
This method contains the behaviours to be aplied at the very
beginning of the script. In this abstract class, it opens the source
and destination files. Implementors can override this method to add
additional behaviours.
@return \common_report_Report | [
"Behaviour",
"to",
"be",
"triggered",
"at",
"the",
"beginning",
"of",
"the",
"script",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/scripts/tools/AbstractIndexedCsv.php#L380-L407 |
oat-sa/tao-core | scripts/tools/AbstractIndexedCsv.php | AbstractIndexedCsv.afterProcess | protected function afterProcess()
{
@fclose($this->getSourceFp());
@fclose($this->getDestinationFp());
return new Report(
Report::TYPE_INFO,
"Source and Destination files closed."
);
} | php | protected function afterProcess()
{
@fclose($this->getSourceFp());
@fclose($this->getDestinationFp());
return new Report(
Report::TYPE_INFO,
"Source and Destination files closed."
);
} | [
"protected",
"function",
"afterProcess",
"(",
")",
"{",
"@",
"fclose",
"(",
"$",
"this",
"->",
"getSourceFp",
"(",
")",
")",
";",
"@",
"fclose",
"(",
"$",
"this",
"->",
"getDestinationFp",
"(",
")",
")",
";",
"return",
"new",
"Report",
"(",
"Report",
... | Behaviour to be triggered at the end of the script.
This method contains the behaviours to be applied at the end
of the script. In this abstract class, it closes the source
and destination files. Implementors can override this method
to add additional behaviours.
@return \common_report_Report | [
"Behaviour",
"to",
"be",
"triggered",
"at",
"the",
"end",
"of",
"the",
"script",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/scripts/tools/AbstractIndexedCsv.php#L419-L428 |
oat-sa/tao-core | scripts/tools/AbstractIndexedCsv.php | AbstractIndexedCsv.index | protected function index()
{
$index = [];
$scanCount = $this->fillIndex($index, $this->getSourceFp());
$this->setIndex($index);
return new Report(
Report::TYPE_INFO,
$scanCount . " rows scanned for indexing. " . count($index) . " unique values indexed."
);
} | php | protected function index()
{
$index = [];
$scanCount = $this->fillIndex($index, $this->getSourceFp());
$this->setIndex($index);
return new Report(
Report::TYPE_INFO,
$scanCount . " rows scanned for indexing. " . count($index) . " unique values indexed."
);
} | [
"protected",
"function",
"index",
"(",
")",
"{",
"$",
"index",
"=",
"[",
"]",
";",
"$",
"scanCount",
"=",
"$",
"this",
"->",
"fillIndex",
"(",
"$",
"index",
",",
"$",
"this",
"->",
"getSourceFp",
"(",
")",
")",
";",
"$",
"this",
"->",
"setIndex",
... | Indexing method.
This method contains the logic to index the source file.
@return \common_report_Report | [
"Indexing",
"method",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/scripts/tools/AbstractIndexedCsv.php#L437-L447 |
oat-sa/tao-core | models/classes/asset/AssetService.php | AssetService.getAsset | public function getAsset($asset, $extensionId = null)
{
if( ! is_null($extensionId)){
$url = $this->getJsBaseWww($extensionId) . FsUtils::normalizePath($asset);
} else {
$url = $this->getAssetBaseUrl() . FsUtils::normalizePath($asset);
}
$isFolder = (substr_compare($url, '/', strlen($url) - 1) === 0);
$buster = $this->getCacheBuster();
if($buster != false && $isFolder == false) {
$url .= '?' . self::BUSTER_QUERY_KEY . '=' . urlencode($buster);
}
return $url;
} | php | public function getAsset($asset, $extensionId = null)
{
if( ! is_null($extensionId)){
$url = $this->getJsBaseWww($extensionId) . FsUtils::normalizePath($asset);
} else {
$url = $this->getAssetBaseUrl() . FsUtils::normalizePath($asset);
}
$isFolder = (substr_compare($url, '/', strlen($url) - 1) === 0);
$buster = $this->getCacheBuster();
if($buster != false && $isFolder == false) {
$url .= '?' . self::BUSTER_QUERY_KEY . '=' . urlencode($buster);
}
return $url;
} | [
"public",
"function",
"getAsset",
"(",
"$",
"asset",
",",
"$",
"extensionId",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"is_null",
"(",
"$",
"extensionId",
")",
")",
"{",
"$",
"url",
"=",
"$",
"this",
"->",
"getJsBaseWww",
"(",
"$",
"extensionId",
")",
... | Get the full URL of an asset or a folder
@param string $asset the asset or folder path, relative, from the views folder
@param string $extensionId if the asset is relative to an extension base www (optional)
@return string the asset URL | [
"Get",
"the",
"full",
"URL",
"of",
"an",
"asset",
"or",
"a",
"folder"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/asset/AssetService.php#L58-L74 |
oat-sa/tao-core | models/classes/asset/AssetService.php | AssetService.getAssetBaseUrl | protected function getAssetBaseUrl()
{
$baseUrl = $this->hasOption(self::BASE_OPTION_KEY) ? $this->getOption(self::BASE_OPTION_KEY) : ROOT_URL;
$baseUrl = trim($baseUrl);
if(substr($baseUrl, -1) != '/'){
$baseUrl .= '/';
}
return $baseUrl;
} | php | protected function getAssetBaseUrl()
{
$baseUrl = $this->hasOption(self::BASE_OPTION_KEY) ? $this->getOption(self::BASE_OPTION_KEY) : ROOT_URL;
$baseUrl = trim($baseUrl);
if(substr($baseUrl, -1) != '/'){
$baseUrl .= '/';
}
return $baseUrl;
} | [
"protected",
"function",
"getAssetBaseUrl",
"(",
")",
"{",
"$",
"baseUrl",
"=",
"$",
"this",
"->",
"hasOption",
"(",
"self",
"::",
"BASE_OPTION_KEY",
")",
"?",
"$",
"this",
"->",
"getOption",
"(",
"self",
"::",
"BASE_OPTION_KEY",
")",
":",
"ROOT_URL",
";",... | Get the asset BASE URL
@return string the base URL | [
"Get",
"the",
"asset",
"BASE",
"URL"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/asset/AssetService.php#L98-L108 |
oat-sa/tao-core | models/classes/asset/AssetService.php | AssetService.getCacheBuster | public function getCacheBuster()
{
if ($this->hasOption(self::BUSTER_OPTION_KEY)) {
return $this->getOption(self::BUSTER_OPTION_KEY);
} else {
return $this->getServiceLocator()->get(ApplicationService::SERVICE_ID)->getPlatformVersion();
}
} | php | public function getCacheBuster()
{
if ($this->hasOption(self::BUSTER_OPTION_KEY)) {
return $this->getOption(self::BUSTER_OPTION_KEY);
} else {
return $this->getServiceLocator()->get(ApplicationService::SERVICE_ID)->getPlatformVersion();
}
} | [
"public",
"function",
"getCacheBuster",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"hasOption",
"(",
"self",
"::",
"BUSTER_OPTION_KEY",
")",
")",
"{",
"return",
"$",
"this",
"->",
"getOption",
"(",
"self",
"::",
"BUSTER_OPTION_KEY",
")",
";",
"}",
"els... | Get a the cache buster value, if none we use the tao version.
@return string the busteri value | [
"Get",
"a",
"the",
"cache",
"buster",
"value",
"if",
"none",
"we",
"use",
"the",
"tao",
"version",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/asset/AssetService.php#L114-L121 |
oat-sa/tao-core | models/classes/actionQueue/implementation/InstantActionQueue.php | InstantActionQueue.getPosition | public function getPosition(QueuedAction $action, User $user = null)
{
$action->setServiceLocator($this->getServiceManager());
$positions = $this->getPositions($action);
return count($positions);
} | php | public function getPosition(QueuedAction $action, User $user = null)
{
$action->setServiceLocator($this->getServiceManager());
$positions = $this->getPositions($action);
return count($positions);
} | [
"public",
"function",
"getPosition",
"(",
"QueuedAction",
"$",
"action",
",",
"User",
"$",
"user",
"=",
"null",
")",
"{",
"$",
"action",
"->",
"setServiceLocator",
"(",
"$",
"this",
"->",
"getServiceManager",
"(",
")",
")",
";",
"$",
"positions",
"=",
"$... | Note that this method is not transaction safe so there may be collisions.
This implementation supposed to provide approximate position in the queue
@param QueuedAction $action
@param User $user
@return integer
@throws | [
"Note",
"that",
"this",
"method",
"is",
"not",
"transaction",
"safe",
"so",
"there",
"may",
"be",
"collisions",
".",
"This",
"implementation",
"supposed",
"to",
"provide",
"approximate",
"position",
"in",
"the",
"queue"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/actionQueue/implementation/InstantActionQueue.php#L90-L95 |
oat-sa/tao-core | models/classes/maintenance/MaintenanceState.php | MaintenanceState.toArray | public function toArray()
{
$data = array(
self::ID => $this->id,
self::STATUS => $this->status,
self::START_TIME => $this->startTime->getTimestamp(),
);
if (! is_null($this->endTime)) {
$data[self::END_TIME] = $this->endTime->getTimestamp();
}
return $data;
} | php | public function toArray()
{
$data = array(
self::ID => $this->id,
self::STATUS => $this->status,
self::START_TIME => $this->startTime->getTimestamp(),
);
if (! is_null($this->endTime)) {
$data[self::END_TIME] = $this->endTime->getTimestamp();
}
return $data;
} | [
"public",
"function",
"toArray",
"(",
")",
"{",
"$",
"data",
"=",
"array",
"(",
"self",
"::",
"ID",
"=>",
"$",
"this",
"->",
"id",
",",
"self",
"::",
"STATUS",
"=>",
"$",
"this",
"->",
"status",
",",
"self",
"::",
"START_TIME",
"=>",
"$",
"this",
... | Return the Maintenance state as array, Datetime are converted to timestamp
@return array | [
"Return",
"the",
"Maintenance",
"state",
"as",
"array",
"Datetime",
"are",
"converted",
"to",
"timestamp"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/maintenance/MaintenanceState.php#L93-L106 |
oat-sa/tao-core | models/classes/maintenance/MaintenanceState.php | MaintenanceState.getDateTime | protected function getDateTime($dateTime)
{
if ($dateTime instanceof \DateTime) {
return $dateTime;
}
if ((is_string($dateTime) && (int) $dateTime > 0) || is_numeric($dateTime)) {
return (new \DateTime())->setTimestamp($dateTime);
}
throw new \common_Exception(__('A date has to be a Datetime or timestamp'));
} | php | protected function getDateTime($dateTime)
{
if ($dateTime instanceof \DateTime) {
return $dateTime;
}
if ((is_string($dateTime) && (int) $dateTime > 0) || is_numeric($dateTime)) {
return (new \DateTime())->setTimestamp($dateTime);
}
throw new \common_Exception(__('A date has to be a Datetime or timestamp'));
} | [
"protected",
"function",
"getDateTime",
"(",
"$",
"dateTime",
")",
"{",
"if",
"(",
"$",
"dateTime",
"instanceof",
"\\",
"DateTime",
")",
"{",
"return",
"$",
"dateTime",
";",
"}",
"if",
"(",
"(",
"is_string",
"(",
"$",
"dateTime",
")",
"&&",
"(",
"int",... | Transform a string|Datetime to Datetime
@param $dateTime
@return \DateTime
@throws \common_Exception | [
"Transform",
"a",
"string|Datetime",
"to",
"Datetime"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/maintenance/MaintenanceState.php#L164-L176 |
oat-sa/tao-core | models/classes/maintenance/MaintenanceState.php | MaintenanceState.checkData | protected function checkData(array $data)
{
if (! isset($data[self::STATUS]) || ! in_array($data[self::STATUS], self::$availableStatus)) {
throw new \common_Exception(
__('A maintenance status must have a STATUS: "%s" or "%s"', self::LIVE_MODE, self::OFFLINE_MODE)
);
}
} | php | protected function checkData(array $data)
{
if (! isset($data[self::STATUS]) || ! in_array($data[self::STATUS], self::$availableStatus)) {
throw new \common_Exception(
__('A maintenance status must have a STATUS: "%s" or "%s"', self::LIVE_MODE, self::OFFLINE_MODE)
);
}
} | [
"protected",
"function",
"checkData",
"(",
"array",
"$",
"data",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"data",
"[",
"self",
"::",
"STATUS",
"]",
")",
"||",
"!",
"in_array",
"(",
"$",
"data",
"[",
"self",
"::",
"STATUS",
"]",
",",
"self",
"... | Check data of constructor input
@param array $data
@throws \common_Exception | [
"Check",
"data",
"of",
"constructor",
"input"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/maintenance/MaintenanceState.php#L184-L191 |
oat-sa/tao-core | models/classes/controllerMap/ControllerDescription.php | ControllerDescription.getActions | public function getActions() {
$actions = array();
foreach ($this->class->getMethods(ReflectionMethod::IS_PUBLIC) as $m) {
if ($m->isConstructor() || $m->isDestructor() || in_array($m->name, self::$BLACK_LIST)) {
continue;
}
if (is_subclass_of($m->class, 'Module') || is_subclass_of($m->class, Controller::class)) {
$actions[] = new ActionDescription($m);
}
}
return $actions;
} | php | public function getActions() {
$actions = array();
foreach ($this->class->getMethods(ReflectionMethod::IS_PUBLIC) as $m) {
if ($m->isConstructor() || $m->isDestructor() || in_array($m->name, self::$BLACK_LIST)) {
continue;
}
if (is_subclass_of($m->class, 'Module') || is_subclass_of($m->class, Controller::class)) {
$actions[] = new ActionDescription($m);
}
}
return $actions;
} | [
"public",
"function",
"getActions",
"(",
")",
"{",
"$",
"actions",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"class",
"->",
"getMethods",
"(",
"ReflectionMethod",
"::",
"IS_PUBLIC",
")",
"as",
"$",
"m",
")",
"{",
"if",
"(",
"$",... | Returns ann array of ActionDescription objects
@return array | [
"Returns",
"ann",
"array",
"of",
"ActionDescription",
"objects"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/controllerMap/ControllerDescription.php#L66-L78 |
oat-sa/tao-core | models/classes/import/class.CSVMappingForm.php | tao_models_classes_import_CSVMappingForm.initElements | public function initElements()
{
if(!isset($this->options['class_properties'])){
throw new Exception('No class properties found');
}
if(!isset($this->options['csv_column'])){
throw new Exception('No csv columns found');
}
$columnsOptions = array();
$columnsOptionsLabels = array();
$columnsOptionsLiteral = array();
$columnsOptionsLiteral['csv_select'] = ' --- ' . __('Select') . ' --- ';
$columnsOptionsLiteral['csv_null'] = ' --- ' . __("Don't set");
$columnsOptionsRanged = array();
$columnsOptionsRanged['csv_select'] = ' --- ' . __('Select') . ' --- ';
$columnsOptionsRanged['csv_null'] = ' --- ' . __('Use default value');
// We build the list of CSV columns that can be mapped to
// the target class properties.
if (isset($this->options[tao_helpers_data_CsvFile::FIRST_ROW_COLUMN_NAMES])
&& $this->options[tao_helpers_data_CsvFile::FIRST_ROW_COLUMN_NAMES]){
foreach($this->options['csv_column'] as $i => $column){
$columnsOptions[$i.tao_models_classes_import_CsvImporter::OPTION_POSTFIX] = __('Column') . ' ' . ($i + 1) . ' : ' . $column;
$columnsOptionsLabels[$i.tao_models_classes_import_CsvImporter::OPTION_POSTFIX] = $this->prepareString($column);
}
} else {
// We do not know column so we display more neutral information
// about columns to the end user.
for ($i = 0; $i < count($this->options['csv_column']); $i++){
$columnsOptions[$i.tao_models_classes_import_CsvImporter::OPTION_POSTFIX] = __('Column') . ' ' . ($i + 1);
}
}
foreach($this->options['class_properties'] as $propertyUri => $propertyLabel){
$propElt = tao_helpers_form_FormFactory::getElement($propertyUri, 'Combobox');
$propElt->setDescription($propertyLabel);
// literal or ranged?
$options = array_key_exists($propertyUri, $this->options['ranged_properties'])
? array_merge($columnsOptionsRanged, $columnsOptions)
: array_merge($columnsOptionsLiteral, $columnsOptions);
$value = 'csv_select';
if (isset($_POST[$propertyUri]) && isset($options[$_POST[$propertyUri]])) {
$value = $_POST[$propertyUri];
}
// We trying compare current label with option labels from file and set most suitable
$label = $this->prepareString($propertyLabel);
$value = key(preg_grep("/^$label$/", $columnsOptionsLabels)) ?: $value;
$propElt->setOptions($options);
$propElt->setValue($value);
/** Add mandatory label */
if (tao_helpers_Uri::decode($propertyUri)==OntologyRdfs::RDFS_LABEL) {
$elementEqualsToCsvSelect = new tao_helpers_form_elements_xhtml_Hidden();
$elementEqualsToCsvSelect->setValue('csv_select');
$elementEqualsToCsvSelect->setDescription(' to null');
$propElt->addValidator(tao_helpers_form_FormFactory::getValidator(
'Equals', array(
'reference' => $elementEqualsToCsvSelect,
'invert' => true
)
));
}
$this->form->addElement($propElt);
}
if(count($this->options['class_properties']) > 0){
$this->form->createGroup('property_mapping', __('Map the properties to the CSV columns'), array_keys($this->options['class_properties']));
}
$ranged = array();
foreach($this->options['ranged_properties'] as $propertyUri => $propertyLabel){
$property = new core_kernel_classes_Property(tao_helpers_Uri::decode($propertyUri));
$propElt = tao_helpers_form_GenerisFormFactory::elementMap($property);
if(!is_null($propElt)){
$defName = tao_helpers_Uri::encode($property->getUri()) . self::DEFAULT_VALUES_SUFFIX;
$propElt->setName($defName);
if ($this->form->getElement($propertyUri)->getRawValue()=='csv_null') {
$propElt->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty'));
}
$this->form->addElement($propElt);
$ranged[$defName] = $propElt;
}
}
if(count($this->options['ranged_properties']) > 0){
$this->form->createGroup('ranged_property', __('Define the default values'), array_keys($ranged));
}
$importFileEle = tao_helpers_form_FormFactory::getElement('importFile', 'Hidden');
$this->form->addElement($importFileEle);
$optDelimiter = tao_helpers_form_FormFactory::getElement(tao_helpers_data_CsvFile::FIELD_DELIMITER, 'Hidden');
$this->form->addElement($optDelimiter);
$optEncloser = tao_helpers_form_FormFactory::getElement(tao_helpers_data_CsvFile::FIELD_ENCLOSER, 'Hidden');
$this->form->addElement($optEncloser);
$optMulti = tao_helpers_form_FormFactory::getElement(tao_helpers_data_CsvFile::MULTI_VALUES_DELIMITER, 'Hidden');
$this->form->addElement($optMulti);
if (isset($this->options[tao_models_classes_import_CsvUploadForm::IS_OPTION_FIRST_COLUMN_ENABLE])){
if ($this->options[tao_models_classes_import_CsvUploadForm::IS_OPTION_FIRST_COLUMN_ENABLE] === true){
$optFirstColumn = tao_helpers_form_FormFactory::getElement(tao_helpers_data_CsvFile::FIRST_ROW_COLUMN_NAMES, 'Hidden');
$this->form->addElement($optFirstColumn);
}
}else{
$optFirstColumn = tao_helpers_form_FormFactory::getElement(tao_helpers_data_CsvFile::FIRST_ROW_COLUMN_NAMES, 'Hidden');
$this->form->addElement($optFirstColumn);
}
} | php | public function initElements()
{
if(!isset($this->options['class_properties'])){
throw new Exception('No class properties found');
}
if(!isset($this->options['csv_column'])){
throw new Exception('No csv columns found');
}
$columnsOptions = array();
$columnsOptionsLabels = array();
$columnsOptionsLiteral = array();
$columnsOptionsLiteral['csv_select'] = ' --- ' . __('Select') . ' --- ';
$columnsOptionsLiteral['csv_null'] = ' --- ' . __("Don't set");
$columnsOptionsRanged = array();
$columnsOptionsRanged['csv_select'] = ' --- ' . __('Select') . ' --- ';
$columnsOptionsRanged['csv_null'] = ' --- ' . __('Use default value');
// We build the list of CSV columns that can be mapped to
// the target class properties.
if (isset($this->options[tao_helpers_data_CsvFile::FIRST_ROW_COLUMN_NAMES])
&& $this->options[tao_helpers_data_CsvFile::FIRST_ROW_COLUMN_NAMES]){
foreach($this->options['csv_column'] as $i => $column){
$columnsOptions[$i.tao_models_classes_import_CsvImporter::OPTION_POSTFIX] = __('Column') . ' ' . ($i + 1) . ' : ' . $column;
$columnsOptionsLabels[$i.tao_models_classes_import_CsvImporter::OPTION_POSTFIX] = $this->prepareString($column);
}
} else {
// We do not know column so we display more neutral information
// about columns to the end user.
for ($i = 0; $i < count($this->options['csv_column']); $i++){
$columnsOptions[$i.tao_models_classes_import_CsvImporter::OPTION_POSTFIX] = __('Column') . ' ' . ($i + 1);
}
}
foreach($this->options['class_properties'] as $propertyUri => $propertyLabel){
$propElt = tao_helpers_form_FormFactory::getElement($propertyUri, 'Combobox');
$propElt->setDescription($propertyLabel);
// literal or ranged?
$options = array_key_exists($propertyUri, $this->options['ranged_properties'])
? array_merge($columnsOptionsRanged, $columnsOptions)
: array_merge($columnsOptionsLiteral, $columnsOptions);
$value = 'csv_select';
if (isset($_POST[$propertyUri]) && isset($options[$_POST[$propertyUri]])) {
$value = $_POST[$propertyUri];
}
// We trying compare current label with option labels from file and set most suitable
$label = $this->prepareString($propertyLabel);
$value = key(preg_grep("/^$label$/", $columnsOptionsLabels)) ?: $value;
$propElt->setOptions($options);
$propElt->setValue($value);
/** Add mandatory label */
if (tao_helpers_Uri::decode($propertyUri)==OntologyRdfs::RDFS_LABEL) {
$elementEqualsToCsvSelect = new tao_helpers_form_elements_xhtml_Hidden();
$elementEqualsToCsvSelect->setValue('csv_select');
$elementEqualsToCsvSelect->setDescription(' to null');
$propElt->addValidator(tao_helpers_form_FormFactory::getValidator(
'Equals', array(
'reference' => $elementEqualsToCsvSelect,
'invert' => true
)
));
}
$this->form->addElement($propElt);
}
if(count($this->options['class_properties']) > 0){
$this->form->createGroup('property_mapping', __('Map the properties to the CSV columns'), array_keys($this->options['class_properties']));
}
$ranged = array();
foreach($this->options['ranged_properties'] as $propertyUri => $propertyLabel){
$property = new core_kernel_classes_Property(tao_helpers_Uri::decode($propertyUri));
$propElt = tao_helpers_form_GenerisFormFactory::elementMap($property);
if(!is_null($propElt)){
$defName = tao_helpers_Uri::encode($property->getUri()) . self::DEFAULT_VALUES_SUFFIX;
$propElt->setName($defName);
if ($this->form->getElement($propertyUri)->getRawValue()=='csv_null') {
$propElt->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty'));
}
$this->form->addElement($propElt);
$ranged[$defName] = $propElt;
}
}
if(count($this->options['ranged_properties']) > 0){
$this->form->createGroup('ranged_property', __('Define the default values'), array_keys($ranged));
}
$importFileEle = tao_helpers_form_FormFactory::getElement('importFile', 'Hidden');
$this->form->addElement($importFileEle);
$optDelimiter = tao_helpers_form_FormFactory::getElement(tao_helpers_data_CsvFile::FIELD_DELIMITER, 'Hidden');
$this->form->addElement($optDelimiter);
$optEncloser = tao_helpers_form_FormFactory::getElement(tao_helpers_data_CsvFile::FIELD_ENCLOSER, 'Hidden');
$this->form->addElement($optEncloser);
$optMulti = tao_helpers_form_FormFactory::getElement(tao_helpers_data_CsvFile::MULTI_VALUES_DELIMITER, 'Hidden');
$this->form->addElement($optMulti);
if (isset($this->options[tao_models_classes_import_CsvUploadForm::IS_OPTION_FIRST_COLUMN_ENABLE])){
if ($this->options[tao_models_classes_import_CsvUploadForm::IS_OPTION_FIRST_COLUMN_ENABLE] === true){
$optFirstColumn = tao_helpers_form_FormFactory::getElement(tao_helpers_data_CsvFile::FIRST_ROW_COLUMN_NAMES, 'Hidden');
$this->form->addElement($optFirstColumn);
}
}else{
$optFirstColumn = tao_helpers_form_FormFactory::getElement(tao_helpers_data_CsvFile::FIRST_ROW_COLUMN_NAMES, 'Hidden');
$this->form->addElement($optFirstColumn);
}
} | [
"public",
"function",
"initElements",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"options",
"[",
"'class_properties'",
"]",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'No class properties found'",
")",
";",
"}",
"if",
"(",
"!"... | Short description of method initElements
@access public
@author Bertrand Chevrier, <bertrand.chevrier@tudor.lu>
@throws Exception
@throws common_Exception
@return mixed | [
"Short",
"description",
"of",
"method",
"initElements"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/import/class.CSVMappingForm.php#L77-L193 |
oat-sa/tao-core | models/classes/menu/Perspective.php | Perspective.fromLegacyToolbarAction | public static function fromLegacyToolbarAction(\SimpleXMLElement $node, $structureExtensionId) {
$data = array(
'id' => (string)$node['id'],
'extension' => $structureExtensionId,
'name' => (string)$node['title'],
'level' => (int)$node['level'],
'description' => empty($text) ? null : $text,
'binding' => isset($node['binding']) ? (string)$node['binding'] : (isset($node['js']) ? (string)$node['js'] : null),
'structure' => isset($node['structure']) ? (string)$node['structure'] : null,
'group' => self::GROUP_SETTINGS,
'icon' => isset($node['icon']) ? Icon::fromArray(array('id' => (string)$node['icon']), $structureExtensionId) : null
);
$children = array();
if (isset($node['structure'])) {
$children = array();
// (string)$node['structure']
}
return new static($data, $children);
} | php | public static function fromLegacyToolbarAction(\SimpleXMLElement $node, $structureExtensionId) {
$data = array(
'id' => (string)$node['id'],
'extension' => $structureExtensionId,
'name' => (string)$node['title'],
'level' => (int)$node['level'],
'description' => empty($text) ? null : $text,
'binding' => isset($node['binding']) ? (string)$node['binding'] : (isset($node['js']) ? (string)$node['js'] : null),
'structure' => isset($node['structure']) ? (string)$node['structure'] : null,
'group' => self::GROUP_SETTINGS,
'icon' => isset($node['icon']) ? Icon::fromArray(array('id' => (string)$node['icon']), $structureExtensionId) : null
);
$children = array();
if (isset($node['structure'])) {
$children = array();
// (string)$node['structure']
}
return new static($data, $children);
} | [
"public",
"static",
"function",
"fromLegacyToolbarAction",
"(",
"\\",
"SimpleXMLElement",
"$",
"node",
",",
"$",
"structureExtensionId",
")",
"{",
"$",
"data",
"=",
"array",
"(",
"'id'",
"=>",
"(",
"string",
")",
"$",
"node",
"[",
"'id'",
"]",
",",
"'exten... | Generate a Perspective from a legacy ToolbarAction
@param \SimpleXMLElement $node
@param $structureExtensionId
@return static | [
"Generate",
"a",
"Perspective",
"from",
"a",
"legacy",
"ToolbarAction"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/menu/Perspective.php#L74-L92 |
oat-sa/tao-core | models/classes/taskQueue/Worker/AbstractWorker.php | AbstractWorker.processTask | public function processTask(TaskInterface $task)
{
if ($this->taskLog->getStatus($task->getId()) != TaskLogInterface::STATUS_CANCELLED) {
$report = Report::createInfo(__('Running task %s', $task->getId()));
try {
$this->logDebug('Processing task ' . $task->getId(), $this->getLogContext());
$rowsTouched = $this->taskLog->setStatus($task->getId(), TaskLogInterface::STATUS_RUNNING, TaskLogInterface::STATUS_DEQUEUED);
// if the task is being executed by another worker, just return, no report needs to be saved
if (!$rowsTouched) {
$this->logDebug('Task ' . $task->getId() . ' seems to be processed by another worker.', $this->getLogContext());
return TaskLogInterface::STATUS_UNKNOWN;
}
// let the task know that it is called from a worker
$task->applyWorkerContext();
// execute the task
$taskReport = $task();
if (!$taskReport instanceof Report) {
$this->logWarning('Task ' . $task->getId() . ' should return a report object.', $this->getLogContext());
$taskReport = Report::createInfo(__('Task not returned any report.'));
}
$report->add($taskReport);
unset($taskReport, $rowsTouched);
} catch (\Exception $e) {
$this->logError('Executing task ' . $task->getId() . ' failed with MSG: ' . $e->getMessage(), $this->getLogContext());
$report = Report::createFailure(__('Executing task %s failed', $task->getId()));
}
// Initial status
$status = $report->getType() == Report::TYPE_ERROR || $report->containsError()
? TaskLogInterface::STATUS_FAILED
: TaskLogInterface::STATUS_COMPLETED;
// Change the status if the task has children
if ($task->hasChildren() && $status == TaskLogInterface::STATUS_COMPLETED) {
$status = TaskLogInterface::STATUS_CHILD_RUNNING;
}
$cloneCreated = false;
// if the task is a special sync task: the status of the parent task depends on the status of the remote task.
if ($this->isRemoteTaskSynchroniser($task) && $status == TaskLogInterface::STATUS_COMPLETED) {
// if the remote task is still in progress, we have to reschedule this task
// the RESTApi returns TaskLogCategorizedStatus values
if (in_array($this->getRemoteStatus($task), [CategorizedStatus::STATUS_CREATED, CategorizedStatus::STATUS_IN_PROGRESS])) {
if ($this->queuer->count() <= 1) {
//if there is less than or exactly one task in the queue, let's sleep a bit, in order not to regenerate the same task too much
sleep(3);
}
$cloneCreated = $this->queuer->enqueue(clone $task, $task->getLabel());
} elseif ($this->getRemoteStatus($task) == CategorizedStatus::STATUS_FAILED) {
// if the remote task status is failed
$status = TaskLogInterface::STATUS_FAILED;
}
}
if (!$cloneCreated) {
$this->taskLog->setReport($task->getId(), $report, $status);
} else {
// if there is a clone, delete the old task log
//TODO: once we have the centralized way of cleaning up the log table, this should be refactored
$this->taskLog->getBroker()->deleteById($task->getId());
}
// Update parent
if ($task->hasParent()) {
/** @var EntityInterface $parentLogTask */
$parentLogTask = $this->taskLog->getById($task->getParentId());
if (!$parentLogTask->isMasterStatus()) {
$this->taskLog->updateParent($task->getParentId());
}
}
unset($report);
} else {
$this->taskLog->setReport(
$task->getId(),
Report::createInfo(__('Task %s has been cancelled, message was not processed.', $task->getId())),
TaskLogInterface::STATUS_CANCELLED
);
$status = TaskLogInterface::STATUS_CANCELLED;
}
// delete message from queue
$this->queuer->acknowledge($task);
return $status;
} | php | public function processTask(TaskInterface $task)
{
if ($this->taskLog->getStatus($task->getId()) != TaskLogInterface::STATUS_CANCELLED) {
$report = Report::createInfo(__('Running task %s', $task->getId()));
try {
$this->logDebug('Processing task ' . $task->getId(), $this->getLogContext());
$rowsTouched = $this->taskLog->setStatus($task->getId(), TaskLogInterface::STATUS_RUNNING, TaskLogInterface::STATUS_DEQUEUED);
// if the task is being executed by another worker, just return, no report needs to be saved
if (!$rowsTouched) {
$this->logDebug('Task ' . $task->getId() . ' seems to be processed by another worker.', $this->getLogContext());
return TaskLogInterface::STATUS_UNKNOWN;
}
// let the task know that it is called from a worker
$task->applyWorkerContext();
// execute the task
$taskReport = $task();
if (!$taskReport instanceof Report) {
$this->logWarning('Task ' . $task->getId() . ' should return a report object.', $this->getLogContext());
$taskReport = Report::createInfo(__('Task not returned any report.'));
}
$report->add($taskReport);
unset($taskReport, $rowsTouched);
} catch (\Exception $e) {
$this->logError('Executing task ' . $task->getId() . ' failed with MSG: ' . $e->getMessage(), $this->getLogContext());
$report = Report::createFailure(__('Executing task %s failed', $task->getId()));
}
// Initial status
$status = $report->getType() == Report::TYPE_ERROR || $report->containsError()
? TaskLogInterface::STATUS_FAILED
: TaskLogInterface::STATUS_COMPLETED;
// Change the status if the task has children
if ($task->hasChildren() && $status == TaskLogInterface::STATUS_COMPLETED) {
$status = TaskLogInterface::STATUS_CHILD_RUNNING;
}
$cloneCreated = false;
// if the task is a special sync task: the status of the parent task depends on the status of the remote task.
if ($this->isRemoteTaskSynchroniser($task) && $status == TaskLogInterface::STATUS_COMPLETED) {
// if the remote task is still in progress, we have to reschedule this task
// the RESTApi returns TaskLogCategorizedStatus values
if (in_array($this->getRemoteStatus($task), [CategorizedStatus::STATUS_CREATED, CategorizedStatus::STATUS_IN_PROGRESS])) {
if ($this->queuer->count() <= 1) {
//if there is less than or exactly one task in the queue, let's sleep a bit, in order not to regenerate the same task too much
sleep(3);
}
$cloneCreated = $this->queuer->enqueue(clone $task, $task->getLabel());
} elseif ($this->getRemoteStatus($task) == CategorizedStatus::STATUS_FAILED) {
// if the remote task status is failed
$status = TaskLogInterface::STATUS_FAILED;
}
}
if (!$cloneCreated) {
$this->taskLog->setReport($task->getId(), $report, $status);
} else {
// if there is a clone, delete the old task log
//TODO: once we have the centralized way of cleaning up the log table, this should be refactored
$this->taskLog->getBroker()->deleteById($task->getId());
}
// Update parent
if ($task->hasParent()) {
/** @var EntityInterface $parentLogTask */
$parentLogTask = $this->taskLog->getById($task->getParentId());
if (!$parentLogTask->isMasterStatus()) {
$this->taskLog->updateParent($task->getParentId());
}
}
unset($report);
} else {
$this->taskLog->setReport(
$task->getId(),
Report::createInfo(__('Task %s has been cancelled, message was not processed.', $task->getId())),
TaskLogInterface::STATUS_CANCELLED
);
$status = TaskLogInterface::STATUS_CANCELLED;
}
// delete message from queue
$this->queuer->acknowledge($task);
return $status;
} | [
"public",
"function",
"processTask",
"(",
"TaskInterface",
"$",
"task",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"taskLog",
"->",
"getStatus",
"(",
"$",
"task",
"->",
"getId",
"(",
")",
")",
"!=",
"TaskLogInterface",
"::",
"STATUS_CANCELLED",
")",
"{",
"$... | Because of BC, it is kept as public, later it can be set to protected.
@param TaskInterface $task
@return string
@throws \common_exception_NotFound | [
"Because",
"of",
"BC",
"it",
"is",
"kept",
"as",
"public",
"later",
"it",
"can",
"be",
"set",
"to",
"protected",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/taskQueue/Worker/AbstractWorker.php#L60-L156 |
oat-sa/tao-core | helpers/translation/class.Utils.php | tao_helpers_translation_Utils.getAvailableLanguages | public static function getAvailableLanguages(){
$languages = array();
foreach(common_ext_ExtensionsManager::singleton()->getInstalledExtensions() as $extension){
$localesDir = $extension->getDir() . 'locales/';
foreach(glob($localesDir . '*') as $file){
if(is_dir($file) && file_exists($file . '/messages.po')){
$lang = basename($file);
if(!in_array($lang, $languages)){
$languages[] = $lang;
}
}
}
}
return $languages;
} | php | public static function getAvailableLanguages(){
$languages = array();
foreach(common_ext_ExtensionsManager::singleton()->getInstalledExtensions() as $extension){
$localesDir = $extension->getDir() . 'locales/';
foreach(glob($localesDir . '*') as $file){
if(is_dir($file) && file_exists($file . '/messages.po')){
$lang = basename($file);
if(!in_array($lang, $languages)){
$languages[] = $lang;
}
}
}
}
return $languages;
} | [
"public",
"static",
"function",
"getAvailableLanguages",
"(",
")",
"{",
"$",
"languages",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"common_ext_ExtensionsManager",
"::",
"singleton",
"(",
")",
"->",
"getInstalledExtensions",
"(",
")",
"as",
"$",
"extension",
... | Get the availables locales for the current installation (from installed extensions).
@return string[] the list of all locales supported by the app (even though a locale is used in only one extension). | [
"Get",
"the",
"availables",
"locales",
"for",
"the",
"current",
"installation",
"(",
"from",
"installed",
"extensions",
")",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/translation/class.Utils.php#L57-L71 |
oat-sa/tao-core | models/classes/http/LegacyController.php | LegacyController.getRawParameter | protected function getRawParameter($paramName)
{
$raw = $this->getRequest()->getRawParameters();
if (!isset($raw[$paramName])) {
throw new \common_exception_MissingParameter($paramName);
}
return $raw[$paramName];
} | php | protected function getRawParameter($paramName)
{
$raw = $this->getRequest()->getRawParameters();
if (!isset($raw[$paramName])) {
throw new \common_exception_MissingParameter($paramName);
}
return $raw[$paramName];
} | [
"protected",
"function",
"getRawParameter",
"(",
"$",
"paramName",
")",
"{",
"$",
"raw",
"=",
"$",
"this",
"->",
"getRequest",
"(",
")",
"->",
"getRawParameters",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"raw",
"[",
"$",
"paramName",
"]",
")... | Returns a request parameter unencoded
@param string $paramName
@throws \common_exception_MissingParameter
@return string | [
"Returns",
"a",
"request",
"parameter",
"unencoded"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/http/LegacyController.php#L113-L120 |
oat-sa/tao-core | models/classes/http/LegacyController.php | LegacyController.hasHeader | public function hasHeader($name)
{
$name = strtolower($name);
if (!$this->request) {
return $this->getRequest()->hasHeader($name);
}
return parent::hasHeader($name);
} | php | public function hasHeader($name)
{
$name = strtolower($name);
if (!$this->request) {
return $this->getRequest()->hasHeader($name);
}
return parent::hasHeader($name);
} | [
"public",
"function",
"hasHeader",
"(",
"$",
"name",
")",
"{",
"$",
"name",
"=",
"strtolower",
"(",
"$",
"name",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"request",
")",
"{",
"return",
"$",
"this",
"->",
"getRequest",
"(",
")",
"->",
"hasHeader... | @see parent::hasHeader()
@return bool | [
"@see",
"parent",
"::",
"hasHeader",
"()"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/http/LegacyController.php#L140-L147 |
oat-sa/tao-core | models/classes/http/LegacyController.php | LegacyController.getHeader | public function getHeader($name, $default = null)
{
if (!$this->request) {
return $this->getRequest()->getHeader($name);
}
return parent::getHeader($name, $default);
} | php | public function getHeader($name, $default = null)
{
if (!$this->request) {
return $this->getRequest()->getHeader($name);
}
return parent::getHeader($name, $default);
} | [
"public",
"function",
"getHeader",
"(",
"$",
"name",
",",
"$",
"default",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"request",
")",
"{",
"return",
"$",
"this",
"->",
"getRequest",
"(",
")",
"->",
"getHeader",
"(",
"$",
"name",
")",
... | @see parent::getHeader()
@param $default
@return mixed | [
"@see",
"parent",
"::",
"getHeader",
"()"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/http/LegacyController.php#L155-L161 |
oat-sa/tao-core | models/classes/http/LegacyController.php | LegacyController.hasCookie | public function hasCookie($name)
{
if (!$this->request) {
return $this->getRequest()->hasCookie($name);
}
return parent::hasCookie($name);
} | php | public function hasCookie($name)
{
if (!$this->request) {
return $this->getRequest()->hasCookie($name);
}
return parent::hasCookie($name);
} | [
"public",
"function",
"hasCookie",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"request",
")",
"{",
"return",
"$",
"this",
"->",
"getRequest",
"(",
")",
"->",
"hasCookie",
"(",
"$",
"name",
")",
";",
"}",
"return",
"parent",
"::"... | @see parent::hasCookie()
@return bool | [
"@see",
"parent",
"::",
"hasCookie",
"()"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/http/LegacyController.php#L168-L174 |
oat-sa/tao-core | models/classes/http/LegacyController.php | LegacyController.getCookie | public function getCookie($name, $default = null)
{
if (!$this->request) {
return $this->getRequest()->getCookie($name);
}
return parent::getCookie($name, $default);
} | php | public function getCookie($name, $default = null)
{
if (!$this->request) {
return $this->getRequest()->getCookie($name);
}
return parent::getCookie($name, $default);
} | [
"public",
"function",
"getCookie",
"(",
"$",
"name",
",",
"$",
"default",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"request",
")",
"{",
"return",
"$",
"this",
"->",
"getRequest",
"(",
")",
"->",
"getCookie",
"(",
"$",
"name",
")",
... | @see parent::getCookie()
@param $name
@param $default
@return bool|mixed | [
"@see",
"parent",
"::",
"getCookie",
"()"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/http/LegacyController.php#L183-L189 |
oat-sa/tao-core | models/classes/http/LegacyController.php | LegacyController.setCookie | public function setCookie($name, $value = null, $expire = null,
$domainPath = null, $https = null, $httpOnly = null)
{
if (!$this->response) {
return $this->getResponse()->setCookie($name, $value, $expire, $domainPath, $https, $httpOnly);
}
return parent::setCookie($name, $value, $expire, $domainPath, $https, $httpOnly);
} | php | public function setCookie($name, $value = null, $expire = null,
$domainPath = null, $https = null, $httpOnly = null)
{
if (!$this->response) {
return $this->getResponse()->setCookie($name, $value, $expire, $domainPath, $https, $httpOnly);
}
return parent::setCookie($name, $value, $expire, $domainPath, $https, $httpOnly);
} | [
"public",
"function",
"setCookie",
"(",
"$",
"name",
",",
"$",
"value",
"=",
"null",
",",
"$",
"expire",
"=",
"null",
",",
"$",
"domainPath",
"=",
"null",
",",
"$",
"https",
"=",
"null",
",",
"$",
"httpOnly",
"=",
"null",
")",
"{",
"if",
"(",
"!"... | @see parent::setCookie()
@param $name
@param null $value
@param null $expire
@param null $domainPath
@param null $https
@param null $httpOnly
@return bool|void | [
"@see",
"parent",
"::",
"setCookie",
"()"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/http/LegacyController.php#L319-L326 |
oat-sa/tao-core | models/classes/http/LegacyController.php | LegacyController.setContentHeader | public function setContentHeader($contentType, $charset = 'UTF-8')
{
if (!$this->response) {
return $this->getResponse()->setContentHeader($contentType, $charset);
}
return parent::setContentHeader($contentType, $charset);
} | php | public function setContentHeader($contentType, $charset = 'UTF-8')
{
if (!$this->response) {
return $this->getResponse()->setContentHeader($contentType, $charset);
}
return parent::setContentHeader($contentType, $charset);
} | [
"public",
"function",
"setContentHeader",
"(",
"$",
"contentType",
",",
"$",
"charset",
"=",
"'UTF-8'",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"response",
")",
"{",
"return",
"$",
"this",
"->",
"getResponse",
"(",
")",
"->",
"setContentHeader",
"("... | @see parent::setContentHeader()
@param $contentType
@param string $charset
@return Controller | [
"@see",
"parent",
"::",
"setContentHeader",
"()"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/http/LegacyController.php#L335-L341 |
oat-sa/tao-core | models/classes/http/LegacyController.php | LegacyController.logDeprecated | protected function logDeprecated($function = null)
{
return;
$message = '[DEPRECATED] Deprecated call ';
if (!is_null($function)) {
$message .= 'of "' . $function . '"';
}
$message .= ' (' . get_called_class() .')';
\common_Logger::i($message);
} | php | protected function logDeprecated($function = null)
{
return;
$message = '[DEPRECATED] Deprecated call ';
if (!is_null($function)) {
$message .= 'of "' . $function . '"';
}
$message .= ' (' . get_called_class() .')';
\common_Logger::i($message);
} | [
"protected",
"function",
"logDeprecated",
"(",
"$",
"function",
"=",
"null",
")",
"{",
"return",
";",
"$",
"message",
"=",
"'[DEPRECATED] Deprecated call '",
";",
"if",
"(",
"!",
"is_null",
"(",
"$",
"function",
")",
")",
"{",
"$",
"message",
".=",
"'of \... | Mark a method as deprecated
@param null $function | [
"Mark",
"a",
"method",
"as",
"deprecated"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/http/LegacyController.php#L374-L383 |
oat-sa/tao-core | models/classes/Tree/GetTreeService.php | GetTreeService.handle | public function handle(GetTreeRequest $request)
{
if(!tao_helpers_Request::isAjax()){
throw new common_exception_IsAjaxAction(__FUNCTION__);
}
$factory = new GenerisTreeFactory(
$request->isShowInstance(),
$request->getOpenNodes(),
$request->getLimit(),
$request->getOffset(),
$request->getResourceUrisToShow(),
$request->getFilters(),
$request->getFiltersOptions(),
[]
);
$treeWrapper = new TreeWrapper($factory->buildTree($request->getClass()));
if ($request->isHideNode()) {
$treeWrapper = $treeWrapper->getDefaultChildren();
}
return $treeWrapper;
} | php | public function handle(GetTreeRequest $request)
{
if(!tao_helpers_Request::isAjax()){
throw new common_exception_IsAjaxAction(__FUNCTION__);
}
$factory = new GenerisTreeFactory(
$request->isShowInstance(),
$request->getOpenNodes(),
$request->getLimit(),
$request->getOffset(),
$request->getResourceUrisToShow(),
$request->getFilters(),
$request->getFiltersOptions(),
[]
);
$treeWrapper = new TreeWrapper($factory->buildTree($request->getClass()));
if ($request->isHideNode()) {
$treeWrapper = $treeWrapper->getDefaultChildren();
}
return $treeWrapper;
} | [
"public",
"function",
"handle",
"(",
"GetTreeRequest",
"$",
"request",
")",
"{",
"if",
"(",
"!",
"tao_helpers_Request",
"::",
"isAjax",
"(",
")",
")",
"{",
"throw",
"new",
"common_exception_IsAjaxAction",
"(",
"__FUNCTION__",
")",
";",
"}",
"$",
"factory",
"... | @param GetTreeRequest $request
@return TreeWrapper
@throws common_exception_IsAjaxAction | [
"@param",
"GetTreeRequest",
"$request",
"@return",
"TreeWrapper"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/Tree/GetTreeService.php#L20-L44 |
oat-sa/tao-core | models/classes/auth/AbstractAuthService.php | AbstractAuthService.getAuthType | public function getAuthType(\core_kernel_classes_Resource $resource = null)
{
if ($resource) {
$authTypeUri = $resource->getUri();
foreach ($this->getOption(self::OPTION_TYPES) as $type) {
if ($type instanceof AbstractAuthType && $type->getAuthClass()->getUri() == $authTypeUri) {
$authType = $type;
}
}
} else {
$authType = $this->getOption(self::OPTION_DEFAULT_TYPE);
}
if (!isset($authType) || !is_a($authType, AbstractAuthType::class)) {
throw new \common_Exception('Auth type not defined');
}
return $authType;
} | php | public function getAuthType(\core_kernel_classes_Resource $resource = null)
{
if ($resource) {
$authTypeUri = $resource->getUri();
foreach ($this->getOption(self::OPTION_TYPES) as $type) {
if ($type instanceof AbstractAuthType && $type->getAuthClass()->getUri() == $authTypeUri) {
$authType = $type;
}
}
} else {
$authType = $this->getOption(self::OPTION_DEFAULT_TYPE);
}
if (!isset($authType) || !is_a($authType, AbstractAuthType::class)) {
throw new \common_Exception('Auth type not defined');
}
return $authType;
} | [
"public",
"function",
"getAuthType",
"(",
"\\",
"core_kernel_classes_Resource",
"$",
"resource",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"resource",
")",
"{",
"$",
"authTypeUri",
"=",
"$",
"resource",
"->",
"getUri",
"(",
")",
";",
"foreach",
"(",
"$",
"t... | Get the authType form config
@param \core_kernel_classes_Resource|null $resource
@return AbstractAuthType
@throws \common_Exception | [
"Get",
"the",
"authType",
"form",
"config"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/auth/AbstractAuthService.php#L49-L67 |
oat-sa/tao-core | models/classes/websource/TokenWebSource.php | TokenWebSource.generateToken | protected function generateToken($relPath) {
$time = time();
return $time.'/'.md5($time.$relPath.$this->getOption(self::OPTION_SECRET));
} | php | protected function generateToken($relPath) {
$time = time();
return $time.'/'.md5($time.$relPath.$this->getOption(self::OPTION_SECRET));
} | [
"protected",
"function",
"generateToken",
"(",
"$",
"relPath",
")",
"{",
"$",
"time",
"=",
"time",
"(",
")",
";",
"return",
"$",
"time",
".",
"'/'",
".",
"md5",
"(",
"$",
"time",
".",
"$",
"relPath",
".",
"$",
"this",
"->",
"getOption",
"(",
"self"... | Generate a token for the resource
Same algorithm is implemented again in getFile.php
@param string $relPath
@return string | [
"Generate",
"a",
"token",
"for",
"the",
"resource",
"Same",
"algorithm",
"is",
"implemented",
"again",
"in",
"getFile",
".",
"php"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/websource/TokenWebSource.php#L69-L72 |
oat-sa/tao-core | actions/form/class.UserPassword.php | tao_actions_form_UserPassword.initElements | public function initElements()
{
$pass1Element = tao_helpers_form_FormFactory::getElement('oldpassword', 'Hiddenbox');
$pass1Element->setDescription(__('Old Password'));
$pass1Element->addValidator(
tao_helpers_form_FormFactory::getValidator('Callback', array(
'message' => __('Passwords are not matching'),
'object' => tao_models_classes_UserService::singleton(),
'method' => 'isPasswordValid',
'param' => tao_models_classes_UserService::singleton()->getCurrentUser()
)));
$this->form->addElement($pass1Element);
$pass2Element = tao_helpers_form_FormFactory::getElement('newpassword', 'Hiddenbox');
$pass2Element->setDescription(__('New password'));
$pass2Element->addValidators( PasswordConstraintsService::singleton()->getValidators() );
$pass2Element->setBreakOnFirstError( false );
$this->form->addElement($pass2Element);
$pass3Element = tao_helpers_form_FormFactory::getElement('newpassword2', 'Hiddenbox');
$pass3Element->setDescription(__('Repeat new password'));
$pass3Element->addValidators(array(
tao_helpers_form_FormFactory::getValidator('Password', array('password2_ref' => $pass2Element)),
));
$this->form->addElement($pass3Element);
} | php | public function initElements()
{
$pass1Element = tao_helpers_form_FormFactory::getElement('oldpassword', 'Hiddenbox');
$pass1Element->setDescription(__('Old Password'));
$pass1Element->addValidator(
tao_helpers_form_FormFactory::getValidator('Callback', array(
'message' => __('Passwords are not matching'),
'object' => tao_models_classes_UserService::singleton(),
'method' => 'isPasswordValid',
'param' => tao_models_classes_UserService::singleton()->getCurrentUser()
)));
$this->form->addElement($pass1Element);
$pass2Element = tao_helpers_form_FormFactory::getElement('newpassword', 'Hiddenbox');
$pass2Element->setDescription(__('New password'));
$pass2Element->addValidators( PasswordConstraintsService::singleton()->getValidators() );
$pass2Element->setBreakOnFirstError( false );
$this->form->addElement($pass2Element);
$pass3Element = tao_helpers_form_FormFactory::getElement('newpassword2', 'Hiddenbox');
$pass3Element->setDescription(__('Repeat new password'));
$pass3Element->addValidators(array(
tao_helpers_form_FormFactory::getValidator('Password', array('password2_ref' => $pass2Element)),
));
$this->form->addElement($pass3Element);
} | [
"public",
"function",
"initElements",
"(",
")",
"{",
"$",
"pass1Element",
"=",
"tao_helpers_form_FormFactory",
"::",
"getElement",
"(",
"'oldpassword'",
",",
"'Hiddenbox'",
")",
";",
"$",
"pass1Element",
"->",
"setDescription",
"(",
"__",
"(",
"'Old Password'",
")... | Short description of method initElements
@access public
@author Joel Bout, <joel.bout@tudor.lu> | [
"Short",
"description",
"of",
"method",
"initElements"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/form/class.UserPassword.php#L57-L84 |
oat-sa/tao-core | actions/class.File.php | tao_actions_File.upload | public function upload()
{
$response = array('uploaded' => false);
foreach ((array)$_FILES as $file) {
$targetFolder = isset($_POST['folder']) ? $_POST['folder'] : '/';
$response = array_merge($response, $this->uploadFile($file, $targetFolder . '/'));
}
$this->returnJson($response);
} | php | public function upload()
{
$response = array('uploaded' => false);
foreach ((array)$_FILES as $file) {
$targetFolder = isset($_POST['folder']) ? $_POST['folder'] : '/';
$response = array_merge($response, $this->uploadFile($file, $targetFolder . '/'));
}
$this->returnJson($response);
} | [
"public",
"function",
"upload",
"(",
")",
"{",
"$",
"response",
"=",
"array",
"(",
"'uploaded'",
"=>",
"false",
")",
";",
"foreach",
"(",
"(",
"array",
")",
"$",
"_FILES",
"as",
"$",
"file",
")",
"{",
"$",
"targetFolder",
"=",
"isset",
"(",
"$",
"_... | Upload a file using http and copy it from the tmp dir to the target folder
@return void | [
"Upload",
"a",
"file",
"using",
"http",
"and",
"copy",
"it",
"from",
"the",
"tmp",
"dir",
"to",
"the",
"target",
"folder"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.File.php#L47-L56 |
oat-sa/tao-core | actions/class.File.php | tao_actions_File.uploadFile | protected function uploadFile($postedFile, $folder)
{
$returnValue = [];
if (isset($postedFile['tmp_name'], $postedFile['name']) && $postedFile['tmp_name']) {
$returnValue = $this->getServiceLocator()->get(UploadService::SERVICE_ID)->uploadFile($postedFile, $folder);
}
return $returnValue;
} | php | protected function uploadFile($postedFile, $folder)
{
$returnValue = [];
if (isset($postedFile['tmp_name'], $postedFile['name']) && $postedFile['tmp_name']) {
$returnValue = $this->getServiceLocator()->get(UploadService::SERVICE_ID)->uploadFile($postedFile, $folder);
}
return $returnValue;
} | [
"protected",
"function",
"uploadFile",
"(",
"$",
"postedFile",
",",
"$",
"folder",
")",
"{",
"$",
"returnValue",
"=",
"[",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"postedFile",
"[",
"'tmp_name'",
"]",
",",
"$",
"postedFile",
"[",
"'name'",
"]",
")",
... | Get, check and move the file uploaded (described in the posetedFile parameter)
@param array $postedFile
@param string $folder
@return array $data
@throws \oat\oatbox\service\ServiceNotFoundException
@throws \common_Exception | [
"Get",
"check",
"and",
"move",
"the",
"file",
"uploaded",
"(",
"described",
"in",
"the",
"posetedFile",
"parameter",
")"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.File.php#L67-L75 |
oat-sa/tao-core | actions/class.File.php | tao_actions_File.downloadFile | public function downloadFile()
{
if($this->hasRequestParameter('id')){
$fileService = $this->getServiceLocator()->get(FileReferenceSerializer::SERVICE_ID);
$file = $fileService->unserialize($this->getRequestParameter('id'));
header("Content-Disposition: attachment; filename=\"{$file->getBasename()}\"");
tao_helpers_Http::returnStream($file->readPsrStream(), $file->getMimeType());
}
} | php | public function downloadFile()
{
if($this->hasRequestParameter('id')){
$fileService = $this->getServiceLocator()->get(FileReferenceSerializer::SERVICE_ID);
$file = $fileService->unserialize($this->getRequestParameter('id'));
header("Content-Disposition: attachment; filename=\"{$file->getBasename()}\"");
tao_helpers_Http::returnStream($file->readPsrStream(), $file->getMimeType());
}
} | [
"public",
"function",
"downloadFile",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"hasRequestParameter",
"(",
"'id'",
")",
")",
"{",
"$",
"fileService",
"=",
"$",
"this",
"->",
"getServiceLocator",
"(",
")",
"->",
"get",
"(",
"FileReferenceSerializer",
":... | Download a resource file content
@param {String} uri Uri of the resource file | [
"Download",
"a",
"resource",
"file",
"content"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.File.php#L81-L90 |
oat-sa/tao-core | actions/class.RestTrait.php | tao_actions_RestTrait.returnFailure | protected function returnFailure(Exception $exception, $withMessage=true)
{
$handler = new RestExceptionHandler();
$handler->sendHeader($exception);
$data = array();
if ($withMessage) {
$data['success'] = false;
$data['errorCode'] = $exception->getCode();
$data['errorMsg'] = $this->getErrorMessage($exception);
$data['version'] = TAO_VERSION;
}
echo $this->encode($data);
exit(0);
} | php | protected function returnFailure(Exception $exception, $withMessage=true)
{
$handler = new RestExceptionHandler();
$handler->sendHeader($exception);
$data = array();
if ($withMessage) {
$data['success'] = false;
$data['errorCode'] = $exception->getCode();
$data['errorMsg'] = $this->getErrorMessage($exception);
$data['version'] = TAO_VERSION;
}
echo $this->encode($data);
exit(0);
} | [
"protected",
"function",
"returnFailure",
"(",
"Exception",
"$",
"exception",
",",
"$",
"withMessage",
"=",
"true",
")",
"{",
"$",
"handler",
"=",
"new",
"RestExceptionHandler",
"(",
")",
";",
"$",
"handler",
"->",
"sendHeader",
"(",
"$",
"exception",
")",
... | @OA\Schema(
schema="tao.RestTrait.FailureResponse",
description="Error response with success=false",
allOf={
@OA\Schema(ref="#/components/schemas/tao.RestTrait.BaseResponse")
},
@OA\Property(
property="success",
type="boolean",
example=false,
description="Indicates error"
),
@OA\Property(
property="errorCode",
type="integer",
description="Exception error code"
),
@OA\Property(
property="errorMsg",
type="string",
description="Exception message, not localized"
)
)
Return failed Rest response
Set header http by using handle()
If $withMessage is true:
Send response with success, code, message & version of TAO
@param Exception $exception
@param $withMessage
@throws common_exception_NotImplemented | [
"@OA",
"\\",
"Schema",
"(",
"schema",
"=",
"tao",
".",
"RestTrait",
".",
"FailureResponse",
"description",
"=",
"Error",
"response",
"with",
"success",
"=",
"false",
"allOf",
"=",
"{",
"@OA",
"\\",
"Schema",
"(",
"ref",
"=",
"#",
"/",
"components",
"/",
... | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.RestTrait.php#L96-L111 |
oat-sa/tao-core | actions/class.RestTrait.php | tao_actions_RestTrait.returnSuccess | protected function returnSuccess($rawData = array(), $withMessage=true)
{
$data = array();
if ($withMessage) {
$data['success'] = true;
$data['data'] = $rawData;
$data['version'] = TAO_VERSION;
} else {
$data = $rawData;
}
echo $this->encode($data);
exit(0);
} | php | protected function returnSuccess($rawData = array(), $withMessage=true)
{
$data = array();
if ($withMessage) {
$data['success'] = true;
$data['data'] = $rawData;
$data['version'] = TAO_VERSION;
} else {
$data = $rawData;
}
echo $this->encode($data);
exit(0);
} | [
"protected",
"function",
"returnSuccess",
"(",
"$",
"rawData",
"=",
"array",
"(",
")",
",",
"$",
"withMessage",
"=",
"true",
")",
"{",
"$",
"data",
"=",
"array",
"(",
")",
";",
"if",
"(",
"$",
"withMessage",
")",
"{",
"$",
"data",
"[",
"'success'",
... | @OA\Schema(
schema="tao.RestTrait.SuccessResponse",
description="Response with data and success=true",
allOf={
@OA\Schema(ref="#/components/schemas/tao.RestTrait.BaseResponse"),
},
@OA\Property(
property="success",
type="boolean",
example=true,
description="Indicates success"
),
@OA\Property(
property="data",
type="object",
description="Payload"
)
)
Return success Rest response
Send response with success, data & version of TAO
@param array $rawData
@param bool $withMessage
@throws common_exception_NotImplemented | [
"@OA",
"\\",
"Schema",
"(",
"schema",
"=",
"tao",
".",
"RestTrait",
".",
"SuccessResponse",
"description",
"=",
"Response",
"with",
"data",
"and",
"success",
"=",
"true",
"allOf",
"=",
"{",
"@OA",
"\\",
"Schema",
"(",
"ref",
"=",
"#",
"/",
"components",
... | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.RestTrait.php#L140-L153 |
oat-sa/tao-core | actions/class.RestTrait.php | tao_actions_RestTrait.encode | protected function encode($data)
{
switch ($this->responseEncoding){
case "application/rdf+xml":
throw new common_exception_NotImplemented();
break;
case "text/xml":
case "application/xml":
return tao_helpers_Xml::from_array($data);
case "application/json":
default:
return json_encode($data);
}
} | php | protected function encode($data)
{
switch ($this->responseEncoding){
case "application/rdf+xml":
throw new common_exception_NotImplemented();
break;
case "text/xml":
case "application/xml":
return tao_helpers_Xml::from_array($data);
case "application/json":
default:
return json_encode($data);
}
} | [
"protected",
"function",
"encode",
"(",
"$",
"data",
")",
"{",
"switch",
"(",
"$",
"this",
"->",
"responseEncoding",
")",
"{",
"case",
"\"application/rdf+xml\"",
":",
"throw",
"new",
"common_exception_NotImplemented",
"(",
")",
";",
"break",
";",
"case",
"\"te... | Encode data regarding responseEncoding
@param $data
@return string
@throws common_exception_NotImplemented | [
"Encode",
"data",
"regarding",
"responseEncoding"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.RestTrait.php#L162-L175 |
oat-sa/tao-core | actions/class.RestTrait.php | tao_actions_RestTrait.getErrorMessage | protected function getErrorMessage(Exception $exception)
{
$defaultMessage = __('Unexpected error. Please contact administrator');
if (DEBUG_MODE) {
$defaultMessage = $exception->getMessage();
}
return ($exception instanceof common_exception_UserReadableException) ? $exception->getUserMessage() : $defaultMessage;
} | php | protected function getErrorMessage(Exception $exception)
{
$defaultMessage = __('Unexpected error. Please contact administrator');
if (DEBUG_MODE) {
$defaultMessage = $exception->getMessage();
}
return ($exception instanceof common_exception_UserReadableException) ? $exception->getUserMessage() : $defaultMessage;
} | [
"protected",
"function",
"getErrorMessage",
"(",
"Exception",
"$",
"exception",
")",
"{",
"$",
"defaultMessage",
"=",
"__",
"(",
"'Unexpected error. Please contact administrator'",
")",
";",
"if",
"(",
"DEBUG_MODE",
")",
"{",
"$",
"defaultMessage",
"=",
"$",
"exce... | Generate safe message preventing exposing sensitive date in non develop mode
@param Exception $exception
@return string | [
"Generate",
"safe",
"message",
"preventing",
"exposing",
"sensitive",
"date",
"in",
"non",
"develop",
"mode"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.RestTrait.php#L182-L189 |
oat-sa/tao-core | models/classes/service/class.VariableParameter.php | tao_models_classes_service_VariableParameter.toOntology | public function toOntology() {
$serviceCallClass = new core_kernel_classes_Class(WfEngineOntology::CLASS_URI_ACTUAL_PARAMETER);
$resource = $serviceCallClass->createInstanceWithProperties(array(
WfEngineOntology::PROPERTY_ACTUAL_PARAMETER_FORMAL_PARAMETER => $this->getDefinition(),
WfEngineOntology::PROPERTY_ACTUAL_PARAMETER_PROCESS_VARIABLE => $this->variable
));
return $resource;
} | php | public function toOntology() {
$serviceCallClass = new core_kernel_classes_Class(WfEngineOntology::CLASS_URI_ACTUAL_PARAMETER);
$resource = $serviceCallClass->createInstanceWithProperties(array(
WfEngineOntology::PROPERTY_ACTUAL_PARAMETER_FORMAL_PARAMETER => $this->getDefinition(),
WfEngineOntology::PROPERTY_ACTUAL_PARAMETER_PROCESS_VARIABLE => $this->variable
));
return $resource;
} | [
"public",
"function",
"toOntology",
"(",
")",
"{",
"$",
"serviceCallClass",
"=",
"new",
"core_kernel_classes_Class",
"(",
"WfEngineOntology",
"::",
"CLASS_URI_ACTUAL_PARAMETER",
")",
";",
"$",
"resource",
"=",
"$",
"serviceCallClass",
"->",
"createInstanceWithProperties... | (non-PHPdoc)
@see tao_models_classes_service_Parameter::serialize() | [
"(",
"non",
"-",
"PHPdoc",
")"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/service/class.VariableParameter.php#L65-L72 |
oat-sa/tao-core | models/classes/ClassServiceTrait.php | ClassServiceTrait.deleteClass | public function deleteClass(\core_kernel_classes_Class $clazz)
{
$returnValue = (bool) false;
if ($clazz->isSubClassOf($this->getRootClass()) && ! $clazz->equals($this->getRootClass())) {
$returnValue = true;
$instances = $clazz->getInstances();
foreach ($instances as $instance) {
$this->deleteResource($instance);
}
$subclasses = $clazz->getSubClasses(false);
foreach ($subclasses as $subclass) {
$returnValue = $returnValue && $this->deleteClass($subclass);
}
foreach ($clazz->getProperties() as $classProperty) {
$returnValue = $returnValue && $this->deleteClassProperty($classProperty);
}
$returnValue = $returnValue && $clazz->delete();
} else {
\common_Logger::w('Tried to delete class ' . $clazz->getUri() . ' as if it were a subclass of ' . $this->getRootClass()->getUri());
}
return (bool) $returnValue;
} | php | public function deleteClass(\core_kernel_classes_Class $clazz)
{
$returnValue = (bool) false;
if ($clazz->isSubClassOf($this->getRootClass()) && ! $clazz->equals($this->getRootClass())) {
$returnValue = true;
$instances = $clazz->getInstances();
foreach ($instances as $instance) {
$this->deleteResource($instance);
}
$subclasses = $clazz->getSubClasses(false);
foreach ($subclasses as $subclass) {
$returnValue = $returnValue && $this->deleteClass($subclass);
}
foreach ($clazz->getProperties() as $classProperty) {
$returnValue = $returnValue && $this->deleteClassProperty($classProperty);
}
$returnValue = $returnValue && $clazz->delete();
} else {
\common_Logger::w('Tried to delete class ' . $clazz->getUri() . ' as if it were a subclass of ' . $this->getRootClass()->getUri());
}
return (bool) $returnValue;
} | [
"public",
"function",
"deleteClass",
"(",
"\\",
"core_kernel_classes_Class",
"$",
"clazz",
")",
"{",
"$",
"returnValue",
"=",
"(",
"bool",
")",
"false",
";",
"if",
"(",
"$",
"clazz",
"->",
"isSubClassOf",
"(",
"$",
"this",
"->",
"getRootClass",
"(",
")",
... | Delete a subclass
@access public
@param \core_kernel_classes_Class $clazz
@return boolean
@throws \common_exception_Error | [
"Delete",
"a",
"subclass"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/ClassServiceTrait.php#L59-L84 |
oat-sa/tao-core | models/classes/ClassServiceTrait.php | ClassServiceTrait.deleteClassProperty | public function deleteClassProperty(\core_kernel_classes_Property $property)
{
$indexes = $property->getPropertyValues(new \core_kernel_classes_Property(OntologyIndex::PROPERTY_INDEX));
//delete property and the existing values of this property
if ($returnValue = $property->delete(true)) {
//delete index linked to the property
foreach ($indexes as $indexUri) {
$index = new \core_kernel_classes_Resource($indexUri);
$returnValue = $this->deletePropertyIndex($index);
}
}
return $returnValue;
} | php | public function deleteClassProperty(\core_kernel_classes_Property $property)
{
$indexes = $property->getPropertyValues(new \core_kernel_classes_Property(OntologyIndex::PROPERTY_INDEX));
//delete property and the existing values of this property
if ($returnValue = $property->delete(true)) {
//delete index linked to the property
foreach ($indexes as $indexUri) {
$index = new \core_kernel_classes_Resource($indexUri);
$returnValue = $this->deletePropertyIndex($index);
}
}
return $returnValue;
} | [
"public",
"function",
"deleteClassProperty",
"(",
"\\",
"core_kernel_classes_Property",
"$",
"property",
")",
"{",
"$",
"indexes",
"=",
"$",
"property",
"->",
"getPropertyValues",
"(",
"new",
"\\",
"core_kernel_classes_Property",
"(",
"OntologyIndex",
"::",
"PROPERTY_... | remove a class property
@param \core_kernel_classes_Property $property
@return bool
@throws \common_exception_Error | [
"remove",
"a",
"class",
"property"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/ClassServiceTrait.php#L93-L107 |
oat-sa/tao-core | helpers/translation/class.PHPFileWriter.php | tao_helpers_translation_PHPFileWriter.write | public function write()
{
$tf = $this->getTranslationFile();
$buffer = "<?php\n";
foreach ($tf->getTranslationUnits() as $tu){
// Prevent empty messages.
if ($tu->getSource() != '' && $tu->getTarget() != ''){
$escapes = array("\\", '$', '"', "\n", "\t", "\v", "\r", "\f");
$replace = array("\\\\", '\\$', '\\"', "\\n", "\\t", "\\v", "\\r", "\\f");
$source = str_replace($escapes, $replace, $tu->getSource());
$target = str_replace($escapes, $replace, $tu->getTarget());
$buffer .= '$GLOBALS[\'__l10n\']["' . $source . '"]="' . $target . '";' . "\n";
}
}
$buffer .= "\n?>";
file_put_contents($this->getFilePath(), $buffer);
} | php | public function write()
{
$tf = $this->getTranslationFile();
$buffer = "<?php\n";
foreach ($tf->getTranslationUnits() as $tu){
// Prevent empty messages.
if ($tu->getSource() != '' && $tu->getTarget() != ''){
$escapes = array("\\", '$', '"', "\n", "\t", "\v", "\r", "\f");
$replace = array("\\\\", '\\$', '\\"', "\\n", "\\t", "\\v", "\\r", "\\f");
$source = str_replace($escapes, $replace, $tu->getSource());
$target = str_replace($escapes, $replace, $tu->getTarget());
$buffer .= '$GLOBALS[\'__l10n\']["' . $source . '"]="' . $target . '";' . "\n";
}
}
$buffer .= "\n?>";
file_put_contents($this->getFilePath(), $buffer);
} | [
"public",
"function",
"write",
"(",
")",
"{",
"$",
"tf",
"=",
"$",
"this",
"->",
"getTranslationFile",
"(",
")",
";",
"$",
"buffer",
"=",
"\"<?php\\n\"",
";",
"foreach",
"(",
"$",
"tf",
"->",
"getTranslationUnits",
"(",
")",
"as",
"$",
"tu",
")",
"{"... | Writes the TranslationFile as a PHP compiled file.
@access public
@author Jerome Bogaerts, <jerome.bogaerts@tudor.lu>
@return mixed | [
"Writes",
"the",
"TranslationFile",
"as",
"a",
"PHP",
"compiled",
"file",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/translation/class.PHPFileWriter.php#L47-L66 |
oat-sa/tao-core | helpers/translation/class.RDFFileWriter.php | tao_helpers_translation_RDFFileWriter.write | public function write()
{
$targetPath = $this->getFilePath();
$file = $this->getTranslationFile();
$semanticNamespaces = array('rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
'rdfs' => 'http://www.w3.org/2000/01/rdf-schema#');
$xmlNS = 'http://www.w3.org/XML/1998/namespace';
$xmlnsNS = 'http://www.w3.org/2000/xmlns/';
try {
$targetFile = new DOMDocument('1.0', 'UTF-8');
$targetFile->formatOutput = true;
// Create the RDF root node and annotate if possible.
$rdfNode = $targetFile->createElementNS($semanticNamespaces['rdf'], 'rdf:RDF');
$targetFile->appendChild($rdfNode);
$rootAnnotations = $this->getTranslationFile()->getAnnotations();
if (count($rootAnnotations)){
$annotationsString = tao_helpers_translation_RDFUtils::serializeAnnotations($rootAnnotations);
$annotationsNode = $targetFile->createComment("\n " . $annotationsString . "\n");
$targetFile->insertBefore($annotationsNode, $rdfNode);
}
$rdfNode->setAttributeNS($xmlNS, 'xml:base', $file->getBase());
$rdfNode->setAttributeNS($xmlnsNS, 'xmlns:rdfs', $semanticNamespaces['rdfs']);
$xPath = new DOMXPath($targetFile);
$xPath->registerNamespace($semanticNamespaces['rdf'], 'rdf');
$xPath->registerNamespace($semanticNamespaces['rdfs'], 'rdfs');
foreach ($file->getTranslationUnits() as $tu){
// Look if the predicate is a semantic namespace.
$uri = explode('#', $tu->getPredicate());
if (count($uri) == 2) {
$namespace = $uri[0] . '#';
$qName = $uri[1];
if (($searchedNS = array_search($namespace, $semanticNamespaces)) !== false) {
$tuNode = $targetFile->createElement("${searchedNS}:${qName}");
$tuNode->setAttributeNS($xmlNS, 'xml:lang', $tu->getTargetLanguage());
$cdataValue = (($tu->getTarget() == '') ? $tu->getSource() : $tu->getTarget());
$tuNodeValue = $targetFile->createCDATASection($cdataValue);
$tuNode->appendChild($tuNodeValue);
// Check if an rdf:Description exists for
// the target of the TranslationUnit.
$subject = $tu->getSubject();
$result = $xPath->query("//rdf:Description[@rdf:about='${subject}']");
if ($result->length > 0){
// Append to the existing rdf:Description.
$existingDescription = $result->item(0);
$existingDescription->appendChild($tuNode);
}
else {
// Append to a new rdf:Description node.
$descriptionNode = $targetFile->createElementNS($semanticNamespaces['rdf'], 'rdf:Description');
$descriptionNode->setAttributeNS($semanticNamespaces['rdf'], 'rdf:about', $subject);
$descriptionNode->appendChild($tuNode);
$rdfNode->appendChild($descriptionNode);
}
// Finally add annotations.
$annotations = $tu->getAnnotations();
if (count($annotations) > 0){
$annotationString = "\n " . tao_helpers_translation_RDFUtils::serializeAnnotations($annotations) . "\n ";
$annotationNode = $targetFile->createComment($annotationString);
$tuNode->parentNode->insertBefore($annotationNode, $tuNode);
}
}
}
}
$targetFile->save($targetPath);
}
catch (DOMException $e) {
throw new tao_helpers_translation_TranslationException("An error occured while writing the RDF File at '${targetPath}'.");
}
} | php | public function write()
{
$targetPath = $this->getFilePath();
$file = $this->getTranslationFile();
$semanticNamespaces = array('rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
'rdfs' => 'http://www.w3.org/2000/01/rdf-schema#');
$xmlNS = 'http://www.w3.org/XML/1998/namespace';
$xmlnsNS = 'http://www.w3.org/2000/xmlns/';
try {
$targetFile = new DOMDocument('1.0', 'UTF-8');
$targetFile->formatOutput = true;
// Create the RDF root node and annotate if possible.
$rdfNode = $targetFile->createElementNS($semanticNamespaces['rdf'], 'rdf:RDF');
$targetFile->appendChild($rdfNode);
$rootAnnotations = $this->getTranslationFile()->getAnnotations();
if (count($rootAnnotations)){
$annotationsString = tao_helpers_translation_RDFUtils::serializeAnnotations($rootAnnotations);
$annotationsNode = $targetFile->createComment("\n " . $annotationsString . "\n");
$targetFile->insertBefore($annotationsNode, $rdfNode);
}
$rdfNode->setAttributeNS($xmlNS, 'xml:base', $file->getBase());
$rdfNode->setAttributeNS($xmlnsNS, 'xmlns:rdfs', $semanticNamespaces['rdfs']);
$xPath = new DOMXPath($targetFile);
$xPath->registerNamespace($semanticNamespaces['rdf'], 'rdf');
$xPath->registerNamespace($semanticNamespaces['rdfs'], 'rdfs');
foreach ($file->getTranslationUnits() as $tu){
// Look if the predicate is a semantic namespace.
$uri = explode('#', $tu->getPredicate());
if (count($uri) == 2) {
$namespace = $uri[0] . '#';
$qName = $uri[1];
if (($searchedNS = array_search($namespace, $semanticNamespaces)) !== false) {
$tuNode = $targetFile->createElement("${searchedNS}:${qName}");
$tuNode->setAttributeNS($xmlNS, 'xml:lang', $tu->getTargetLanguage());
$cdataValue = (($tu->getTarget() == '') ? $tu->getSource() : $tu->getTarget());
$tuNodeValue = $targetFile->createCDATASection($cdataValue);
$tuNode->appendChild($tuNodeValue);
// Check if an rdf:Description exists for
// the target of the TranslationUnit.
$subject = $tu->getSubject();
$result = $xPath->query("//rdf:Description[@rdf:about='${subject}']");
if ($result->length > 0){
// Append to the existing rdf:Description.
$existingDescription = $result->item(0);
$existingDescription->appendChild($tuNode);
}
else {
// Append to a new rdf:Description node.
$descriptionNode = $targetFile->createElementNS($semanticNamespaces['rdf'], 'rdf:Description');
$descriptionNode->setAttributeNS($semanticNamespaces['rdf'], 'rdf:about', $subject);
$descriptionNode->appendChild($tuNode);
$rdfNode->appendChild($descriptionNode);
}
// Finally add annotations.
$annotations = $tu->getAnnotations();
if (count($annotations) > 0){
$annotationString = "\n " . tao_helpers_translation_RDFUtils::serializeAnnotations($annotations) . "\n ";
$annotationNode = $targetFile->createComment($annotationString);
$tuNode->parentNode->insertBefore($annotationNode, $tuNode);
}
}
}
}
$targetFile->save($targetPath);
}
catch (DOMException $e) {
throw new tao_helpers_translation_TranslationException("An error occured while writing the RDF File at '${targetPath}'.");
}
} | [
"public",
"function",
"write",
"(",
")",
"{",
"$",
"targetPath",
"=",
"$",
"this",
"->",
"getFilePath",
"(",
")",
";",
"$",
"file",
"=",
"$",
"this",
"->",
"getTranslationFile",
"(",
")",
";",
"$",
"semanticNamespaces",
"=",
"array",
"(",
"'rdf'",
"=>"... | Writes the RDF file on the file system.
@access public
@author Jerome Bogaerts, <jerome.bogaerts@tudor.lu>
@return mixed | [
"Writes",
"the",
"RDF",
"file",
"on",
"the",
"file",
"system",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/translation/class.RDFFileWriter.php#L47-L128 |
oat-sa/tao-core | models/classes/datatable/implementation/DatatableRequest.php | DatatableRequest.getRows | public function getRows()
{
$rows = isset($this->requestParams[self::PARAM_ROWS])
? $this->requestParams[self::PARAM_ROWS]
: self::DEFAULT_ROWS;
return (integer)$rows;
} | php | public function getRows()
{
$rows = isset($this->requestParams[self::PARAM_ROWS])
? $this->requestParams[self::PARAM_ROWS]
: self::DEFAULT_ROWS;
return (integer)$rows;
} | [
"public",
"function",
"getRows",
"(",
")",
"{",
"$",
"rows",
"=",
"isset",
"(",
"$",
"this",
"->",
"requestParams",
"[",
"self",
"::",
"PARAM_ROWS",
"]",
")",
"?",
"$",
"this",
"->",
"requestParams",
"[",
"self",
"::",
"PARAM_ROWS",
"]",
":",
"self",
... | Get amount of records per page
@return integer | [
"Get",
"amount",
"of",
"records",
"per",
"page"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/datatable/implementation/DatatableRequest.php#L64-L71 |
oat-sa/tao-core | models/classes/datatable/implementation/DatatableRequest.php | DatatableRequest.getPage | public function getPage()
{
$page = isset($this->requestParams[self::PARAM_PAGE]) ? $this->requestParams[self::PARAM_PAGE] : self::DEFAULT_PAGE;
return (integer)$page;
} | php | public function getPage()
{
$page = isset($this->requestParams[self::PARAM_PAGE]) ? $this->requestParams[self::PARAM_PAGE] : self::DEFAULT_PAGE;
return (integer)$page;
} | [
"public",
"function",
"getPage",
"(",
")",
"{",
"$",
"page",
"=",
"isset",
"(",
"$",
"this",
"->",
"requestParams",
"[",
"self",
"::",
"PARAM_PAGE",
"]",
")",
"?",
"$",
"this",
"->",
"requestParams",
"[",
"self",
"::",
"PARAM_PAGE",
"]",
":",
"self",
... | Get page number
@return integer | [
"Get",
"page",
"number"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/datatable/implementation/DatatableRequest.php#L77-L81 |
oat-sa/tao-core | models/classes/datatable/implementation/DatatableRequest.php | DatatableRequest.getSortBy | public function getSortBy()
{
$sortBy = isset($this->requestParams[self::PARAM_SORT_BY]) ?
$this->requestParams[self::PARAM_SORT_BY] : self::DEFAULT_SORT_BY;
return $sortBy;
} | php | public function getSortBy()
{
$sortBy = isset($this->requestParams[self::PARAM_SORT_BY]) ?
$this->requestParams[self::PARAM_SORT_BY] : self::DEFAULT_SORT_BY;
return $sortBy;
} | [
"public",
"function",
"getSortBy",
"(",
")",
"{",
"$",
"sortBy",
"=",
"isset",
"(",
"$",
"this",
"->",
"requestParams",
"[",
"self",
"::",
"PARAM_SORT_BY",
"]",
")",
"?",
"$",
"this",
"->",
"requestParams",
"[",
"self",
"::",
"PARAM_SORT_BY",
"]",
":",
... | Get sorting column name
@return string | [
"Get",
"sorting",
"column",
"name"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/datatable/implementation/DatatableRequest.php#L87-L92 |
oat-sa/tao-core | models/classes/datatable/implementation/DatatableRequest.php | DatatableRequest.getSortOrder | public function getSortOrder()
{
$sortOrder = isset($this->requestParams[self::PARAM_SORT_ORDER]) ?
$this->requestParams[self::PARAM_SORT_ORDER] : self::DEFAULT_SORT_ORDER;
$sortOrder = mb_strtolower($sortOrder);
if (!in_array($sortOrder, ['asc', 'desc'])) {
$sortOrder = self::DEFAULT_SORT_ORDER;
}
return $sortOrder;
} | php | public function getSortOrder()
{
$sortOrder = isset($this->requestParams[self::PARAM_SORT_ORDER]) ?
$this->requestParams[self::PARAM_SORT_ORDER] : self::DEFAULT_SORT_ORDER;
$sortOrder = mb_strtolower($sortOrder);
if (!in_array($sortOrder, ['asc', 'desc'])) {
$sortOrder = self::DEFAULT_SORT_ORDER;
}
return $sortOrder;
} | [
"public",
"function",
"getSortOrder",
"(",
")",
"{",
"$",
"sortOrder",
"=",
"isset",
"(",
"$",
"this",
"->",
"requestParams",
"[",
"self",
"::",
"PARAM_SORT_ORDER",
"]",
")",
"?",
"$",
"this",
"->",
"requestParams",
"[",
"self",
"::",
"PARAM_SORT_ORDER",
"... | Get sorting direction
@return string | [
"Get",
"sorting",
"direction"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/datatable/implementation/DatatableRequest.php#L98-L109 |
oat-sa/tao-core | models/classes/datatable/implementation/DatatableRequest.php | DatatableRequest.getSortType | public function getSortType()
{
$sortType = isset($this->requestParams[self::PARAM_SORT_TYPE]) ?
$this->requestParams[self::PARAM_SORT_TYPE] : self::DEFAULT_SORT_TYPE;
$sortType= mb_strtolower($sortType);
if(!in_array($sortType, ['string', 'numeric'])) {
$sortType = self::DEFAULT_SORT_TYPE;
}
return $sortType;
} | php | public function getSortType()
{
$sortType = isset($this->requestParams[self::PARAM_SORT_TYPE]) ?
$this->requestParams[self::PARAM_SORT_TYPE] : self::DEFAULT_SORT_TYPE;
$sortType= mb_strtolower($sortType);
if(!in_array($sortType, ['string', 'numeric'])) {
$sortType = self::DEFAULT_SORT_TYPE;
}
return $sortType;
} | [
"public",
"function",
"getSortType",
"(",
")",
"{",
"$",
"sortType",
"=",
"isset",
"(",
"$",
"this",
"->",
"requestParams",
"[",
"self",
"::",
"PARAM_SORT_TYPE",
"]",
")",
"?",
"$",
"this",
"->",
"requestParams",
"[",
"self",
"::",
"PARAM_SORT_TYPE",
"]",
... | Get sorting type
@return string | [
"Get",
"sorting",
"type"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/datatable/implementation/DatatableRequest.php#L115-L126 |
oat-sa/tao-core | models/classes/datatable/implementation/DatatableRequest.php | DatatableRequest.getFilters | public function getFilters()
{
$filters = isset($this->requestParams[self::PARAM_FILTERS]) ?
$this->requestParams[self::PARAM_FILTERS] : self::DEFAULT_FILTERS;
return $filters;
} | php | public function getFilters()
{
$filters = isset($this->requestParams[self::PARAM_FILTERS]) ?
$this->requestParams[self::PARAM_FILTERS] : self::DEFAULT_FILTERS;
return $filters;
} | [
"public",
"function",
"getFilters",
"(",
")",
"{",
"$",
"filters",
"=",
"isset",
"(",
"$",
"this",
"->",
"requestParams",
"[",
"self",
"::",
"PARAM_FILTERS",
"]",
")",
"?",
"$",
"this",
"->",
"requestParams",
"[",
"self",
"::",
"PARAM_FILTERS",
"]",
":",... | Get filters
@return array | [
"Get",
"filters"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/datatable/implementation/DatatableRequest.php#L132-L138 |
oat-sa/tao-core | helpers/grid/class.Column.php | tao_helpers_grid_Column.setType | public function setType($type)
{
$returnValue = (bool) false;
$this->type = $type;
$returnValue = true;
return (bool) $returnValue;
} | php | public function setType($type)
{
$returnValue = (bool) false;
$this->type = $type;
$returnValue = true;
return (bool) $returnValue;
} | [
"public",
"function",
"setType",
"(",
"$",
"type",
")",
"{",
"$",
"returnValue",
"=",
"(",
"bool",
")",
"false",
";",
"$",
"this",
"->",
"type",
"=",
"$",
"type",
";",
"$",
"returnValue",
"=",
"true",
";",
"return",
"(",
"bool",
")",
"$",
"returnVa... | Short description of method setType
@access public
@author Somsack Sipasseuth, <somsack.sipasseuth@tudor.lu>
@param string type
@return boolean | [
"Short",
"description",
"of",
"method",
"setType"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/grid/class.Column.php#L114-L124 |
oat-sa/tao-core | helpers/grid/class.Column.php | tao_helpers_grid_Column.setTitle | public function setTitle($title)
{
$returnValue = (bool) false;
$this->title = $title;
$returnValue = true;
return (bool) $returnValue;
} | php | public function setTitle($title)
{
$returnValue = (bool) false;
$this->title = $title;
$returnValue = true;
return (bool) $returnValue;
} | [
"public",
"function",
"setTitle",
"(",
"$",
"title",
")",
"{",
"$",
"returnValue",
"=",
"(",
"bool",
")",
"false",
";",
"$",
"this",
"->",
"title",
"=",
"$",
"title",
";",
"$",
"returnValue",
"=",
"true",
";",
"return",
"(",
"bool",
")",
"$",
"retu... | Short description of method setTitle
@access public
@author Somsack Sipasseuth, <somsack.sipasseuth@tudor.lu>
@param string title
@return boolean | [
"Short",
"description",
"of",
"method",
"setTitle"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/grid/class.Column.php#L152-L162 |
oat-sa/tao-core | helpers/grid/class.Column.php | tao_helpers_grid_Column.setAdapter | public function setAdapter( tao_helpers_grid_Cell_Adapter $adapter)
{
$returnValue = (bool) false;
if(!is_null($adapter)){
$this->adapters[] = $adapter;
$returnValue = true;
}
return (bool) $returnValue;
} | php | public function setAdapter( tao_helpers_grid_Cell_Adapter $adapter)
{
$returnValue = (bool) false;
if(!is_null($adapter)){
$this->adapters[] = $adapter;
$returnValue = true;
}
return (bool) $returnValue;
} | [
"public",
"function",
"setAdapter",
"(",
"tao_helpers_grid_Cell_Adapter",
"$",
"adapter",
")",
"{",
"$",
"returnValue",
"=",
"(",
"bool",
")",
"false",
";",
"if",
"(",
"!",
"is_null",
"(",
"$",
"adapter",
")",
")",
"{",
"$",
"this",
"->",
"adapters",
"["... | Short description of method setAdapter
@access public
@author Somsack Sipasseuth, <somsack.sipasseuth@tudor.lu>
@param Adapter adapter
@return boolean | [
"Short",
"description",
"of",
"method",
"setAdapter"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/grid/class.Column.php#L208-L220 |
oat-sa/tao-core | helpers/grid/class.Column.php | tao_helpers_grid_Column.hasAdapter | public function hasAdapter($type = '')
{
$returnValue = (bool) false;
$adapterClass = empty($type)?'tao_helpers_grid_Cell_Adapter':$type;
foreach($this->adapters as $adapter){
if($adapter instanceof $adapterClass){
$returnValue = true;
break;
}
}
return (bool) $returnValue;
} | php | public function hasAdapter($type = '')
{
$returnValue = (bool) false;
$adapterClass = empty($type)?'tao_helpers_grid_Cell_Adapter':$type;
foreach($this->adapters as $adapter){
if($adapter instanceof $adapterClass){
$returnValue = true;
break;
}
}
return (bool) $returnValue;
} | [
"public",
"function",
"hasAdapter",
"(",
"$",
"type",
"=",
"''",
")",
"{",
"$",
"returnValue",
"=",
"(",
"bool",
")",
"false",
";",
"$",
"adapterClass",
"=",
"empty",
"(",
"$",
"type",
")",
"?",
"'tao_helpers_grid_Cell_Adapter'",
":",
"$",
"type",
";",
... | Short description of method hasAdapter
@access public
@author Somsack Sipasseuth, <somsack.sipasseuth@tudor.lu>
@param string type (to check if the adaptor is of a certain type)
@return boolean | [
"Short",
"description",
"of",
"method",
"hasAdapter"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/grid/class.Column.php#L230-L246 |
oat-sa/tao-core | helpers/grid/class.Column.php | tao_helpers_grid_Column.getAdaptersData | public function getAdaptersData($rowId, $cellValue = null, $evaluateData = true)
{
$returnValue = null;
if($this->hasAdapter()){
foreach($this->adapters as $adapter){
if($adapter instanceof tao_helpers_grid_Cell_Adapter){
$cellValue = $adapter->getValue($rowId, $this->id, $cellValue);
}
}
$returnValue = $cellValue;
}
if($evaluateData){
//allow returning to type "string" or "Grid" only
if ($returnValue instanceof tao_helpers_grid_Grid) {
$returnValue = $returnValue->toArray();
} else if ($returnValue instanceof tao_helpers_grid_GridContainer) {
$returnValue = $returnValue->toArray();
} else if(is_array($returnValue)){
//ok; authorize array type
}else{
$returnValue = (string) $returnValue;
}
}
return $returnValue;
} | php | public function getAdaptersData($rowId, $cellValue = null, $evaluateData = true)
{
$returnValue = null;
if($this->hasAdapter()){
foreach($this->adapters as $adapter){
if($adapter instanceof tao_helpers_grid_Cell_Adapter){
$cellValue = $adapter->getValue($rowId, $this->id, $cellValue);
}
}
$returnValue = $cellValue;
}
if($evaluateData){
//allow returning to type "string" or "Grid" only
if ($returnValue instanceof tao_helpers_grid_Grid) {
$returnValue = $returnValue->toArray();
} else if ($returnValue instanceof tao_helpers_grid_GridContainer) {
$returnValue = $returnValue->toArray();
} else if(is_array($returnValue)){
//ok; authorize array type
}else{
$returnValue = (string) $returnValue;
}
}
return $returnValue;
} | [
"public",
"function",
"getAdaptersData",
"(",
"$",
"rowId",
",",
"$",
"cellValue",
"=",
"null",
",",
"$",
"evaluateData",
"=",
"true",
")",
"{",
"$",
"returnValue",
"=",
"null",
";",
"if",
"(",
"$",
"this",
"->",
"hasAdapter",
"(",
")",
")",
"{",
"fo... | Short description of method getAdaptersData
@access public
@author Somsack Sipasseuth, <somsack.sipasseuth@tudor.lu>
@param string rowId
@param string cellValue (tao_helpers_grid_Grid, tao_helpers_grid_GridContainer or string)
@param bool evaluateData
@return mixed | [
"Short",
"description",
"of",
"method",
"getAdaptersData"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/grid/class.Column.php#L258-L289 |
oat-sa/tao-core | helpers/grid/class.Column.php | tao_helpers_grid_Column.getAdapter | public function getAdapter($type)
{
$returnValue = null;
foreach($this->adapters as $adapter){
if($adapter instanceof $type){
$returnValue = $adapter;
break;
}
}
return $returnValue;
} | php | public function getAdapter($type)
{
$returnValue = null;
foreach($this->adapters as $adapter){
if($adapter instanceof $type){
$returnValue = $adapter;
break;
}
}
return $returnValue;
} | [
"public",
"function",
"getAdapter",
"(",
"$",
"type",
")",
"{",
"$",
"returnValue",
"=",
"null",
";",
"foreach",
"(",
"$",
"this",
"->",
"adapters",
"as",
"$",
"adapter",
")",
"{",
"if",
"(",
"$",
"adapter",
"instanceof",
"$",
"type",
")",
"{",
"$",
... | Short description of method getAdapter
@access public
@author Somsack Sipasseuth, <somsack.sipasseuth@tudor.lu>
@param type
@return tao_helpers_transfert_Adapter | [
"Short",
"description",
"of",
"method",
"getAdapter"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/grid/class.Column.php#L299-L313 |
oat-sa/tao-core | models/classes/messaging/transportStrategy/MailAdapter.php | MailAdapter.getMailer | protected function getMailer()
{
$mailer = new \PHPMailer();
$SMTPConfig = $this->getOption(self::CONFIG_SMTP_CONFIG);
$mailer->IsSMTP();
$mailer->SMTPKeepAlive = true;
$mailer->Debugoutput = 'error_log';
$mailer->Host = $SMTPConfig['SMTP_HOST'];
$mailer->Port = $SMTPConfig['SMTP_PORT'];
$mailer->Username = $SMTPConfig['SMTP_USER'];
$mailer->Password = $SMTPConfig['SMTP_PASS'];
if (isset($SMTPConfig['DEBUG_MODE'])) {
$mailer->SMTPDebug = $SMTPConfig['DEBUG_MODE'];
}
if (isset($SMTPConfig['Mailer'])) {
$mailer->Mailer = $SMTPConfig['Mailer'];
}
if (isset($SMTPConfig['SMTP_AUTH'])) {
$mailer->SMTPAuth = $SMTPConfig['SMTP_AUTH'];
}
if (isset($SMTPConfig['SMTP_SECURE'])) {
$mailer->SMTPSecure = $SMTPConfig['SMTP_SECURE'];
}
return $mailer;
} | php | protected function getMailer()
{
$mailer = new \PHPMailer();
$SMTPConfig = $this->getOption(self::CONFIG_SMTP_CONFIG);
$mailer->IsSMTP();
$mailer->SMTPKeepAlive = true;
$mailer->Debugoutput = 'error_log';
$mailer->Host = $SMTPConfig['SMTP_HOST'];
$mailer->Port = $SMTPConfig['SMTP_PORT'];
$mailer->Username = $SMTPConfig['SMTP_USER'];
$mailer->Password = $SMTPConfig['SMTP_PASS'];
if (isset($SMTPConfig['DEBUG_MODE'])) {
$mailer->SMTPDebug = $SMTPConfig['DEBUG_MODE'];
}
if (isset($SMTPConfig['Mailer'])) {
$mailer->Mailer = $SMTPConfig['Mailer'];
}
if (isset($SMTPConfig['SMTP_AUTH'])) {
$mailer->SMTPAuth = $SMTPConfig['SMTP_AUTH'];
}
if (isset($SMTPConfig['SMTP_SECURE'])) {
$mailer->SMTPSecure = $SMTPConfig['SMTP_SECURE'];
}
return $mailer;
} | [
"protected",
"function",
"getMailer",
"(",
")",
"{",
"$",
"mailer",
"=",
"new",
"\\",
"PHPMailer",
"(",
")",
";",
"$",
"SMTPConfig",
"=",
"$",
"this",
"->",
"getOption",
"(",
"self",
"::",
"CONFIG_SMTP_CONFIG",
")",
";",
"$",
"mailer",
"->",
"IsSMTP",
... | Initialize PHPMailer
@access public
@author Bertrand Chevrier, <bertrand.chevrier@tudor.lu>
@return \PHPMailer | [
"Initialize",
"PHPMailer"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/messaging/transportStrategy/MailAdapter.php#L53-L82 |
oat-sa/tao-core | models/classes/messaging/transportStrategy/MailAdapter.php | MailAdapter.send | public function send(Message $message)
{
$mailer = $this->getMailer();
$mailer->SetFrom($this->getFrom($message));
$mailer->AddReplyTo($this->getFrom($message));
$mailer->Subject = $message->getTitle();
$mailer->AltBody = strip_tags(preg_replace("/<br.*>/i", "\n", $message->getBody()));
$mailer->MsgHTML($message->getBody());
$mailer->AddAddress($this->getUserMail($message->getTo()));
$result = false;
try {
if ($mailer->Send()) {
$message->setStatus(\oat\tao\model\messaging\Message::STATUS_SENT);
$result = true;
}
if ($mailer->IsError()) {
$message->setStatus(\oat\tao\model\messaging\Message::STATUS_ERROR);
}
} catch (phpmailerException $pe) {
\common_Logger::e($pe->getMessage());
}
$mailer->ClearReplyTos();
$mailer->ClearAllRecipients();
$mailer->SmtpClose();
return $result;
} | php | public function send(Message $message)
{
$mailer = $this->getMailer();
$mailer->SetFrom($this->getFrom($message));
$mailer->AddReplyTo($this->getFrom($message));
$mailer->Subject = $message->getTitle();
$mailer->AltBody = strip_tags(preg_replace("/<br.*>/i", "\n", $message->getBody()));
$mailer->MsgHTML($message->getBody());
$mailer->AddAddress($this->getUserMail($message->getTo()));
$result = false;
try {
if ($mailer->Send()) {
$message->setStatus(\oat\tao\model\messaging\Message::STATUS_SENT);
$result = true;
}
if ($mailer->IsError()) {
$message->setStatus(\oat\tao\model\messaging\Message::STATUS_ERROR);
}
} catch (phpmailerException $pe) {
\common_Logger::e($pe->getMessage());
}
$mailer->ClearReplyTos();
$mailer->ClearAllRecipients();
$mailer->SmtpClose();
return $result;
} | [
"public",
"function",
"send",
"(",
"Message",
"$",
"message",
")",
"{",
"$",
"mailer",
"=",
"$",
"this",
"->",
"getMailer",
"(",
")",
";",
"$",
"mailer",
"->",
"SetFrom",
"(",
"$",
"this",
"->",
"getFrom",
"(",
"$",
"message",
")",
")",
";",
"$",
... | Sent email message
@access public
@author Bertrand Chevrier, <bertrand.chevrier@tudor.lu>
@param Message $message
@return boolean whether message was sent | [
"Sent",
"email",
"message"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/messaging/transportStrategy/MailAdapter.php#L92-L119 |
oat-sa/tao-core | models/classes/messaging/transportStrategy/MailAdapter.php | MailAdapter.getUserMail | public function getUserMail(User $user)
{
$userMail = current($user->getPropertyValues(GenerisRdf::PROPERTY_USER_MAIL));
if (!$userMail || !filter_var($userMail, FILTER_VALIDATE_EMAIL)) {
throw new Exception('User email is not valid.');
}
return $userMail;
} | php | public function getUserMail(User $user)
{
$userMail = current($user->getPropertyValues(GenerisRdf::PROPERTY_USER_MAIL));
if (!$userMail || !filter_var($userMail, FILTER_VALIDATE_EMAIL)) {
throw new Exception('User email is not valid.');
}
return $userMail;
} | [
"public",
"function",
"getUserMail",
"(",
"User",
"$",
"user",
")",
"{",
"$",
"userMail",
"=",
"current",
"(",
"$",
"user",
"->",
"getPropertyValues",
"(",
"GenerisRdf",
"::",
"PROPERTY_USER_MAIL",
")",
")",
";",
"if",
"(",
"!",
"$",
"userMail",
"||",
"!... | Get user email address.
@param User $user
@return string
@throws Exception if email address is not valid | [
"Get",
"user",
"email",
"address",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/messaging/transportStrategy/MailAdapter.php#L127-L136 |
oat-sa/tao-core | models/classes/messaging/transportStrategy/MailAdapter.php | MailAdapter.getFrom | public function getFrom(Message $message = null)
{
$from = $message === null ? null : $message->getFrom();
if (!$from) {
$from = $this->getOption(self::CONFIG_DEFAULT_SENDER);
}
return $from;
} | php | public function getFrom(Message $message = null)
{
$from = $message === null ? null : $message->getFrom();
if (!$from) {
$from = $this->getOption(self::CONFIG_DEFAULT_SENDER);
}
return $from;
} | [
"public",
"function",
"getFrom",
"(",
"Message",
"$",
"message",
"=",
"null",
")",
"{",
"$",
"from",
"=",
"$",
"message",
"===",
"null",
"?",
"null",
":",
"$",
"message",
"->",
"getFrom",
"(",
")",
";",
"if",
"(",
"!",
"$",
"from",
")",
"{",
"$",... | Get a "From" address. If it was not specified for message then value will be retrieved from config.
@param Message $message (optional)
@return string | [
"Get",
"a",
"From",
"address",
".",
"If",
"it",
"was",
"not",
"specified",
"for",
"message",
"then",
"value",
"will",
"be",
"retrieved",
"from",
"config",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/messaging/transportStrategy/MailAdapter.php#L143-L150 |
oat-sa/tao-core | models/classes/maintenance/MaintenanceStorage.php | MaintenanceStorage.setPlatformState | public function setPlatformState(MaintenanceState $state)
{
if ($previous = $this->getDriver()->get(self::PREFIX . self::LAST_MODE)) {
$currentState = new MaintenanceState(json_decode($previous, true));
$currentState->setEndTime($state->getStartTime());
$this->getDriver()->set(self::PREFIX . $currentState->getId(), json_encode($currentState->toArray()));
$state->setId($currentState->getId() + 1);
}
$this->getDriver()->set(self::PREFIX . self::LAST_MODE, json_encode($state->toArray()));
} | php | public function setPlatformState(MaintenanceState $state)
{
if ($previous = $this->getDriver()->get(self::PREFIX . self::LAST_MODE)) {
$currentState = new MaintenanceState(json_decode($previous, true));
$currentState->setEndTime($state->getStartTime());
$this->getDriver()->set(self::PREFIX . $currentState->getId(), json_encode($currentState->toArray()));
$state->setId($currentState->getId() + 1);
}
$this->getDriver()->set(self::PREFIX . self::LAST_MODE, json_encode($state->toArray()));
} | [
"public",
"function",
"setPlatformState",
"(",
"MaintenanceState",
"$",
"state",
")",
"{",
"if",
"(",
"$",
"previous",
"=",
"$",
"this",
"->",
"getDriver",
"(",
")",
"->",
"get",
"(",
"self",
"::",
"PREFIX",
".",
"self",
"::",
"LAST_MODE",
")",
")",
"{... | Persist the maintenance state
If old maintenance exists, set key with old state id
Persist new maintenance state with key 'last'
@param MaintenanceState $state | [
"Persist",
"the",
"maintenance",
"state"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/maintenance/MaintenanceStorage.php#L54-L66 |
oat-sa/tao-core | models/classes/maintenance/MaintenanceStorage.php | MaintenanceStorage.getHistory | public function getHistory()
{
$history = array(
1 => new MaintenanceState(json_decode($this->getDriver()->get(self::PREFIX . self::LAST_MODE), true))
);
$i = 2;
while ($data = json_decode($this->getDriver()->get(self::PREFIX . $i), true)) {
$history[$i] = new MaintenanceState($data);
$i++;
}
return $history;
} | php | public function getHistory()
{
$history = array(
1 => new MaintenanceState(json_decode($this->getDriver()->get(self::PREFIX . self::LAST_MODE), true))
);
$i = 2;
while ($data = json_decode($this->getDriver()->get(self::PREFIX . $i), true)) {
$history[$i] = new MaintenanceState($data);
$i++;
}
return $history;
} | [
"public",
"function",
"getHistory",
"(",
")",
"{",
"$",
"history",
"=",
"array",
"(",
"1",
"=>",
"new",
"MaintenanceState",
"(",
"json_decode",
"(",
"$",
"this",
"->",
"getDriver",
"(",
")",
"->",
"get",
"(",
"self",
"::",
"PREFIX",
".",
"self",
"::",
... | Get maintenance history as list of state
@todo Return an arrayIterator
@return array | [
"Get",
"maintenance",
"history",
"as",
"list",
"of",
"state"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/maintenance/MaintenanceStorage.php#L74-L86 |
oat-sa/tao-core | models/classes/maintenance/MaintenanceStorage.php | MaintenanceStorage.getCurrentPlatformState | public function getCurrentPlatformState()
{
$data = json_decode($this->getDriver()->get(self::PREFIX . self::LAST_MODE), true);
if (! $data) {
throw new \common_exception_NotFound();
}
return new MaintenanceState($data);
} | php | public function getCurrentPlatformState()
{
$data = json_decode($this->getDriver()->get(self::PREFIX . self::LAST_MODE), true);
if (! $data) {
throw new \common_exception_NotFound();
}
return new MaintenanceState($data);
} | [
"public",
"function",
"getCurrentPlatformState",
"(",
")",
"{",
"$",
"data",
"=",
"json_decode",
"(",
"$",
"this",
"->",
"getDriver",
"(",
")",
"->",
"get",
"(",
"self",
"::",
"PREFIX",
".",
"self",
"::",
"LAST_MODE",
")",
",",
"true",
")",
";",
"if",
... | Get the current state of the platform
@return MaintenanceState
@throws \common_exception_NotFound If no state is set | [
"Get",
"the",
"current",
"state",
"of",
"the",
"platform"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/maintenance/MaintenanceStorage.php#L94-L101 |
oat-sa/tao-core | helpers/form/validators/class.Integer.php | tao_helpers_form_validators_Integer.evaluate | public function evaluate($values)
{
$returnValue = (bool) false;
if ($values == intval($values)) {
$returnValue = parent::evaluate($values);
} else {
$returnValue = false;
$this->setMessage(__('The value of this field must be an integer'));
}
return (bool) $returnValue;
} | php | public function evaluate($values)
{
$returnValue = (bool) false;
if ($values == intval($values)) {
$returnValue = parent::evaluate($values);
} else {
$returnValue = false;
$this->setMessage(__('The value of this field must be an integer'));
}
return (bool) $returnValue;
} | [
"public",
"function",
"evaluate",
"(",
"$",
"values",
")",
"{",
"$",
"returnValue",
"=",
"(",
"bool",
")",
"false",
";",
"if",
"(",
"$",
"values",
"==",
"intval",
"(",
"$",
"values",
")",
")",
"{",
"$",
"returnValue",
"=",
"parent",
"::",
"evaluate",... | Short description of method evaluate
@access public
@author Jehan Bihin, <jehan.bihin@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.Integer.php#L48-L61 |
oat-sa/tao-core | install/services/class.CheckPHPConfigService.php | tao_install_services_CheckPHPConfigService.execute | public function execute(){
// contains an array of 'component', associated input 'data'
// and service 'class'.
$componentToData = array();
$content = json_decode($this->getData()->getContent(), true);
if (self::getRequestMethod() == 'get'){
// We extract the checks to perform from the manifests
// depending on the distribution.
$content['value'] = tao_install_utils_ChecksHelper::getRawChecks($content['extensions']);
}
// Deal with checks to be done.
$collection = new common_configuration_ComponentCollection();
foreach ($content['value'] as $config){
$class = new ReflectionClass('tao_install_services_' . $config['type'] . 'Service');
$buildMethod = $class->getMethod('buildComponent');
$args = new tao_install_services_Data(json_encode($config));
$component = $buildMethod->invoke(null, $args);
$collection->addComponent($component);
if (!empty($config['value']['silent']) && is_bool($config['value']['silent'])){
$collection->silent($component);
}
$componentToData[] = array('component' => $component,
'id' => $config['value']['id'],
'data' => $args,
'class' => $class);
}
// Deal with the dependencies.
foreach ($content['value'] as $config){
if (!empty($config['value']['dependsOn']) && is_array($config['value']['dependsOn'])){
foreach ($config['value']['dependsOn'] as $d){
// Find the component it depends on and tell the ComponentCollection.
$dependent = self::getComponentById($componentToData, $config['value']['id']);
$dependency = self::getComponentById($componentToData, $d);
if (!empty($dependent) && !empty($dependency)){
$collection->addDependency($dependent, $dependency);
}
}
}
}
// Deal with results to be sent to the client.
$resultValue = array();
$reports = $collection->check();
foreach($reports as $r){
$component = $r->getComponent();
// For the retrieved component, what was the associated data and class ?
$associatedData = null;
$class = null;
foreach ($componentToData as $ctd)
{
if ($component == $ctd['component']){
$associatedData = $ctd['data'];
$class = $ctd['class'];
}
}
$buildMethod = $class->getMethod('buildResult');
$serviceResult = $buildMethod->invoke(null, $associatedData, $r, $component);
$resultValue[] = $serviceResult->getContent();
}
// Sort by 'optional'.
usort($resultValue, array('tao_install_services_CheckPHPConfigService' , 'sortReports'));
$resultData = json_encode(array('type' => 'ReportCollection',
'value' => '{RETURN_VALUE}'));
$resultData = str_replace('"{RETURN_VALUE}"', '[' . implode(',', $resultValue) . ']', $resultData);
$this->setResult(new tao_install_services_Data($resultData));
} | php | public function execute(){
// contains an array of 'component', associated input 'data'
// and service 'class'.
$componentToData = array();
$content = json_decode($this->getData()->getContent(), true);
if (self::getRequestMethod() == 'get'){
// We extract the checks to perform from the manifests
// depending on the distribution.
$content['value'] = tao_install_utils_ChecksHelper::getRawChecks($content['extensions']);
}
// Deal with checks to be done.
$collection = new common_configuration_ComponentCollection();
foreach ($content['value'] as $config){
$class = new ReflectionClass('tao_install_services_' . $config['type'] . 'Service');
$buildMethod = $class->getMethod('buildComponent');
$args = new tao_install_services_Data(json_encode($config));
$component = $buildMethod->invoke(null, $args);
$collection->addComponent($component);
if (!empty($config['value']['silent']) && is_bool($config['value']['silent'])){
$collection->silent($component);
}
$componentToData[] = array('component' => $component,
'id' => $config['value']['id'],
'data' => $args,
'class' => $class);
}
// Deal with the dependencies.
foreach ($content['value'] as $config){
if (!empty($config['value']['dependsOn']) && is_array($config['value']['dependsOn'])){
foreach ($config['value']['dependsOn'] as $d){
// Find the component it depends on and tell the ComponentCollection.
$dependent = self::getComponentById($componentToData, $config['value']['id']);
$dependency = self::getComponentById($componentToData, $d);
if (!empty($dependent) && !empty($dependency)){
$collection->addDependency($dependent, $dependency);
}
}
}
}
// Deal with results to be sent to the client.
$resultValue = array();
$reports = $collection->check();
foreach($reports as $r){
$component = $r->getComponent();
// For the retrieved component, what was the associated data and class ?
$associatedData = null;
$class = null;
foreach ($componentToData as $ctd)
{
if ($component == $ctd['component']){
$associatedData = $ctd['data'];
$class = $ctd['class'];
}
}
$buildMethod = $class->getMethod('buildResult');
$serviceResult = $buildMethod->invoke(null, $associatedData, $r, $component);
$resultValue[] = $serviceResult->getContent();
}
// Sort by 'optional'.
usort($resultValue, array('tao_install_services_CheckPHPConfigService' , 'sortReports'));
$resultData = json_encode(array('type' => 'ReportCollection',
'value' => '{RETURN_VALUE}'));
$resultData = str_replace('"{RETURN_VALUE}"', '[' . implode(',', $resultValue) . ']', $resultData);
$this->setResult(new tao_install_services_Data($resultData));
} | [
"public",
"function",
"execute",
"(",
")",
"{",
"// contains an array of 'component', associated input 'data' \r",
"// and service 'class'.\r",
"$",
"componentToData",
"=",
"array",
"(",
")",
";",
"$",
"content",
"=",
"json_decode",
"(",
"$",
"this",
"->",
"getData",
... | Executes the main logic of the service.
@return tao_install_services_Data The result of the service execution. | [
"Executes",
"the",
"main",
"logic",
"of",
"the",
"service",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/install/services/class.CheckPHPConfigService.php#L50-L128 |
oat-sa/tao-core | install/services/class.CheckPHPConfigService.php | tao_install_services_CheckPHPConfigService.sortReports | private static function sortReports ($a, $b){
$a = json_decode($a, true);
$b = json_decode($b, true);
if ($a['value']['optional'] == $b['value']['optional']){
return 0;
}
else{
return ($a['value']['optional'] < $b['value']['optional']) ? -1 : 1;
}
} | php | private static function sortReports ($a, $b){
$a = json_decode($a, true);
$b = json_decode($b, true);
if ($a['value']['optional'] == $b['value']['optional']){
return 0;
}
else{
return ($a['value']['optional'] < $b['value']['optional']) ? -1 : 1;
}
} | [
"private",
"static",
"function",
"sortReports",
"(",
"$",
"a",
",",
"$",
"b",
")",
"{",
"$",
"a",
"=",
"json_decode",
"(",
"$",
"a",
",",
"true",
")",
";",
"$",
"b",
"=",
"json_decode",
"(",
"$",
"b",
",",
"true",
")",
";",
"if",
"(",
"$",
"a... | Report sorting function.
@param string $a JSON encoded report.
@param string $b JSON encoded report.
@return boolean Comparison result. | [
"Report",
"sorting",
"function",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/install/services/class.CheckPHPConfigService.php#L136-L146 |
oat-sa/tao-core | install/services/class.CheckPHPConfigService.php | tao_install_services_CheckPHPConfigService.getComponentById | public static function getComponentById(array $componentToData, $id){
foreach ($componentToData as $ctd){
if ($ctd['id'] == $id){
return $ctd['component'];
}
}
return null;
} | php | public static function getComponentById(array $componentToData, $id){
foreach ($componentToData as $ctd){
if ($ctd['id'] == $id){
return $ctd['component'];
}
}
return null;
} | [
"public",
"static",
"function",
"getComponentById",
"(",
"array",
"$",
"componentToData",
",",
"$",
"id",
")",
"{",
"foreach",
"(",
"$",
"componentToData",
"as",
"$",
"ctd",
")",
"{",
"if",
"(",
"$",
"ctd",
"[",
"'id'",
"]",
"==",
"$",
"id",
")",
"{"... | Returns a component stored in an array of array. The searched key is 'id'. If matched,
the component instance is returned. Otherwise null.
@param array $componentToData
@param string $id
@return common_configuration_Component | [
"Returns",
"a",
"component",
"stored",
"in",
"an",
"array",
"of",
"array",
".",
"The",
"searched",
"key",
"is",
"id",
".",
"If",
"matched",
"the",
"component",
"instance",
"is",
"returned",
".",
"Otherwise",
"null",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/install/services/class.CheckPHPConfigService.php#L187-L195 |
oat-sa/tao-core | helpers/form/elements/Validators.php | Validators.getOptions | public function getOptions() {
$options = parent::getOptions();
$statusProperty = new core_kernel_classes_Property(TaoOntology::PROPERTY_ABSTRACT_MODEL_STATUS);
$current = $this->getEvaluatedValue();
$options = array();
$map = ValidationRuleRegistry::getRegistry()->getMap();
foreach (ValidationRuleRegistry::getRegistry()->getMap() as $id => $validator) {
$options[$id] = $id;
}
return $options;
} | php | public function getOptions() {
$options = parent::getOptions();
$statusProperty = new core_kernel_classes_Property(TaoOntology::PROPERTY_ABSTRACT_MODEL_STATUS);
$current = $this->getEvaluatedValue();
$options = array();
$map = ValidationRuleRegistry::getRegistry()->getMap();
foreach (ValidationRuleRegistry::getRegistry()->getMap() as $id => $validator) {
$options[$id] = $id;
}
return $options;
} | [
"public",
"function",
"getOptions",
"(",
")",
"{",
"$",
"options",
"=",
"parent",
"::",
"getOptions",
"(",
")",
";",
"$",
"statusProperty",
"=",
"new",
"core_kernel_classes_Property",
"(",
"TaoOntology",
"::",
"PROPERTY_ABSTRACT_MODEL_STATUS",
")",
";",
"$",
"cu... | (non-PHPdoc)
@see tao_helpers_form_elements_MultipleElement::getOptions() | [
"(",
"non",
"-",
"PHPdoc",
")"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/elements/Validators.php#L50-L63 |
oat-sa/tao-core | helpers/form/elements/xhtml/class.GenerisAsyncFile.php | tao_helpers_form_elements_xhtml_GenerisAsyncFile.feed | public function feed()
{
if (isset($_POST[$this->name])) {
$structure = json_decode($_POST[$this->name], true);
if ($structure !== false) {
$description = new tao_helpers_form_data_UploadFileDescription(array_key_exists('name',
$structure) ? $structure['name'] : null,
array_key_exists('size', $structure) ? $structure['size'] : null,
array_key_exists('type', $structure) ? $structure['type'] : null,
array_key_exists('uploaded_file', $structure) ? $structure['uploaded_file'] : null,
array_key_exists('action', $structure) ? $structure['action'] : null);
$this->setValue($description);
} else {
// else, no file was selected by the end user.
// set the value as empty in order
$this->setValue($_POST[$this->name]);
}
}
} | php | public function feed()
{
if (isset($_POST[$this->name])) {
$structure = json_decode($_POST[$this->name], true);
if ($structure !== false) {
$description = new tao_helpers_form_data_UploadFileDescription(array_key_exists('name',
$structure) ? $structure['name'] : null,
array_key_exists('size', $structure) ? $structure['size'] : null,
array_key_exists('type', $structure) ? $structure['type'] : null,
array_key_exists('uploaded_file', $structure) ? $structure['uploaded_file'] : null,
array_key_exists('action', $structure) ? $structure['action'] : null);
$this->setValue($description);
} else {
// else, no file was selected by the end user.
// set the value as empty in order
$this->setValue($_POST[$this->name]);
}
}
} | [
"public",
"function",
"feed",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"_POST",
"[",
"$",
"this",
"->",
"name",
"]",
")",
")",
"{",
"$",
"structure",
"=",
"json_decode",
"(",
"$",
"_POST",
"[",
"$",
"this",
"->",
"name",
"]",
",",
"true",
"... | Short description of method feed
@access public
@author Jerome Bogaerts, <jerome@taotesting.com>
@return mixed | [
"Short",
"description",
"of",
"method",
"feed"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/elements/xhtml/class.GenerisAsyncFile.php#L41-L60 |
oat-sa/tao-core | helpers/form/elements/xhtml/class.GenerisAsyncFile.php | tao_helpers_form_elements_xhtml_GenerisAsyncFile.render | public function render()
{
$widgetContainerId = $this->buildWidgetContainerId();
$returnValue = $this->renderLabel();
$returnValue .= "<div id='${widgetContainerId}' class='form-elt-container file-uploader'>";
if ($this->value instanceof tao_helpers_form_data_UploadFileDescription && $this->value->getAction() == tao_helpers_form_data_UploadFileDescription::FORM_ACTION_DELETE) {
// File deleted, nothing to render
} elseif ($this->value instanceof tao_helpers_form_data_FileDescription && ($file = $this->value->getFile()) != null) {
// A file is stored or has just been uploaded.
$shownFileName = $this->value->getName();
$shownFileSize = $this->value->getSize();
$shownFileSize = number_format($shownFileSize / 1000, 2); // to kb.
$shownFileTxt = sprintf(__('%s (%s kb)'), $shownFileName, $shownFileSize);
$deleteButtonTitle = __("Delete");
$deleteButtonId = $this->buildDeleteButtonId();
$downloadButtonTitle = __("Download");
$downloadButtonId = $this->buildDownloadButtonId();
$iFrameId = $this->buildIframeId();
$returnValue .= "<span class=\"widget_AsyncFile_fileinfo\">${shownFileTxt}</span>";
$returnValue .= "<button id=\"${downloadButtonId}\" type=\"button\" class=\"download btn-neutral small icon-download\" title=\"${downloadButtonTitle}\">";
$returnValue .= "<button id=\"${deleteButtonId}\" type=\"button\" class=\"delete btn-error small icon-bin\" title=\"${deleteButtonTitle}\"/>";
$returnValue .= "<iframe style=\"display:none\" id=\"${iFrameId}\" frameborder=\"0\"/>";
// Inject behaviour of the Delete/Download buttons component in response.
$returnValue .= self::embedBehaviour($this->buildDeleterBehaviour() . $this->buildDownloaderBehaviour());
} else {
// No file stored yet.
// Inject behaviour of the AsyncFileUpload component in response.
$returnValue .= self::embedBehaviour($this->buildUploaderBehaviour());
}
$returnValue .= "</div>";
return (string) $returnValue;
} | php | public function render()
{
$widgetContainerId = $this->buildWidgetContainerId();
$returnValue = $this->renderLabel();
$returnValue .= "<div id='${widgetContainerId}' class='form-elt-container file-uploader'>";
if ($this->value instanceof tao_helpers_form_data_UploadFileDescription && $this->value->getAction() == tao_helpers_form_data_UploadFileDescription::FORM_ACTION_DELETE) {
// File deleted, nothing to render
} elseif ($this->value instanceof tao_helpers_form_data_FileDescription && ($file = $this->value->getFile()) != null) {
// A file is stored or has just been uploaded.
$shownFileName = $this->value->getName();
$shownFileSize = $this->value->getSize();
$shownFileSize = number_format($shownFileSize / 1000, 2); // to kb.
$shownFileTxt = sprintf(__('%s (%s kb)'), $shownFileName, $shownFileSize);
$deleteButtonTitle = __("Delete");
$deleteButtonId = $this->buildDeleteButtonId();
$downloadButtonTitle = __("Download");
$downloadButtonId = $this->buildDownloadButtonId();
$iFrameId = $this->buildIframeId();
$returnValue .= "<span class=\"widget_AsyncFile_fileinfo\">${shownFileTxt}</span>";
$returnValue .= "<button id=\"${downloadButtonId}\" type=\"button\" class=\"download btn-neutral small icon-download\" title=\"${downloadButtonTitle}\">";
$returnValue .= "<button id=\"${deleteButtonId}\" type=\"button\" class=\"delete btn-error small icon-bin\" title=\"${deleteButtonTitle}\"/>";
$returnValue .= "<iframe style=\"display:none\" id=\"${iFrameId}\" frameborder=\"0\"/>";
// Inject behaviour of the Delete/Download buttons component in response.
$returnValue .= self::embedBehaviour($this->buildDeleterBehaviour() . $this->buildDownloaderBehaviour());
} else {
// No file stored yet.
// Inject behaviour of the AsyncFileUpload component in response.
$returnValue .= self::embedBehaviour($this->buildUploaderBehaviour());
}
$returnValue .= "</div>";
return (string) $returnValue;
} | [
"public",
"function",
"render",
"(",
")",
"{",
"$",
"widgetContainerId",
"=",
"$",
"this",
"->",
"buildWidgetContainerId",
"(",
")",
";",
"$",
"returnValue",
"=",
"$",
"this",
"->",
"renderLabel",
"(",
")",
";",
"$",
"returnValue",
".=",
"\"<div id='${widget... | Short description of method render
@access public
@author Jerome Bogaerts, <jerome@taotesting.com>
@return string | [
"Short",
"description",
"of",
"method",
"render"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/elements/xhtml/class.GenerisAsyncFile.php#L69-L107 |
oat-sa/tao-core | helpers/form/elements/xhtml/class.GenerisAsyncFile.php | tao_helpers_form_elements_xhtml_GenerisAsyncFile.buildDeleterBehaviour | public function buildDeleterBehaviour()
{
return '$(document).ready(function() {
$("#' . $this->buildDeleteButtonId() . '").click(function() {
var $form = $(this).parents("form"),
$fileHandling = $form.find("[name=\'' . $this->getName() . '\']");
if(!$fileHandling.length) {
$fileHandling = $("<input>", { name: "' . $this->getName() . '", type: "hidden" });
$form.prepend($fileHandling);
}
$fileHandling.val("{\\"action\\":\\"delete\\"}");
$("#' . $this->buildWidgetContainerId() . '").empty();
' . $this->buildUploaderBehaviour(true) . '
});
});';
} | php | public function buildDeleterBehaviour()
{
return '$(document).ready(function() {
$("#' . $this->buildDeleteButtonId() . '").click(function() {
var $form = $(this).parents("form"),
$fileHandling = $form.find("[name=\'' . $this->getName() . '\']");
if(!$fileHandling.length) {
$fileHandling = $("<input>", { name: "' . $this->getName() . '", type: "hidden" });
$form.prepend($fileHandling);
}
$fileHandling.val("{\\"action\\":\\"delete\\"}");
$("#' . $this->buildWidgetContainerId() . '").empty();
' . $this->buildUploaderBehaviour(true) . '
});
});';
} | [
"public",
"function",
"buildDeleterBehaviour",
"(",
")",
"{",
"return",
"'$(document).ready(function() {\n $(\"#'",
".",
"$",
"this",
"->",
"buildDeleteButtonId",
"(",
")",
".",
"'\").click(function() {\n var $form = $(this).parents(\"form\")... | Short description of method buildDeleterBehaviour
@access public
@author Jerome Bogaerts, <jerome@taotesting.com>
@return string | [
"Short",
"description",
"of",
"method",
"buildDeleterBehaviour"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/elements/xhtml/class.GenerisAsyncFile.php#L128-L143 |
oat-sa/tao-core | helpers/form/elements/xhtml/class.GenerisAsyncFile.php | tao_helpers_form_elements_xhtml_GenerisAsyncFile.buildUploaderBehaviour | public function buildUploaderBehaviour($deleted = false)
{
$returnValue = (string) '';
$widgetName = $this->buildWidgetName();
// get the upload max size (the min of those 3 directives)
$max_upload = (int) (ini_get('upload_max_filesize'));
$max_post = (int) (ini_get('post_max_size'));
$memory_limit = (int) (ini_get('memory_limit'));
$fileSize = min($max_upload, $max_post, $memory_limit) * 1024 * 1024;
$mimetypes = array();
// add a client validation
foreach ($this->validators as $validator) {
// get the valid file extensions
if ($validator instanceof tao_helpers_form_validators_FileMimeType) {
$options = $validator->getOptions();
if (isset($options['mimetype'])) {
$mimetypes = $options['mimetype'];
}
}
// get the max file size
if ($validator instanceof tao_helpers_form_validators_FileSize) {
$options = $validator->getOptions();
if (isset($options['max'])) {
$validatorMax = (int) $options['max'];
if ($validatorMax > 0 && $validatorMax < $fileSize) {
$fileSize = $validatorMax;
}
}
}
}
// default value for 'auto' is 'true':
$auto = 'true';
if (isset($this->attributes['auto'])) {
if (! $this->attributes['auto'] || $this->attributes['auto'] === 'false') {
$auto = 'false';
}
unset($this->attributes['auto']);
}
// initialize the Uploader Js component
$returnValue .= '
require([\'jquery\', \'ui/feedback\', \'ui/uploader\'], function($, feedback){
$("#' . $this->buildWidgetContainerId() . '").uploader({
uploadUrl: "' . ROOT_URL . 'tao/File/upload",
autoUpload: "' . $auto . '" ,
showResetButton: "' . ! $auto . '" ,
showUploadButton: "' . ! $auto . '" ,
fileSelect : function(files, done){
var error = [],
givenLength = files.length,
filters = "' . implode(',', $mimetypes) . '".split(",").filter(function(e){return e.length});
if (filters.length){
files = _.filter(files, function(file){
return _.contains(filters, file.type);
});
if(files.length !== givenLength){
error.push( "Unauthorized files have been removed");
}
}
files = _.filter(files, function(file){
return file.size <= ' . $fileSize . ';
});
if(files.length !== givenLength && !error.length){
error.push( "Size limit is ' . $fileSize . ' bytes");
}
if (error.length){
feedback().error(error.join(","));
}
done(files);
if ( ' . $auto . ' ){
$(this).uploader("upload");
}
}
}).on("upload.uploader", function(e, file, result){
if ( result && result.uploaded ){
var $container = $(e.target);
var $form = $container.parents("form");
var $fileHandling = $form.find("[name=\'file_handling\']");
$container.append($("<input type=\'hidden\' name=\'' . $this->getName() . '\'/>").val(result.data));
}
})
});';
return (string) $returnValue;
} | php | public function buildUploaderBehaviour($deleted = false)
{
$returnValue = (string) '';
$widgetName = $this->buildWidgetName();
// get the upload max size (the min of those 3 directives)
$max_upload = (int) (ini_get('upload_max_filesize'));
$max_post = (int) (ini_get('post_max_size'));
$memory_limit = (int) (ini_get('memory_limit'));
$fileSize = min($max_upload, $max_post, $memory_limit) * 1024 * 1024;
$mimetypes = array();
// add a client validation
foreach ($this->validators as $validator) {
// get the valid file extensions
if ($validator instanceof tao_helpers_form_validators_FileMimeType) {
$options = $validator->getOptions();
if (isset($options['mimetype'])) {
$mimetypes = $options['mimetype'];
}
}
// get the max file size
if ($validator instanceof tao_helpers_form_validators_FileSize) {
$options = $validator->getOptions();
if (isset($options['max'])) {
$validatorMax = (int) $options['max'];
if ($validatorMax > 0 && $validatorMax < $fileSize) {
$fileSize = $validatorMax;
}
}
}
}
// default value for 'auto' is 'true':
$auto = 'true';
if (isset($this->attributes['auto'])) {
if (! $this->attributes['auto'] || $this->attributes['auto'] === 'false') {
$auto = 'false';
}
unset($this->attributes['auto']);
}
// initialize the Uploader Js component
$returnValue .= '
require([\'jquery\', \'ui/feedback\', \'ui/uploader\'], function($, feedback){
$("#' . $this->buildWidgetContainerId() . '").uploader({
uploadUrl: "' . ROOT_URL . 'tao/File/upload",
autoUpload: "' . $auto . '" ,
showResetButton: "' . ! $auto . '" ,
showUploadButton: "' . ! $auto . '" ,
fileSelect : function(files, done){
var error = [],
givenLength = files.length,
filters = "' . implode(',', $mimetypes) . '".split(",").filter(function(e){return e.length});
if (filters.length){
files = _.filter(files, function(file){
return _.contains(filters, file.type);
});
if(files.length !== givenLength){
error.push( "Unauthorized files have been removed");
}
}
files = _.filter(files, function(file){
return file.size <= ' . $fileSize . ';
});
if(files.length !== givenLength && !error.length){
error.push( "Size limit is ' . $fileSize . ' bytes");
}
if (error.length){
feedback().error(error.join(","));
}
done(files);
if ( ' . $auto . ' ){
$(this).uploader("upload");
}
}
}).on("upload.uploader", function(e, file, result){
if ( result && result.uploaded ){
var $container = $(e.target);
var $form = $container.parents("form");
var $fileHandling = $form.find("[name=\'file_handling\']");
$container.append($("<input type=\'hidden\' name=\'' . $this->getName() . '\'/>").val(result.data));
}
})
});';
return (string) $returnValue;
} | [
"public",
"function",
"buildUploaderBehaviour",
"(",
"$",
"deleted",
"=",
"false",
")",
"{",
"$",
"returnValue",
"=",
"(",
"string",
")",
"''",
";",
"$",
"widgetName",
"=",
"$",
"this",
"->",
"buildWidgetName",
"(",
")",
";",
"// get the upload max size (the m... | Short description of method buildUploaderBehaviour
@access public
@author Jerome Bogaerts, <jerome@taotesting.com>
@param boolean deleted
@return string | [
"Short",
"description",
"of",
"method",
"buildUploaderBehaviour"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/elements/xhtml/class.GenerisAsyncFile.php#L153-L251 |
oat-sa/tao-core | helpers/form/elements/xhtml/class.GenerisAsyncFile.php | tao_helpers_form_elements_xhtml_GenerisAsyncFile.buildDownloaderBehaviour | public function buildDownloaderBehaviour()
{
$returnValue = (string) '';
$downloadButtonId = $this->buildDownloadButtonId();
$iFrameId = $this->buildIframeId();
$serial = $this->value->getFileSerial();
$returnValue .= '$(document).ready(function() {';
$returnValue .= ' $("#' . $downloadButtonId . '").click(function() {';
$returnValue .= ' $("#' . $iFrameId . '").attr("src", ' . json_encode(_url('downloadFile', 'File', 'tao', array(
'id' => $serial))) . ')';
$returnValue .= ' });';
$returnValue .= '});';
return (string) $returnValue;
} | php | public function buildDownloaderBehaviour()
{
$returnValue = (string) '';
$downloadButtonId = $this->buildDownloadButtonId();
$iFrameId = $this->buildIframeId();
$serial = $this->value->getFileSerial();
$returnValue .= '$(document).ready(function() {';
$returnValue .= ' $("#' . $downloadButtonId . '").click(function() {';
$returnValue .= ' $("#' . $iFrameId . '").attr("src", ' . json_encode(_url('downloadFile', 'File', 'tao', array(
'id' => $serial))) . ')';
$returnValue .= ' });';
$returnValue .= '});';
return (string) $returnValue;
} | [
"public",
"function",
"buildDownloaderBehaviour",
"(",
")",
"{",
"$",
"returnValue",
"=",
"(",
"string",
")",
"''",
";",
"$",
"downloadButtonId",
"=",
"$",
"this",
"->",
"buildDownloadButtonId",
"(",
")",
";",
"$",
"iFrameId",
"=",
"$",
"this",
"->",
"buil... | Short description of method buildDownloaderBehaviour
@access public
@author Jerome Bogaerts, <jerome@taotesting.com>
@return string | [
"Short",
"description",
"of",
"method",
"buildDownloaderBehaviour"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/elements/xhtml/class.GenerisAsyncFile.php#L341-L357 |
oat-sa/tao-core | models/classes/security/xsrf/TokenService.php | TokenService.createToken | public function createToken()
{
$time = microtime(true);
$token = $this->generate();
$store = $this->getStore();
$pool = $this->invalidate($store->getTokens());
$pool[] = [
'ts' => $time,
'token' => $token
];
$store->setTokens($pool);
return $token;
} | php | public function createToken()
{
$time = microtime(true);
$token = $this->generate();
$store = $this->getStore();
$pool = $this->invalidate($store->getTokens());
$pool[] = [
'ts' => $time,
'token' => $token
];
$store->setTokens($pool);
return $token;
} | [
"public",
"function",
"createToken",
"(",
")",
"{",
"$",
"time",
"=",
"microtime",
"(",
"true",
")",
";",
"$",
"token",
"=",
"$",
"this",
"->",
"generate",
"(",
")",
";",
"$",
"store",
"=",
"$",
"this",
"->",
"getStore",
"(",
")",
";",
"$",
"pool... | Generates, stores and return a brand new token
Triggers the pool invalidation.
@return string the token | [
"Generates",
"stores",
"and",
"return",
"a",
"brand",
"new",
"token",
"Triggers",
"the",
"pool",
"invalidation",
"."
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/security/xsrf/TokenService.php#L80-L97 |
oat-sa/tao-core | models/classes/security/xsrf/TokenService.php | TokenService.checkToken | public function checkToken($token)
{
$actualTime = microtime(true);
$timeLimit = $this->getTimeLimit();
$pool = $this->getStore()->getTokens();
if(!is_null($pool)){
foreach($pool as $savedToken){
if($savedToken['token'] == $token){
if($timeLimit > 0){
return $savedToken['ts'] + $timeLimit > $actualTime;
}
return true;
}
}
}
return false;
} | php | public function checkToken($token)
{
$actualTime = microtime(true);
$timeLimit = $this->getTimeLimit();
$pool = $this->getStore()->getTokens();
if(!is_null($pool)){
foreach($pool as $savedToken){
if($savedToken['token'] == $token){
if($timeLimit > 0){
return $savedToken['ts'] + $timeLimit > $actualTime;
}
return true;
}
}
}
return false;
} | [
"public",
"function",
"checkToken",
"(",
"$",
"token",
")",
"{",
"$",
"actualTime",
"=",
"microtime",
"(",
"true",
")",
";",
"$",
"timeLimit",
"=",
"$",
"this",
"->",
"getTimeLimit",
"(",
")",
";",
"$",
"pool",
"=",
"$",
"this",
"->",
"getStore",
"("... | Check if the given token is valid
(does not revoke)
@param string $token The given token to validate
@return boolean | [
"Check",
"if",
"the",
"given",
"token",
"is",
"valid",
"(",
"does",
"not",
"revoke",
")"
] | train | https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/security/xsrf/TokenService.php#L106-L124 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.