sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function getFieldsByName($name)
{
$result = [];
foreach ($this->fields as $field) {
if ($field->getName() == $name) {
$result[] = $field;
}
}
return $result;
}
|
Return a list of fields which have the name which equals the given name
@param string $name
@return AbstractFormField[]
|
entailment
|
public function getFieldsByClass($className)
{
$result = [];
foreach ($this->fields as $field) {
if ($field instanceof $className ||
get_class($field) == $className ||
(new \ReflectionClass($field))->getShortName() == $className
) {
$result[] = $field;
}
}
return $result;
}
|
Return a list of fields which have the name which equals the given name
@param string $className
@return AbstractFormField[]
|
entailment
|
public function getFieldValue($name)
{
// if not yet in the cache, look it up
if (!array_key_exists($name, static::$cache)) {
if ($this->getMethod() == Form::METHOD_GET) {
$list = $_GET;
} else {
$list = $_POST;
}
// look it up directly in the get/post array
if (array_key_exists($name, $list)) {
static::$cache[$name] = $list[$name];
} // check for braces (array names?)
elseif (preg_match_all('/\[(.*)\]/U', $name, $match, PREG_OFFSET_CAPTURE)) {
// Walk all found matches and create a list of names
// (could be more, like "field[name1][name2]
$names = [];
foreach ($match[0] as $i => $part) {
if ($i == 0) {
$names[] = substr($name, 0, $part[1]);
}
$names[] = substr($name, $part[1] + 1, strlen($part[0]) - 2);
}
// now, create a copy of our input array and walk the array.
// First look for name1, then go into that array and continue with name2, etc.
$base = $list;
foreach ($names as $keyName) {
if ((string)$keyName !== "") {
if (is_array($base) && array_key_exists($keyName, $base)) {
$base = $base[$keyName];
} // no value found!
else {
$base = null;
}
}
}
static::$cache[$name] = $base;
} else {
static::$cache[$name] = null;
}
// do we have a value?
if (static::$cache[$name]) {
// make sure we filter the input
if ($this->encodingFilter instanceof InterfaceEncodingFilter) {
// filter the input
static::$cache[$name] = $this->encodingFilter->filter(static::$cache[$name]);
}
}
}
return static::$cache[$name];
}
|
Return's the fields value from the GET or POST array, or null if not found.
NOTE: This function should NOT be used for retrieving the value which is set in the field itsself,
because this function will only retrieve the value from GET/POST array.
To retrieve the current value for the field itsself, please use:
```php
$form -> getFieldByName('x') -> getValue();
```
This method can handle field names with "square brackets" in it, but it
only works well if the square brackets have a 'name' in it.
For example; "record[1]" as name works fine, but if you name your fields
"record[]", we don't known the differences between the fields, and is thus not
recommended!
All fields will call this method to 'ask' for their value if the form was submitted.
@param string $name
@return mixed
|
entailment
|
public function removeField(Element $field)
{
foreach ($this->fields as $i => $elem) {
if ($elem == $field) {
unset($this->fields[$i]);
break;
}
}
return $this;
}
|
Remove a field from the form
@param Element $field
@return Form
|
entailment
|
public function removeAllFieldsByName($name)
{
foreach ($this->fields as $i => $field) {
if ($field->getName() == $name) {
unset($this->fields[$i]);
}
}
return $this;
}
|
Remove all fields by the given name.
If there are more then 1 field with the given name, then all will be removed.
@param $name
@return Form
|
entailment
|
public function removeFieldById($id)
{
foreach ($this->fields as $i => $field) {
if ($field->getId() == $id) {
unset($this->fields[$i]);
break;
}
}
return $this;
}
|
Remove a field from the form by the name of the field
@param $id
@return Form
|
entailment
|
public function isCsrfValid()
{
// csrf protection is disabled.
if (!$this->isCsrfProtectionEnabled()) {
return true;
}
// the form is not submitted
if (!$this->isSubmitted()) {
return true;
}
// the form is valid, so the csrf is also valid.
if ($this->isValid()) {
return true;
}
// the form is invalid. Let's check if the CSRF value is the problem.
foreach ($this->fields as $field) {
if ($field instanceof AbstractFormField && $field->getName() == 'csrftoken' && !$field->isValid()) {
return false;
}
}
// the field is not the problem...
return true;
}
|
Check if the Cross-Site-Request-Forgery (CSRF) security token was valid or not.
@return boolean
|
entailment
|
public function getErrorMessages()
{
$errors = [];
foreach ($this->fields as $field) {
if ($field instanceof AbstractFormField && !$field->isValid()) {
$fldErrors = $field->getErrorMessages();
$errors = array_merge($errors, $fldErrors);
}
}
return $errors;
}
|
Fetch all error messages for fields
@return array
|
entailment
|
public function setEncodingFilter(InterfaceEncodingFilter $value)
{
$this->encodingFilter = $value;
// initialize the encoder.
$this->encodingFilter->init($this);
return $this;
}
|
Set an encodingFilter.
This filter will be used to filter all the imput so that its of the correct character encoding.
@param InterfaceEncodingFilter $value
@return Form
|
entailment
|
public function setEnctype($enctype)
{
$enctype = strtolower(trim($enctype));
if (in_array($enctype, [
self::ENCTYPE_MULTIPART,
self::ENCTYPE_PLAIN,
self::ENCTYPE_URLENCODED
])) {
$this->enctype = $enctype;
} else {
throw new \Exception('Incorrect enctype given!');
}
return $this;
}
|
Set how form-data should be encoded before sending it to a server
Possible values:
- application/x-www-form-urlencoded
sdfkjsdhfkjhsdjfhkjsdhfkjhsdfkjhsdkjhsdfkjhsdkjfhsdkjhfsdkjhfkjshdkfjhsdkjfhsdkjhfkjsdhfkjsdhfkjhsdkjfhsdkjfhkjsdhfkjdhdkjfh
- multipart/form-data
- text/plain
@param string $enctype
@return Form
@throws \Exception
|
entailment
|
public function submitButton($name, $value = '')
{
$button = new SubmitButton($this, $value);
$button->setName($name);
return $button;
}
|
Create a new SubmitButton
@param string $name
@param string $value
@return SubmitButton
|
entailment
|
public function imageButton($name, $src = '')
{
$button = new ImageButton($this, $src);
$button->setName($name);
return $button;
}
|
Create a new ImageButton
@param string $name
@param string $src
@return ImageButton
|
entailment
|
public function isValid()
{
$value = $this->field->getValue();
if (is_array($value) || is_object($value)) {
throw new \Exception("This validator only works on scalar types!");
}
// required but not given
if ($this->required && $value == null) {
return false;
} // if the field is not required and the value is empty, then it's also valid
elseif (!$this->required && $value == "") {
return true;
}
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
return false;
}
if ($this->checkIfDomainExists) {
$host = substr(strstr($value, '@'), 1);
if (function_exists('getmxrr')) {
$tmp = null;
if (!getmxrr($host, $tmp)) {
// this will catch dns do not have an mx record.
if (!checkdnsrr($host, 'ANY')) {
// invalid!
return false;
}
}
} else {
// tries to fetch the ip address,
// but it returns a string containing the unmodified hostname on failure.
if ($host == gethostbyname($host)) {
// host is still the same, thus invalid
return false;
}
}
}
return true;
}
|
Check if the given field is valid or not.
@return bool
@throws \Exception
|
entailment
|
public function setValue($value)
{
parent::setValue($value);
$this->setChecked($this->form->getFieldValue($this->name) == $this->getValue());
return $this;
}
|
Set the value for this field and return the CheckBox reference
@param string $value
@return RadioButton
|
entailment
|
public function setName($name)
{
$this->name = $name;
$this->setChecked($this->form->getFieldValue($this->name) == $this->getValue());
return $this;
}
|
Set the name
@param string $name
@return RadioButton
|
entailment
|
public function setChecked($checked = true)
{
$this->clearCache();
$this->checked = (bool)$checked;
return $this;
}
|
Specifies that an input element should be preselected when the page loads
@param bool $checked
@return RadioButton
|
entailment
|
public function addAttribute($name, $value = '')
{
$org = $this->getAttribute($name);
if ($org) {
$value = trim($org . $value);
}
$this->attributes[$name] = $value;
return $this;
}
|
Add an attribute.
If the attribute exist, the value will be merged with the existing value
(concatting the value).
Note: No extra space is added!
@param string $name
@param string $value
@return $this
|
entailment
|
public function isValid()
{
$value = $this->field->getValue();
if (is_array($value) || is_object($value)) {
throw new \Exception("This validator only works on scalar types!");
}
// required but not given
if ($this->required && $value == null) {
return false;
} // if the field is not required and the value is empty, then it's also valid
elseif (!$this->required && $value == "") {
return true;
}
// now, walk all chars and check if they are in the blacklist
for ($i = 0; $i < strlen($value); $i++) {
if (in_array(strval($value[$i]), $this->blacklist, true)) {
// not in the blacklist!
return false;
}
}
// if here, everything is ok!
return true;
}
|
Check if the given field is valid or not.
@return bool
@throws \Exception
|
entailment
|
public function setBlacklist($blacklist)
{
if (is_array($blacklist)) {
$this->blacklist = array_map('strval', $blacklist);
} elseif ($blacklist instanceof \ArrayObject && true) {
$this->blacklist = array_map('strval', $blacklist->getArrayCopy());
} elseif (is_string($blacklist)) {
$this->blacklist = [];
for ($i = 0; $i < strlen($blacklist); $i++) {
$this->blacklist[] = $blacklist[$i];
}
} else {
throw new \Exception('Incorrect blacklist given. Allowed blacklist are: string, array or ArrayObject.');
}
}
|
Set the blacklist of characters which are allowed for this field.
This can either be an array or a string.
@param array|\ArrayObject|string $blacklist
@throws \Exception
|
entailment
|
public function isValid()
{
$value = $this->field->getValue();
// required but not given
if ($this->required && !$value) {
return false;
} // if the field is not required and the value is empty, then it's also valid
elseif (!$this->required && $value == "") {
return true;
}
// radio button or checkbox
if ($this->field instanceof CheckBox || $this->field instanceof RadioButton) {
if (!$this->field->isChecked()) {
return false;
}
}
// values not the same
if ($value != $this->compareValue) {
return $this->not ? true : false;
}
// if here, it's ok
return $this->not ? false : true;
}
|
Check if the given field is valid or not.
@return boolean
|
entailment
|
protected function getMethodNameForClass(Element $element)
{
// if a method exists for this element, then use that one
$className = get_class($element);
// strip namespaces;
$className = substr($className, strrpos($className, '\\') + 1);
// make first char lower case
return strtolower(substr($className, 0, 1)) . substr($className, 1);
}
|
Return the name of the method as we would expect it for this class.
It creates method names like this:
```FormHandler\Fields\TextField => textField```
```FormHandler\Fields\RadioButton => radioButton```
@param Element $element
@return string
|
entailment
|
protected function parseTag(Tag $tag, Element $element)
{
$list = [
'disabled' => 'isDisabled',
'readonly' => 'isReadonly',
'required' => 'isRequired',
'placeholder' => 'getPlaceholder',
'id' => 'getId',
'title' => 'getTitle',
'style' => 'getStyle',
'class' => 'getClass',
'tabindex' => 'getTabindex',
'accesskey' => 'getAccessKey',
'size' => 'getSize'
];
foreach ($list as $attribute => $method) {
if (method_exists($element, $method)) {
$value = $element->$method();
if (substr($method, 0, 2) == 'is') {
if ($value) {
$tag->setAttribute($attribute, $attribute);
}
} else {
$tag->setAttribute($attribute, $value);
}
}
}
if (method_exists($element, 'getName') && $element->getName()) {
$name = $element->getName();
$suffix = '';
if (method_exists($element, 'isMultiple') && $element->isMultiple() && substr($name, -1) != ']') {
$suffix = '[]';
}
$tag->setAttribute('name', $name . $suffix);
}
if (method_exists($element, 'getValue') &&
$element->getValue() !== null &&
$tag->getName() != 'textarea' &&
is_scalar($element->getValue())
) {
$tag->setAttribute('value', htmlentities($element->getValue(), ENT_QUOTES, 'UTF-8'));
}
foreach ($element->getAttributes() as $name => $value) {
$tag->setAttribute($name, $value);
}
return $tag->render();
}
|
Parse the given element and put it's attributes in the given tag.
Then render the HTML tag and return its HTML body.
@param Tag $tag
@param Element $element
@return string
|
entailment
|
public function isValid()
{
// these schemes are allowed
$allowedSchemes = $this->getAllowedSchemes();
// get the field value
$url = $this->field->getValue();
// not required and empty? Then its valid
if ($this->isNotRequiredAndEmpty($url)) {
return true;
}
if ($this->getMaxLength() && strlen($url) > $this->getMaxLength()) {
// Over maximum length.
return false;
}
// do simple validation
if (!filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED | FILTER_FLAG_SCHEME_REQUIRED)) {
return false;
}
// check if we have a tld
if (!$this->isSkipTldCheck() && !preg_match('#\.[a-z]{2,}$#', parse_url($url, PHP_URL_HOST))) {
return false;
}
// further validation is required.
if (in_array(parse_url($url, PHP_URL_SCHEME), $allowedSchemes)) {
return true;
}
return false;
}
|
Check if the given field is valid or not.
@return boolean
|
entailment
|
public function setName($name)
{
$this->name = $name;
$this->setValue($this->form->getFieldValue($this->name));
return $this;
}
|
Set the name
@param string $name
@return HiddenField
|
entailment
|
public function setField(AbstractFormField $field)
{
if (!($field instanceof SelectField)) {
throw new \Exception('The validator "' . get_class($this) . '" only works on select fields!');
}
$this->field = $field;
}
|
Set the field which should be validated.
@param AbstractFormField $field
@throws \Exception
|
entailment
|
public function isValid()
{
// get the submitted value
$value = $this->field->getForm()->getFieldValue($this->field->getName());
// required but not given
if ($this->required && $value == null) {
return false;
} // if the field is not required and the value is empty, then it's also valid
elseif (!$this->required && $value == "") {
return true;
}
// check if multiple values are returned and if this is allowed.
if (is_array($value) && !$this->field->isMultiple()) {
return false;
}
// check if the submitted value(s) are in the options value's
$options = $this->field->getOptions();
if (!is_array($value)) {
$value = (array)$value;
}
// check if the selected options exist
if (!$this->checkIfOptionsExists($value, $options)) {
return false;
}
return true;
}
|
Check if the given field is valid or not.
@return boolean
|
entailment
|
protected function checkIfOptionsExists(array $values, array $options)
{
foreach ($values as $selected) {
$found = false;
// walk all options
foreach ($options as $option) {
if ($option instanceof Option) {
if ($option->getValue() == $selected) {
$found = true;
break;
}
} elseif ($option instanceof Optgroup) {
$options2 = $option->getOptions();
foreach ($options2 as $option2) {
if ($option2->getValue() == $selected) {
$found = true;
break 2;
}
}
}
}
// if not found, then error!
if (!$found) {
// troubles? Then you want to probably log something here
return false;
}
}
return true;
}
|
Check if the given value(s) exists in the options of the selectfield.
@param array $values
@param array $options
@return bool
|
entailment
|
public function isValid()
{
$value = $this->field->getValue();
if (is_array($value) || is_object($value)) {
throw new \Exception("This validator only works on scalar types!");
}
// required but not given
if ($this->required && $value == null) {
return false;
} // if the field is not required and the value is empty, then it's also valid
elseif (!$this->required && $value == "") {
return true;
}
$len = strlen($value);
// shorter then min length
if ($len < $this->getMinLength()) {
return false;
}
// bigger then the given length
if ($this->getMaxLength() > 0 && $len > $this->getMaxLength()) {
return false;
}
return true;
}
|
Check if the given field is valid or not.
@return bool
@throws \Exception
|
entailment
|
protected function selectOptionsFromValue()
{
if (!$this->options) {
return;
}
// there is no current value known. So, just stop.
if ($this->value === null) {
return;
}
// walk all options
foreach ($this->options as $option) {
if ($option instanceof Option) {
if (is_array($this->value)) {
$option->setSelected(in_array($option->getValue(), $this->value));
} else {
$option->setSelected($option->getValue() == $this->value);
}
} else {
if ($option instanceof Optgroup) {
$options = $option->getOptions();
if ($options) {
foreach ($options as $option2) {
if (is_array($this->value)) {
$option2->setSelected(in_array($option2->getValue(), $this->value));
} else {
$option2->setSelected($option2->getValue() == $this->value);
}
}
}
}
}
}
}
|
This function will use the "value" for this field to
select the correct options
|
entailment
|
public function addOptionsAsArray(array $options, $useArrayKeyAsValue = true)
{
foreach ($options as $value => $label) {
$option = new Option();
$option->setLabel($label);
$option->setValue($useArrayKeyAsValue ? $value : $label);
$this->options[] = $option;
}
// this will auto select the options based on this fields value
$this->selectOptionsFromValue();
return $this;
}
|
Add options with an assoc array
@param array $options
@param boolean $useArrayKeyAsValue
@return SelectField
|
entailment
|
public function addOptions(array $options)
{
foreach ($options as $option) {
$this->options[] = $option;
}
// this will auto select the options based on this fields value
$this->selectOptionsFromValue();
return $this;
}
|
Add more options to this selectfield
@param array $options
@return SelectField
|
entailment
|
public function getValue()
{
$selected = [];
// walk all options
foreach ($this->options as $option) {
if ($option instanceof Option) {
if ($option->isSelected()) {
$selected[] = $option->getValue();
}
} else {
if ($option instanceof Optgroup) {
$options = $option->getOptions();
foreach ($options as $option2) {
if ($option2->isSelected()) {
$selected[] = $option2->getValue();
}
}
}
}
}
$count = sizeof($selected);
if ($count > 0) {
if ($this->isMultiple()) {
return $selected;
} else {
// return last selected item as value
return $selected[$count - 1];
}
}
return $this->isMultiple() ? [] : "";
}
|
Return the value for this field.
This will return an array if the field
is setup as "multiple". Otherwise it will return a string with the selected value.
@return array|string
|
entailment
|
public function getOptionByValue($value)
{
// walk all options
foreach ($this->options as $option) {
if ($option instanceof Option) {
if ($option->getValue() == $value) {
return $option;
}
} else {
if ($option instanceof Optgroup) {
$options = $option->getOptions();
foreach ($options as $option2) {
if ($option2->getValue() == $value) {
return $option2;
}
}
}
}
}
return null;
}
|
Return the option which has the given value.
If there are multiple options with the same value, the first will be returned.
@param $value
@return Option
|
entailment
|
public function removeOptionByValue($value)
{
// walk all options
$options = $this->options;
// Empty options;
$this->options = [];
foreach ($options as $option) {
if ($option instanceof Option) {
if ($option->getValue() != $value) {
$this->options[] = $option;
}
} else {
if ($option instanceof Optgroup) {
$subOptions = [];
$options2 = $option->getOptions();
foreach ($options2 as $option2) {
if ($option2->getValue() != $value) {
$subOptions[] = $option2;
}
}
$option->setOptions($subOptions);
if (sizeof($subOptions) > 0) {
$this->options[] = $option;
}
}
}
}
return $this;
}
|
Remove option by value.
In case that the option was nested in an Optgroup,
and it was the only option in that optgroup, then the
optgroup is also removed.
@param $value
@return SelectField
|
entailment
|
public function isValid()
{
$value = $this->field->getValue();
// field is empty and its not required. It's thus valid.
if ($value == '' && $this->required == false) {
return true;
}
$parsedDate = date_parse($value);
if ($parsedDate['warning_count'] == 0 &&
$parsedDate['error_count'] == 0 &&
isset($parsedDate['year']) &&
isset($parsedDate['month'])
) {
return true;
}
return false;
}
|
Check if the given field is valid or not. The date should be parsable by strtotime.
@return boolean
|
entailment
|
public function isValid()
{
$response = call_user_func_array($this->userFunction, array(
&$this->field
));
if ($response === true) {
return true;
}
if (is_string($response)) {
$this->setErrorMessage($response);
}
return false;
}
|
Check if the given field is valid or not.
@return boolean
|
entailment
|
public function render(Element $element)
{
// For all non-checkbox fields...
if ($element instanceof AbstractFormField && !$element instanceof CheckBox) {
if (!$element->getId()) {
$element->setId('field-' . uniqid());
}
// Render our label
$label = new Tag('label');
$label->setAttribute('for', $element->getId());
$label->setInnerHtml($element->getTitle());
// If no labels are wanted, we set it to "Screen Reader" only,
// @see http://getbootstrap.com/css/#callout-inline-form-labels
if ($this->mode == self::MODE_INLINE_NO_LABELS) {
$label->setAttribute('class', 'sr-only');
}
// Render our field, but with an css class "form-control"
$element->addClass('form-control');
$field = parent::render($element);
// Render a help block if an help-text is set.
$helpBlock = '';
if ($element->getHelpText()) {
$helpTag = new Tag('p');
$helpTag->setAttribute('class', 'help-block');
$helpTag->setInnerHtml($element->getHelpText());
$helpBlock = $helpTag->render();
}
// Now render our container div, which will contain all of the above
$tag = new Tag('div');
$cssClass = 'form-group';
if ($element->getForm()->isSubmitted()) {
if (!$element->isValid()) {
$cssClass .= ' has-error has-feedback';
} else {
$cssClass .= ' has-success has-feedback';
}
}
$tag->setAttribute('class', $cssClass);
$tag->setInnerHtml(
$label->render() . PHP_EOL .
$field . PHP_EOL .
$helpBlock . PHP_EOL
);
return $tag->render();
} elseif ($element instanceof AbstractFormButton) {
$element->addClass('btn');
$buttons = $element->getForm()->getFieldsByClass('\FormHandler\Field\AbstractFormButton');
if (sizeof($buttons) == 1) {
$element->addClass('btn-primary');
}
return parent::render($element);
}
return parent::render($element);
}
|
This method is executed when an Element needs to be rendered.
Here we add some logic to add the label, an optional help block and the form group.
@param Element $element
@return string
|
entailment
|
public function radioButton(RadioButton $radioButton)
{
$label = new Tag('label');
$tag = new Tag('input');
$tag->setAttribute('type', 'checkbox');
if ($radioButton->isChecked()) {
$tag->setAttribute('checked', 'checked');
}
$tagHtml = $this->parseTag($tag, $radioButton);
$label->setInnerHtml(
$tagHtml . ' ' . ($radioButton->getLabel() ?: $radioButton->getTitle())
);
$div = new Tag('div');
$cssClass = 'radio';
if( $radioButton->isDisabled() ) {
$cssClass .= ' disabled';
}
if ($radioButton->getForm()->isSubmitted()) {
if (!$radioButton->isValid()) {
$cssClass .= ' has-error has-feedback';
} else {
$cssClass .= ' has-success has-feedback';
}
}
$div->setAttribute('class', $cssClass);
$div->setInnerHtml($label->render());
$html = $div->render();
// if it's an horizontal form, then add some more classes
if ($this->mode == self::MODE_HORIZONTAL) {
$innerDiv = new Tag('div');
$innerDiv->setAttribute('class', 'col-sm-offset-2 col-sm-10');
$innerDiv->setInnerHtml($html);
$outerDiv = new Tag('div');
$outerDiv->setAttribute('class', 'form-group');
$outerDiv->setInnerHtml($innerDiv->render());
$html = $outerDiv->render();
}
return $html;
}
|
Render a RadioButton
@param RadioButton $radioButton
@return string
|
entailment
|
public function form(Form $form)
{
if ($this->mode == self::MODE_INLINE || $this->mode == self::MODE_INLINE_NO_LABELS) {
$form->addClass('form-inline');
} elseif ($this->mode == self::MODE_HORIZONTAL) {
$form->addClass('form-horizontal');
}
return parent::form($form);
}
|
Render a Form,
@param Form $form
@return string
|
entailment
|
public function setEmailPassword($email, $password)
{
if (isset($this->apikey)) {
throw new \Exception(
"ApiKey already set."
);
}
$this->emailPassword = $email.': '.$password;
return $this;
}
|
Set email and password for Email:Password authentication.
@param string $email
@param string $password
@return Credentials
|
entailment
|
public function setApiKey($apikey)
{
if (isset($this->emailPassword)) {
throw new \Exception(
"EmailPassword already set."
);
}
$this->apikey = $apikey . ':';
return $this;
}
|
Set email and password for Email:Password authentication.
@param string $apikey
@return Credentials
|
entailment
|
private function getStatus()
{
if (!($statusArray = preg_grep('/^HTTP\/(1.0|1.1)\s+(\d+)\s+(.+)/', $this->headers))) {
throw new \RuntimeException('Could not determine HTTP status from API response');
}
if (!preg_match('/^HTTP\/(1.0|1.1)\s+(\d+)\s+(.+)/', $statusArray[0], $matchesArray)) {
throw new \RuntimeException('Could not determine HTTP status from API response');
}
return array(
'code' => $matchesArray[2],
'message' => $matchesArray[3],
);
}
|
Extract the HTTP status code and message
from the Response headers
@param void
@return mixed[]
|
entailment
|
private static function toArrayRecursive($object)
{
$output = get_object_vars($object);
foreach ($output as $key => $value) {
if ($value instanceof \DateTime) {
$output[$key] = $value->format('c');
} elseif (is_object($value)) {
$output[$key] = static::toArrayRecursive($value);
}
}
return $output;
}
|
Recursively cast an object into an array.
@param mixed $object
@return mixed[]
|
entailment
|
private static function mapDataToEntity($entityName, \stdClass $data)
{
$entity = new $entityName();
if (!($entity instanceof Entity)) {
throw new \RuntimeException(
sprintf(
'Object "%s" must extend Entity',
$entityName
)
);
}
$foreignKeyEntityMap = $entity->foreignKeyEntityMap();
$properties = array_keys(get_object_vars($data));
foreach ($properties as $propertyName) {
if (!property_exists($entity, $propertyName)) {
throw new \UnexpectedValueException(
sprintf(
'Property %s->%s does not exist',
get_class($entity),
$propertyName
)
);
}
if (isset($foreignKeyEntityMap[$propertyName])) {
$entity->$propertyName = self::mapDataToEntity(
$foreignKeyEntityMap[$propertyName],
$data->$propertyName
);
} elseif (is_string($data->$propertyName) && preg_match('/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/', $data->$propertyName)) {
$entity->$propertyName = new \DateTime($data->$propertyName);
} else {
$entity->$propertyName = json_decode(json_encode($data->$propertyName), true);
}
}
return $entity;
}
|
Map array of data to an entity
@param mixed $entityName
@param mixed $data
@return Entity
|
entailment
|
public static function makeFromResponse($entityName, $content)
{
$content = $content;
$output = array();
if (is_array($content)) {
foreach ($content as $entityData) {
$output[] = self::makeFromResponse($entityName, $entityData);
}
} elseif (is_object($content)) {
$output = self::mapDataToEntity($entityName, $content);
} else {
$output = $content;
}
return $output;
}
|
Make an array of specified entity from a Response
@param mixed $entityName
@param Response $response
@return Entity[]
|
entailment
|
private function makeEndPointUrls()
{
$endPointUrls;
foreach ($this->methodNameEntityMap as $classes) {
$endPointUrls[$classes] = $this->apiurl.$this->endPointUrls[$classes];
}
$this->endPointUrls = $endPointUrls;
}
|
Get API EndPoint URL from an entity name
@param mixed $entityName
@return string
|
entailment
|
private function getEntityName($methodName)
{
if (!preg_match('/^get(.+)$/', $methodName, $matchesArray)) {
throw new \BadMethodCallException(
sprintf(
'Method %s::%s does not exist',
get_class($this),
$methodName
)
);
}
if (!isset($this->methodNameEntityMap[$matchesArray[1]])) {
throw new \BadMethodCallException(
sprintf(
'%s is missing an methodNameMap entry for %s',
get_class($this),
$methodName
)
);
}
return $this->methodNameEntityMap[$matchesArray[1]];
}
|
Get entity name from __call method name
@param mixed $methodName
@return string
|
entailment
|
private function curlInit()
{
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlHandle, CURLOPT_VERBOSE, false);
curl_setopt($curlHandle, CURLOPT_HEADER, true);
curl_setopt($curlHandle, CURLOPT_USERPWD, (string)$this->credentials);
curl_setopt($curlHandle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curlHandle, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curlHandle, CURLOPT_TIMEOUT, 4);
curl_setopt($curlHandle, CURLOPT_FOLLOWLOCATION, true);
return $curlHandle;
}
|
Initialise cURL with the options we need
to communicate successfully with API URL.
@param void
@return resource
|
entailment
|
private function curlExec($curlHandle, $endPointUrl)
{
curl_setopt($curlHandle, CURLOPT_URL, $endPointUrl);
if (($response = @curl_exec($curlHandle)) === false) {
throw new \RuntimeException(
sprintf(
'cURL Error (%d): %s',
curl_errno($curlHandle),
curl_error($curlHandle)
)
);
}
curl_close($curlHandle);
$response_parts = explode("\r\n\r\n", $response);
$content = array_pop($response_parts);
$headers = explode("\r\n", array_pop($response_parts));
return new Response($endPointUrl, $content, $headers);
}
|
Execute cURL request using the specified API EndPoint
@param mixed $curlHandle
@param mixed $endPointUrl
@return Response
|
entailment
|
private function curlGet($endPointUrl)
{
$curlHandle = $this->curlInit();
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $this->childauth);
return $this->curlExec(
$curlHandle,
$endPointUrl
);
}
|
Make a GET request using cURL
@param mixed $endPointUrl
@return Response
|
entailment
|
private function applyOffsetLimit($endPointUrl)
{
$endPointUrlArray = parse_url($endPointUrl);
if (!isset($endPointUrlArray['query'])) {
$endPointUrlArray['query'] = null;
}
parse_str($endPointUrlArray['query'], $queryStringArray);
$queryStringArray['offset'] = $this->offset;
$queryStringArray['limit'] = min(max(1, $this->limit), 500);
$endPointUrlArray['query'] = http_build_query($queryStringArray, null, '&');
$endPointUrl = (isset($endPointUrlArray['scheme'])) ? "{$endPointUrlArray['scheme']}://" : '';
$endPointUrl.= (isset($endPointUrlArray['host'])) ? "{$endPointUrlArray['host']}" : '';
$endPointUrl.= (isset($endPointUrlArray['port'])) ? ":{$endPointUrlArray['port']}" : '';
$endPointUrl.= (isset($endPointUrlArray['path'])) ? "{$endPointUrlArray['path']}" : '';
$endPointUrl.= (isset($endPointUrlArray['query'])) ? "?{$endPointUrlArray['query']}" : '';
return $endPointUrl;
}
|
Apply offset and limit to a end point URL.
@param mixed $endPointUrl
@return string
|
entailment
|
private function curlSend()
{
$arguments = func_get_args();
$httpMethod = array_shift($arguments);
$data = array_shift($arguments);
$endPointUrl = array_shift($arguments);
$curlHandle = $this->curlInit();
curl_setopt($curlHandle, CURLOPT_CUSTOMREQUEST, $httpMethod);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, (string)$data);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array_merge(array('Content-Type: application/json'), $this->childauth));
return $this->curlExec(
$curlHandle,
$endPointUrl
);
}
|
Make a POST/PUT/DELETE request using cURL
@param Entity $entity
@param mixed $httpMethod
@return Response
|
entailment
|
public function deleteApiKey($apikey)
{
$endPointUrl = $this->apiurl."/account/apikey/".$apikey;
$response = $this->curlDelete($endPointUrl);
return $response;
}
|
Delete an ApiKey for a child account
@param string $apikey
@return Response
|
entailment
|
public function deleteTag($tag)
{
$endPointUrl = $this->apiurl."/account/tag/".$tag;
$response = $this->curlDelete($endPointUrl);
return $response;
}
|
Delete a tag for a child account
@param string $tag
@return Response
|
entailment
|
public function deleteAccount()
{
if (!isset($this->childauth)) {
throw new Exception(
sprintf(
'No child authentication set - cannot delete your own account.'
)
);
}
$endPointUrl = $this->apiurl."/account/";
$response = $this->curlDelete($endPointUrl);
return $response;
}
|
Delete a child account
MUST have $this->childauth set to run.
@return Response
|
entailment
|
public function getClientKey($uuid, $edition, $version)
{
$endPointUrl = $this->apiurl."/client/key/".$uuid."?edition=".$edition."&version=".$version;
$response = $this->curlGet($endPointUrl);
return $response;
}
|
Returns a client key.
@param string $uuid
@param string $edition
@param string $version
@return Resposne
|
entailment
|
public function getPrintJobStates()
{
$arguments = func_get_args();
if (count($arguments) > 1) {
throw new InvalidArgumentException(
sprintf(
'Too many arguments given to getPrintJobsStates.'
)
);
}
$endPointUrl = $this->apiurl."/printjobs/";
if (count($arguments) == 0) {
$endPointUrl.= 'states/';
} else {
$arg_1 = array_shift($arguments);
$endPointUrl.= $arg_1.'/states/';
}
$response = $this->curlGet($endPointUrl);
if ($response->getStatusCode() != '200') {
throw new \RuntimeException(
sprintf(
'HTTP Error (%d): %s',
$response->getStatusCode(),
$response->getStatusMessage()
)
);
}
return Entity::makeFromResponse("PrintNode\State", json_decode($response->getContent()));
}
|
Gets print job states.
@param string $printjobId OPTIONAL:if unset gives states relative to all printjobs.
@return Entity[]
|
entailment
|
public function getScales($computerId)
{
$endPointUrl = $this->apiurl."/computer/";
$endPointUrl.= $computerId;
$endPointUrl.= '/scales';
$response = $this->curlGet($endPointUrl);
if ($response->getStatusCode() != '200') {
throw new \RuntimeException(
sprintf(
'HTTP Error (%d): %s',
$response->getStatusCode(),
$response->getStatusMessage()
)
);
}
return Entity::makeFromResponse("PrintNode\Scale", json_decode($response->getContent()));
}
|
Gets scales relative to a computer.
@param string $computerId id of computer to find scales
@return Entity[]
|
entailment
|
public function patch(Entity $entity)
{
if (!($entity instanceof Entity)) {
throw new \InvalidArgumentException(
sprintf(
'Invalid argument type passed to patch. Expecting Entity got %s',
gettype($entity)
)
);
}
$endPointUrl = $this->getEndPointUrl(get_class($entity));
if (method_exists($entity, 'endPointUrlArg')) {
$endPointUrl.= '/'.$entity->endPointUrlArg();
}
if (method_exists($entity, 'formatForPatch')) {
$entity = $entity->formatForPatch();
}
return $this->curlSend('PATCH', $entity, $endPointUrl);
}
|
PATCH (update) the specified entity
@param Entity $entity
@return Response
|
entailment
|
public function post(Entity $entity)
{
if (!($entity instanceof Entity)) {
throw new \InvalidArgumentException(
sprintf(
'Invalid argument type passed to patch. Expecting Entity got %s',
gettype($entity)
)
);
}
$endPointUrl = $this->getEndPointUrl(get_class($entity));
if (method_exists($entity, 'endPointUrlArg')) {
$endPointUrl.= '/'.$entity->endPointUrlArg();
}
if (method_exists($entity, 'formatForPost')){
$entity = $entity->formatForPost();
}
return $this->curlSend('POST', $entity, $endPointUrl);
}
|
POST (create) the specified entity
@param Entity $entity
@return Response
|
entailment
|
public function put()
{
$arguments = func_get_args();
$entity = array_shift($arguments);
if (!($entity instanceof Entity)) {
throw new \InvalidArgumentException(
sprintf(
'Invalid argument type passed to patch. Expecting Entity got %s',
gettype($entity)
)
);
}
$endPointUrl = $this->getEndPointUrl(get_class($entity));
foreach ($arguments as $argument) {
$endPointUrl.= '/'.$argument;
}
return $this->curlSend('PUT', $entity, $endPointUrl);
}
|
PUT (update) the specified entity
@param Entity $entity
@return Response
|
entailment
|
public function delete(Entity $entity)
{
$endPointUrl = $this->getEndPointUrl(get_class($entity));
if (method_exists($entity, 'endPointUrlArg')) {
$endPointUrl.= '/'.$entity->endPointUrlArg();
}
return $this->curlDelete($endPointUrl);
}
|
DELETE (delete) the specified entity
@param Entity $entity
@return Response
|
entailment
|
public function setInstallments($installments)
{
$isOneTimePayment = (
$this->product === PaymentMethod::DEBITO ||
$this->product === PaymentMethod::CREDITO_A_VISTA
);
if ($isOneTimePayment && $installments !== 1) {
throw new \UnexpectedValueException('Para crédito à vista ou débito, o número de parcelas deve ser 1');
}
if ($installments < 1 || strlen($installments) > 2) {
throw new \UnexpectedValueException(
'O número de parcelas deve ser maior ou igual a 1 e deve ter no máximo 2 dígitos'
);
}
$this->installments = $installments;
}
|
@param string $installments
@throws \UnexpectedValueException se a forma de pagamento for débito ou
crédito à vista e o número de parcelas for diferente de 1
@throws \UnexpectedValueException se o número de parcelas for menor que 1
ou o número de parcelas não estiver com 2 dígitos
|
entailment
|
public function setExpiration($expirationYear, $expirationMonth)
{
if (!is_numeric($expirationYear) || strlen($expirationYear) != 4) {
throw new \UnexpectedValueException('O ano de expiração do cartão deve ser um número de 4 dígitos');
}
if (!is_numeric($expirationMonth) || $expirationMonth < 1 || $expirationMonth > 12) {
throw new \UnexpectedValueException('O mês de expiração do cartão deve ser um número entre 1 e 12');
}
$this->expiration = sprintf('%4d%02d', $expirationYear, $expirationMonth);
}
|
@param string $expirationYear
@param string $expirationMonth
@throws \UnexpectedValueException se o ano de expiração não for numérico
ou não conter 4 dígitos
@throws \UnexpectedValueException se o mês de expiração não for numérico
ou não estiver entre 1 e 12
|
entailment
|
public function serialize($transaction)
{
libxml_use_internal_errors(true);
$document = new DOMDocument('1.0', 'utf-8');
$requisicaoTransacao = $this->createConsultationRequest($transaction, $document);
$document->appendChild($requisicaoTransacao);
if (is_file('ecommerce.xsd') && is_readable('ecommerce.xsd')) {
$document->schemaValidate('ecommerce.xsd');
}
$exception = new \DomainException('Erro na criação do XML');
$count = 0;
foreach (libxml_get_errors() as $error) {
$exception = new \DomainException($error->message, $error->code, $exception);
++$count;
}
libxml_clear_errors();
if ($count) {
echo $document->saveXML();
throw $exception;
}
return $document->saveXML();
}
|
{@inheritDoc}
|
entailment
|
public function serialize($holder)
{
libxml_use_internal_errors(true);
$document = new DOMDocument('1.0', 'utf-8');
$requisicaoToken = $this->createRequisicaoToken($holder, $document);
$document->appendChild($requisicaoToken);
if (is_file('ecommerce.xsd') && is_readable('ecommerce.xsd')) {
$document->schemaValidate('ecommerce.xsd');
}
$exception = new \DomainException('Erro na criação do XML');
$count = 0;
foreach (libxml_get_errors() as $error) {
$exception = new \DomainException($error->message, $error->code, $exception);
++$count;
}
libxml_clear_errors();
if ($count) {
echo $document->saveXML();
throw $exception;
}
return $document->saveXML();
}
|
{@inheritDoc}
|
entailment
|
public function generate()
{
if (TL_MODE === 'BE') {
return parent::generate();
}
// Generate the list in related categories mode
if ($this->news_relatedCategories) {
return $this->generateRelated();
}
return parent::generate();
}
|
Set the flag to filter news by categories
@return string
|
entailment
|
protected function generateRelated()
{
$this->news_archives = $this->sortOutProtected(StringUtil::deserialize($this->news_archives, true));
// Return if there are no archives
if (count($this->news_archives) === 0) {
return '';
}
$alias = Input::get('items') ?: Input::get('auto_item');
// Return if the news item was not found
if (($news = NewsModel::findPublishedByParentAndIdOrAlias($alias, $this->news_archives)) === null) {
return '';
}
// Store the news item for further reference
$this->currentNews = $news;
return parent::generate();
}
|
Generate the list in related categories mode
Use the categories of the current news item. The module must be
on the same page as news reader module.
@return string
|
entailment
|
public function onNewsListCountItems(array $archives, $featured, ModuleNewsList $module)
{
if (null === ($criteria = $this->getCriteria($archives, $featured, $module))) {
return 0;
}
return $criteria->getNewsModelAdapter()->countBy($criteria->getColumns(), $criteria->getValues());
}
|
On news list count items.
@param array $archives
@param bool|null $featured
@param ModuleNewsList $module
@return int
|
entailment
|
public function onNewsListFetchItems(array $archives, $featured, $limit, $offset, ModuleNewsList $module)
{
if (null === ($criteria = $this->getCriteria($archives, $featured, $module))) {
return null;
}
$criteria->setLimit($limit);
$criteria->setOffset($offset);
return $criteria->getNewsModelAdapter()->findBy(
$criteria->getColumns(),
$criteria->getValues(),
$criteria->getOptions()
);
}
|
On news list fetch items.
@param array $archives
@param bool|null $featured
@param int $limit
@param int $offset
@param ModuleNewsList $module
@return Collection|null
|
entailment
|
private function getCriteria(array $archives, $featured, ModuleNewsList $module)
{
try {
$criteria = $this->searchBuilder->getCriteriaForListModule($archives, $featured, $module);
} catch (CategoryNotFoundException $e) {
throw new PageNotFoundException($e->getMessage());
}
return $criteria;
}
|
Get the criteria.
@param array $archives
@param bool|null $featured
@param ModuleNewsList $module
@return NewsCriteria|null
@throws PageNotFoundException
|
entailment
|
public function generate()
{
// Return if the element is not published
if (TL_MODE === 'FE'
&& !BE_USER_LOGGED_IN
&& ($this->invisible || ($this->start > 0 && $this->start > \time()) || ($this->stop > 0 && $this->stop < \time()))
) {
return '';
}
// Return if the module could not be found
if (null === ($moduleModel = ModuleModel::findByPk($this->news_module))) {
return '';
}
$class = Module::findClass($moduleModel->type);
// Return if the class does not exist
if (!\class_exists($class)) {
return '';
}
$moduleModel->typePrefix = 'ce_';
/** @var Module $module */
$module = new $class($moduleModel, $this->strColumn);
$this->mergeCssId($module);
// Override news filter settings
$module->news_filterCategories = $this->news_filterCategories;
$module->news_relatedCategories = $this->news_relatedCategories;
$module->news_includeSubcategories = $this->news_includeSubcategories;
$module->news_filterDefault = $this->news_filterDefault;
$module->news_filterPreserve = $this->news_filterPreserve;
$module->news_categoryFilterPage = $this->news_categoryFilterPage;
$module->news_categoryImgSize = $this->news_categoryImgSize;
return $module->generate();
}
|
Parse the template.
@return string
|
entailment
|
private function mergeCssId(Module $module)
{
$cssID = StringUtil::deserialize($module->cssID, true);
// Override the CSS ID (see #305)
if ($this->cssID[0]) {
$cssID[0] = $this->cssID[0];
}
// Merge the CSS classes (see #6011)
if ($this->cssID[1]) {
$cssID[1] = \trim($cssID[1].' '.$this->cssID[1]);
}
$module->cssID = $cssID;
}
|
Merge the CSS/ID stuff.
@param Module $module
|
entailment
|
public function setBasicCriteria(array $archives, $sorting = null)
{
$archives = $this->parseIds($archives);
if (0 === \count($archives)) {
throw new NoNewsException();
}
$t = $this->getNewsModelAdapter()->getTable();
$this->columns[] = "$t.pid IN(".\implode(',', \array_map('intval', $archives)).')';
// Set the sorting
switch ($sorting) {
case 'order_headline_asc':
$this->options['order'] = "$t.headline";
break;
case 'order_headline_desc':
$this->options['order'] = "$t.headline DESC";
break;
case 'order_random':
$this->options['order'] = 'RAND()';
break;
case 'order_date_asc':
$this->options['order'] = "$t.date";
break;
default:
$this->options['order'] = "$t.date DESC";
break;
}
// Never return unpublished elements in the back end, so they don't end up in the RSS feed
if (!BE_USER_LOGGED_IN || TL_MODE === 'BE') {
/** @var Date $dateAdapter */
$dateAdapter = $this->framework->getAdapter(Date::class);
$time = $dateAdapter->floorToMinute();
$this->columns[] = "($t.start=? OR $t.start<=?) AND ($t.stop=? OR $t.stop>?) AND $t.published=?";
$this->values = \array_merge($this->values, ['', $time, '', ($time + 60), 1]);
}
}
|
Set the basic criteria.
@param array $archives
@param string $sorting
@throws NoNewsException
|
entailment
|
public function setFeatured($enable)
{
$t = $this->getNewsModelAdapter()->getTable();
if (true === $enable) {
$this->columns[] = "$t.featured=?";
$this->values[] = 1;
} elseif (false === $enable) {
$this->columns[] = "$t.featured=?";
$this->values[] = '';
}
}
|
Set the features items.
@param bool $enable
|
entailment
|
public function setTimeFrame($begin, $end)
{
$t = $this->getNewsModelAdapter()->getTable();
$this->columns[] = "$t.date>=? AND $t.date<=?";
$this->values[] = $begin;
$this->values[] = $end;
}
|
Set the time frame.
@param int $begin
@param int $end
|
entailment
|
public function setDefaultCategories(array $defaultCategories, $includeSubcategories = true, $order = null)
{
$defaultCategories = $this->parseIds($defaultCategories);
if (0 === \count($defaultCategories)) {
throw new NoNewsException();
}
// Include the subcategories
if ($includeSubcategories) {
/** @var NewsCategoryModel $newsCategoryModel */
$newsCategoryModel = $this->framework->getAdapter(NewsCategoryModel::class);
$defaultCategories = $newsCategoryModel->getAllSubcategoriesIds($defaultCategories);
}
/** @var Model $model */
$model = $this->framework->getAdapter(Model::class);
$newsIds = $model->getReferenceValues('tl_news', 'categories', $defaultCategories);
$newsIds = $this->parseIds($newsIds);
if (0 === \count($newsIds)) {
throw new NoNewsException();
}
$t = $this->getNewsModelAdapter()->getTable();
$this->columns['defaultCategories'] = "$t.id IN(".\implode(',', $newsIds).')';
// Order news items by best match
if ($order === 'best_match') {
$mapper = [];
// Build the mapper
foreach (array_unique($newsIds) as $newsId) {
$mapper[$newsId] = count(array_intersect($defaultCategories, array_unique($model->getRelatedValues($t, 'categories', $newsId))));
}
arsort($mapper);
$this->options['order'] = Database::getInstance()->findInSet("$t.id", array_keys($mapper));
}
}
|
Set the default categories.
@param array $defaultCategories
@param bool $includeSubcategories
@param string|null $order
@throws NoNewsException
|
entailment
|
public function setCategory($category, $preserveDefault = false, $includeSubcategories = false)
{
/** @var Model $model */
$model = $this->framework->getAdapter(Model::class);
// Include the subcategories
if ($includeSubcategories) {
/** @var NewsCategoryModel $newsCategoryModel */
$newsCategoryModel = $this->framework->getAdapter(NewsCategoryModel::class);
$category = $newsCategoryModel->getAllSubcategoriesIds($category);
}
$newsIds = $model->getReferenceValues('tl_news', 'categories', $category);
$newsIds = $this->parseIds($newsIds);
if (0 === \count($newsIds)) {
throw new NoNewsException();
}
// Do not preserve the default categories
if (!$preserveDefault) {
unset($this->columns['defaultCategories']);
}
$t = $this->getNewsModelAdapter()->getTable();
$this->columns[] = "$t.id IN(".\implode(',', $newsIds).')';
}
|
Set the category.
@param int $category
@param bool $preserveDefault
@param bool $includeSubcategories
@return NoNewsException
|
entailment
|
public function setExcludedNews(array $newsIds)
{
$newsIds = $this->parseIds($newsIds);
if (0 === \count($newsIds)) {
throw new NoNewsException();
}
$t = $this->getNewsModelAdapter()->getTable();
$this->columns[] = "$t.id NOT IN (".\implode(',', $newsIds).')';
}
|
Set the excluded news IDs.
@param array $newsIds
|
entailment
|
private function parseIds(array $ids)
{
$ids = \array_map('intval', $ids);
$ids = \array_filter($ids);
$ids = \array_unique($ids);
return \array_values($ids);
}
|
Parse the record IDs.
@param array $ids
@return array
|
entailment
|
public function onSubmitCallback(DataContainer $dc)
{
// Schedule a news feed update
if ('tl_news_category' === $dc->table && $dc->id) {
/** @var Model $modelAdapter */
$modelAdapter = $this->framework->getAdapter(Model::class);
$newsIds = $modelAdapter->getReferenceValues('tl_news', 'categories', $dc->id);
$newsIds = \array_map('intval', \array_unique($newsIds));
if (\count($newsIds) > 0) {
$archiveIds = $this->db
->executeQuery('SELECT DISTINCT(pid) FROM tl_news WHERE id IN ('.\implode(',', $newsIds).')')
->fetchAll(\PDO::FETCH_COLUMN, 0);
$session = $this->session->get('news_feed_updater');
$session = \array_merge((array) $session, $archiveIds);
$this->session->set('news_feed_updater', \array_unique($session));
}
}
}
|
On data container submit callback.
@param DataContainer $dc
|
entailment
|
private function generateFeed($method)
{
$session = $this->session->get('news_feed_updater');
if (!\is_array($session) || empty($session)) {
return;
}
$feedGenerator = new FeedGenerator();
foreach ($session as $id) {
$feedGenerator->$method($id);
}
(new Automator())->generateSitemap();
$this->session->set('news_feed_updater', null);
}
|
Generate the feed.
@param string $method
|
entailment
|
public function onLoadCallback(DataContainer $dc)
{
if (!$this->permissionChecker->canUserManageCategories() && !$this->permissionChecker->canUserAssignCategories()) {
throw new AccessDeniedException('User has no permissions to manage news categories');
}
// Disable some features if user is not allowed to manage categories
if (!$this->permissionChecker->canUserManageCategories()) {
$GLOBALS['TL_DCA'][$dc->table]['config']['closed'] = true;
$GLOBALS['TL_DCA'][$dc->table]['config']['notEditable'] = true;
$GLOBALS['TL_DCA'][$dc->table]['config']['notDeletable'] = true;
$GLOBALS['TL_DCA'][$dc->table]['config']['notCopyable'] = true;
$GLOBALS['TL_DCA'][$dc->table]['config']['notSortable'] = true;
unset($GLOBALS['TL_DCA'][$dc->table]['list']['global_operations']['all']);
$GLOBALS['TL_DCA'][$dc->table]['list']['operations'] = array_intersect_key(
$GLOBALS['TL_DCA'][$dc->table]['list']['operations'],
array_flip(['show'])
);
}
/** @var Input $input */
$input = $this->framework->getAdapter(Input::class);
// Get the news categories root set previously in session (see #137)
if (isset($_SESSION['NEWS_CATEGORIES_ROOT']) && $input->get('picker')) {
$GLOBALS['TL_DCA'][$dc->table]['list']['sorting']['root'] = $_SESSION['NEWS_CATEGORIES_ROOT'];
unset($_SESSION['NEWS_CATEGORIES_ROOT']);
} else {
unset($GLOBALS['TL_DCA'][$dc->table]['list']['sorting']['root']);
}
// Limit the allowed roots for the user
if (null !== ($roots = $this->permissionChecker->getUserAllowedRoots())) {
if (isset($GLOBALS['TL_DCA'][$dc->table]['list']['sorting']['root']) && is_array($GLOBALS['TL_DCA'][$dc->table]['list']['sorting']['root'])) {
$GLOBALS['TL_DCA'][$dc->table]['list']['sorting']['root'] = array_intersect($GLOBALS['TL_DCA'][$dc->table]['list']['sorting']['root'], $roots);
} else {
$GLOBALS['TL_DCA'][$dc->table]['list']['sorting']['root'] = $roots;
}
// Check current action
switch ($action = $input->get('act')) {
case 'edit':
$categoryId = (int) $input->get('id');
// Dynamically add the record to the user profile
if (!$this->permissionChecker->isUserAllowedNewsCategory($categoryId)) {
/** @var \Symfony\Component\HttpFoundation\Session\Attribute\AttributeBagInterface $sessionBag */
$sessionBag = $this->session->getbag('contao_backend');
$newRecords = $sessionBag->get('new_records');
$newRecords = \is_array($newRecords[$dc->table]) ? \array_map('intval', $newRecords[$dc->table]) : [];
if (\in_array($categoryId, $newRecords, true)) {
$this->permissionChecker->addCategoryToAllowedRoots($categoryId);
}
}
// no break;
case 'copy':
case 'delete':
case 'show':
$categoryId = (int) $input->get('id');
if (!$this->permissionChecker->isUserAllowedNewsCategory($categoryId)) {
throw new AccessDeniedException(\sprintf('Not enough permissions to %s news category ID %s.', $action, $categoryId));
}
break;
case 'editAll':
case 'deleteAll':
case 'overrideAll':
$session = $this->session->all();
$session['CURRENT']['IDS'] = \array_intersect($session['CURRENT']['IDS'], $roots);
$this->session->replace($session);
break;
}
}
}
|
On data container load.
@param DataContainer $dc
|
entailment
|
public function onPasteButtonCallback(DataContainer $dc, array $row, $table, $cr, array $clipboard = null)
{
$disablePA = false;
$disablePI = false;
// Disable all buttons if there is a circular reference
if (null !== $clipboard && (
('cut' === $clipboard['mode'] && ($cr || (int) $clipboard['id'] === (int) $row['id']))
|| ('cutAll' === $clipboard['mode'] && ($cr || \in_array((int) $row['id'], \array_map('intval', $clipboard['id']), true)))
)
) {
$disablePA = true;
$disablePI = true;
}
$return = '';
if ($row['id'] > 0) {
$return = $this->generatePasteImage('pasteafter', $disablePA, $table, $row, $clipboard);
}
return $return.$this->generatePasteImage('pasteinto', $disablePI, $table, $row, $clipboard);
}
|
On paste button callback.
@param DataContainer $dc
@param array $row
@param string $table
@param bool $cr
@param array|null $clipboard
@return string
|
entailment
|
public function onLabelCallback(array $row, $label, DataContainer $dc, $attributes)
{
/** @var Image $imageAdapter */
$imageAdapter = $this->framework->getAdapter(Image::class);
// Align the icon with the text
if (false !== \stripos($attributes, 'style="')) {
$attributes = \str_replace('style="', 'style="vertical-align:text-top;', $attributes);
} else {
$attributes .= \trim($attributes.' style="vertical-align:text-top;"');
}
return $imageAdapter->getHtml('iconPLAIN.svg', '', $attributes).' '.$label;
}
|
On label callback.
@param array $row
@param string $label
@param DataContainer $dc
@param string $attributes
@return string
|
entailment
|
public function onGenerateAlias($value, DataContainer $dc)
{
$autoAlias = false;
// Generate alias if there is none
if (!$value) {
$autoAlias = true;
$value = StringUtil::generateAlias($dc->activeRecord->frontendTitle ?: $dc->activeRecord->title);
}
if (MultilingualHelper::isActive() && $dc instanceof Driver) {
$exists = $this->db->fetchColumn(
"SELECT id FROM {$dc->table} WHERE alias=? AND id!=? AND {$dc->getLanguageColumn()}=?",
[$value, $dc->activeRecord->id, $dc->getCurrentLanguage()]
);
} else {
$exists = $this->db->fetchColumn(
"SELECT id FROM {$dc->table} WHERE alias=? AND id!=?",
[$value, $dc->activeRecord->id]
);
}
// Check whether the category alias exists
if ($exists) {
if ($autoAlias) {
$value .= '-'.$dc->activeRecord->id;
} else {
throw new \RuntimeException(\sprintf($GLOBALS['TL_LANG']['ERR']['aliasExists'], $value));
}
}
return $value;
}
|
On generate the category alias.
@param string $value
@param DataContainer $dc
@throws \RuntimeException
@return string
|
entailment
|
private function generatePasteImage($type, $disabled, $table, array $row, array $clipboard = null)
{
/**
* @var Backend
* @var Image $imageAdapter
*/
$backendAdapter = $this->framework->getAdapter(Backend::class);
$imageAdapter = $this->framework->getAdapter(Image::class);
if ($disabled) {
return $imageAdapter->getHtml($type.'_.svg').' ';
}
$url = \sprintf('act=%s&mode=%s&pid=%s', $clipboard['mode'], ('pasteafter' === $type ? 1 : 2), $row['id']);
// Add the ID to the URL if the clipboard does not contain any
if (!\is_array($clipboard['id'])) {
$url .= '&id='.$clipboard['id'];
}
return \sprintf(
'<a href="%s" title="%s" onclick="Backend.getScrollOffset()">%s</a> ',
$backendAdapter->addToUrl($url),
specialchars(\sprintf($GLOBALS['TL_LANG'][$table][$type][1], $row['id'])),
$imageAdapter->getHtml($type.'.svg', \sprintf($GLOBALS['TL_LANG'][$table][$type][1], $row['id']))
);
}
|
Generate the paste image.
@param string $type
@param bool $disabled
@param string $table
@param array $row
@param array|null $clipboard
@return string
|
entailment
|
public function onParseArticles(FrontendTemplate $template, array $data, Module $module)
{
/** @var NewsCategoryModel $newsCategoryModelAdapter */
$newsCategoryModelAdapter = $this->framework->getAdapter(NewsCategoryModel::class);
if (null === ($models = $newsCategoryModelAdapter->findPublishedByNews($data['id']))) {
return;
}
$this->addCategoriesToTemplate($template, $module, $models);
}
|
On parse the articles.
@param FrontendTemplate $template
@param array $data
@param Module $module
|
entailment
|
private function addCategoriesToTemplate(FrontendTemplate $template, Module $module, Collection $categories)
{
$data = [];
$list = [];
$cssClasses = trimsplit(' ', $template->class);
/** @var NewsCategoryModel $category */
foreach ($categories as $category) {
// Skip the categories not eligible for the current module
if (!$this->manager->isVisibleForModule($category, $module)) {
continue;
}
// Add category to data and list
$data[$category->id] = $this->generateCategoryData($category, $module);
$list[$category->id] = $category->getTitle();
// Add the category CSS classes to news class
$cssClasses = \array_merge($cssClasses, trimsplit(' ', $category->getCssClass()));
}
// Sort the categories data alphabetically
\uasort($data, function ($a, $b) {
return \strnatcasecmp($a['name'], $b['name']);
});
// Sort the category list alphabetically
\asort($list);
$template->categories = $data;
$template->categoriesList = $list;
if (count($cssClasses = \array_unique($cssClasses)) > 0) {
$template->class = ' ' . \implode(' ', $cssClasses);
}
}
|
Add categories to the template.
@param FrontendTemplate $template
@param Module $module
@param Collection $categories
|
entailment
|
private function generateCategoryData(NewsCategoryModel $category, Module $module)
{
$data = $category->row();
$data['model'] = $category;
$data['name'] = $category->getTitle();
$data['class'] = $category->getCssClass();
$data['href'] = '';
$data['hrefWithParam'] = '';
$data['targetPage'] = null;
/** @var StringUtil $stringUtilAdapter */
$stringUtilAdapter = $this->framework->getAdapter(StringUtil::class);
$data['linkTitle'] = $stringUtilAdapter->specialchars($data['name']);
/** @var PageModel $pageAdapter */
$pageAdapter = $this->framework->getAdapter(PageModel::class);
// Overwrite the category links with filter page set in module
if ($module->news_categoryFilterPage && null !== ($targetPage = $pageAdapter->findPublishedById($module->news_categoryFilterPage))) {
$data['href'] = $this->manager->generateUrl($category, $targetPage);
$data['hrefWithParam'] = $data['href'];
$data['targetPage'] = $targetPage;
} elseif (null !== ($targetPage = $this->manager->getTargetPage($category))) {
// Add the category target page and URLs
$data['href'] = $targetPage->getFrontendUrl();
$data['hrefWithParam'] = $this->manager->generateUrl($category, $targetPage);
$data['targetPage'] = $targetPage;
}
// Register a function to generate category URL manually
$data['generateUrl'] = function (PageModel $page, $absolute = false) use ($category) {
return $this->manager->generateUrl($category, $page, $absolute);
};
// Add the image
if (null !== ($image = $this->manager->getImage($category))) {
/** @var Controller $controllerAdapter */
$controllerAdapter = $this->framework->getAdapter(Controller::class);
$data['image'] = new \stdClass();
$controllerAdapter->addImageToTemplate($data['image'], ['singleSRC' => $image->path, 'size' => $module->news_categoryImgSize]);
} else {
$data['image'] = null;
}
return $data;
}
|
Generate the category data.
@param NewsCategoryModel $category
@param Module $module
@return array
|
entailment
|
public function generate()
{
$values = [];
// Can be an array
if (!empty($this->varValue) && null !== ($categories = NewsCategoryModel::findMultipleByIds((array) $this->varValue))) {
/** @var NewsCategoryModel $category */
foreach ($categories as $category) {
$values[$category->id] = Image::getHtml('iconPLAIN.svg').' '.$category->title;
}
}
$return = '<input type="hidden" name="'.$this->strName.'" id="ctrl_'.$this->strId.'" value="'.implode(',', array_keys($values)).'">'.($this->sorting ? '
<input type="hidden" name="'.$this->strOrderName.'" id="ctrl_'.$this->strOrderId.'" value="'.$this->{$this->orderField}.'">' : '').'
<div class="selector_container">'.(($this->sorting && count($values) > 1) ? '
<p class="sort_hint">'.$GLOBALS['TL_LANG']['MSC']['dragItemsHint'].'</p>' : '').'
<ul id="sort_'.$this->strId.'" class="'.($this->sorting ? 'sortable' : '').'">';
foreach ($values as $k => $v) {
$return .= '<li data-id="'.$k.'">'.$v.'</li>';
}
$return .= '</ul>';
$pickerBuilder = System::getContainer()->get('contao.picker.builder');
if (!$pickerBuilder->supportsContext('newsCategories')) {
$return .= '
<p><button class="tl_submit" disabled>'.$GLOBALS['TL_LANG']['MSC']['changeSelection'].'</button></p>';
} else {
$extras = ['fieldType' => $this->fieldType];
if (is_array($this->rootNodes)) {
$extras['rootNodes'] = array_values($this->rootNodes);
}
$return .= '
<p><a href="'.ampersand($pickerBuilder->getUrl('newsCategories', $extras)).'" class="tl_submit" id="pt_'.$this->strName.'">'.$GLOBALS['TL_LANG']['MSC']['changeSelection'].'</a></p>
<script>
$("pt_'.$this->strName.'").addEvent("click", function(e) {
e.preventDefault();
Backend.openModalSelector({
"id": "tl_listing",
"title": "'.StringUtil::specialchars(str_replace("'", "\\'", $GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->strField]['label'][0])).'",
"url": this.href + document.getElementById("ctrl_'.$this->strId.'").value,
"callback": function(table, value) {
new Request.Contao({
evalScripts: false,
onSuccess: function(txt, json) {
$("ctrl_'.$this->strId.'").getParent("div").set("html", json.content);
json.javascript && Browser.exec(json.javascript);
}
}).post({"action":"reloadNewsCategoriesWidget", "name":"'.$this->strId.'", "value":value.join("\t"), "REQUEST_TOKEN":"'.REQUEST_TOKEN.'"});
}
});
});
</script>'.($this->sorting ? '
<script>Backend.makeMultiSrcSortable("sort_'.$this->strId.'", "ctrl_'.$this->strId.'", "ctrl_'.$this->strId.'")</script>' : '');
}
$return = '<div>'.$return.'</div></div>';
return $return;
}
|
Generate the widget and return it as string.
@return string
|
entailment
|
protected function validator($input)
{
$this->checkValue($input);
if ($this->hasErrors()) {
return '';
}
if (!$input) {
if ($this->mandatory) {
$this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['mandatory'], $this->strLabel));
}
return '';
} elseif (false === strpos($input, ',')) {
return $this->multiple ? [(int) $input] : (int) $input;
}
$arrValue = array_map('intval', array_filter(explode(',', $input)));
return $this->multiple ? $arrValue : $arrValue[0];
}
|
Return an array if the "multiple" attribute is set.
@param mixed $input
@return mixed
|
entailment
|
protected function checkValue($input)
{
if ('' === $input || !is_array($this->rootNodes)) {
return;
}
if (false === strpos($input, ',')) {
$ids = [(int) $input];
} else {
$ids = array_map('intval', array_filter(explode(',', $input)));
}
if (count(array_diff($ids, array_merge($this->rootNodes, Database::getInstance()->getChildRecords($this->rootNodes, 'tl_news_category')))) > 0) {
$this->addError($GLOBALS['TL_LANG']['ERR']['invalidPages']);
}
}
|
Check the selected value.
@param string $input
|
entailment
|
public function onGetNewsModules()
{
$modules = [];
$records = $this->db->fetchAll("SELECT m.id, m.name, t.name AS theme FROM tl_module m LEFT JOIN tl_theme t ON m.pid=t.id WHERE m.type IN ('newslist', 'newsarchive') ORDER BY t.name, m.name");
foreach ($records as $record) {
$modules[$record['theme']][$record['id']] = \sprintf('%s (ID %s)', $record['name'], $record['id']);
}
return $modules;
}
|
Get news modules and return them as array.
@return array
|
entailment
|
public function getCriteriaForArchiveModule(array $archives, $begin, $end, Module $module)
{
$criteria = new NewsCriteria($this->framework);
try {
$criteria->setBasicCriteria($archives, $module->news_order);
// Set the time frame
$criteria->setTimeFrame($begin, $end);
// Set the regular list criteria
$this->setRegularListCriteria($criteria, $module);
} catch (NoNewsException $e) {
return null;
}
return $criteria;
}
|
Get the criteria for archive module.
@param array $archives
@param int $begin
@param int $end
@param Module $module
@return NewsCriteria|null
|
entailment
|
public function getCriteriaForListModule(array $archives, $featured, Module $module)
{
$criteria = new NewsCriteria($this->framework);
try {
$criteria->setBasicCriteria($archives, $module->news_order);
// Set the featured filter
if (null !== $featured) {
$criteria->setFeatured($featured);
}
// Set the criteria for related categories
if ($module->news_relatedCategories) {
$this->setRelatedListCriteria($criteria, $module);
} else {
// Set the regular list criteria
$this->setRegularListCriteria($criteria, $module);
}
} catch (NoNewsException $e) {
return null;
}
return $criteria;
}
|
Get the criteria for list module.
@param array $archives
@param bool|null $featured
@param Module $module
@return NewsCriteria|null
|
entailment
|
public function getCriteriaForMenuModule(array $archives, Module $module)
{
$criteria = new NewsCriteria($this->framework);
try {
$criteria->setBasicCriteria($archives, $module->news_order);
// Set the regular list criteria
$this->setRegularListCriteria($criteria, $module);
} catch (NoNewsException $e) {
return null;
}
return $criteria;
}
|
Get the criteria for menu module.
@param array $archives
@param Module $module
@return NewsCriteria|null
|
entailment
|
private function setRegularListCriteria(NewsCriteria $criteria, Module $module)
{
// Filter by default categories
if (\count($default = StringUtil::deserialize($module->news_filterDefault, true)) > 0) {
$criteria->setDefaultCategories($default);
}
// Filter by multiple active categories
if ($module->news_filterCategoriesCumulative) {
/** @var Input $input */
$input = $this->framework->getAdapter(Input::class);
$param = $this->manager->getParameterName();
if ($aliases = $input->get($param)) {
$aliases = StringUtil::trimsplit(CumulativeFilterModule::getCategorySeparator(), $aliases);
$aliases = array_unique(array_filter($aliases));
if (count($aliases) > 0) {
/** @var NewsCategoryModel $model */
$model = $this->framework->getAdapter(NewsCategoryModel::class);
foreach ($aliases as $alias) {
// Return null if the category does not exist
if (null === ($category = $model->findPublishedByIdOrAlias($alias))) {
throw new CategoryNotFoundException(sprintf('News category "%s" was not found', $alias));
}
$criteria->setCategory($category->id, (bool) $module->news_filterPreserve, (bool) $module->news_includeSubcategories);
}
}
}
return;
}
// Filter by active category
if ($module->news_filterCategories) {
/** @var Input $input */
$input = $this->framework->getAdapter(Input::class);
$param = $this->manager->getParameterName();
if ($alias = $input->get($param)) {
/** @var NewsCategoryModel $model */
$model = $this->framework->getAdapter(NewsCategoryModel::class);
// Return null if the category does not exist
if (null === ($category = $model->findPublishedByIdOrAlias($alias))) {
throw new CategoryNotFoundException(sprintf('News category "%s" was not found', $alias));
}
$criteria->setCategory($category->id, (bool) $module->news_filterPreserve, (bool) $module->news_includeSubcategories);
}
}
}
|
Set the regular list criteria.
@param NewsCriteria $criteria
@param Module $module
@throws CategoryNotFoundException
@throws NoNewsException
|
entailment
|
private function setRelatedListCriteria(NewsCriteria $criteria, Module $module)
{
if (null === ($news = $module->currentNews)) {
throw new NoNewsException();
}
/** @var Model $adapter */
$adapter = $this->framework->getAdapter(Model::class);
$categories = \array_unique($adapter->getRelatedValues($news->getTable(), 'categories', $news->id));
// This news has no news categories assigned
if (0 === \count($categories)) {
throw new NoNewsException();
}
$categories = \array_map('intval', $categories);
$excluded = $this->db->fetchAll('SELECT id FROM tl_news_category WHERE excludeInRelated=1');
// Exclude the categories
foreach ($excluded as $category) {
if (false !== ($index = \array_search((int) $category['id'], $categories, true))) {
unset($categories[$index]);
}
}
// Exclude categories by root
if ($module->news_categoriesRoot > 0) {
$categories = array_intersect($categories, NewsCategoryModel::getAllSubcategoriesIds($module->news_categoriesRoot));
}
// There are no categories left
if (0 === \count($categories)) {
throw new NoNewsException();
}
$criteria->setDefaultCategories($categories, (bool) $module->news_includeSubcategories, $module->news_relatedCategoriesOrder);
$criteria->setExcludedNews([$news->id]);
}
|
Set the related list criteria.
@param NewsCriteria $criteria
@param Module $module
@throws NoNewsException
|
entailment
|
private function updateAlias(ChangelanguageNavigationEvent $event)
{
/** @var NewsCategoryModel $modelAdapter */
$modelAdapter = $this->framework->getAdapter(NewsCategoryModel::class);
$param = $this->manager->getParameterName();
if (!($alias = $event->getUrlParameterBag()->getUrlAttribute($param))) {
return;
}
$model = $modelAdapter->findPublishedByIdOrAlias($alias);
// Set the alias only for multilingual models
if (null !== $model && $model instanceof Multilingual) {
$event->getUrlParameterBag()->setUrlAttribute(
$param,
$model->getAlias($event->getNavigationItem()->getRootPage()->rootLanguage)
);
}
}
|
Update the category alias value.
@param ChangelanguageNavigationEvent $event
|
entailment
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.