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
symphonycms/symphony-2
symphony/lib/toolkit/class.widget.php
Widget.TableHead
public static function TableHead(array $columns = null) { $thead = new XMLElement('thead'); $tr = new XMLElement('tr'); if (is_array($columns) && !empty($columns)) { foreach ($columns as $col) { $th = new XMLElement('th'); if (is_object($col[0])) { $th->appendChild($col[0]); } else { $th->setValue($col[0]); } if ($col[1] && $col[1] != '') { $th->setAttribute('scope', $col[1]); } if (!empty($col[2]) && is_array($col[2])) { $th->setAttributeArray($col[2]); } $tr->appendChild($th); } } $thead->appendChild($tr); return $thead; }
php
public static function TableHead(array $columns = null) { $thead = new XMLElement('thead'); $tr = new XMLElement('tr'); if (is_array($columns) && !empty($columns)) { foreach ($columns as $col) { $th = new XMLElement('th'); if (is_object($col[0])) { $th->appendChild($col[0]); } else { $th->setValue($col[0]); } if ($col[1] && $col[1] != '') { $th->setAttribute('scope', $col[1]); } if (!empty($col[2]) && is_array($col[2])) { $th->setAttributeArray($col[2]); } $tr->appendChild($th); } } $thead->appendChild($tr); return $thead; }
[ "public", "static", "function", "TableHead", "(", "array", "$", "columns", "=", "null", ")", "{", "$", "thead", "=", "new", "XMLElement", "(", "'thead'", ")", ";", "$", "tr", "=", "new", "XMLElement", "(", "'tr'", ")", ";", "if", "(", "is_array", "(", "$", "columns", ")", "&&", "!", "empty", "(", "$", "columns", ")", ")", "{", "foreach", "(", "$", "columns", "as", "$", "col", ")", "{", "$", "th", "=", "new", "XMLElement", "(", "'th'", ")", ";", "if", "(", "is_object", "(", "$", "col", "[", "0", "]", ")", ")", "{", "$", "th", "->", "appendChild", "(", "$", "col", "[", "0", "]", ")", ";", "}", "else", "{", "$", "th", "->", "setValue", "(", "$", "col", "[", "0", "]", ")", ";", "}", "if", "(", "$", "col", "[", "1", "]", "&&", "$", "col", "[", "1", "]", "!=", "''", ")", "{", "$", "th", "->", "setAttribute", "(", "'scope'", ",", "$", "col", "[", "1", "]", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "col", "[", "2", "]", ")", "&&", "is_array", "(", "$", "col", "[", "2", "]", ")", ")", "{", "$", "th", "->", "setAttributeArray", "(", "$", "col", "[", "2", "]", ")", ";", "}", "$", "tr", "->", "appendChild", "(", "$", "th", ")", ";", "}", "}", "$", "thead", "->", "appendChild", "(", "$", "tr", ")", ";", "return", "$", "thead", ";", "}" ]
Generates a XMLElement representation of `<thead>` from an array containing column names and any other attributes. @param array $columns An array of column arrays, where the first item is the name of the column, the second is the scope attribute, and the third is an array of possible attributes. ` array( array('Column Name', 'scope', array('class'=>'th-class')) ) ` @return XMLElement
[ "Generates", "a", "XMLElement", "representation", "of", "<thead", ">", "from", "an", "array", "containing", "column", "names", "and", "any", "other", "attributes", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.widget.php#L387-L417
symphonycms/symphony-2
symphony/lib/toolkit/class.widget.php
Widget.TableBody
public static function TableBody(array $rows, $class = null, $id = null, array $attributes = null) { General::ensureType(array( 'class' => array('var' => $class, 'type' => 'string', 'optional' => true), 'id' => array('var' => $id, 'type' => 'string', 'optional' => true) )); $tbody = new XMLElement('tbody'); if ($class) { $tbody->setAttribute('class', $class); } if ($id) { $tbody->setAttribute('id', $id); } if (is_array($attributes) && !empty($attributes)) { $tbody->setAttributeArray($attributes); } foreach ($rows as $row) { $tbody->appendChild($row); } return $tbody; }
php
public static function TableBody(array $rows, $class = null, $id = null, array $attributes = null) { General::ensureType(array( 'class' => array('var' => $class, 'type' => 'string', 'optional' => true), 'id' => array('var' => $id, 'type' => 'string', 'optional' => true) )); $tbody = new XMLElement('tbody'); if ($class) { $tbody->setAttribute('class', $class); } if ($id) { $tbody->setAttribute('id', $id); } if (is_array($attributes) && !empty($attributes)) { $tbody->setAttributeArray($attributes); } foreach ($rows as $row) { $tbody->appendChild($row); } return $tbody; }
[ "public", "static", "function", "TableBody", "(", "array", "$", "rows", ",", "$", "class", "=", "null", ",", "$", "id", "=", "null", ",", "array", "$", "attributes", "=", "null", ")", "{", "General", "::", "ensureType", "(", "array", "(", "'class'", "=>", "array", "(", "'var'", "=>", "$", "class", ",", "'type'", "=>", "'string'", ",", "'optional'", "=>", "true", ")", ",", "'id'", "=>", "array", "(", "'var'", "=>", "$", "id", ",", "'type'", "=>", "'string'", ",", "'optional'", "=>", "true", ")", ")", ")", ";", "$", "tbody", "=", "new", "XMLElement", "(", "'tbody'", ")", ";", "if", "(", "$", "class", ")", "{", "$", "tbody", "->", "setAttribute", "(", "'class'", ",", "$", "class", ")", ";", "}", "if", "(", "$", "id", ")", "{", "$", "tbody", "->", "setAttribute", "(", "'id'", ",", "$", "id", ")", ";", "}", "if", "(", "is_array", "(", "$", "attributes", ")", "&&", "!", "empty", "(", "$", "attributes", ")", ")", "{", "$", "tbody", "->", "setAttributeArray", "(", "$", "attributes", ")", ";", "}", "foreach", "(", "$", "rows", "as", "$", "row", ")", "{", "$", "tbody", "->", "appendChild", "(", "$", "row", ")", ";", "}", "return", "$", "tbody", ";", "}" ]
Generates a XMLElement representation of `<tbody>` from an array containing `<tr>` XMLElements @see toolkit.Widget#TableRow() @param array $rows An array of XMLElements of `<tr>`'s. @param string $class (optional) The class attribute of the resulting `<tbody>` @param string $id (optional) The id attribute of the resulting `<tbody>` @param array $attributes (optional) Any additional attributes can be included in an associative array with the key being the name and the value being the value of the attribute. Attributes set from this array will override existing attributes set by previous params. @throws InvalidArgumentException @return XMLElement
[ "Generates", "a", "XMLElement", "representation", "of", "<tbody", ">", "from", "an", "array", "containing", "<tr", ">", "XMLElements" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.widget.php#L438-L464
symphonycms/symphony-2
symphony/lib/toolkit/class.widget.php
Widget.TableRow
public static function TableRow(array $cells, $class = null, $id = null, $rowspan = null, Array $attributes = null) { General::ensureType(array( 'class' => array('var' => $class, 'type' => 'string', 'optional' => true), 'id' => array('var' => $id, 'type' => 'string', 'optional' => true), 'rowspan' => array('var' => $rowspan, 'type' => 'int', 'optional' => true) )); $tr = new XMLElement('tr'); if ($class) { $tr->setAttribute('class', $class); } if ($id) { $tr->setAttribute('id', $id); } if ($rowspan) { $tr->setAttribute('rowspan', $rowspan); } if (is_array($attributes) && !empty($attributes)) { $tr->setAttributeArray($attributes); } foreach ($cells as $cell) { $tr->appendChild($cell); } return $tr; }
php
public static function TableRow(array $cells, $class = null, $id = null, $rowspan = null, Array $attributes = null) { General::ensureType(array( 'class' => array('var' => $class, 'type' => 'string', 'optional' => true), 'id' => array('var' => $id, 'type' => 'string', 'optional' => true), 'rowspan' => array('var' => $rowspan, 'type' => 'int', 'optional' => true) )); $tr = new XMLElement('tr'); if ($class) { $tr->setAttribute('class', $class); } if ($id) { $tr->setAttribute('id', $id); } if ($rowspan) { $tr->setAttribute('rowspan', $rowspan); } if (is_array($attributes) && !empty($attributes)) { $tr->setAttributeArray($attributes); } foreach ($cells as $cell) { $tr->appendChild($cell); } return $tr; }
[ "public", "static", "function", "TableRow", "(", "array", "$", "cells", ",", "$", "class", "=", "null", ",", "$", "id", "=", "null", ",", "$", "rowspan", "=", "null", ",", "Array", "$", "attributes", "=", "null", ")", "{", "General", "::", "ensureType", "(", "array", "(", "'class'", "=>", "array", "(", "'var'", "=>", "$", "class", ",", "'type'", "=>", "'string'", ",", "'optional'", "=>", "true", ")", ",", "'id'", "=>", "array", "(", "'var'", "=>", "$", "id", ",", "'type'", "=>", "'string'", ",", "'optional'", "=>", "true", ")", ",", "'rowspan'", "=>", "array", "(", "'var'", "=>", "$", "rowspan", ",", "'type'", "=>", "'int'", ",", "'optional'", "=>", "true", ")", ")", ")", ";", "$", "tr", "=", "new", "XMLElement", "(", "'tr'", ")", ";", "if", "(", "$", "class", ")", "{", "$", "tr", "->", "setAttribute", "(", "'class'", ",", "$", "class", ")", ";", "}", "if", "(", "$", "id", ")", "{", "$", "tr", "->", "setAttribute", "(", "'id'", ",", "$", "id", ")", ";", "}", "if", "(", "$", "rowspan", ")", "{", "$", "tr", "->", "setAttribute", "(", "'rowspan'", ",", "$", "rowspan", ")", ";", "}", "if", "(", "is_array", "(", "$", "attributes", ")", "&&", "!", "empty", "(", "$", "attributes", ")", ")", "{", "$", "tr", "->", "setAttributeArray", "(", "$", "attributes", ")", ";", "}", "foreach", "(", "$", "cells", "as", "$", "cell", ")", "{", "$", "tr", "->", "appendChild", "(", "$", "cell", ")", ";", "}", "return", "$", "tr", ";", "}" ]
Generates a XMLElement representation of `<tr>` from an array containing column names and any other attributes. @param array $cells An array of XMLElements of `<td>`'s. See Widget::TableData @param string $class (optional) The class attribute of the resulting `<tr>` @param string $id (optional) The id attribute of the resulting `<tr>` @param integer $rowspan (optional) The rowspan attribute of the resulting `<tr>` @param array $attributes (optional) Any additional attributes can be included in an associative array with the key being the name and the value being the value of the attribute. Attributes set from this array will override existing attributes set by previous params. @throws InvalidArgumentException @return XMLElement
[ "Generates", "a", "XMLElement", "representation", "of", "<tr", ">", "from", "an", "array", "containing", "column", "names", "and", "any", "other", "attributes", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.widget.php#L486-L517
symphonycms/symphony-2
symphony/lib/toolkit/class.widget.php
Widget.TableData
public static function TableData($value, $class = null, $id = null, $colspan = null, Array $attributes = null) { General::ensureType(array( 'class' => array('var' => $class, 'type' => 'string', 'optional' => true), 'id' => array('var' => $id, 'type' => 'string', 'optional' => true), 'colspan' => array('var' => $colspan, 'type' => 'int', 'optional' => true) )); if (is_object($value)) { $td = new XMLElement('td'); $td->appendChild($value); } else { $td = new XMLElement('td', $value); } if ($class) { $td->setAttribute('class', $class); } if ($id) { $td->setAttribute('id', $id); } if ($colspan) { $td->setAttribute('colspan', $colspan); } if (is_array($attributes) && !empty($attributes)) { $td->setAttributeArray($attributes); } return $td; }
php
public static function TableData($value, $class = null, $id = null, $colspan = null, Array $attributes = null) { General::ensureType(array( 'class' => array('var' => $class, 'type' => 'string', 'optional' => true), 'id' => array('var' => $id, 'type' => 'string', 'optional' => true), 'colspan' => array('var' => $colspan, 'type' => 'int', 'optional' => true) )); if (is_object($value)) { $td = new XMLElement('td'); $td->appendChild($value); } else { $td = new XMLElement('td', $value); } if ($class) { $td->setAttribute('class', $class); } if ($id) { $td->setAttribute('id', $id); } if ($colspan) { $td->setAttribute('colspan', $colspan); } if (is_array($attributes) && !empty($attributes)) { $td->setAttributeArray($attributes); } return $td; }
[ "public", "static", "function", "TableData", "(", "$", "value", ",", "$", "class", "=", "null", ",", "$", "id", "=", "null", ",", "$", "colspan", "=", "null", ",", "Array", "$", "attributes", "=", "null", ")", "{", "General", "::", "ensureType", "(", "array", "(", "'class'", "=>", "array", "(", "'var'", "=>", "$", "class", ",", "'type'", "=>", "'string'", ",", "'optional'", "=>", "true", ")", ",", "'id'", "=>", "array", "(", "'var'", "=>", "$", "id", ",", "'type'", "=>", "'string'", ",", "'optional'", "=>", "true", ")", ",", "'colspan'", "=>", "array", "(", "'var'", "=>", "$", "colspan", ",", "'type'", "=>", "'int'", ",", "'optional'", "=>", "true", ")", ")", ")", ";", "if", "(", "is_object", "(", "$", "value", ")", ")", "{", "$", "td", "=", "new", "XMLElement", "(", "'td'", ")", ";", "$", "td", "->", "appendChild", "(", "$", "value", ")", ";", "}", "else", "{", "$", "td", "=", "new", "XMLElement", "(", "'td'", ",", "$", "value", ")", ";", "}", "if", "(", "$", "class", ")", "{", "$", "td", "->", "setAttribute", "(", "'class'", ",", "$", "class", ")", ";", "}", "if", "(", "$", "id", ")", "{", "$", "td", "->", "setAttribute", "(", "'id'", ",", "$", "id", ")", ";", "}", "if", "(", "$", "colspan", ")", "{", "$", "td", "->", "setAttribute", "(", "'colspan'", ",", "$", "colspan", ")", ";", "}", "if", "(", "is_array", "(", "$", "attributes", ")", "&&", "!", "empty", "(", "$", "attributes", ")", ")", "{", "$", "td", "->", "setAttributeArray", "(", "$", "attributes", ")", ";", "}", "return", "$", "td", ";", "}" ]
Generates a XMLElement representation of a `<td>`. @param XMLElement|string $value Either an XMLElement object, or a string for the value of the resulting `<td>` @param string $class (optional) The class attribute of the resulting `<td>` @param string $id (optional) The id attribute of the resulting `<td>` @param integer $colspan (optional) The colspan attribute of the resulting `<td>` @param array $attributes (optional) Any additional attributes can be included in an associative array with the key being the name and the value being the value of the attribute. Attributes set from this array will override existing attributes set by previous params. @throws InvalidArgumentException @return XMLElement
[ "Generates", "a", "XMLElement", "representation", "of", "a", "<td", ">", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.widget.php#L539-L571
symphonycms/symphony-2
symphony/lib/toolkit/class.widget.php
Widget.Time
public static function Time($string = 'now', $format = __SYM_TIME_FORMAT__, $pubdate = false) { // Parse date $date = DateTimeObj::parse($string); // Create element $obj = new XMLElement('time', Lang::localizeDate($date->format($format))); $obj->setAttribute('datetime', $date->format(DateTime::ISO8601)); $obj->setAttribute('utc', $date->format('U')); // Pubdate? if ($pubdate === true) { $obj->setAttribute('pubdate', 'pubdate'); } return $obj; }
php
public static function Time($string = 'now', $format = __SYM_TIME_FORMAT__, $pubdate = false) { // Parse date $date = DateTimeObj::parse($string); // Create element $obj = new XMLElement('time', Lang::localizeDate($date->format($format))); $obj->setAttribute('datetime', $date->format(DateTime::ISO8601)); $obj->setAttribute('utc', $date->format('U')); // Pubdate? if ($pubdate === true) { $obj->setAttribute('pubdate', 'pubdate'); } return $obj; }
[ "public", "static", "function", "Time", "(", "$", "string", "=", "'now'", ",", "$", "format", "=", "__SYM_TIME_FORMAT__", ",", "$", "pubdate", "=", "false", ")", "{", "// Parse date", "$", "date", "=", "DateTimeObj", "::", "parse", "(", "$", "string", ")", ";", "// Create element", "$", "obj", "=", "new", "XMLElement", "(", "'time'", ",", "Lang", "::", "localizeDate", "(", "$", "date", "->", "format", "(", "$", "format", ")", ")", ")", ";", "$", "obj", "->", "setAttribute", "(", "'datetime'", ",", "$", "date", "->", "format", "(", "DateTime", "::", "ISO8601", ")", ")", ";", "$", "obj", "->", "setAttribute", "(", "'utc'", ",", "$", "date", "->", "format", "(", "'U'", ")", ")", ";", "// Pubdate?", "if", "(", "$", "pubdate", "===", "true", ")", "{", "$", "obj", "->", "setAttribute", "(", "'pubdate'", ",", "'pubdate'", ")", ";", "}", "return", "$", "obj", ";", "}" ]
Generates a XMLElement representation of a `<time>` @since Symphony 2.3 @param string $string A string containing date and time, defaults to the current date and time @param string $format (optional) A valid PHP date format, defaults to `__SYM_TIME_FORMAT__` @param boolean $pubdate (optional) A flag to make the given date a publish date @return XMLElement
[ "Generates", "a", "XMLElement", "representation", "of", "a", "<time", ">" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.widget.php#L585-L601
symphonycms/symphony-2
symphony/lib/toolkit/class.widget.php
Widget.Select
public static function Select($name, array $options = null, array $attributes = null) { General::ensureType(array( 'name' => array('var' => $name, 'type' => 'string') )); $obj = new XMLElement('select'); $obj->setAttribute('name', $name); $obj->setSelfClosingTag(false); if (is_array($attributes) && !empty($attributes)) { $obj->setAttributeArray($attributes); } if (!is_array($options) || empty($options)) { if (!isset($attributes['disabled'])) { $obj->setAttribute('disabled', 'disabled'); } return $obj; } foreach ($options as $o) { // Optgroup if (isset($o['label'])) { $optgroup = new XMLElement('optgroup'); $optgroup->setAttribute('label', $o['label']); if (isset($o['data-label'])) { $optgroup->setAttribute('data-label', $o['data-label']); } foreach ($o['options'] as $option) { $optgroup->appendChild( Widget::__SelectBuildOption($option) ); } $obj->appendChild($optgroup); } else { $obj->appendChild(Widget::__SelectBuildOption($o)); } } return $obj; }
php
public static function Select($name, array $options = null, array $attributes = null) { General::ensureType(array( 'name' => array('var' => $name, 'type' => 'string') )); $obj = new XMLElement('select'); $obj->setAttribute('name', $name); $obj->setSelfClosingTag(false); if (is_array($attributes) && !empty($attributes)) { $obj->setAttributeArray($attributes); } if (!is_array($options) || empty($options)) { if (!isset($attributes['disabled'])) { $obj->setAttribute('disabled', 'disabled'); } return $obj; } foreach ($options as $o) { // Optgroup if (isset($o['label'])) { $optgroup = new XMLElement('optgroup'); $optgroup->setAttribute('label', $o['label']); if (isset($o['data-label'])) { $optgroup->setAttribute('data-label', $o['data-label']); } foreach ($o['options'] as $option) { $optgroup->appendChild( Widget::__SelectBuildOption($option) ); } $obj->appendChild($optgroup); } else { $obj->appendChild(Widget::__SelectBuildOption($o)); } } return $obj; }
[ "public", "static", "function", "Select", "(", "$", "name", ",", "array", "$", "options", "=", "null", ",", "array", "$", "attributes", "=", "null", ")", "{", "General", "::", "ensureType", "(", "array", "(", "'name'", "=>", "array", "(", "'var'", "=>", "$", "name", ",", "'type'", "=>", "'string'", ")", ")", ")", ";", "$", "obj", "=", "new", "XMLElement", "(", "'select'", ")", ";", "$", "obj", "->", "setAttribute", "(", "'name'", ",", "$", "name", ")", ";", "$", "obj", "->", "setSelfClosingTag", "(", "false", ")", ";", "if", "(", "is_array", "(", "$", "attributes", ")", "&&", "!", "empty", "(", "$", "attributes", ")", ")", "{", "$", "obj", "->", "setAttributeArray", "(", "$", "attributes", ")", ";", "}", "if", "(", "!", "is_array", "(", "$", "options", ")", "||", "empty", "(", "$", "options", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "attributes", "[", "'disabled'", "]", ")", ")", "{", "$", "obj", "->", "setAttribute", "(", "'disabled'", ",", "'disabled'", ")", ";", "}", "return", "$", "obj", ";", "}", "foreach", "(", "$", "options", "as", "$", "o", ")", "{", "// Optgroup", "if", "(", "isset", "(", "$", "o", "[", "'label'", "]", ")", ")", "{", "$", "optgroup", "=", "new", "XMLElement", "(", "'optgroup'", ")", ";", "$", "optgroup", "->", "setAttribute", "(", "'label'", ",", "$", "o", "[", "'label'", "]", ")", ";", "if", "(", "isset", "(", "$", "o", "[", "'data-label'", "]", ")", ")", "{", "$", "optgroup", "->", "setAttribute", "(", "'data-label'", ",", "$", "o", "[", "'data-label'", "]", ")", ";", "}", "foreach", "(", "$", "o", "[", "'options'", "]", "as", "$", "option", ")", "{", "$", "optgroup", "->", "appendChild", "(", "Widget", "::", "__SelectBuildOption", "(", "$", "option", ")", ")", ";", "}", "$", "obj", "->", "appendChild", "(", "$", "optgroup", ")", ";", "}", "else", "{", "$", "obj", "->", "appendChild", "(", "Widget", "::", "__SelectBuildOption", "(", "$", "o", ")", ")", ";", "}", "}", "return", "$", "obj", ";", "}" ]
Generates a XMLElement representation of a `<select>`. This uses the private function `__SelectBuildOption()` to build XMLElements of options given the `$options` array. @see toolkit.Widget::__SelectBuildOption() @param string $name The name attribute of the resulting `<select>` @param array $options (optional) An array containing the data for each `<option>` for this `<select>`. If the array is associative, it is assumed that `<optgroup>` are to be created, otherwise it's an array of the containing the option data. If no options are provided an empty `<select>` XMLElement is returned. ` array( array($value, $selected, $desc, $class, $id, $attr) ) array( array('label' => 'Optgroup', 'data-label' => 'optgroup', 'options' = array( array($value, $selected, $desc, $class, $id, $attr) ) ) ` @param array $attributes (optional) Any additional attributes can be included in an associative array with the key being the name and the value being the value of the attribute. Attributes set from this array will override existing attributes set by previous params. @throws InvalidArgumentException @return XMLElement
[ "Generates", "a", "XMLElement", "representation", "of", "a", "<select", ">", ".", "This", "uses", "the", "private", "function", "__SelectBuildOption", "()", "to", "build", "XMLElements", "of", "options", "given", "the", "$options", "array", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.widget.php#L635-L681
symphonycms/symphony-2
symphony/lib/toolkit/class.widget.php
Widget.__SelectBuildOption
private static function __SelectBuildOption($option) { list($value, $selected, $desc, $class, $id, $attributes) = array_pad($option, 6, null); if (!$desc) { $desc = $value; } $obj = new XMLElement('option', "$desc"); $obj->setSelfClosingTag(false); $obj->setAttribute('value', "$value"); if (!empty($class)) { $obj->setAttribute('class', $class); } if (!empty($id)) { $obj->setAttribute('id', $id); } if (is_array($attributes) && !empty($attributes)) { $obj->setAttributeArray($attributes); } if ($selected) { $obj->setAttribute('selected', 'selected'); } return $obj; }
php
private static function __SelectBuildOption($option) { list($value, $selected, $desc, $class, $id, $attributes) = array_pad($option, 6, null); if (!$desc) { $desc = $value; } $obj = new XMLElement('option', "$desc"); $obj->setSelfClosingTag(false); $obj->setAttribute('value', "$value"); if (!empty($class)) { $obj->setAttribute('class', $class); } if (!empty($id)) { $obj->setAttribute('id', $id); } if (is_array($attributes) && !empty($attributes)) { $obj->setAttributeArray($attributes); } if ($selected) { $obj->setAttribute('selected', 'selected'); } return $obj; }
[ "private", "static", "function", "__SelectBuildOption", "(", "$", "option", ")", "{", "list", "(", "$", "value", ",", "$", "selected", ",", "$", "desc", ",", "$", "class", ",", "$", "id", ",", "$", "attributes", ")", "=", "array_pad", "(", "$", "option", ",", "6", ",", "null", ")", ";", "if", "(", "!", "$", "desc", ")", "{", "$", "desc", "=", "$", "value", ";", "}", "$", "obj", "=", "new", "XMLElement", "(", "'option'", ",", "\"$desc\"", ")", ";", "$", "obj", "->", "setSelfClosingTag", "(", "false", ")", ";", "$", "obj", "->", "setAttribute", "(", "'value'", ",", "\"$value\"", ")", ";", "if", "(", "!", "empty", "(", "$", "class", ")", ")", "{", "$", "obj", "->", "setAttribute", "(", "'class'", ",", "$", "class", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "id", ")", ")", "{", "$", "obj", "->", "setAttribute", "(", "'id'", ",", "$", "id", ")", ";", "}", "if", "(", "is_array", "(", "$", "attributes", ")", "&&", "!", "empty", "(", "$", "attributes", ")", ")", "{", "$", "obj", "->", "setAttributeArray", "(", "$", "attributes", ")", ";", "}", "if", "(", "$", "selected", ")", "{", "$", "obj", "->", "setAttribute", "(", "'selected'", ",", "'selected'", ")", ";", "}", "return", "$", "obj", ";", "}" ]
This function is used internally by the `Widget::Select()` to build an XMLElement of an `<option>` from an array. @param array $option An array containing the data a single `<option>` for this `<select>`. The array can contain the following params: string $value The value attribute of the resulting `<option>` boolean $selected Whether this `<option>` should be selected string $desc (optional) The text of the resulting `<option>`. If omitted $value will be used a default. string $class (optional) The class attribute of the resulting `<option>` string $id (optional) The id attribute of the resulting `<option>` array $attributes (optional) Any additional attributes can be included in an associative array with the key being the name and the value being the value of the attribute. Attributes set from this array will override existing attributes set by previous params. `array( array('one-shot', false, 'One Shot', 'my-option') )` @return XMLElement
[ "This", "function", "is", "used", "internally", "by", "the", "Widget", "::", "Select", "()", "to", "build", "an", "XMLElement", "of", "an", "<option", ">", "from", "an", "array", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.widget.php#L711-L740
symphonycms/symphony-2
symphony/lib/toolkit/class.widget.php
Widget.Apply
public static function Apply(array $options = null) { $fieldset = new XMLElement('fieldset', null, array('class' => 'apply')); $div = new XMLElement('div'); $div->appendChild(Widget::Label(__('Actions'), null, 'accessible', null, array( 'for' => 'with-selected' ))); $div->appendChild(Widget::Select('with-selected', $options, array( 'id' => 'with-selected' ))); $fieldset->appendChild($div); $fieldset->appendChild(new XMLElement('button', __('Apply'), array('name' => 'action[apply]', 'type' => 'submit'))); return $fieldset; }
php
public static function Apply(array $options = null) { $fieldset = new XMLElement('fieldset', null, array('class' => 'apply')); $div = new XMLElement('div'); $div->appendChild(Widget::Label(__('Actions'), null, 'accessible', null, array( 'for' => 'with-selected' ))); $div->appendChild(Widget::Select('with-selected', $options, array( 'id' => 'with-selected' ))); $fieldset->appendChild($div); $fieldset->appendChild(new XMLElement('button', __('Apply'), array('name' => 'action[apply]', 'type' => 'submit'))); return $fieldset; }
[ "public", "static", "function", "Apply", "(", "array", "$", "options", "=", "null", ")", "{", "$", "fieldset", "=", "new", "XMLElement", "(", "'fieldset'", ",", "null", ",", "array", "(", "'class'", "=>", "'apply'", ")", ")", ";", "$", "div", "=", "new", "XMLElement", "(", "'div'", ")", ";", "$", "div", "->", "appendChild", "(", "Widget", "::", "Label", "(", "__", "(", "'Actions'", ")", ",", "null", ",", "'accessible'", ",", "null", ",", "array", "(", "'for'", "=>", "'with-selected'", ")", ")", ")", ";", "$", "div", "->", "appendChild", "(", "Widget", "::", "Select", "(", "'with-selected'", ",", "$", "options", ",", "array", "(", "'id'", "=>", "'with-selected'", ")", ")", ")", ";", "$", "fieldset", "->", "appendChild", "(", "$", "div", ")", ";", "$", "fieldset", "->", "appendChild", "(", "new", "XMLElement", "(", "'button'", ",", "__", "(", "'Apply'", ")", ",", "array", "(", "'name'", "=>", "'action[apply]'", ",", "'type'", "=>", "'submit'", ")", ")", ")", ";", "return", "$", "fieldset", ";", "}" ]
Generates a XMLElement representation of a `<fieldset>` containing the "With selected…" menu. This uses the private function `__SelectBuildOption()` to build `XMLElement`'s of options given the `$options` array. @since Symphony 2.3 @see toolkit.Widget::__SelectBuildOption() @param array $options (optional) An array containing the data for each `<option>` for this `<select>`. If the array is associative, it is assumed that `<optgroup>` are to be created, otherwise it's an array of the containing the option data. If no options are provided an empty `<select>` XMLElement is returned. ` array( array($value, $selected, $desc, $class, $id, $attr) ) array( array('label' => 'Optgroup', 'options' = array( array($value, $selected, $desc, $class, $id, $attr) ) ) ` @throws InvalidArgumentException @return XMLElement
[ "Generates", "a", "XMLElement", "representation", "of", "a", "<fieldset", ">", "containing", "the", "With", "selected…", "menu", ".", "This", "uses", "the", "private", "function", "__SelectBuildOption", "()", "to", "build", "XMLElement", "s", "of", "options", "given", "the", "$options", "array", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.widget.php#L768-L782
symphonycms/symphony-2
symphony/lib/toolkit/class.widget.php
Widget.Error
public static function Error(XMLElement $element, $message) { General::ensureType(array( 'message' => array('var' => $message, 'type' => 'string') )); $div = new XMLElement('div'); $div->setAttributeArray(array('class' => 'invalid')); $div->appendChild($element); $div->appendChild(new XMLElement('p', $message)); return $div; }
php
public static function Error(XMLElement $element, $message) { General::ensureType(array( 'message' => array('var' => $message, 'type' => 'string') )); $div = new XMLElement('div'); $div->setAttributeArray(array('class' => 'invalid')); $div->appendChild($element); $div->appendChild(new XMLElement('p', $message)); return $div; }
[ "public", "static", "function", "Error", "(", "XMLElement", "$", "element", ",", "$", "message", ")", "{", "General", "::", "ensureType", "(", "array", "(", "'message'", "=>", "array", "(", "'var'", "=>", "$", "message", ",", "'type'", "=>", "'string'", ")", ")", ")", ";", "$", "div", "=", "new", "XMLElement", "(", "'div'", ")", ";", "$", "div", "->", "setAttributeArray", "(", "array", "(", "'class'", "=>", "'invalid'", ")", ")", ";", "$", "div", "->", "appendChild", "(", "$", "element", ")", ";", "$", "div", "->", "appendChild", "(", "new", "XMLElement", "(", "'p'", ",", "$", "message", ")", ")", ";", "return", "$", "div", ";", "}" ]
Will wrap a `<div>` around a desired element to trigger the default Symphony error styling. @since Symphony 2.3 @param XMLElement $element The element that should be wrapped with an error @param string $message The text for this error. This will be appended after the $element, but inside the wrapping `<div>` @throws InvalidArgumentException @return XMLElement
[ "Will", "wrap", "a", "<div", ">", "around", "a", "desired", "element", "to", "trigger", "the", "default", "Symphony", "error", "styling", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.widget.php#L797-L810
symphonycms/symphony-2
symphony/lib/toolkit/class.widget.php
Widget.Drawer
public static function Drawer($id = '', $label = '', XMLElement $content = null, $default_state = 'closed', $context = '', array $attributes = array()) { $id = Lang::createHandle($id); $contents = new XMLElement('div', $content, array( 'class' => 'contents' )); $contents->setElementStyle('html'); $drawer = new XMLElement('div', $contents, $attributes); $drawer->setAttribute('data-default-state', $default_state); $drawer->setAttribute('data-context', $context); $drawer->setAttribute('data-label', $label); $drawer->setAttribute('data-interactive', 'data-interactive'); $drawer->addClass('drawer'); $drawer->setAttribute('id', 'drawer-' . $id); return $drawer; }
php
public static function Drawer($id = '', $label = '', XMLElement $content = null, $default_state = 'closed', $context = '', array $attributes = array()) { $id = Lang::createHandle($id); $contents = new XMLElement('div', $content, array( 'class' => 'contents' )); $contents->setElementStyle('html'); $drawer = new XMLElement('div', $contents, $attributes); $drawer->setAttribute('data-default-state', $default_state); $drawer->setAttribute('data-context', $context); $drawer->setAttribute('data-label', $label); $drawer->setAttribute('data-interactive', 'data-interactive'); $drawer->addClass('drawer'); $drawer->setAttribute('id', 'drawer-' . $id); return $drawer; }
[ "public", "static", "function", "Drawer", "(", "$", "id", "=", "''", ",", "$", "label", "=", "''", ",", "XMLElement", "$", "content", "=", "null", ",", "$", "default_state", "=", "'closed'", ",", "$", "context", "=", "''", ",", "array", "$", "attributes", "=", "array", "(", ")", ")", "{", "$", "id", "=", "Lang", "::", "createHandle", "(", "$", "id", ")", ";", "$", "contents", "=", "new", "XMLElement", "(", "'div'", ",", "$", "content", ",", "array", "(", "'class'", "=>", "'contents'", ")", ")", ";", "$", "contents", "->", "setElementStyle", "(", "'html'", ")", ";", "$", "drawer", "=", "new", "XMLElement", "(", "'div'", ",", "$", "contents", ",", "$", "attributes", ")", ";", "$", "drawer", "->", "setAttribute", "(", "'data-default-state'", ",", "$", "default_state", ")", ";", "$", "drawer", "->", "setAttribute", "(", "'data-context'", ",", "$", "context", ")", ";", "$", "drawer", "->", "setAttribute", "(", "'data-label'", ",", "$", "label", ")", ";", "$", "drawer", "->", "setAttribute", "(", "'data-interactive'", ",", "'data-interactive'", ")", ";", "$", "drawer", "->", "addClass", "(", "'drawer'", ")", ";", "$", "drawer", "->", "setAttribute", "(", "'id'", ",", "'drawer-'", ".", "$", "id", ")", ";", "return", "$", "drawer", ";", "}" ]
Generates a XMLElement representation of a Symphony drawer widget. A widget is identified by it's `$label`, and it's contents is defined by the `XMLElement`, `$content`. @since Symphony 2.3 @param string $id The id attribute for this drawer @param string $label A name for this drawer @param XMLElement $content An XMLElement containing the HTML that should be contained inside the drawer. @param string $default_state This parameter defines whether the drawer will be open or closed by default. It defaults to closed. @param string $context @param array $attributes (optional) Any additional attributes can be included in an associative array with the key being the name and the value being the value of the attribute. Attributes set from this array will override existing attributes set by previous params, except the `id` attribute. @return XMLElement
[ "Generates", "a", "XMLElement", "representation", "of", "a", "Symphony", "drawer", "widget", ".", "A", "widget", "is", "identified", "by", "it", "s", "$label", "and", "it", "s", "contents", "is", "defined", "by", "the", "XMLElement", "$content", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.widget.php#L836-L854
symphonycms/symphony-2
symphony/lib/toolkit/class.widget.php
Widget.Calendar
public static function Calendar($time = true) { $calendar = new XMLElement('div'); $calendar->setAttribute('class', 'calendar'); $date = DateTimeObj::convertDateToMoment(DateTimeObj::getSetting('date_format')); if ($date) { if ($time === true) { $separator = DateTimeObj::getSetting('datetime_separator'); $time = DateTimeObj::convertTimeToMoment(DateTimeObj::getSetting('time_format')); $calendar->setAttribute('data-calendar', 'datetime'); $calendar->setAttribute('data-format', $date . $separator . $time); } else { $calendar->setAttribute('data-calendar', 'date'); $calendar->setAttribute('data-format', $date); } } return $calendar; }
php
public static function Calendar($time = true) { $calendar = new XMLElement('div'); $calendar->setAttribute('class', 'calendar'); $date = DateTimeObj::convertDateToMoment(DateTimeObj::getSetting('date_format')); if ($date) { if ($time === true) { $separator = DateTimeObj::getSetting('datetime_separator'); $time = DateTimeObj::convertTimeToMoment(DateTimeObj::getSetting('time_format')); $calendar->setAttribute('data-calendar', 'datetime'); $calendar->setAttribute('data-format', $date . $separator . $time); } else { $calendar->setAttribute('data-calendar', 'date'); $calendar->setAttribute('data-format', $date); } } return $calendar; }
[ "public", "static", "function", "Calendar", "(", "$", "time", "=", "true", ")", "{", "$", "calendar", "=", "new", "XMLElement", "(", "'div'", ")", ";", "$", "calendar", "->", "setAttribute", "(", "'class'", ",", "'calendar'", ")", ";", "$", "date", "=", "DateTimeObj", "::", "convertDateToMoment", "(", "DateTimeObj", "::", "getSetting", "(", "'date_format'", ")", ")", ";", "if", "(", "$", "date", ")", "{", "if", "(", "$", "time", "===", "true", ")", "{", "$", "separator", "=", "DateTimeObj", "::", "getSetting", "(", "'datetime_separator'", ")", ";", "$", "time", "=", "DateTimeObj", "::", "convertTimeToMoment", "(", "DateTimeObj", "::", "getSetting", "(", "'time_format'", ")", ")", ";", "$", "calendar", "->", "setAttribute", "(", "'data-calendar'", ",", "'datetime'", ")", ";", "$", "calendar", "->", "setAttribute", "(", "'data-format'", ",", "$", "date", ".", "$", "separator", ".", "$", "time", ")", ";", "}", "else", "{", "$", "calendar", "->", "setAttribute", "(", "'data-calendar'", ",", "'date'", ")", ";", "$", "calendar", "->", "setAttribute", "(", "'data-format'", ",", "$", "date", ")", ";", "}", "}", "return", "$", "calendar", ";", "}" ]
Generates a XMLElement representation of a Symphony calendar. @since Symphony 2.6 @param boolean $time Wheather or not to display the time, defaults to true @return XMLElement
[ "Generates", "a", "XMLElement", "representation", "of", "a", "Symphony", "calendar", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.widget.php#L864-L884
symphonycms/symphony-2
symphony/lib/toolkit/class.resourcemanager.php
ResourceManager.getSortingField
public static function getSortingField($type) { $result = Symphony::Configuration()->get(self::getColumnFromType($type) . '_index_sortby', 'sorting'); return (is_null($result) ? 'name' : $result); }
php
public static function getSortingField($type) { $result = Symphony::Configuration()->get(self::getColumnFromType($type) . '_index_sortby', 'sorting'); return (is_null($result) ? 'name' : $result); }
[ "public", "static", "function", "getSortingField", "(", "$", "type", ")", "{", "$", "result", "=", "Symphony", "::", "Configuration", "(", ")", "->", "get", "(", "self", "::", "getColumnFromType", "(", "$", "type", ")", ".", "'_index_sortby'", ",", "'sorting'", ")", ";", "return", "(", "is_null", "(", "$", "result", ")", "?", "'name'", ":", "$", "result", ")", ";", "}" ]
Returns the axis a given resource type will be sorted by. The following handles are available: `name`, `source`, `release-date` and `author`. Defaults to 'name'. @param integer $type The resource type, either `RESOURCE_TYPE_EVENT` or `RESOURCE_TYPE_DS` @return string The axis handle.
[ "Returns", "the", "axis", "a", "given", "resource", "type", "will", "be", "sorted", "by", ".", "The", "following", "handles", "are", "available", ":", "name", "source", "release", "-", "date", "and", "author", ".", "Defaults", "to", "name", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.resourcemanager.php#L74-L79
symphonycms/symphony-2
symphony/lib/toolkit/class.resourcemanager.php
ResourceManager.setSortingField
public static function setSortingField($type, $sort, $write = true) { Symphony::Configuration()->set(self::getColumnFromType($type) . '_index_sortby', $sort, 'sorting'); if ($write) { Symphony::Configuration()->write(); } }
php
public static function setSortingField($type, $sort, $write = true) { Symphony::Configuration()->set(self::getColumnFromType($type) . '_index_sortby', $sort, 'sorting'); if ($write) { Symphony::Configuration()->write(); } }
[ "public", "static", "function", "setSortingField", "(", "$", "type", ",", "$", "sort", ",", "$", "write", "=", "true", ")", "{", "Symphony", "::", "Configuration", "(", ")", "->", "set", "(", "self", "::", "getColumnFromType", "(", "$", "type", ")", ".", "'_index_sortby'", ",", "$", "sort", ",", "'sorting'", ")", ";", "if", "(", "$", "write", ")", "{", "Symphony", "::", "Configuration", "(", ")", "->", "write", "(", ")", ";", "}", "}" ]
Saves the new axis a given resource type will be sorted by. @param integer $type The resource type, either `RESOURCE_TYPE_EVENT` or `RESOURCE_TYPE_DS` @param string $sort The axis handle. @param boolean $write If false, the new settings won't be written on the configuration file. Defaults to true.
[ "Saves", "the", "new", "axis", "a", "given", "resource", "type", "will", "be", "sorted", "by", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.resourcemanager.php#L107-L114
symphonycms/symphony-2
symphony/lib/toolkit/class.resourcemanager.php
ResourceManager.setSortingOrder
public static function setSortingOrder($type, $order, $write = true) { Symphony::Configuration()->set(self::getColumnFromType($type) . '_index_order', $order, 'sorting'); if ($write) { Symphony::Configuration()->write(); } }
php
public static function setSortingOrder($type, $order, $write = true) { Symphony::Configuration()->set(self::getColumnFromType($type) . '_index_order', $order, 'sorting'); if ($write) { Symphony::Configuration()->write(); } }
[ "public", "static", "function", "setSortingOrder", "(", "$", "type", ",", "$", "order", ",", "$", "write", "=", "true", ")", "{", "Symphony", "::", "Configuration", "(", ")", "->", "set", "(", "self", "::", "getColumnFromType", "(", "$", "type", ")", ".", "'_index_order'", ",", "$", "order", ",", "'sorting'", ")", ";", "if", "(", "$", "write", ")", "{", "Symphony", "::", "Configuration", "(", ")", "->", "write", "(", ")", ";", "}", "}" ]
Saves the new sort order for a given resource type. @param integer $type The resource type, either `RESOURCE_TYPE_EVENT` or `RESOURCE_TYPE_DS` @param string $order Either 'asc' or 'desc'. @param boolean $write If false, the new settings won't be written on the configuration file. Defaults to true.
[ "Saves", "the", "new", "sort", "order", "for", "a", "given", "resource", "type", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.resourcemanager.php#L127-L134
symphonycms/symphony-2
symphony/lib/toolkit/class.resourcemanager.php
ResourceManager.fetch
public static function fetch($type, array $select = array(), array $where = array(), $order_by = null) { $manager = self::getManagerFromType($type); if (!isset($manager)) { throw new Exception(__('Unable to find a Manager class for this resource.')); } $resources = call_user_func(array($manager, 'listAll')); foreach ($resources as &$r) { // If source is numeric, it's considered to be a Symphony Section if (isset($r['source']) && General::intval($r['source']) > 0) { $section = SectionManager::fetch($r['source']); if ($section !== false) { $r['source'] = array( 'name' => General::sanitize($section->get('name')), 'handle' => General::sanitize($section->get('handle')), 'id' => $r['source'] ); } else { unset($r['source']); } // If source is set but no numeric, it's considered to be a Symphony Type (e.g. authors or navigation) } elseif (isset($r['source'])) { $r['source'] = array( 'name' => ucwords(General::sanitize($r['source'])), 'handle' => General::sanitize($r['source']), ); // Resource provided by extension? } else { $extension = self::__getExtensionFromHandle($type, $r['handle']); if (!empty($extension)) { $extension = Symphony::ExtensionManager()->about($extension); $r['source'] = array( 'name' => General::sanitize($extension['name']), 'handle' => Lang::createHandle($extension['name']) ); } } } if (empty($select) && empty($where) && is_null($order_by)) { return $resources; } if (!is_null($order_by) && !empty($resources)) { $author = $label = $source = $name = array(); $order_by = array_map('strtolower', explode(' ', $order_by)); $order = ($order_by[1] == 'desc') ? SORT_DESC : SORT_ASC; $sort = $order_by[0]; if ($sort == 'author') { foreach ($resources as $key => $about) { $author[$key] = $about['author']['name']; $label[$key] = $key; } array_multisort($author, $order, $label, SORT_ASC, $resources); } elseif ($sort == 'release-date') { foreach ($resources as $key => $about) { $author[$key] = $about['release-date']; $label[$key] = $key; } array_multisort($author, $order, $label, SORT_ASC, $resources); } elseif ($sort == 'source') { foreach ($resources as $key => $about) { $source[$key] = $about['source']['handle']; $label[$key] = $key; } array_multisort($source, $order, $label, SORT_ASC, $resources); } elseif ($sort == 'name') { foreach ($resources as $key => $about) { $name[$key] = strtolower($about['name']); $label[$key] = $key; } array_multisort($name, $order, $label, SORT_ASC, $resources); } } $data = array(); foreach ($resources as $i => $res) { $data[$i] = array(); foreach ($res as $key => $value) { // If $select is empty, we assume every field is requested if (in_array($key, $select) || empty($select)) { $data[$i][$key] = $value; } } } return $data; }
php
public static function fetch($type, array $select = array(), array $where = array(), $order_by = null) { $manager = self::getManagerFromType($type); if (!isset($manager)) { throw new Exception(__('Unable to find a Manager class for this resource.')); } $resources = call_user_func(array($manager, 'listAll')); foreach ($resources as &$r) { // If source is numeric, it's considered to be a Symphony Section if (isset($r['source']) && General::intval($r['source']) > 0) { $section = SectionManager::fetch($r['source']); if ($section !== false) { $r['source'] = array( 'name' => General::sanitize($section->get('name')), 'handle' => General::sanitize($section->get('handle')), 'id' => $r['source'] ); } else { unset($r['source']); } // If source is set but no numeric, it's considered to be a Symphony Type (e.g. authors or navigation) } elseif (isset($r['source'])) { $r['source'] = array( 'name' => ucwords(General::sanitize($r['source'])), 'handle' => General::sanitize($r['source']), ); // Resource provided by extension? } else { $extension = self::__getExtensionFromHandle($type, $r['handle']); if (!empty($extension)) { $extension = Symphony::ExtensionManager()->about($extension); $r['source'] = array( 'name' => General::sanitize($extension['name']), 'handle' => Lang::createHandle($extension['name']) ); } } } if (empty($select) && empty($where) && is_null($order_by)) { return $resources; } if (!is_null($order_by) && !empty($resources)) { $author = $label = $source = $name = array(); $order_by = array_map('strtolower', explode(' ', $order_by)); $order = ($order_by[1] == 'desc') ? SORT_DESC : SORT_ASC; $sort = $order_by[0]; if ($sort == 'author') { foreach ($resources as $key => $about) { $author[$key] = $about['author']['name']; $label[$key] = $key; } array_multisort($author, $order, $label, SORT_ASC, $resources); } elseif ($sort == 'release-date') { foreach ($resources as $key => $about) { $author[$key] = $about['release-date']; $label[$key] = $key; } array_multisort($author, $order, $label, SORT_ASC, $resources); } elseif ($sort == 'source') { foreach ($resources as $key => $about) { $source[$key] = $about['source']['handle']; $label[$key] = $key; } array_multisort($source, $order, $label, SORT_ASC, $resources); } elseif ($sort == 'name') { foreach ($resources as $key => $about) { $name[$key] = strtolower($about['name']); $label[$key] = $key; } array_multisort($name, $order, $label, SORT_ASC, $resources); } } $data = array(); foreach ($resources as $i => $res) { $data[$i] = array(); foreach ($res as $key => $value) { // If $select is empty, we assume every field is requested if (in_array($key, $select) || empty($select)) { $data[$i][$key] = $value; } } } return $data; }
[ "public", "static", "function", "fetch", "(", "$", "type", ",", "array", "$", "select", "=", "array", "(", ")", ",", "array", "$", "where", "=", "array", "(", ")", ",", "$", "order_by", "=", "null", ")", "{", "$", "manager", "=", "self", "::", "getManagerFromType", "(", "$", "type", ")", ";", "if", "(", "!", "isset", "(", "$", "manager", ")", ")", "{", "throw", "new", "Exception", "(", "__", "(", "'Unable to find a Manager class for this resource.'", ")", ")", ";", "}", "$", "resources", "=", "call_user_func", "(", "array", "(", "$", "manager", ",", "'listAll'", ")", ")", ";", "foreach", "(", "$", "resources", "as", "&", "$", "r", ")", "{", "// If source is numeric, it's considered to be a Symphony Section", "if", "(", "isset", "(", "$", "r", "[", "'source'", "]", ")", "&&", "General", "::", "intval", "(", "$", "r", "[", "'source'", "]", ")", ">", "0", ")", "{", "$", "section", "=", "SectionManager", "::", "fetch", "(", "$", "r", "[", "'source'", "]", ")", ";", "if", "(", "$", "section", "!==", "false", ")", "{", "$", "r", "[", "'source'", "]", "=", "array", "(", "'name'", "=>", "General", "::", "sanitize", "(", "$", "section", "->", "get", "(", "'name'", ")", ")", ",", "'handle'", "=>", "General", "::", "sanitize", "(", "$", "section", "->", "get", "(", "'handle'", ")", ")", ",", "'id'", "=>", "$", "r", "[", "'source'", "]", ")", ";", "}", "else", "{", "unset", "(", "$", "r", "[", "'source'", "]", ")", ";", "}", "// If source is set but no numeric, it's considered to be a Symphony Type (e.g. authors or navigation)", "}", "elseif", "(", "isset", "(", "$", "r", "[", "'source'", "]", ")", ")", "{", "$", "r", "[", "'source'", "]", "=", "array", "(", "'name'", "=>", "ucwords", "(", "General", "::", "sanitize", "(", "$", "r", "[", "'source'", "]", ")", ")", ",", "'handle'", "=>", "General", "::", "sanitize", "(", "$", "r", "[", "'source'", "]", ")", ",", ")", ";", "// Resource provided by extension?", "}", "else", "{", "$", "extension", "=", "self", "::", "__getExtensionFromHandle", "(", "$", "type", ",", "$", "r", "[", "'handle'", "]", ")", ";", "if", "(", "!", "empty", "(", "$", "extension", ")", ")", "{", "$", "extension", "=", "Symphony", "::", "ExtensionManager", "(", ")", "->", "about", "(", "$", "extension", ")", ";", "$", "r", "[", "'source'", "]", "=", "array", "(", "'name'", "=>", "General", "::", "sanitize", "(", "$", "extension", "[", "'name'", "]", ")", ",", "'handle'", "=>", "Lang", "::", "createHandle", "(", "$", "extension", "[", "'name'", "]", ")", ")", ";", "}", "}", "}", "if", "(", "empty", "(", "$", "select", ")", "&&", "empty", "(", "$", "where", ")", "&&", "is_null", "(", "$", "order_by", ")", ")", "{", "return", "$", "resources", ";", "}", "if", "(", "!", "is_null", "(", "$", "order_by", ")", "&&", "!", "empty", "(", "$", "resources", ")", ")", "{", "$", "author", "=", "$", "label", "=", "$", "source", "=", "$", "name", "=", "array", "(", ")", ";", "$", "order_by", "=", "array_map", "(", "'strtolower'", ",", "explode", "(", "' '", ",", "$", "order_by", ")", ")", ";", "$", "order", "=", "(", "$", "order_by", "[", "1", "]", "==", "'desc'", ")", "?", "SORT_DESC", ":", "SORT_ASC", ";", "$", "sort", "=", "$", "order_by", "[", "0", "]", ";", "if", "(", "$", "sort", "==", "'author'", ")", "{", "foreach", "(", "$", "resources", "as", "$", "key", "=>", "$", "about", ")", "{", "$", "author", "[", "$", "key", "]", "=", "$", "about", "[", "'author'", "]", "[", "'name'", "]", ";", "$", "label", "[", "$", "key", "]", "=", "$", "key", ";", "}", "array_multisort", "(", "$", "author", ",", "$", "order", ",", "$", "label", ",", "SORT_ASC", ",", "$", "resources", ")", ";", "}", "elseif", "(", "$", "sort", "==", "'release-date'", ")", "{", "foreach", "(", "$", "resources", "as", "$", "key", "=>", "$", "about", ")", "{", "$", "author", "[", "$", "key", "]", "=", "$", "about", "[", "'release-date'", "]", ";", "$", "label", "[", "$", "key", "]", "=", "$", "key", ";", "}", "array_multisort", "(", "$", "author", ",", "$", "order", ",", "$", "label", ",", "SORT_ASC", ",", "$", "resources", ")", ";", "}", "elseif", "(", "$", "sort", "==", "'source'", ")", "{", "foreach", "(", "$", "resources", "as", "$", "key", "=>", "$", "about", ")", "{", "$", "source", "[", "$", "key", "]", "=", "$", "about", "[", "'source'", "]", "[", "'handle'", "]", ";", "$", "label", "[", "$", "key", "]", "=", "$", "key", ";", "}", "array_multisort", "(", "$", "source", ",", "$", "order", ",", "$", "label", ",", "SORT_ASC", ",", "$", "resources", ")", ";", "}", "elseif", "(", "$", "sort", "==", "'name'", ")", "{", "foreach", "(", "$", "resources", "as", "$", "key", "=>", "$", "about", ")", "{", "$", "name", "[", "$", "key", "]", "=", "strtolower", "(", "$", "about", "[", "'name'", "]", ")", ";", "$", "label", "[", "$", "key", "]", "=", "$", "key", ";", "}", "array_multisort", "(", "$", "name", ",", "$", "order", ",", "$", "label", ",", "SORT_ASC", ",", "$", "resources", ")", ";", "}", "}", "$", "data", "=", "array", "(", ")", ";", "foreach", "(", "$", "resources", "as", "$", "i", "=>", "$", "res", ")", "{", "$", "data", "[", "$", "i", "]", "=", "array", "(", ")", ";", "foreach", "(", "$", "res", "as", "$", "key", "=>", "$", "value", ")", "{", "// If $select is empty, we assume every field is requested", "if", "(", "in_array", "(", "$", "key", ",", "$", "select", ")", "||", "empty", "(", "$", "select", ")", ")", "{", "$", "data", "[", "$", "i", "]", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}", "}", "return", "$", "data", ";", "}" ]
This function will return an associative array of resource information. The information returned is defined by the `$select` parameter, which will allow a developer to restrict what information is returned about the resource. Optionally, `$where` (not implemented) and `$order_by` parameters allow a developer to further refine their query. @param integer $type The type of the resource (needed to retrieve the correct Manager) @param array $select (optional) Accepts an array of keys to return from the manager's `listAll()` method. If omitted, all keys will be returned. @param array $where (optional) Not implemented. @param string $order_by (optional) Allows a developer to return the resources in a particular order. The syntax is the same as other `fetch` methods. If omitted this will return resources ordered by `name`. @throws SymphonyErrorPage @throws Exception @return array An associative array of resource information, formatted in the same way as the resource's manager `listAll()` method.
[ "This", "function", "will", "return", "an", "associative", "array", "of", "resource", "information", ".", "The", "information", "returned", "is", "defined", "by", "the", "$select", "parameter", "which", "will", "allow", "a", "developer", "to", "restrict", "what", "information", "is", "returned", "about", "the", "resource", ".", "Optionally", "$where", "(", "not", "implemented", ")", "and", "$order_by", "parameters", "allow", "a", "developer", "to", "further", "refine", "their", "query", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.resourcemanager.php#L159-L260
symphonycms/symphony-2
symphony/lib/toolkit/class.resourcemanager.php
ResourceManager.__getExtensionFromHandle
public static function __getExtensionFromHandle($type, $r_handle) { $manager = self::getManagerFromType($type); if (!isset($manager)) { throw new Exception(__('Unable to find a Manager class for this resource.')); } $type = str_replace('_', '-', self::getColumnFromType($type)); preg_match('/extensions\/(.*)\/' . $type . '/', call_user_func(array($manager, '__getClassPath'), $r_handle), $data); $data = array_splice($data, 1); if (empty($data)) { return null; } else { return $data[0]; } }
php
public static function __getExtensionFromHandle($type, $r_handle) { $manager = self::getManagerFromType($type); if (!isset($manager)) { throw new Exception(__('Unable to find a Manager class for this resource.')); } $type = str_replace('_', '-', self::getColumnFromType($type)); preg_match('/extensions\/(.*)\/' . $type . '/', call_user_func(array($manager, '__getClassPath'), $r_handle), $data); $data = array_splice($data, 1); if (empty($data)) { return null; } else { return $data[0]; } }
[ "public", "static", "function", "__getExtensionFromHandle", "(", "$", "type", ",", "$", "r_handle", ")", "{", "$", "manager", "=", "self", "::", "getManagerFromType", "(", "$", "type", ")", ";", "if", "(", "!", "isset", "(", "$", "manager", ")", ")", "{", "throw", "new", "Exception", "(", "__", "(", "'Unable to find a Manager class for this resource.'", ")", ")", ";", "}", "$", "type", "=", "str_replace", "(", "'_'", ",", "'-'", ",", "self", "::", "getColumnFromType", "(", "$", "type", ")", ")", ";", "preg_match", "(", "'/extensions\\/(.*)\\/'", ".", "$", "type", ".", "'/'", ",", "call_user_func", "(", "array", "(", "$", "manager", ",", "'__getClassPath'", ")", ",", "$", "r_handle", ")", ",", "$", "data", ")", ";", "$", "data", "=", "array_splice", "(", "$", "data", ",", "1", ")", ";", "if", "(", "empty", "(", "$", "data", ")", ")", "{", "return", "null", ";", "}", "else", "{", "return", "$", "data", "[", "0", "]", ";", "}", "}" ]
Given the type and handle of a resource, return the extension it belongs to. @param integer $type The resource type, either `RESOURCE_TYPE_EVENT` or `RESOURCE_TYPE_DS` @param string $r_handle The handle of the resource. @throws Exception @return string The extension handle.
[ "Given", "the", "type", "and", "handle", "of", "a", "resource", "return", "the", "extension", "it", "belongs", "to", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.resourcemanager.php#L273-L291
symphonycms/symphony-2
symphony/lib/toolkit/class.resourcemanager.php
ResourceManager.getAttachedPages
public static function getAttachedPages($type, $r_handle) { $col = self::getColumnFromType($type); $pages = PageManager::fetch(false, array('id'), array(sprintf( '`%s` = "%s" OR `%s` REGEXP "%s"', $col, $r_handle, $col, '^' . $r_handle . ',|,' . $r_handle . ',|,' . $r_handle . '$' ))); if (is_array($pages)) { foreach ($pages as $key => &$page) { $pages[$key] = array( 'id' => $page['id'], 'title' => PageManager::resolvePageTitle($page['id']) ); } } return (is_null($pages) ? array() : $pages); }
php
public static function getAttachedPages($type, $r_handle) { $col = self::getColumnFromType($type); $pages = PageManager::fetch(false, array('id'), array(sprintf( '`%s` = "%s" OR `%s` REGEXP "%s"', $col, $r_handle, $col, '^' . $r_handle . ',|,' . $r_handle . ',|,' . $r_handle . '$' ))); if (is_array($pages)) { foreach ($pages as $key => &$page) { $pages[$key] = array( 'id' => $page['id'], 'title' => PageManager::resolvePageTitle($page['id']) ); } } return (is_null($pages) ? array() : $pages); }
[ "public", "static", "function", "getAttachedPages", "(", "$", "type", ",", "$", "r_handle", ")", "{", "$", "col", "=", "self", "::", "getColumnFromType", "(", "$", "type", ")", ";", "$", "pages", "=", "PageManager", "::", "fetch", "(", "false", ",", "array", "(", "'id'", ")", ",", "array", "(", "sprintf", "(", "'`%s` = \"%s\" OR `%s` REGEXP \"%s\"'", ",", "$", "col", ",", "$", "r_handle", ",", "$", "col", ",", "'^'", ".", "$", "r_handle", ".", "',|,'", ".", "$", "r_handle", ".", "',|,'", ".", "$", "r_handle", ".", "'$'", ")", ")", ")", ";", "if", "(", "is_array", "(", "$", "pages", ")", ")", "{", "foreach", "(", "$", "pages", "as", "$", "key", "=>", "&", "$", "page", ")", "{", "$", "pages", "[", "$", "key", "]", "=", "array", "(", "'id'", "=>", "$", "page", "[", "'id'", "]", ",", "'title'", "=>", "PageManager", "::", "resolvePageTitle", "(", "$", "page", "[", "'id'", "]", ")", ")", ";", "}", "}", "return", "(", "is_null", "(", "$", "pages", ")", "?", "array", "(", ")", ":", "$", "pages", ")", ";", "}" ]
Given the resource handle, this function will return an associative array of Page information, filtered by the pages the resource is attached to. @param integer $type The resource type, either `RESOURCE_TYPE_EVENT` or `RESOURCE_TYPE_DS` @param string $r_handle The handle of the resource. @return array An associative array of Page information, according to the pages the resource is attached to.
[ "Given", "the", "resource", "handle", "this", "function", "will", "return", "an", "associative", "array", "of", "Page", "information", "filtered", "by", "the", "pages", "the", "resource", "is", "attached", "to", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.resourcemanager.php#L304-L326
symphonycms/symphony-2
symphony/lib/toolkit/class.resourcemanager.php
ResourceManager.attach
public static function attach($type, $r_handle, $page_id) { $col = self::getColumnFromType($type); $pages = PageManager::fetch(false, array($col), array(sprintf( '`id` = %d', $page_id ))); if (is_array($pages) && count($pages) == 1) { $result = $pages[0][$col]; if (!in_array($r_handle, explode(',', $result))) { if (strlen($result) > 0) { $result .= ','; } $result .= $r_handle; return PageManager::edit($page_id, array( $col => MySQL::cleanValue($result) )); } } return false; }
php
public static function attach($type, $r_handle, $page_id) { $col = self::getColumnFromType($type); $pages = PageManager::fetch(false, array($col), array(sprintf( '`id` = %d', $page_id ))); if (is_array($pages) && count($pages) == 1) { $result = $pages[0][$col]; if (!in_array($r_handle, explode(',', $result))) { if (strlen($result) > 0) { $result .= ','; } $result .= $r_handle; return PageManager::edit($page_id, array( $col => MySQL::cleanValue($result) )); } } return false; }
[ "public", "static", "function", "attach", "(", "$", "type", ",", "$", "r_handle", ",", "$", "page_id", ")", "{", "$", "col", "=", "self", "::", "getColumnFromType", "(", "$", "type", ")", ";", "$", "pages", "=", "PageManager", "::", "fetch", "(", "false", ",", "array", "(", "$", "col", ")", ",", "array", "(", "sprintf", "(", "'`id` = %d'", ",", "$", "page_id", ")", ")", ")", ";", "if", "(", "is_array", "(", "$", "pages", ")", "&&", "count", "(", "$", "pages", ")", "==", "1", ")", "{", "$", "result", "=", "$", "pages", "[", "0", "]", "[", "$", "col", "]", ";", "if", "(", "!", "in_array", "(", "$", "r_handle", ",", "explode", "(", "','", ",", "$", "result", ")", ")", ")", "{", "if", "(", "strlen", "(", "$", "result", ")", ">", "0", ")", "{", "$", "result", ".=", "','", ";", "}", "$", "result", ".=", "$", "r_handle", ";", "return", "PageManager", "::", "edit", "(", "$", "page_id", ",", "array", "(", "$", "col", "=>", "MySQL", "::", "cleanValue", "(", "$", "result", ")", ")", ")", ";", "}", "}", "return", "false", ";", "}" ]
Given a resource type, a handle and a page, this function will attach the given handle (which represents either a datasource or event) to that page. @param integer $type The resource type, either `RESOURCE_TYPE_EVENT` or `RESOURCE_TYPE_DS` @param string $r_handle The handle of the resource. @param integer $page_id The ID of the page. @return boolean
[ "Given", "a", "resource", "type", "a", "handle", "and", "a", "page", "this", "function", "will", "attach", "the", "given", "handle", "(", "which", "represents", "either", "a", "datasource", "or", "event", ")", "to", "that", "page", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.resourcemanager.php#L340-L366
symphonycms/symphony-2
symphony/lib/toolkit/class.resourcemanager.php
ResourceManager.detach
public static function detach($type, $r_handle, $page_id) { $col = self::getColumnFromType($type); $pages = PageManager::fetch(false, array($col), array(sprintf( '`id` = %d', $page_id ))); if (is_array($pages) && count($pages) == 1) { $result = $pages[0][$col]; $values = explode(',', $result); $idx = array_search($r_handle, $values, false); if ($idx !== false) { array_splice($values, $idx, 1); $result = implode(',', $values); return PageManager::edit($page_id, array( $col => MySQL::cleanValue($result) )); } } return false; }
php
public static function detach($type, $r_handle, $page_id) { $col = self::getColumnFromType($type); $pages = PageManager::fetch(false, array($col), array(sprintf( '`id` = %d', $page_id ))); if (is_array($pages) && count($pages) == 1) { $result = $pages[0][$col]; $values = explode(',', $result); $idx = array_search($r_handle, $values, false); if ($idx !== false) { array_splice($values, $idx, 1); $result = implode(',', $values); return PageManager::edit($page_id, array( $col => MySQL::cleanValue($result) )); } } return false; }
[ "public", "static", "function", "detach", "(", "$", "type", ",", "$", "r_handle", ",", "$", "page_id", ")", "{", "$", "col", "=", "self", "::", "getColumnFromType", "(", "$", "type", ")", ";", "$", "pages", "=", "PageManager", "::", "fetch", "(", "false", ",", "array", "(", "$", "col", ")", ",", "array", "(", "sprintf", "(", "'`id` = %d'", ",", "$", "page_id", ")", ")", ")", ";", "if", "(", "is_array", "(", "$", "pages", ")", "&&", "count", "(", "$", "pages", ")", "==", "1", ")", "{", "$", "result", "=", "$", "pages", "[", "0", "]", "[", "$", "col", "]", ";", "$", "values", "=", "explode", "(", "','", ",", "$", "result", ")", ";", "$", "idx", "=", "array_search", "(", "$", "r_handle", ",", "$", "values", ",", "false", ")", ";", "if", "(", "$", "idx", "!==", "false", ")", "{", "array_splice", "(", "$", "values", ",", "$", "idx", ",", "1", ")", ";", "$", "result", "=", "implode", "(", "','", ",", "$", "values", ")", ";", "return", "PageManager", "::", "edit", "(", "$", "page_id", ",", "array", "(", "$", "col", "=>", "MySQL", "::", "cleanValue", "(", "$", "result", ")", ")", ")", ";", "}", "}", "return", "false", ";", "}" ]
Given a resource type, a handle and a page, this function detaches the given handle (which represents either a datasource or event) to that page. @param integer $type The resource type, either `RESOURCE_TYPE_EVENT` or `RESOURCE_TYPE_DS` @param string $r_handle The handle of the resource. @param integer $page_id The ID of the page. @return boolean
[ "Given", "a", "resource", "type", "a", "handle", "and", "a", "page", "this", "function", "detaches", "the", "given", "handle", "(", "which", "represents", "either", "a", "datasource", "or", "event", ")", "to", "that", "page", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.resourcemanager.php#L380-L406
symphonycms/symphony-2
symphony/lib/toolkit/class.resourcemanager.php
ResourceManager.setPages
public static function setPages($type, $r_handle, $pages = array()) { if (!is_array($pages)) { $pages = array(); } // Get attached pages $attached_pages = ResourceManager::getAttachedPages($type, $r_handle); $currently_attached_pages = array(); foreach ($attached_pages as $page) { $currently_attached_pages[] = $page['id']; } // Attach this datasource to any page that is should be attached to $diff_to_attach = array_diff($pages, $currently_attached_pages); foreach ($diff_to_attach as $diff_page) { ResourceManager::attach($type, $r_handle, $diff_page); } // Remove this datasource from any page where it once was, but shouldn't be anymore $diff_to_detach = array_diff($currently_attached_pages, $pages); foreach ($diff_to_detach as $diff_page) { ResourceManager::detach($type, $r_handle, $diff_page); } return true; }
php
public static function setPages($type, $r_handle, $pages = array()) { if (!is_array($pages)) { $pages = array(); } // Get attached pages $attached_pages = ResourceManager::getAttachedPages($type, $r_handle); $currently_attached_pages = array(); foreach ($attached_pages as $page) { $currently_attached_pages[] = $page['id']; } // Attach this datasource to any page that is should be attached to $diff_to_attach = array_diff($pages, $currently_attached_pages); foreach ($diff_to_attach as $diff_page) { ResourceManager::attach($type, $r_handle, $diff_page); } // Remove this datasource from any page where it once was, but shouldn't be anymore $diff_to_detach = array_diff($currently_attached_pages, $pages); foreach ($diff_to_detach as $diff_page) { ResourceManager::detach($type, $r_handle, $diff_page); } return true; }
[ "public", "static", "function", "setPages", "(", "$", "type", ",", "$", "r_handle", ",", "$", "pages", "=", "array", "(", ")", ")", "{", "if", "(", "!", "is_array", "(", "$", "pages", ")", ")", "{", "$", "pages", "=", "array", "(", ")", ";", "}", "// Get attached pages", "$", "attached_pages", "=", "ResourceManager", "::", "getAttachedPages", "(", "$", "type", ",", "$", "r_handle", ")", ";", "$", "currently_attached_pages", "=", "array", "(", ")", ";", "foreach", "(", "$", "attached_pages", "as", "$", "page", ")", "{", "$", "currently_attached_pages", "[", "]", "=", "$", "page", "[", "'id'", "]", ";", "}", "// Attach this datasource to any page that is should be attached to", "$", "diff_to_attach", "=", "array_diff", "(", "$", "pages", ",", "$", "currently_attached_pages", ")", ";", "foreach", "(", "$", "diff_to_attach", "as", "$", "diff_page", ")", "{", "ResourceManager", "::", "attach", "(", "$", "type", ",", "$", "r_handle", ",", "$", "diff_page", ")", ";", "}", "// Remove this datasource from any page where it once was, but shouldn't be anymore", "$", "diff_to_detach", "=", "array_diff", "(", "$", "currently_attached_pages", ",", "$", "pages", ")", ";", "foreach", "(", "$", "diff_to_detach", "as", "$", "diff_page", ")", "{", "ResourceManager", "::", "detach", "(", "$", "type", ",", "$", "r_handle", ",", "$", "diff_page", ")", ";", "}", "return", "true", ";", "}" ]
Given a resource type, a handle and an array of pages, this function will ensure that the resource is attached to the given pages. Note that this function will also remove the resource from all pages that are not provided in the `$pages` parameter. @since Symphony 2.4 @param integer $type The resource type, either `RESOURCE_TYPE_EVENT` or `RESOURCE_TYPE_DS` @param string $r_handle The handle of the resource. @param array $pages An array of Page ID's to attach this resource to. @return boolean
[ "Given", "a", "resource", "type", "a", "handle", "and", "an", "array", "of", "pages", "this", "function", "will", "ensure", "that", "the", "resource", "is", "attached", "to", "the", "given", "pages", ".", "Note", "that", "this", "function", "will", "also", "remove", "the", "resource", "from", "all", "pages", "that", "are", "not", "provided", "in", "the", "$pages", "parameter", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.resourcemanager.php#L423-L452
symphonycms/symphony-2
symphony/lib/core/class.datetimeobj.php
DateTimeObj.setSettings
public static function setSettings(array $settings = array()) { // Date format if (isset($settings['date_format'])) { self::$settings['date_format'] = $settings['date_format']; } // Time format if (isset($settings['time_format'])) { self::$settings['time_format'] = $settings['time_format']; } // Datetime separator if (isset($settings['datetime_separator'])) { self::$settings['datetime_separator'] = $settings['datetime_separator']; } elseif (!isset(self::$settings['datetime_separator'])) { self::$settings['datetime_separator'] = ' '; } // Datetime format if (isset($settings['datetime_format'])) { self::$settings['datetime_format'] = $settings['datetime_format']; } elseif (!isset(self::$settings['datetime_format'])) { self::$settings['datetime_format'] = self::$settings['date_format'] . self::$settings['datetime_separator'] . self::$settings['time_format']; } // Timezone if (isset($settings['timezone']) && !empty($settings['timezone'])) { self::$settings['timezone'] = $settings['timezone']; self::setDefaultTimezone($settings['timezone']); } elseif (!isset(self::$settings['timezone'])) { self::$settings['timezone'] = ini_get('date.timezone'); if (empty(self::$settings['timezone'])) { self::$settings['timezone'] = 'UTC'; } } }
php
public static function setSettings(array $settings = array()) { // Date format if (isset($settings['date_format'])) { self::$settings['date_format'] = $settings['date_format']; } // Time format if (isset($settings['time_format'])) { self::$settings['time_format'] = $settings['time_format']; } // Datetime separator if (isset($settings['datetime_separator'])) { self::$settings['datetime_separator'] = $settings['datetime_separator']; } elseif (!isset(self::$settings['datetime_separator'])) { self::$settings['datetime_separator'] = ' '; } // Datetime format if (isset($settings['datetime_format'])) { self::$settings['datetime_format'] = $settings['datetime_format']; } elseif (!isset(self::$settings['datetime_format'])) { self::$settings['datetime_format'] = self::$settings['date_format'] . self::$settings['datetime_separator'] . self::$settings['time_format']; } // Timezone if (isset($settings['timezone']) && !empty($settings['timezone'])) { self::$settings['timezone'] = $settings['timezone']; self::setDefaultTimezone($settings['timezone']); } elseif (!isset(self::$settings['timezone'])) { self::$settings['timezone'] = ini_get('date.timezone'); if (empty(self::$settings['timezone'])) { self::$settings['timezone'] = 'UTC'; } } }
[ "public", "static", "function", "setSettings", "(", "array", "$", "settings", "=", "array", "(", ")", ")", "{", "// Date format", "if", "(", "isset", "(", "$", "settings", "[", "'date_format'", "]", ")", ")", "{", "self", "::", "$", "settings", "[", "'date_format'", "]", "=", "$", "settings", "[", "'date_format'", "]", ";", "}", "// Time format", "if", "(", "isset", "(", "$", "settings", "[", "'time_format'", "]", ")", ")", "{", "self", "::", "$", "settings", "[", "'time_format'", "]", "=", "$", "settings", "[", "'time_format'", "]", ";", "}", "// Datetime separator", "if", "(", "isset", "(", "$", "settings", "[", "'datetime_separator'", "]", ")", ")", "{", "self", "::", "$", "settings", "[", "'datetime_separator'", "]", "=", "$", "settings", "[", "'datetime_separator'", "]", ";", "}", "elseif", "(", "!", "isset", "(", "self", "::", "$", "settings", "[", "'datetime_separator'", "]", ")", ")", "{", "self", "::", "$", "settings", "[", "'datetime_separator'", "]", "=", "' '", ";", "}", "// Datetime format", "if", "(", "isset", "(", "$", "settings", "[", "'datetime_format'", "]", ")", ")", "{", "self", "::", "$", "settings", "[", "'datetime_format'", "]", "=", "$", "settings", "[", "'datetime_format'", "]", ";", "}", "elseif", "(", "!", "isset", "(", "self", "::", "$", "settings", "[", "'datetime_format'", "]", ")", ")", "{", "self", "::", "$", "settings", "[", "'datetime_format'", "]", "=", "self", "::", "$", "settings", "[", "'date_format'", "]", ".", "self", "::", "$", "settings", "[", "'datetime_separator'", "]", ".", "self", "::", "$", "settings", "[", "'time_format'", "]", ";", "}", "// Timezone", "if", "(", "isset", "(", "$", "settings", "[", "'timezone'", "]", ")", "&&", "!", "empty", "(", "$", "settings", "[", "'timezone'", "]", ")", ")", "{", "self", "::", "$", "settings", "[", "'timezone'", "]", "=", "$", "settings", "[", "'timezone'", "]", ";", "self", "::", "setDefaultTimezone", "(", "$", "settings", "[", "'timezone'", "]", ")", ";", "}", "elseif", "(", "!", "isset", "(", "self", "::", "$", "settings", "[", "'timezone'", "]", ")", ")", "{", "self", "::", "$", "settings", "[", "'timezone'", "]", "=", "ini_get", "(", "'date.timezone'", ")", ";", "if", "(", "empty", "(", "self", "::", "$", "settings", "[", "'timezone'", "]", ")", ")", "{", "self", "::", "$", "settings", "[", "'timezone'", "]", "=", "'UTC'", ";", "}", "}", "}" ]
This function takes an array of settings for `DateTimeObj` to use when parsing input dates. The following settings are supported, `time_format`, `date_format`, `datetime_separator` and `timezone`. This equates to Symphony's default `region` group set in the `Configuration` class. If any of these values are not provided the class will fallback to existing `self::$settings` values @since Symphony 2.2.4 @param array $settings An associative array of formats for this class to use to format dates
[ "This", "function", "takes", "an", "array", "of", "settings", "for", "DateTimeObj", "to", "use", "when", "parsing", "input", "dates", ".", "The", "following", "settings", "are", "supported", "time_format", "date_format", "datetime_separator", "and", "timezone", ".", "This", "equates", "to", "Symphony", "s", "default", "region", "group", "set", "in", "the", "Configuration", "class", ".", "If", "any", "of", "these", "values", "are", "not", "provided", "the", "class", "will", "fallback", "to", "existing", "self", "::", "$settings", "values" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.datetimeobj.php#L76-L112
symphonycms/symphony-2
symphony/lib/core/class.datetimeobj.php
DateTimeObj.getSetting
public static function getSetting($name = null) { if (is_null($name)) { return self::$settings; } if (isset(self::$settings[$name])) { return self::$settings[$name]; } return null; }
php
public static function getSetting($name = null) { if (is_null($name)) { return self::$settings; } if (isset(self::$settings[$name])) { return self::$settings[$name]; } return null; }
[ "public", "static", "function", "getSetting", "(", "$", "name", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "name", ")", ")", "{", "return", "self", "::", "$", "settings", ";", "}", "if", "(", "isset", "(", "self", "::", "$", "settings", "[", "$", "name", "]", ")", ")", "{", "return", "self", "::", "$", "settings", "[", "$", "name", "]", ";", "}", "return", "null", ";", "}" ]
Accessor function for the settings of the DateTimeObj. Currently the available settings are `time_format`, `date_format`, `datetime_format` and `datetime_separator`. If `$name` is not provided, the entire `$settings` array is returned. @since Symphony 2.2.4 @param string $name @return array|string|null If `$name` is omitted this function returns array. If `$name` is not set, this fucntion returns `null` If `$name` is set, this function returns string
[ "Accessor", "function", "for", "the", "settings", "of", "the", "DateTimeObj", ".", "Currently", "the", "available", "settings", "are", "time_format", "date_format", "datetime_format", "and", "datetime_separator", ".", "If", "$name", "is", "not", "provided", "the", "entire", "$settings", "array", "is", "returned", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.datetimeobj.php#L127-L138
symphonycms/symphony-2
symphony/lib/core/class.datetimeobj.php
DateTimeObj.validate
public static function validate($string) { try { if (is_numeric($string) && (int)$string == $string) { $date = new DateTime('@' . $string); } else { $date = self::parse($string); } } catch (Exception $ex) { return false; } // String is empty or not a valid date if (empty($string) || $date === false) { return false; // String is a valid date } else { return true; } }
php
public static function validate($string) { try { if (is_numeric($string) && (int)$string == $string) { $date = new DateTime('@' . $string); } else { $date = self::parse($string); } } catch (Exception $ex) { return false; } // String is empty or not a valid date if (empty($string) || $date === false) { return false; // String is a valid date } else { return true; } }
[ "public", "static", "function", "validate", "(", "$", "string", ")", "{", "try", "{", "if", "(", "is_numeric", "(", "$", "string", ")", "&&", "(", "int", ")", "$", "string", "==", "$", "string", ")", "{", "$", "date", "=", "new", "DateTime", "(", "'@'", ".", "$", "string", ")", ";", "}", "else", "{", "$", "date", "=", "self", "::", "parse", "(", "$", "string", ")", ";", "}", "}", "catch", "(", "Exception", "$", "ex", ")", "{", "return", "false", ";", "}", "// String is empty or not a valid date", "if", "(", "empty", "(", "$", "string", ")", "||", "$", "date", "===", "false", ")", "{", "return", "false", ";", "// String is a valid date", "}", "else", "{", "return", "true", ";", "}", "}" ]
Validate a given date and time string @param string $string A date and time string or timestamp to validate @return boolean Returns true for valid dates, otherwise false
[ "Validate", "a", "given", "date", "and", "time", "string" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.datetimeobj.php#L165-L185
symphonycms/symphony-2
symphony/lib/core/class.datetimeobj.php
DateTimeObj.get
public static function get($format, $timestamp = 'now', $timezone = null) { return self::format($timestamp, $format, false, $timezone); }
php
public static function get($format, $timestamp = 'now', $timezone = null) { return self::format($timestamp, $format, false, $timezone); }
[ "public", "static", "function", "get", "(", "$", "format", ",", "$", "timestamp", "=", "'now'", ",", "$", "timezone", "=", "null", ")", "{", "return", "self", "::", "format", "(", "$", "timestamp", ",", "$", "format", ",", "false", ",", "$", "timezone", ")", ";", "}" ]
Given a `$format`, and a `$timestamp`, return the date in the format provided. This function is a basic wrapper for PHP's DateTime object. If the `$timestamp` is omitted, the current timestamp will be used. Optionally, you pass a timezone identifier with this function to localise the output If you like to display a date in the backend, please make use of `DateTimeObj::format()` which allows date and time localization @see class.datetimeobj.php#format() @link http://www.php.net/manual/en/book.datetime.php @param string $format A valid PHP date format @param null|string $timestamp (optional) A unix timestamp to format. 'now' or omitting this parameter will result in the current time being used @param string $timezone (optional) The timezone associated with the timestamp @return string|boolean The formatted date, of if the date could not be parsed, false.
[ "Given", "a", "$format", "and", "a", "$timestamp", "return", "the", "date", "in", "the", "format", "provided", ".", "This", "function", "is", "a", "basic", "wrapper", "for", "PHP", "s", "DateTime", "object", ".", "If", "the", "$timestamp", "is", "omitted", "the", "current", "timestamp", "will", "be", "used", ".", "Optionally", "you", "pass", "a", "timezone", "identifier", "with", "this", "function", "to", "localise", "the", "output" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.datetimeobj.php#L209-L212
symphonycms/symphony-2
symphony/lib/core/class.datetimeobj.php
DateTimeObj.format
public static function format($string = 'now', $format = DateTime::ISO8601, $localize = true, $timezone = null) { // Parse date $date = self::parse($string); if ($date === false) { return false; } // Timezone // If a timezone was given, apply it if (!is_null($timezone)) { $date->setTimezone(new DateTimeZone($timezone)); // No timezone given, apply the default timezone } elseif (isset(self::$settings['timezone'])) { $date->setTimezone(new DateTimeZone(self::$settings['timezone'])); } // Format date $date = $date->format($format); // Localize date // Convert date string from English back to the activated Language if ($localize === true) { $date = Lang::localizeDate($date); } // Return custom formatted date, use ISO 8601 date by default return $date; }
php
public static function format($string = 'now', $format = DateTime::ISO8601, $localize = true, $timezone = null) { // Parse date $date = self::parse($string); if ($date === false) { return false; } // Timezone // If a timezone was given, apply it if (!is_null($timezone)) { $date->setTimezone(new DateTimeZone($timezone)); // No timezone given, apply the default timezone } elseif (isset(self::$settings['timezone'])) { $date->setTimezone(new DateTimeZone(self::$settings['timezone'])); } // Format date $date = $date->format($format); // Localize date // Convert date string from English back to the activated Language if ($localize === true) { $date = Lang::localizeDate($date); } // Return custom formatted date, use ISO 8601 date by default return $date; }
[ "public", "static", "function", "format", "(", "$", "string", "=", "'now'", ",", "$", "format", "=", "DateTime", "::", "ISO8601", ",", "$", "localize", "=", "true", ",", "$", "timezone", "=", "null", ")", "{", "// Parse date", "$", "date", "=", "self", "::", "parse", "(", "$", "string", ")", ";", "if", "(", "$", "date", "===", "false", ")", "{", "return", "false", ";", "}", "// Timezone", "// If a timezone was given, apply it", "if", "(", "!", "is_null", "(", "$", "timezone", ")", ")", "{", "$", "date", "->", "setTimezone", "(", "new", "DateTimeZone", "(", "$", "timezone", ")", ")", ";", "// No timezone given, apply the default timezone", "}", "elseif", "(", "isset", "(", "self", "::", "$", "settings", "[", "'timezone'", "]", ")", ")", "{", "$", "date", "->", "setTimezone", "(", "new", "DateTimeZone", "(", "self", "::", "$", "settings", "[", "'timezone'", "]", ")", ")", ";", "}", "// Format date", "$", "date", "=", "$", "date", "->", "format", "(", "$", "format", ")", ";", "// Localize date", "// Convert date string from English back to the activated Language", "if", "(", "$", "localize", "===", "true", ")", "{", "$", "date", "=", "Lang", "::", "localizeDate", "(", "$", "date", ")", ";", "}", "// Return custom formatted date, use ISO 8601 date by default", "return", "$", "date", ";", "}" ]
Formats the given date and time `$string` based on the given `$format`. Optionally the result will be localized and respect a timezone differing from the system default. The default output is ISO 8601. @since Symphony 2.2.1 @param string $string (optional) A string containing date and time, defaults to the current date and time @param string $format (optional) A valid PHP date format, defaults to ISO 8601 @param boolean $localize (optional) Localizes the output, if true, defaults to true @param string $timezone (optional) The timezone associated with the timestamp @return string|boolean The formatted date, or if the date could not be parsed, false.
[ "Formats", "the", "given", "date", "and", "time", "$string", "based", "on", "the", "given", "$format", ".", "Optionally", "the", "result", "will", "be", "localized", "and", "respect", "a", "timezone", "differing", "from", "the", "system", "default", ".", "The", "default", "output", "is", "ISO", "8601", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.datetimeobj.php#L231-L261
symphonycms/symphony-2
symphony/lib/core/class.datetimeobj.php
DateTimeObj.parse
public static function parse($string) { // Current date and time if ($string == 'now' || empty($string)) { $date = new DateTime(); // Timestamp } elseif (is_numeric($string)) { $date = new DateTime('@' . $string); // Attempt to parse the date provided against the Symphony configuration setting // in an effort to better support multilingual date formats. Should this fail // this block will fallback to just passing the date to DateTime constructor, // which will parse the date assuming it's in an American format. } else { // Standardize date // Convert date string to English $string = Lang::standardizeDate($string); // PHP 5.3: Apply Symphony date format using `createFromFormat` $date = DateTime::createFromFormat(self::$settings['datetime_format'], $string); if ($date === false) { $date = DateTime::createFromFormat(self::$settings['date_format'], $string); } // Handle dates that are in a different format to Symphony's config // DateTime is much the same as `strtotime` and will handle relative // dates. if ($date === false) { try { $date = new DateTime($string); } catch (Exception $ex) { // Invalid date, it can't be parsed return false; } } // If the date is still invalid, just return false. if ($date === false || $date->format('Y') < 0) { return false; } } // Return custom formatted date, use ISO 8601 date by default return $date; }
php
public static function parse($string) { // Current date and time if ($string == 'now' || empty($string)) { $date = new DateTime(); // Timestamp } elseif (is_numeric($string)) { $date = new DateTime('@' . $string); // Attempt to parse the date provided against the Symphony configuration setting // in an effort to better support multilingual date formats. Should this fail // this block will fallback to just passing the date to DateTime constructor, // which will parse the date assuming it's in an American format. } else { // Standardize date // Convert date string to English $string = Lang::standardizeDate($string); // PHP 5.3: Apply Symphony date format using `createFromFormat` $date = DateTime::createFromFormat(self::$settings['datetime_format'], $string); if ($date === false) { $date = DateTime::createFromFormat(self::$settings['date_format'], $string); } // Handle dates that are in a different format to Symphony's config // DateTime is much the same as `strtotime` and will handle relative // dates. if ($date === false) { try { $date = new DateTime($string); } catch (Exception $ex) { // Invalid date, it can't be parsed return false; } } // If the date is still invalid, just return false. if ($date === false || $date->format('Y') < 0) { return false; } } // Return custom formatted date, use ISO 8601 date by default return $date; }
[ "public", "static", "function", "parse", "(", "$", "string", ")", "{", "// Current date and time", "if", "(", "$", "string", "==", "'now'", "||", "empty", "(", "$", "string", ")", ")", "{", "$", "date", "=", "new", "DateTime", "(", ")", ";", "// Timestamp", "}", "elseif", "(", "is_numeric", "(", "$", "string", ")", ")", "{", "$", "date", "=", "new", "DateTime", "(", "'@'", ".", "$", "string", ")", ";", "// Attempt to parse the date provided against the Symphony configuration setting", "// in an effort to better support multilingual date formats. Should this fail", "// this block will fallback to just passing the date to DateTime constructor,", "// which will parse the date assuming it's in an American format.", "}", "else", "{", "// Standardize date", "// Convert date string to English", "$", "string", "=", "Lang", "::", "standardizeDate", "(", "$", "string", ")", ";", "// PHP 5.3: Apply Symphony date format using `createFromFormat`", "$", "date", "=", "DateTime", "::", "createFromFormat", "(", "self", "::", "$", "settings", "[", "'datetime_format'", "]", ",", "$", "string", ")", ";", "if", "(", "$", "date", "===", "false", ")", "{", "$", "date", "=", "DateTime", "::", "createFromFormat", "(", "self", "::", "$", "settings", "[", "'date_format'", "]", ",", "$", "string", ")", ";", "}", "// Handle dates that are in a different format to Symphony's config", "// DateTime is much the same as `strtotime` and will handle relative", "// dates.", "if", "(", "$", "date", "===", "false", ")", "{", "try", "{", "$", "date", "=", "new", "DateTime", "(", "$", "string", ")", ";", "}", "catch", "(", "Exception", "$", "ex", ")", "{", "// Invalid date, it can't be parsed", "return", "false", ";", "}", "}", "// If the date is still invalid, just return false.", "if", "(", "$", "date", "===", "false", "||", "$", "date", "->", "format", "(", "'Y'", ")", "<", "0", ")", "{", "return", "false", ";", "}", "}", "// Return custom formatted date, use ISO 8601 date by default", "return", "$", "date", ";", "}" ]
Parses the given string and returns a DateTime object. @since Symphony 2.3 @param string $string (optional) A string containing date and time, defaults to the current date and time @return DateTime|boolean The DateTime object, or if the date could not be parsed, false.
[ "Parses", "the", "given", "string", "and", "returns", "a", "DateTime", "object", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.datetimeobj.php#L272-L319
symphonycms/symphony-2
symphony/lib/core/class.datetimeobj.php
DateTimeObj.getTimezonesSelectOptions
public static function getTimezonesSelectOptions($selected = null) { $zones = self::getZones(); $groups = array(); foreach ($zones as $zone => $value) { if ($value >= 1024) { break; } $timezones = self::getTimezones($zone); $options = array(); foreach ($timezones as $timezone) { $tz = new DateTime('now', new DateTimeZone($timezone)); $options[] = array($timezone, ($timezone == $selected), sprintf( "%s %s", str_replace('_', ' ', substr(strrchr($timezone, '/'), 1)), $tz->format('P') )); } $groups[] = array('label' => ucwords(strtolower($zone)), 'options' => $options); } return $groups; }
php
public static function getTimezonesSelectOptions($selected = null) { $zones = self::getZones(); $groups = array(); foreach ($zones as $zone => $value) { if ($value >= 1024) { break; } $timezones = self::getTimezones($zone); $options = array(); foreach ($timezones as $timezone) { $tz = new DateTime('now', new DateTimeZone($timezone)); $options[] = array($timezone, ($timezone == $selected), sprintf( "%s %s", str_replace('_', ' ', substr(strrchr($timezone, '/'), 1)), $tz->format('P') )); } $groups[] = array('label' => ucwords(strtolower($zone)), 'options' => $options); } return $groups; }
[ "public", "static", "function", "getTimezonesSelectOptions", "(", "$", "selected", "=", "null", ")", "{", "$", "zones", "=", "self", "::", "getZones", "(", ")", ";", "$", "groups", "=", "array", "(", ")", ";", "foreach", "(", "$", "zones", "as", "$", "zone", "=>", "$", "value", ")", "{", "if", "(", "$", "value", ">=", "1024", ")", "{", "break", ";", "}", "$", "timezones", "=", "self", "::", "getTimezones", "(", "$", "zone", ")", ";", "$", "options", "=", "array", "(", ")", ";", "foreach", "(", "$", "timezones", "as", "$", "timezone", ")", "{", "$", "tz", "=", "new", "DateTime", "(", "'now'", ",", "new", "DateTimeZone", "(", "$", "timezone", ")", ")", ";", "$", "options", "[", "]", "=", "array", "(", "$", "timezone", ",", "(", "$", "timezone", "==", "$", "selected", ")", ",", "sprintf", "(", "\"%s %s\"", ",", "str_replace", "(", "'_'", ",", "' '", ",", "substr", "(", "strrchr", "(", "$", "timezone", ",", "'/'", ")", ",", "1", ")", ")", ",", "$", "tz", "->", "format", "(", "'P'", ")", ")", ")", ";", "}", "$", "groups", "[", "]", "=", "array", "(", "'label'", "=>", "ucwords", "(", "strtolower", "(", "$", "zone", ")", ")", ",", "'options'", "=>", "$", "options", ")", ";", "}", "return", "$", "groups", ";", "}" ]
Loads all available timezones using `getTimezones()` and builds an array where timezones are grouped by their region (Europe/America etc.) The options array that is returned is designed to be used with `Widget::Select` @since Symphony 2.3 @see core.DateTimeObj#getTimezones() @see core.Widget#Select() @param string $selected A preselected timezone, defaults to null @return array An associative array, for use with `Widget::Select`
[ "Loads", "all", "available", "timezones", "using", "getTimezones", "()", "and", "builds", "an", "array", "where", "timezones", "are", "grouped", "by", "their", "region", "(", "Europe", "/", "America", "etc", ".", ")", "The", "options", "array", "that", "is", "returned", "is", "designed", "to", "be", "used", "with", "Widget", "::", "Select" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.datetimeobj.php#L383-L410
symphonycms/symphony-2
symphony/lib/core/class.datetimeobj.php
DateTimeObj.getDateFormatsSelectOptions
public static function getDateFormatsSelectOptions($selected = null) { $formats = self::getDateFormats(); $options = array(); foreach ($formats as $option) { $leadingZero = ''; if (strpos($option, 'j') !== false || strpos($option, 'n') !== false) { $leadingZero = ' (' . __('no leading zeros') . ')'; } $options[] = array($option, $option == $selected, self::format('now', $option) . $leadingZero); } return $options; }
php
public static function getDateFormatsSelectOptions($selected = null) { $formats = self::getDateFormats(); $options = array(); foreach ($formats as $option) { $leadingZero = ''; if (strpos($option, 'j') !== false || strpos($option, 'n') !== false) { $leadingZero = ' (' . __('no leading zeros') . ')'; } $options[] = array($option, $option == $selected, self::format('now', $option) . $leadingZero); } return $options; }
[ "public", "static", "function", "getDateFormatsSelectOptions", "(", "$", "selected", "=", "null", ")", "{", "$", "formats", "=", "self", "::", "getDateFormats", "(", ")", ";", "$", "options", "=", "array", "(", ")", ";", "foreach", "(", "$", "formats", "as", "$", "option", ")", "{", "$", "leadingZero", "=", "''", ";", "if", "(", "strpos", "(", "$", "option", ",", "'j'", ")", "!==", "false", "||", "strpos", "(", "$", "option", ",", "'n'", ")", "!==", "false", ")", "{", "$", "leadingZero", "=", "' ('", ".", "__", "(", "'no leading zeros'", ")", ".", "')'", ";", "}", "$", "options", "[", "]", "=", "array", "(", "$", "option", ",", "$", "option", "==", "$", "selected", ",", "self", "::", "format", "(", "'now'", ",", "$", "option", ")", ".", "$", "leadingZero", ")", ";", "}", "return", "$", "options", ";", "}" ]
Returns an array of the date formats Symphony supports by applying the format to the current datetime. The array returned is for use with `Widget::Select()` @since Symphony 2.3 @see core.Widget#Select() @param string $selected A preselected date format, defaults to null @return array An associative array, for use with `Widget::Select`
[ "Returns", "an", "array", "of", "the", "date", "formats", "Symphony", "supports", "by", "applying", "the", "format", "to", "the", "current", "datetime", ".", "The", "array", "returned", "is", "for", "use", "with", "Widget", "::", "Select", "()" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.datetimeobj.php#L489-L505
symphonycms/symphony-2
symphony/lib/core/class.datetimeobj.php
DateTimeObj.getTimeFormatsSelectOptions
public static function getTimeFormatsSelectOptions($selected = null) { $formats = self::getTimeFormats(); $options = array(); foreach ($formats as $option) { $options[] = array($option, $option == $selected, self::get($option)); } return $options; }
php
public static function getTimeFormatsSelectOptions($selected = null) { $formats = self::getTimeFormats(); $options = array(); foreach ($formats as $option) { $options[] = array($option, $option == $selected, self::get($option)); } return $options; }
[ "public", "static", "function", "getTimeFormatsSelectOptions", "(", "$", "selected", "=", "null", ")", "{", "$", "formats", "=", "self", "::", "getTimeFormats", "(", ")", ";", "$", "options", "=", "array", "(", ")", ";", "foreach", "(", "$", "formats", "as", "$", "option", ")", "{", "$", "options", "[", "]", "=", "array", "(", "$", "option", ",", "$", "option", "==", "$", "selected", ",", "self", "::", "get", "(", "$", "option", ")", ")", ";", "}", "return", "$", "options", ";", "}" ]
Returns an array of the time formats Symphony supports by applying the format to the current datetime. The array returned is for use with `Widget::Select()` @since Symphony 2.3 @see core.Widget#Select() @param string $selected A preselected time format, defaults to null @return array An associative array, for use with `Widget::Select`
[ "Returns", "an", "array", "of", "the", "time", "formats", "Symphony", "supports", "by", "applying", "the", "format", "to", "the", "current", "datetime", ".", "The", "array", "returned", "is", "for", "use", "with", "Widget", "::", "Select", "()" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.datetimeobj.php#L571-L581
symphonycms/symphony-2
symphony/lib/core/class.errorhandler.php
GenericExceptionHandler.initialise
public static function initialise(Log $Log = null) { if (!is_null($Log)) { self::$_Log = $Log; } set_exception_handler(array(__CLASS__, 'handler')); register_shutdown_function(array(__CLASS__, 'shutdown')); }
php
public static function initialise(Log $Log = null) { if (!is_null($Log)) { self::$_Log = $Log; } set_exception_handler(array(__CLASS__, 'handler')); register_shutdown_function(array(__CLASS__, 'shutdown')); }
[ "public", "static", "function", "initialise", "(", "Log", "$", "Log", "=", "null", ")", "{", "if", "(", "!", "is_null", "(", "$", "Log", ")", ")", "{", "self", "::", "$", "_Log", "=", "$", "Log", ";", "}", "set_exception_handler", "(", "array", "(", "__CLASS__", ",", "'handler'", ")", ")", ";", "register_shutdown_function", "(", "array", "(", "__CLASS__", ",", "'shutdown'", ")", ")", ";", "}" ]
Initialise will set the error handler to be the `__CLASS__::handler` function. @param Log $Log An instance of a Symphony Log object to write errors to
[ "Initialise", "will", "set", "the", "error", "handler", "to", "be", "the", "__CLASS__", "::", "handler", "function", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.errorhandler.php#L33-L41
symphonycms/symphony-2
symphony/lib/core/class.errorhandler.php
GenericExceptionHandler.__nearbyLines
protected static function __nearbyLines($line, $file, $window = 5) { if (!file_exists($file)) { return array(); } return array_slice(file($file), ($line - 1) - $window, $window * 2, true); }
php
protected static function __nearbyLines($line, $file, $window = 5) { if (!file_exists($file)) { return array(); } return array_slice(file($file), ($line - 1) - $window, $window * 2, true); }
[ "protected", "static", "function", "__nearbyLines", "(", "$", "line", ",", "$", "file", ",", "$", "window", "=", "5", ")", "{", "if", "(", "!", "file_exists", "(", "$", "file", ")", ")", "{", "return", "array", "(", ")", ";", "}", "return", "array_slice", "(", "file", "(", "$", "file", ")", ",", "(", "$", "line", "-", "1", ")", "-", "$", "window", ",", "$", "window", "*", "2", ",", "true", ")", ";", "}" ]
Retrieves a window of lines before and after the line where the error occurred so that a developer can help debug the exception @param integer $line The line where the error occurred. @param string $file The file that holds the logic that caused the error. @param integer $window The number of lines either side of the line where the error occurred to show @return array
[ "Retrieves", "a", "window", "of", "lines", "before", "and", "after", "the", "line", "where", "the", "error", "occurred", "so", "that", "a", "developer", "can", "help", "debug", "the", "exception" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.errorhandler.php#L56-L63
symphonycms/symphony-2
symphony/lib/core/class.errorhandler.php
GenericExceptionHandler.handler
public static function handler($e) { $output = ''; try { // Instead of just throwing an empty page, return a 404 page. if (self::$enabled !== true) { $e = new FrontendPageNotFoundException(); } // Validate the type, resolve to a 404 if not valid if (!static::isValidThrowable($e)) { $e = new FrontendPageNotFoundException(); } $exception_type = get_class($e); if (class_exists("{$exception_type}Handler") && method_exists("{$exception_type}Handler", 'render')) { $class = "{$exception_type}Handler"; } else { $class = __CLASS__; } // Exceptions should be logged if they are not caught. if (self::$_Log instanceof Log) { self::$_Log->pushExceptionToLog($e, true); } $output = call_user_func(array($class, 'render'), $e); // If an exception was raised trying to render the exception, fall back // to the generic exception handler } catch (Exception $e) { try { $output = call_user_func(array('GenericExceptionHandler', 'render'), $e); // If the generic exception handler couldn't do it, well we're in bad // shape, just output a plaintext response! } catch (Exception $e) { echo "<pre>"; echo 'A severe error occurred whilst trying to handle an exception, check the Symphony log for more details' . PHP_EOL; echo $e->getMessage() . ' on ' . $e->getLine() . ' of file ' . $e->getFile() . PHP_EOL; exit; } } // Pending nothing disasterous, we should have `$e` and `$output` values here. if (!headers_sent()) { cleanup_session_cookies(); // Inspect the exception to determine the best status code $httpStatus = null; if ($e instanceof SymphonyErrorPage) { $httpStatus = $e->getHttpStatusCode(); } elseif ($e instanceof FrontendPageNotFoundException) { $httpStatus = Page::HTTP_STATUS_NOT_FOUND; } if (!$httpStatus || $httpStatus == Page::HTTP_STATUS_OK) { $httpStatus = Page::HTTP_STATUS_ERROR; } Page::renderStatusCode($httpStatus); header('Content-Type: text/html; charset=utf-8'); } echo $output; exit; }
php
public static function handler($e) { $output = ''; try { // Instead of just throwing an empty page, return a 404 page. if (self::$enabled !== true) { $e = new FrontendPageNotFoundException(); } // Validate the type, resolve to a 404 if not valid if (!static::isValidThrowable($e)) { $e = new FrontendPageNotFoundException(); } $exception_type = get_class($e); if (class_exists("{$exception_type}Handler") && method_exists("{$exception_type}Handler", 'render')) { $class = "{$exception_type}Handler"; } else { $class = __CLASS__; } // Exceptions should be logged if they are not caught. if (self::$_Log instanceof Log) { self::$_Log->pushExceptionToLog($e, true); } $output = call_user_func(array($class, 'render'), $e); // If an exception was raised trying to render the exception, fall back // to the generic exception handler } catch (Exception $e) { try { $output = call_user_func(array('GenericExceptionHandler', 'render'), $e); // If the generic exception handler couldn't do it, well we're in bad // shape, just output a plaintext response! } catch (Exception $e) { echo "<pre>"; echo 'A severe error occurred whilst trying to handle an exception, check the Symphony log for more details' . PHP_EOL; echo $e->getMessage() . ' on ' . $e->getLine() . ' of file ' . $e->getFile() . PHP_EOL; exit; } } // Pending nothing disasterous, we should have `$e` and `$output` values here. if (!headers_sent()) { cleanup_session_cookies(); // Inspect the exception to determine the best status code $httpStatus = null; if ($e instanceof SymphonyErrorPage) { $httpStatus = $e->getHttpStatusCode(); } elseif ($e instanceof FrontendPageNotFoundException) { $httpStatus = Page::HTTP_STATUS_NOT_FOUND; } if (!$httpStatus || $httpStatus == Page::HTTP_STATUS_OK) { $httpStatus = Page::HTTP_STATUS_ERROR; } Page::renderStatusCode($httpStatus); header('Content-Type: text/html; charset=utf-8'); } echo $output; exit; }
[ "public", "static", "function", "handler", "(", "$", "e", ")", "{", "$", "output", "=", "''", ";", "try", "{", "// Instead of just throwing an empty page, return a 404 page.", "if", "(", "self", "::", "$", "enabled", "!==", "true", ")", "{", "$", "e", "=", "new", "FrontendPageNotFoundException", "(", ")", ";", "}", "// Validate the type, resolve to a 404 if not valid", "if", "(", "!", "static", "::", "isValidThrowable", "(", "$", "e", ")", ")", "{", "$", "e", "=", "new", "FrontendPageNotFoundException", "(", ")", ";", "}", "$", "exception_type", "=", "get_class", "(", "$", "e", ")", ";", "if", "(", "class_exists", "(", "\"{$exception_type}Handler\"", ")", "&&", "method_exists", "(", "\"{$exception_type}Handler\"", ",", "'render'", ")", ")", "{", "$", "class", "=", "\"{$exception_type}Handler\"", ";", "}", "else", "{", "$", "class", "=", "__CLASS__", ";", "}", "// Exceptions should be logged if they are not caught.", "if", "(", "self", "::", "$", "_Log", "instanceof", "Log", ")", "{", "self", "::", "$", "_Log", "->", "pushExceptionToLog", "(", "$", "e", ",", "true", ")", ";", "}", "$", "output", "=", "call_user_func", "(", "array", "(", "$", "class", ",", "'render'", ")", ",", "$", "e", ")", ";", "// If an exception was raised trying to render the exception, fall back", "// to the generic exception handler", "}", "catch", "(", "Exception", "$", "e", ")", "{", "try", "{", "$", "output", "=", "call_user_func", "(", "array", "(", "'GenericExceptionHandler'", ",", "'render'", ")", ",", "$", "e", ")", ";", "// If the generic exception handler couldn't do it, well we're in bad", "// shape, just output a plaintext response!", "}", "catch", "(", "Exception", "$", "e", ")", "{", "echo", "\"<pre>\"", ";", "echo", "'A severe error occurred whilst trying to handle an exception, check the Symphony log for more details'", ".", "PHP_EOL", ";", "echo", "$", "e", "->", "getMessage", "(", ")", ".", "' on '", ".", "$", "e", "->", "getLine", "(", ")", ".", "' of file '", ".", "$", "e", "->", "getFile", "(", ")", ".", "PHP_EOL", ";", "exit", ";", "}", "}", "// Pending nothing disasterous, we should have `$e` and `$output` values here.", "if", "(", "!", "headers_sent", "(", ")", ")", "{", "cleanup_session_cookies", "(", ")", ";", "// Inspect the exception to determine the best status code", "$", "httpStatus", "=", "null", ";", "if", "(", "$", "e", "instanceof", "SymphonyErrorPage", ")", "{", "$", "httpStatus", "=", "$", "e", "->", "getHttpStatusCode", "(", ")", ";", "}", "elseif", "(", "$", "e", "instanceof", "FrontendPageNotFoundException", ")", "{", "$", "httpStatus", "=", "Page", "::", "HTTP_STATUS_NOT_FOUND", ";", "}", "if", "(", "!", "$", "httpStatus", "||", "$", "httpStatus", "==", "Page", "::", "HTTP_STATUS_OK", ")", "{", "$", "httpStatus", "=", "Page", "::", "HTTP_STATUS_ERROR", ";", "}", "Page", "::", "renderStatusCode", "(", "$", "httpStatus", ")", ";", "header", "(", "'Content-Type: text/html; charset=utf-8'", ")", ";", "}", "echo", "$", "output", ";", "exit", ";", "}" ]
The handler function is given an Throwable and will call it's render function to display the Throwable to a user. After calling the render function, the output is displayed and then exited to prevent any further logic from occurring. @since Symphony 2.7.0 This function works with both Exception and Throwable Supporting both PHP 5.6 and 7 forces use to not qualify the $e parameter @param Throwable $e The Throwable object @return string The result of the Throwable's render function
[ "The", "handler", "function", "is", "given", "an", "Throwable", "and", "will", "call", "it", "s", "render", "function", "to", "display", "the", "Throwable", "to", "a", "user", ".", "After", "calling", "the", "render", "function", "the", "output", "is", "displayed", "and", "then", "exited", "to", "prevent", "any", "further", "logic", "from", "occurring", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.errorhandler.php#L95-L163
symphonycms/symphony-2
symphony/lib/core/class.errorhandler.php
GenericExceptionHandler.getTemplate
public static function getTemplate($name) { $format = '%s/%s.tpl'; if (file_exists($template = sprintf($format, WORKSPACE . '/template', $name))) { return $template; } elseif (file_exists($template = sprintf($format, TEMPLATE, $name))) { return $template; } else { return false; } }
php
public static function getTemplate($name) { $format = '%s/%s.tpl'; if (file_exists($template = sprintf($format, WORKSPACE . '/template', $name))) { return $template; } elseif (file_exists($template = sprintf($format, TEMPLATE, $name))) { return $template; } else { return false; } }
[ "public", "static", "function", "getTemplate", "(", "$", "name", ")", "{", "$", "format", "=", "'%s/%s.tpl'", ";", "if", "(", "file_exists", "(", "$", "template", "=", "sprintf", "(", "$", "format", ",", "WORKSPACE", ".", "'/template'", ",", "$", "name", ")", ")", ")", "{", "return", "$", "template", ";", "}", "elseif", "(", "file_exists", "(", "$", "template", "=", "sprintf", "(", "$", "format", ",", "TEMPLATE", ",", "$", "name", ")", ")", ")", "{", "return", "$", "template", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Returns the path to the error-template by looking at the `WORKSPACE/template/` directory, then at the `TEMPLATES` directory for the convention `*.tpl`. If the template is not found, `false` is returned @since Symphony 2.3 @param string $name Name of the template @return string|false String, which is the path to the template if the template is found, false otherwise
[ "Returns", "the", "path", "to", "the", "error", "-", "template", "by", "looking", "at", "the", "WORKSPACE", "/", "template", "/", "directory", "then", "at", "the", "TEMPLATES", "directory", "for", "the", "convention", "*", ".", "tpl", ".", "If", "the", "template", "is", "not", "found", "false", "is", "returned" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.errorhandler.php#L177-L188
symphonycms/symphony-2
symphony/lib/core/class.errorhandler.php
GenericExceptionHandler.render
public static function render($e) { $lines = null; foreach (self::__nearByLines($e->getLine(), $e->getFile()) as $line => $string) { $lines .= sprintf( '<li%s><strong>%d</strong> <code>%s</code></li>', (($line+1) == $e->getLine() ? ' class="error"' : null), ++$line, str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', htmlspecialchars($string)) ); } $trace = null; foreach ($e->getTrace() as $t) { $trace .= sprintf( '<li><code><em>[%s:%d]</em></code></li><li><code>&#160;&#160;&#160;&#160;%s%s%s();</code></li>', (isset($t['file']) ? $t['file'] : null), (isset($t['line']) ? $t['line'] : null), (isset($t['class']) ? $t['class'] : null), (isset($t['type']) ? $t['type'] : null), $t['function'] ); } $queries = null; if (is_object(Symphony::Database())) { $debug = Symphony::Database()->debug(); if (!empty($debug)) { foreach ($debug as $query) { $queries .= sprintf( '<li><em>[%01.4f]</em><code> %s;</code> </li>', (isset($query['execution_time']) ? $query['execution_time'] : null), htmlspecialchars($query['query']) ); } } } return self::renderHtml( 'fatalerror.generic', ($e instanceof ErrorException ? GenericErrorHandler::$errorTypeStrings[$e->getSeverity()] : 'Fatal Error'), $e->getMessage(), $e->getFile(), $e->getLine(), $lines, $trace, $queries ); }
php
public static function render($e) { $lines = null; foreach (self::__nearByLines($e->getLine(), $e->getFile()) as $line => $string) { $lines .= sprintf( '<li%s><strong>%d</strong> <code>%s</code></li>', (($line+1) == $e->getLine() ? ' class="error"' : null), ++$line, str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', htmlspecialchars($string)) ); } $trace = null; foreach ($e->getTrace() as $t) { $trace .= sprintf( '<li><code><em>[%s:%d]</em></code></li><li><code>&#160;&#160;&#160;&#160;%s%s%s();</code></li>', (isset($t['file']) ? $t['file'] : null), (isset($t['line']) ? $t['line'] : null), (isset($t['class']) ? $t['class'] : null), (isset($t['type']) ? $t['type'] : null), $t['function'] ); } $queries = null; if (is_object(Symphony::Database())) { $debug = Symphony::Database()->debug(); if (!empty($debug)) { foreach ($debug as $query) { $queries .= sprintf( '<li><em>[%01.4f]</em><code> %s;</code> </li>', (isset($query['execution_time']) ? $query['execution_time'] : null), htmlspecialchars($query['query']) ); } } } return self::renderHtml( 'fatalerror.generic', ($e instanceof ErrorException ? GenericErrorHandler::$errorTypeStrings[$e->getSeverity()] : 'Fatal Error'), $e->getMessage(), $e->getFile(), $e->getLine(), $lines, $trace, $queries ); }
[ "public", "static", "function", "render", "(", "$", "e", ")", "{", "$", "lines", "=", "null", ";", "foreach", "(", "self", "::", "__nearByLines", "(", "$", "e", "->", "getLine", "(", ")", ",", "$", "e", "->", "getFile", "(", ")", ")", "as", "$", "line", "=>", "$", "string", ")", "{", "$", "lines", ".=", "sprintf", "(", "'<li%s><strong>%d</strong> <code>%s</code></li>'", ",", "(", "(", "$", "line", "+", "1", ")", "==", "$", "e", "->", "getLine", "(", ")", "?", "' class=\"error\"'", ":", "null", ")", ",", "++", "$", "line", ",", "str_replace", "(", "\"\\t\"", ",", "'&nbsp;&nbsp;&nbsp;&nbsp;'", ",", "htmlspecialchars", "(", "$", "string", ")", ")", ")", ";", "}", "$", "trace", "=", "null", ";", "foreach", "(", "$", "e", "->", "getTrace", "(", ")", "as", "$", "t", ")", "{", "$", "trace", ".=", "sprintf", "(", "'<li><code><em>[%s:%d]</em></code></li><li><code>&#160;&#160;&#160;&#160;%s%s%s();</code></li>'", ",", "(", "isset", "(", "$", "t", "[", "'file'", "]", ")", "?", "$", "t", "[", "'file'", "]", ":", "null", ")", ",", "(", "isset", "(", "$", "t", "[", "'line'", "]", ")", "?", "$", "t", "[", "'line'", "]", ":", "null", ")", ",", "(", "isset", "(", "$", "t", "[", "'class'", "]", ")", "?", "$", "t", "[", "'class'", "]", ":", "null", ")", ",", "(", "isset", "(", "$", "t", "[", "'type'", "]", ")", "?", "$", "t", "[", "'type'", "]", ":", "null", ")", ",", "$", "t", "[", "'function'", "]", ")", ";", "}", "$", "queries", "=", "null", ";", "if", "(", "is_object", "(", "Symphony", "::", "Database", "(", ")", ")", ")", "{", "$", "debug", "=", "Symphony", "::", "Database", "(", ")", "->", "debug", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "debug", ")", ")", "{", "foreach", "(", "$", "debug", "as", "$", "query", ")", "{", "$", "queries", ".=", "sprintf", "(", "'<li><em>[%01.4f]</em><code> %s;</code> </li>'", ",", "(", "isset", "(", "$", "query", "[", "'execution_time'", "]", ")", "?", "$", "query", "[", "'execution_time'", "]", ":", "null", ")", ",", "htmlspecialchars", "(", "$", "query", "[", "'query'", "]", ")", ")", ";", "}", "}", "}", "return", "self", "::", "renderHtml", "(", "'fatalerror.generic'", ",", "(", "$", "e", "instanceof", "ErrorException", "?", "GenericErrorHandler", "::", "$", "errorTypeStrings", "[", "$", "e", "->", "getSeverity", "(", ")", "]", ":", "'Fatal Error'", ")", ",", "$", "e", "->", "getMessage", "(", ")", ",", "$", "e", "->", "getFile", "(", ")", ",", "$", "e", "->", "getLine", "(", ")", ",", "$", "lines", ",", "$", "trace", ",", "$", "queries", ")", ";", "}" ]
The render function will take an Throwable and output a HTML page @since Symphony 2.7.0 This function works with both Exception and Throwable @param Throwable $e The Throwable object @return string An HTML string
[ "The", "render", "function", "will", "take", "an", "Throwable", "and", "output", "a", "HTML", "page" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.errorhandler.php#L201-L253
symphonycms/symphony-2
symphony/lib/core/class.errorhandler.php
GenericExceptionHandler.shutdown
public static function shutdown() { $last_error = error_get_last(); if (!is_null($last_error) && $last_error['type'] === E_ERROR) { $code = $last_error['type']; $message = $last_error['message']; $file = $last_error['file']; $line = $last_error['line']; try { // Log the error message if (self::$_Log instanceof Log) { self::$_Log->pushToLog(sprintf( '%s %s: %s%s%s', __CLASS__, $code, $message, ($line ? " on line $line" : null), ($file ? " of file $file" : null) ), $code, true); } ob_clean(); // Display the error message echo self::renderHtml( 'fatalerror.fatal', 'Fatal Error', $message, $file, $line ); } catch (Exception $e) { echo "<pre>"; echo 'A severe error occurred whilst trying to handle an exception, check the Symphony log for more details' . PHP_EOL; echo $e->getMessage() . ' on ' . $e->getLine() . ' of file ' . $e->getFile() . PHP_EOL; } } }
php
public static function shutdown() { $last_error = error_get_last(); if (!is_null($last_error) && $last_error['type'] === E_ERROR) { $code = $last_error['type']; $message = $last_error['message']; $file = $last_error['file']; $line = $last_error['line']; try { // Log the error message if (self::$_Log instanceof Log) { self::$_Log->pushToLog(sprintf( '%s %s: %s%s%s', __CLASS__, $code, $message, ($line ? " on line $line" : null), ($file ? " of file $file" : null) ), $code, true); } ob_clean(); // Display the error message echo self::renderHtml( 'fatalerror.fatal', 'Fatal Error', $message, $file, $line ); } catch (Exception $e) { echo "<pre>"; echo 'A severe error occurred whilst trying to handle an exception, check the Symphony log for more details' . PHP_EOL; echo $e->getMessage() . ' on ' . $e->getLine() . ' of file ' . $e->getFile() . PHP_EOL; } } }
[ "public", "static", "function", "shutdown", "(", ")", "{", "$", "last_error", "=", "error_get_last", "(", ")", ";", "if", "(", "!", "is_null", "(", "$", "last_error", ")", "&&", "$", "last_error", "[", "'type'", "]", "===", "E_ERROR", ")", "{", "$", "code", "=", "$", "last_error", "[", "'type'", "]", ";", "$", "message", "=", "$", "last_error", "[", "'message'", "]", ";", "$", "file", "=", "$", "last_error", "[", "'file'", "]", ";", "$", "line", "=", "$", "last_error", "[", "'line'", "]", ";", "try", "{", "// Log the error message", "if", "(", "self", "::", "$", "_Log", "instanceof", "Log", ")", "{", "self", "::", "$", "_Log", "->", "pushToLog", "(", "sprintf", "(", "'%s %s: %s%s%s'", ",", "__CLASS__", ",", "$", "code", ",", "$", "message", ",", "(", "$", "line", "?", "\" on line $line\"", ":", "null", ")", ",", "(", "$", "file", "?", "\" of file $file\"", ":", "null", ")", ")", ",", "$", "code", ",", "true", ")", ";", "}", "ob_clean", "(", ")", ";", "// Display the error message", "echo", "self", "::", "renderHtml", "(", "'fatalerror.fatal'", ",", "'Fatal Error'", ",", "$", "message", ",", "$", "file", ",", "$", "line", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "echo", "\"<pre>\"", ";", "echo", "'A severe error occurred whilst trying to handle an exception, check the Symphony log for more details'", ".", "PHP_EOL", ";", "echo", "$", "e", "->", "getMessage", "(", ")", ".", "' on '", ".", "$", "e", "->", "getLine", "(", ")", ".", "' of file '", ".", "$", "e", "->", "getFile", "(", ")", ".", "PHP_EOL", ";", "}", "}", "}" ]
The shutdown function will capture any fatal errors and format them as a usual Symphony page. @since Symphony 2.4
[ "The", "shutdown", "function", "will", "capture", "any", "fatal", "errors", "and", "format", "them", "as", "a", "usual", "Symphony", "page", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.errorhandler.php#L261-L300
symphonycms/symphony-2
symphony/lib/core/class.errorhandler.php
GenericExceptionHandler.renderHtml
public static function renderHtml($template, $heading, $message, $file = null, $line = null, $lines = null, $trace = null, $queries = null) { $html = sprintf( file_get_contents(self::getTemplate($template)), $heading, General::unwrapCDATA($message), $file, $line, $lines, $trace, $queries ); $html = str_replace('{ASSETS_URL}', ASSETS_URL, $html); $html = str_replace('{SYMPHONY_URL}', SYMPHONY_URL, $html); $html = str_replace('{URL}', URL, $html); return $html; }
php
public static function renderHtml($template, $heading, $message, $file = null, $line = null, $lines = null, $trace = null, $queries = null) { $html = sprintf( file_get_contents(self::getTemplate($template)), $heading, General::unwrapCDATA($message), $file, $line, $lines, $trace, $queries ); $html = str_replace('{ASSETS_URL}', ASSETS_URL, $html); $html = str_replace('{SYMPHONY_URL}', SYMPHONY_URL, $html); $html = str_replace('{URL}', URL, $html); return $html; }
[ "public", "static", "function", "renderHtml", "(", "$", "template", ",", "$", "heading", ",", "$", "message", ",", "$", "file", "=", "null", ",", "$", "line", "=", "null", ",", "$", "lines", "=", "null", ",", "$", "trace", "=", "null", ",", "$", "queries", "=", "null", ")", "{", "$", "html", "=", "sprintf", "(", "file_get_contents", "(", "self", "::", "getTemplate", "(", "$", "template", ")", ")", ",", "$", "heading", ",", "General", "::", "unwrapCDATA", "(", "$", "message", ")", ",", "$", "file", ",", "$", "line", ",", "$", "lines", ",", "$", "trace", ",", "$", "queries", ")", ";", "$", "html", "=", "str_replace", "(", "'{ASSETS_URL}'", ",", "ASSETS_URL", ",", "$", "html", ")", ";", "$", "html", "=", "str_replace", "(", "'{SYMPHONY_URL}'", ",", "SYMPHONY_URL", ",", "$", "html", ")", ";", "$", "html", "=", "str_replace", "(", "'{URL}'", ",", "URL", ",", "$", "html", ")", ";", "return", "$", "html", ";", "}" ]
This function will fetch the desired `$template`, and output the Throwable in a user friendly way. @since Symphony 2.4 @param string $template The template name, which should correspond to something in the TEMPLATE directory, eg `fatalerror.fatal`. @since Symphony 2.7.0 This function works with both Exception and Throwable @param string $heading @param string $message @param string $file @param string $line @param string $lines @param string $trace @param string $queries @return string The HTML of the formatted error message.
[ "This", "function", "will", "fetch", "the", "desired", "$template", "and", "output", "the", "Throwable", "in", "a", "user", "friendly", "way", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.errorhandler.php#L324-L342
symphonycms/symphony-2
symphony/lib/core/class.errorhandler.php
GenericErrorHandler.initialise
public static function initialise(Log $Log = null) { if (!is_null($Log)) { self::$_Log = $Log; } set_error_handler(array(__CLASS__, 'handler'), error_reporting()); }
php
public static function initialise(Log $Log = null) { if (!is_null($Log)) { self::$_Log = $Log; } set_error_handler(array(__CLASS__, 'handler'), error_reporting()); }
[ "public", "static", "function", "initialise", "(", "Log", "$", "Log", "=", "null", ")", "{", "if", "(", "!", "is_null", "(", "$", "Log", ")", ")", "{", "self", "::", "$", "_Log", "=", "$", "Log", ";", "}", "set_error_handler", "(", "array", "(", "__CLASS__", ",", "'handler'", ")", ",", "error_reporting", "(", ")", ")", ";", "}" ]
Initialise will set the error handler to be the `__CLASS__::handler` function. @param Log|null $Log (optional) An instance of a Symphony Log object to write errors to
[ "Initialise", "will", "set", "the", "error", "handler", "to", "be", "the", "__CLASS__", "::", "handler", "function", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.errorhandler.php#L413-L420
symphonycms/symphony-2
symphony/lib/core/class.errorhandler.php
GenericErrorHandler.handler
public static function handler($code, $message, $file = null, $line = null) { // Only log if the error won't be raised to an exception and the error is not `E_STRICT` if (!self::$logDisabled && !in_array($code, array(E_STRICT)) && self::$_Log instanceof Log) { self::$_Log->pushToLog(sprintf( '%s %s: %s%s%s', __CLASS__, $code, $message, ($line ? " on line $line" : null), ($file ? " of file $file" : null) ), $code, true); } if (self::isEnabled()) { throw new ErrorException($message, 0, $code, $file, $line); } // This is needed to stop php from processing the error // See http://php.net/manual/en/function.set-error-handler.php return true; }
php
public static function handler($code, $message, $file = null, $line = null) { // Only log if the error won't be raised to an exception and the error is not `E_STRICT` if (!self::$logDisabled && !in_array($code, array(E_STRICT)) && self::$_Log instanceof Log) { self::$_Log->pushToLog(sprintf( '%s %s: %s%s%s', __CLASS__, $code, $message, ($line ? " on line $line" : null), ($file ? " of file $file" : null) ), $code, true); } if (self::isEnabled()) { throw new ErrorException($message, 0, $code, $file, $line); } // This is needed to stop php from processing the error // See http://php.net/manual/en/function.set-error-handler.php return true; }
[ "public", "static", "function", "handler", "(", "$", "code", ",", "$", "message", ",", "$", "file", "=", "null", ",", "$", "line", "=", "null", ")", "{", "// Only log if the error won't be raised to an exception and the error is not `E_STRICT`", "if", "(", "!", "self", "::", "$", "logDisabled", "&&", "!", "in_array", "(", "$", "code", ",", "array", "(", "E_STRICT", ")", ")", "&&", "self", "::", "$", "_Log", "instanceof", "Log", ")", "{", "self", "::", "$", "_Log", "->", "pushToLog", "(", "sprintf", "(", "'%s %s: %s%s%s'", ",", "__CLASS__", ",", "$", "code", ",", "$", "message", ",", "(", "$", "line", "?", "\" on line $line\"", ":", "null", ")", ",", "(", "$", "file", "?", "\" of file $file\"", ":", "null", ")", ")", ",", "$", "code", ",", "true", ")", ";", "}", "if", "(", "self", "::", "isEnabled", "(", ")", ")", "{", "throw", "new", "ErrorException", "(", "$", "message", ",", "0", ",", "$", "code", ",", "$", "file", ",", "$", "line", ")", ";", "}", "// This is needed to stop php from processing the error", "// See http://php.net/manual/en/function.set-error-handler.php", "return", "true", ";", "}" ]
The handler function will write the error to the `$Log` if it is not `E_NOTICE` or `E_STRICT` before raising the error as an Exception. This allows all `E_WARNING` to actually be captured by an Exception handler. @param integer $code The error code, one of the PHP error constants @param string $message The message of the error, this will be written to the log and displayed as the exception message @param string $file The file that holds the logic that caused the error. Defaults to null @param integer $line The line where the error occurred. @throws ErrorException @return boolean Usually a string of HTML that will displayed to a user
[ "The", "handler", "function", "will", "write", "the", "error", "to", "the", "$Log", "if", "it", "is", "not", "E_NOTICE", "or", "E_STRICT", "before", "raising", "the", "error", "as", "an", "Exception", ".", "This", "allows", "all", "E_WARNING", "to", "actually", "be", "captured", "by", "an", "Exception", "handler", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.errorhandler.php#L451-L472
symphonycms/symphony-2
symphony/lib/core/class.cacheable.php
Cacheable.write
public function write($hash, $data, $ttl = null, $namespace = null) { if ($this->cacheProvider instanceof iNamespacedCache) { return $this->cacheProvider->write($hash, $data, $ttl, $namespace); } return $this->cacheProvider->write($hash, $data, $ttl); }
php
public function write($hash, $data, $ttl = null, $namespace = null) { if ($this->cacheProvider instanceof iNamespacedCache) { return $this->cacheProvider->write($hash, $data, $ttl, $namespace); } return $this->cacheProvider->write($hash, $data, $ttl); }
[ "public", "function", "write", "(", "$", "hash", ",", "$", "data", ",", "$", "ttl", "=", "null", ",", "$", "namespace", "=", "null", ")", "{", "if", "(", "$", "this", "->", "cacheProvider", "instanceof", "iNamespacedCache", ")", "{", "return", "$", "this", "->", "cacheProvider", "->", "write", "(", "$", "hash", ",", "$", "data", ",", "$", "ttl", ",", "$", "namespace", ")", ";", "}", "return", "$", "this", "->", "cacheProvider", "->", "write", "(", "$", "hash", ",", "$", "data", ",", "$", "ttl", ")", ";", "}" ]
A wrapper for writing data in the cache. @param string $hash A @param string $data The data to be cached @param integer $ttl A integer representing how long the data should be valid for in minutes. By default this is null, meaning the data is valid forever @param string $namespace Write an item and save in a namespace for ease of bulk operations later @return boolean If an error occurs, this function will return false otherwise true
[ "A", "wrapper", "for", "writing", "data", "in", "the", "cache", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.cacheable.php#L81-L88
symphonycms/symphony-2
symphony/lib/core/class.cacheable.php
Cacheable.read
public function read($hash, $namespace = null) { if ($this->cacheProvider instanceof iNamespacedCache) { return $this->cacheProvider->read($hash, $namespace); } return $this->cacheProvider->read($hash); }
php
public function read($hash, $namespace = null) { if ($this->cacheProvider instanceof iNamespacedCache) { return $this->cacheProvider->read($hash, $namespace); } return $this->cacheProvider->read($hash); }
[ "public", "function", "read", "(", "$", "hash", ",", "$", "namespace", "=", "null", ")", "{", "if", "(", "$", "this", "->", "cacheProvider", "instanceof", "iNamespacedCache", ")", "{", "return", "$", "this", "->", "cacheProvider", "->", "read", "(", "$", "hash", ",", "$", "namespace", ")", ";", "}", "return", "$", "this", "->", "cacheProvider", "->", "read", "(", "$", "hash", ")", ";", "}" ]
Given the hash of a some data, check to see whether it exists the cache. @param string $hash The hash of the Cached object, as defined by the user @param string $namespace Read multiple items by a namespace @return mixed
[ "Given", "the", "hash", "of", "a", "some", "data", "check", "to", "see", "whether", "it", "exists", "the", "cache", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.cacheable.php#L99-L106
symphonycms/symphony-2
symphony/lib/core/class.cacheable.php
Cacheable.delete
public function delete($hash = null, $namespace = null) { if ($this->cacheProvider instanceof iNamespacedCache) { return $this->cacheProvider->delete($hash, $namespace); } return $this->cacheProvider->delete($hash); }
php
public function delete($hash = null, $namespace = null) { if ($this->cacheProvider instanceof iNamespacedCache) { return $this->cacheProvider->delete($hash, $namespace); } return $this->cacheProvider->delete($hash); }
[ "public", "function", "delete", "(", "$", "hash", "=", "null", ",", "$", "namespace", "=", "null", ")", "{", "if", "(", "$", "this", "->", "cacheProvider", "instanceof", "iNamespacedCache", ")", "{", "return", "$", "this", "->", "cacheProvider", "->", "delete", "(", "$", "hash", ",", "$", "namespace", ")", ";", "}", "return", "$", "this", "->", "cacheProvider", "->", "delete", "(", "$", "hash", ")", ";", "}" ]
Given the hash, this function will remove it from the cache. @param string $hash The user defined hash of the data @param string $namespace Delete multiple items by a namespace @return boolean
[ "Given", "the", "hash", "this", "function", "will", "remove", "it", "from", "the", "cache", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.cacheable.php#L117-L124
symphonycms/symphony-2
symphony/lib/core/class.cacheable.php
Cacheable.check
public function check($hash) { if (Symphony::Log()) { Symphony::Log()->pushDeprecateWarningToLog('Cacheable::check()', 'Cacheable::read()'); } return $this->read($hash); }
php
public function check($hash) { if (Symphony::Log()) { Symphony::Log()->pushDeprecateWarningToLog('Cacheable::check()', 'Cacheable::read()'); } return $this->read($hash); }
[ "public", "function", "check", "(", "$", "hash", ")", "{", "if", "(", "Symphony", "::", "Log", "(", ")", ")", "{", "Symphony", "::", "Log", "(", ")", "->", "pushDeprecateWarningToLog", "(", "'Cacheable::check()'", ",", "'Cacheable::read()'", ")", ";", "}", "return", "$", "this", "->", "read", "(", "$", "hash", ")", ";", "}" ]
@deprecated This function will be removed in Symphony 3.0. Use `read()` instead. @param string $hash The hash of the Cached object, as defined by the user @return mixed
[ "@deprecated", "This", "function", "will", "be", "removed", "in", "Symphony", "3", ".", "0", ".", "Use", "read", "()", "instead", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.cacheable.php#L178-L184
symphonycms/symphony-2
symphony/lib/core/class.cacheable.php
Cacheable.forceExpiry
public function forceExpiry($hash) { if (Symphony::Log()) { Symphony::Log()->pushDeprecateWarningToLog('Cacheable::forceExpiry()', 'Cacheable::delete()'); } return $this->delete($hash); }
php
public function forceExpiry($hash) { if (Symphony::Log()) { Symphony::Log()->pushDeprecateWarningToLog('Cacheable::forceExpiry()', 'Cacheable::delete()'); } return $this->delete($hash); }
[ "public", "function", "forceExpiry", "(", "$", "hash", ")", "{", "if", "(", "Symphony", "::", "Log", "(", ")", ")", "{", "Symphony", "::", "Log", "(", ")", "->", "pushDeprecateWarningToLog", "(", "'Cacheable::forceExpiry()'", ",", "'Cacheable::delete()'", ")", ";", "}", "return", "$", "this", "->", "delete", "(", "$", "hash", ")", ";", "}" ]
@deprecated This function will be removed in Symphony 3.0. Use `delete()` instead. @param string $hash The user defined hash of the data @return boolean
[ "@deprecated", "This", "function", "will", "be", "removed", "in", "Symphony", "3", ".", "0", ".", "Use", "delete", "()", "instead", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.cacheable.php#L193-L199
symphonycms/symphony-2
symphony/lib/core/class.log.php
Log.pushToLog
public function pushToLog($message, $type = E_NOTICE, $writeToLog = false, $addbreak = true, $append = false) { if (!$type) { $type = E_ERROR; } if ($append) { $this->_log[count($this->_log) - 1]['message'] = $this->_log[count($this->_log) - 1]['message'] . $message; } else { array_push($this->_log, array('type' => $type, 'time' => time(), 'message' => $message)); $message = DateTimeObj::get($this->_datetime_format) . ' > ' . $this->__defineNameString($type) . ': ' . $message; } if ($writeToLog && ($this->_filter === -1 || ($this->_filter & $type))) { return $this->writeToLog($message, $addbreak); } }
php
public function pushToLog($message, $type = E_NOTICE, $writeToLog = false, $addbreak = true, $append = false) { if (!$type) { $type = E_ERROR; } if ($append) { $this->_log[count($this->_log) - 1]['message'] = $this->_log[count($this->_log) - 1]['message'] . $message; } else { array_push($this->_log, array('type' => $type, 'time' => time(), 'message' => $message)); $message = DateTimeObj::get($this->_datetime_format) . ' > ' . $this->__defineNameString($type) . ': ' . $message; } if ($writeToLog && ($this->_filter === -1 || ($this->_filter & $type))) { return $this->writeToLog($message, $addbreak); } }
[ "public", "function", "pushToLog", "(", "$", "message", ",", "$", "type", "=", "E_NOTICE", ",", "$", "writeToLog", "=", "false", ",", "$", "addbreak", "=", "true", ",", "$", "append", "=", "false", ")", "{", "if", "(", "!", "$", "type", ")", "{", "$", "type", "=", "E_ERROR", ";", "}", "if", "(", "$", "append", ")", "{", "$", "this", "->", "_log", "[", "count", "(", "$", "this", "->", "_log", ")", "-", "1", "]", "[", "'message'", "]", "=", "$", "this", "->", "_log", "[", "count", "(", "$", "this", "->", "_log", ")", "-", "1", "]", "[", "'message'", "]", ".", "$", "message", ";", "}", "else", "{", "array_push", "(", "$", "this", "->", "_log", ",", "array", "(", "'type'", "=>", "$", "type", ",", "'time'", "=>", "time", "(", ")", ",", "'message'", "=>", "$", "message", ")", ")", ";", "$", "message", "=", "DateTimeObj", "::", "get", "(", "$", "this", "->", "_datetime_format", ")", ".", "' > '", ".", "$", "this", "->", "__defineNameString", "(", "$", "type", ")", ".", "': '", ".", "$", "message", ";", "}", "if", "(", "$", "writeToLog", "&&", "(", "$", "this", "->", "_filter", "===", "-", "1", "||", "(", "$", "this", "->", "_filter", "&", "$", "type", ")", ")", ")", "{", "return", "$", "this", "->", "writeToLog", "(", "$", "message", ",", "$", "addbreak", ")", ";", "}", "}" ]
Given a message, this function will add it to the internal `$_log` so that it can be written to the Log. Optional parameters all the message to be immediately written, insert line breaks or add to the last log message @param string $message The message to add to the Log @param integer $type A PHP error constant for this message, defaults to E_NOTICE. If null or 0, will be converted to E_ERROR. @param boolean $writeToLog If set to true, this message will be immediately written to the log. By default this is set to false, which means that it will only be added to the array ready for writing @param boolean $addbreak To be used in conjunction with `$writeToLog`, this will add a line break before writing this message in the log file. Defaults to true. @param boolean $append If set to true, the given `$message` will be append to the previous log message found in the `$_log` array @return boolean|null If `$writeToLog` is passed, this function will return boolean, otherwise void
[ "Given", "a", "message", "this", "function", "will", "add", "it", "to", "the", "internal", "$_log", "so", "that", "it", "can", "be", "written", "to", "the", "Log", ".", "Optional", "parameters", "all", "the", "message", "to", "be", "immediately", "written", "insert", "line", "breaks", "or", "add", "to", "the", "last", "log", "message" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.log.php#L223-L239
symphonycms/symphony-2
symphony/lib/core/class.log.php
Log.writeToLog
public function writeToLog($message, $addbreak = true) { if (file_exists($this->_log_path) && !is_writable($this->_log_path)) { $this->pushToLog('Could not write to Log. It is not readable.'); return false; } $permissions = class_exists('Symphony', false) ? Symphony::Configuration()->get('write_mode', 'file') : '0664'; return General::writeFile($this->_log_path, $message . ($addbreak ? PHP_EOL : ''), $permissions, 'a+'); }
php
public function writeToLog($message, $addbreak = true) { if (file_exists($this->_log_path) && !is_writable($this->_log_path)) { $this->pushToLog('Could not write to Log. It is not readable.'); return false; } $permissions = class_exists('Symphony', false) ? Symphony::Configuration()->get('write_mode', 'file') : '0664'; return General::writeFile($this->_log_path, $message . ($addbreak ? PHP_EOL : ''), $permissions, 'a+'); }
[ "public", "function", "writeToLog", "(", "$", "message", ",", "$", "addbreak", "=", "true", ")", "{", "if", "(", "file_exists", "(", "$", "this", "->", "_log_path", ")", "&&", "!", "is_writable", "(", "$", "this", "->", "_log_path", ")", ")", "{", "$", "this", "->", "pushToLog", "(", "'Could not write to Log. It is not readable.'", ")", ";", "return", "false", ";", "}", "$", "permissions", "=", "class_exists", "(", "'Symphony'", ",", "false", ")", "?", "Symphony", "::", "Configuration", "(", ")", "->", "get", "(", "'write_mode'", ",", "'file'", ")", ":", "'0664'", ";", "return", "General", "::", "writeFile", "(", "$", "this", "->", "_log_path", ",", "$", "message", ".", "(", "$", "addbreak", "?", "PHP_EOL", ":", "''", ")", ",", "$", "permissions", ",", "'a+'", ")", ";", "}" ]
This function will write the given message to the log file. Messages will be appended the existing log file. @param string $message The message to add to the Log @param boolean $addbreak To be used in conjunction with `$writeToLog`, this will add a line break before writing this message in the log file. Defaults to true. @return boolean Returns true if the message was written successfully, false otherwise
[ "This", "function", "will", "write", "the", "given", "message", "to", "the", "log", "file", ".", "Messages", "will", "be", "appended", "the", "existing", "log", "file", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.log.php#L253-L263
symphonycms/symphony-2
symphony/lib/core/class.log.php
Log.pushExceptionToLog
public function pushExceptionToLog($exception, $writeToLog = false, $addbreak = true, $append = false) { $message = sprintf( '%s %s - %s on line %d of %s', get_class($exception), $exception->getCode(), $exception->getMessage(), $exception->getLine(), $exception->getFile() ); return $this->pushToLog($message, $exception->getCode(), $writeToLog, $addbreak, $append); }
php
public function pushExceptionToLog($exception, $writeToLog = false, $addbreak = true, $append = false) { $message = sprintf( '%s %s - %s on line %d of %s', get_class($exception), $exception->getCode(), $exception->getMessage(), $exception->getLine(), $exception->getFile() ); return $this->pushToLog($message, $exception->getCode(), $writeToLog, $addbreak, $append); }
[ "public", "function", "pushExceptionToLog", "(", "$", "exception", ",", "$", "writeToLog", "=", "false", ",", "$", "addbreak", "=", "true", ",", "$", "append", "=", "false", ")", "{", "$", "message", "=", "sprintf", "(", "'%s %s - %s on line %d of %s'", ",", "get_class", "(", "$", "exception", ")", ",", "$", "exception", "->", "getCode", "(", ")", ",", "$", "exception", "->", "getMessage", "(", ")", ",", "$", "exception", "->", "getLine", "(", ")", ",", "$", "exception", "->", "getFile", "(", ")", ")", ";", "return", "$", "this", "->", "pushToLog", "(", "$", "message", ",", "$", "exception", "->", "getCode", "(", ")", ",", "$", "writeToLog", ",", "$", "addbreak", ",", "$", "append", ")", ";", "}" ]
Given an Throwable, this function will add it to the internal `$_log` so that it can be written to the Log. @since Symphony 2.3.2 @since Symphony 2.7.0 This function works with both Exceptions and Throwable Supporting both PHP 5.6 and 7 forces use to not qualify the $e parameter @param Throwable $exception @param boolean $writeToLog If set to true, this message will be immediately written to the log. By default this is set to false, which means that it will only be added to the array ready for writing @param boolean $addbreak To be used in conjunction with `$writeToLog`, this will add a line break before writing this message in the log file. Defaults to true. @param boolean $append If set to true, the given `$message` will be append to the previous log message found in the `$_log` array @return boolean|null If `$writeToLog` is passed, this function will return boolean, otherwise void
[ "Given", "an", "Throwable", "this", "function", "will", "add", "it", "to", "the", "internal", "$_log", "so", "that", "it", "can", "be", "written", "to", "the", "Log", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.log.php#L290-L302
symphonycms/symphony-2
symphony/lib/core/class.log.php
Log.pushDeprecateWarningToLog
public function pushDeprecateWarningToLog($method, $alternative = null, array $opts = array()) { $defaults = array( 'message-format' => __('The method `%s` is deprecated.'), 'alternative-format' => __('Please use `%s` instead.'), 'removal-format' => __('It will be removed in Symphony %s.'), 'removal-version' => '3.0.0', 'write-to-log' => true, 'addbreak' => true, 'append' => false, 'addtrace' => true, ); $opts = array_replace($defaults, $opts); $message = sprintf($opts['message-format'], $method); if (!empty($opts['removal-version'])) { $message .= ' ' . sprintf($opts['removal-format'], $opts['removal-version']); } if (!empty($alternative)) { $message .= ' ' . sprintf($opts['alternative-format'], $alternative); } if ($opts['addtrace'] === true) { if (version_compare(phpversion(), '5.4', '<')) { $trace = debug_backtrace(0); } else { $trace = debug_backtrace(0, 3); } $index = isset($trace[2]['class']) ? 2 : 1; $caller = $trace[$index]['class'] . '::' . $trace[$index]['function'] . '()'; $file = basename($trace[$index - 1]['file']); $line = $trace[$index - 1]['line']; $message .= " Called from `$caller` in $file at line $line"; } return $this->pushToLog($message, E_DEPRECATED, $opts['write-to-log'], $opts['addbreak'], $opts['append']); }
php
public function pushDeprecateWarningToLog($method, $alternative = null, array $opts = array()) { $defaults = array( 'message-format' => __('The method `%s` is deprecated.'), 'alternative-format' => __('Please use `%s` instead.'), 'removal-format' => __('It will be removed in Symphony %s.'), 'removal-version' => '3.0.0', 'write-to-log' => true, 'addbreak' => true, 'append' => false, 'addtrace' => true, ); $opts = array_replace($defaults, $opts); $message = sprintf($opts['message-format'], $method); if (!empty($opts['removal-version'])) { $message .= ' ' . sprintf($opts['removal-format'], $opts['removal-version']); } if (!empty($alternative)) { $message .= ' ' . sprintf($opts['alternative-format'], $alternative); } if ($opts['addtrace'] === true) { if (version_compare(phpversion(), '5.4', '<')) { $trace = debug_backtrace(0); } else { $trace = debug_backtrace(0, 3); } $index = isset($trace[2]['class']) ? 2 : 1; $caller = $trace[$index]['class'] . '::' . $trace[$index]['function'] . '()'; $file = basename($trace[$index - 1]['file']); $line = $trace[$index - 1]['line']; $message .= " Called from `$caller` in $file at line $line"; } return $this->pushToLog($message, E_DEPRECATED, $opts['write-to-log'], $opts['addbreak'], $opts['append']); }
[ "public", "function", "pushDeprecateWarningToLog", "(", "$", "method", ",", "$", "alternative", "=", "null", ",", "array", "$", "opts", "=", "array", "(", ")", ")", "{", "$", "defaults", "=", "array", "(", "'message-format'", "=>", "__", "(", "'The method `%s` is deprecated.'", ")", ",", "'alternative-format'", "=>", "__", "(", "'Please use `%s` instead.'", ")", ",", "'removal-format'", "=>", "__", "(", "'It will be removed in Symphony %s.'", ")", ",", "'removal-version'", "=>", "'3.0.0'", ",", "'write-to-log'", "=>", "true", ",", "'addbreak'", "=>", "true", ",", "'append'", "=>", "false", ",", "'addtrace'", "=>", "true", ",", ")", ";", "$", "opts", "=", "array_replace", "(", "$", "defaults", ",", "$", "opts", ")", ";", "$", "message", "=", "sprintf", "(", "$", "opts", "[", "'message-format'", "]", ",", "$", "method", ")", ";", "if", "(", "!", "empty", "(", "$", "opts", "[", "'removal-version'", "]", ")", ")", "{", "$", "message", ".=", "' '", ".", "sprintf", "(", "$", "opts", "[", "'removal-format'", "]", ",", "$", "opts", "[", "'removal-version'", "]", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "alternative", ")", ")", "{", "$", "message", ".=", "' '", ".", "sprintf", "(", "$", "opts", "[", "'alternative-format'", "]", ",", "$", "alternative", ")", ";", "}", "if", "(", "$", "opts", "[", "'addtrace'", "]", "===", "true", ")", "{", "if", "(", "version_compare", "(", "phpversion", "(", ")", ",", "'5.4'", ",", "'<'", ")", ")", "{", "$", "trace", "=", "debug_backtrace", "(", "0", ")", ";", "}", "else", "{", "$", "trace", "=", "debug_backtrace", "(", "0", ",", "3", ")", ";", "}", "$", "index", "=", "isset", "(", "$", "trace", "[", "2", "]", "[", "'class'", "]", ")", "?", "2", ":", "1", ";", "$", "caller", "=", "$", "trace", "[", "$", "index", "]", "[", "'class'", "]", ".", "'::'", ".", "$", "trace", "[", "$", "index", "]", "[", "'function'", "]", ".", "'()'", ";", "$", "file", "=", "basename", "(", "$", "trace", "[", "$", "index", "-", "1", "]", "[", "'file'", "]", ")", ";", "$", "line", "=", "$", "trace", "[", "$", "index", "-", "1", "]", "[", "'line'", "]", ";", "$", "message", ".=", "\" Called from `$caller` in $file at line $line\"", ";", "}", "return", "$", "this", "->", "pushToLog", "(", "$", "message", ",", "E_DEPRECATED", ",", "$", "opts", "[", "'write-to-log'", "]", ",", "$", "opts", "[", "'addbreak'", "]", ",", "$", "opts", "[", "'append'", "]", ")", ";", "}" ]
Given an method name, this function will properly format a message and pass it down to `pushToLog()` @see Log::pushToLog() @since Symphony 2.7.0 @param string $method The name of the deprecated call @param string $alternative The name of the new method to use @param array $opts (optional) @param string $opts.message-format The sprintf format to apply to $method @param string $opts.alternative-format The sprintf format to apply to $alternative @param string $opts.removal-format The sprintf format to apply to $opts.removal-version @param string $opts.removal-version The Symphony version at which the removal is planned @param boolean $opts.write-to-log If set to true, this message will be immediately written to the log. By default this is set to false, which means that it will only be added to the array ready for writing @param boolean $opts.addbreak To be used in conjunction with `$opts.write-to-log`, this will add a line break before writing this message in the log file. Defaults to true. @param boolean $opts.append If set to true, the given `$message` will be append to the previous log message found in the `$_log` array @param boolean $opts.addtrace If set to true, the caller of the function will be added. Defaults to true. @return boolean|null If `$writeToLog` is passed, this function will return boolean, otherwise void
[ "Given", "an", "method", "name", "this", "function", "will", "properly", "format", "a", "message", "and", "pass", "it", "down", "to", "pushToLog", "()" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.log.php#L339-L374
symphonycms/symphony-2
symphony/lib/core/class.log.php
Log.open
public function open($flag = self::APPEND, $mode = 0777) { if (!file_exists($this->_log_path)) { $flag = self::OVERWRITE; } if ($flag == self::APPEND && file_exists($this->_log_path) && is_readable($this->_log_path)) { if ($this->_max_size > 0 && filesize($this->_log_path) > $this->_max_size) { $flag = self::OVERWRITE; if ($this->_archive) { $this->close(); $file = $this->_log_path . DateTimeObj::get('Ymdh').'.gz'; if (function_exists('gzopen64')) { $handle = gzopen64($file, 'w9'); } else { $handle = gzopen($file, 'w9'); } gzwrite($handle, file_get_contents($this->_log_path)); gzclose($handle); chmod($file, intval($mode, 8)); } } } if ($flag == self::OVERWRITE) { General::deleteFile($this->_log_path); $this->writeToLog('============================================', true); $this->writeToLog('Log Created: ' . DateTimeObj::get('c'), true); $this->writeToLog('============================================', true); @chmod($this->_log_path, intval($mode, 8)); return 1; } return 2; }
php
public function open($flag = self::APPEND, $mode = 0777) { if (!file_exists($this->_log_path)) { $flag = self::OVERWRITE; } if ($flag == self::APPEND && file_exists($this->_log_path) && is_readable($this->_log_path)) { if ($this->_max_size > 0 && filesize($this->_log_path) > $this->_max_size) { $flag = self::OVERWRITE; if ($this->_archive) { $this->close(); $file = $this->_log_path . DateTimeObj::get('Ymdh').'.gz'; if (function_exists('gzopen64')) { $handle = gzopen64($file, 'w9'); } else { $handle = gzopen($file, 'w9'); } gzwrite($handle, file_get_contents($this->_log_path)); gzclose($handle); chmod($file, intval($mode, 8)); } } } if ($flag == self::OVERWRITE) { General::deleteFile($this->_log_path); $this->writeToLog('============================================', true); $this->writeToLog('Log Created: ' . DateTimeObj::get('c'), true); $this->writeToLog('============================================', true); @chmod($this->_log_path, intval($mode, 8)); return 1; } return 2; }
[ "public", "function", "open", "(", "$", "flag", "=", "self", "::", "APPEND", ",", "$", "mode", "=", "0777", ")", "{", "if", "(", "!", "file_exists", "(", "$", "this", "->", "_log_path", ")", ")", "{", "$", "flag", "=", "self", "::", "OVERWRITE", ";", "}", "if", "(", "$", "flag", "==", "self", "::", "APPEND", "&&", "file_exists", "(", "$", "this", "->", "_log_path", ")", "&&", "is_readable", "(", "$", "this", "->", "_log_path", ")", ")", "{", "if", "(", "$", "this", "->", "_max_size", ">", "0", "&&", "filesize", "(", "$", "this", "->", "_log_path", ")", ">", "$", "this", "->", "_max_size", ")", "{", "$", "flag", "=", "self", "::", "OVERWRITE", ";", "if", "(", "$", "this", "->", "_archive", ")", "{", "$", "this", "->", "close", "(", ")", ";", "$", "file", "=", "$", "this", "->", "_log_path", ".", "DateTimeObj", "::", "get", "(", "'Ymdh'", ")", ".", "'.gz'", ";", "if", "(", "function_exists", "(", "'gzopen64'", ")", ")", "{", "$", "handle", "=", "gzopen64", "(", "$", "file", ",", "'w9'", ")", ";", "}", "else", "{", "$", "handle", "=", "gzopen", "(", "$", "file", ",", "'w9'", ")", ";", "}", "gzwrite", "(", "$", "handle", ",", "file_get_contents", "(", "$", "this", "->", "_log_path", ")", ")", ";", "gzclose", "(", "$", "handle", ")", ";", "chmod", "(", "$", "file", ",", "intval", "(", "$", "mode", ",", "8", ")", ")", ";", "}", "}", "}", "if", "(", "$", "flag", "==", "self", "::", "OVERWRITE", ")", "{", "General", "::", "deleteFile", "(", "$", "this", "->", "_log_path", ")", ";", "$", "this", "->", "writeToLog", "(", "'============================================'", ",", "true", ")", ";", "$", "this", "->", "writeToLog", "(", "'Log Created: '", ".", "DateTimeObj", "::", "get", "(", "'c'", ")", ",", "true", ")", ";", "$", "this", "->", "writeToLog", "(", "'============================================'", ",", "true", ")", ";", "@", "chmod", "(", "$", "this", "->", "_log_path", ",", "intval", "(", "$", "mode", ",", "8", ")", ")", ";", "return", "1", ";", "}", "return", "2", ";", "}" ]
The function handles the rotation of the log files. By default it will open the current log file, 'main', which is written to `$_log_path` and check it's file size doesn't exceed `$_max_size`. If it does, the log is appended with a date stamp and if `$_archive` has been set, it will be archived and stored. If a log file has exceeded it's size, or `Log::OVERWRITE` flag is set, the existing log file is removed and a new one created. Essentially, if a log file has not reached it's `$_max_size` and the the flag is not set to `Log::OVERWRITE`, this function does nothing. @link http://au.php.net/manual/en/function.intval.php @param integer $flag One of the Log constants, either `Log::APPEND` or `Log::OVERWRITE` By default this is `Log::APPEND` @param integer $mode The file mode used to apply to the archived log, by default this is 0777. Note that this parameter is modified using PHP's intval function with base 8. @throws Exception @return integer Returns 1 if the log was overwritten, or 2 otherwise.
[ "The", "function", "handles", "the", "rotation", "of", "the", "log", "files", ".", "By", "default", "it", "will", "open", "the", "current", "log", "file", "main", "which", "is", "written", "to", "$_log_path", "and", "check", "it", "s", "file", "size", "doesn", "t", "exceed", "$_max_size", ".", "If", "it", "does", "the", "log", "is", "appended", "with", "a", "date", "stamp", "and", "if", "$_archive", "has", "been", "set", "it", "will", "be", "archived", "and", "stored", ".", "If", "a", "log", "file", "has", "exceeded", "it", "s", "size", "or", "Log", "::", "OVERWRITE", "flag", "is", "set", "the", "existing", "log", "file", "is", "removed", "and", "a", "new", "one", "created", ".", "Essentially", "if", "a", "log", "file", "has", "not", "reached", "it", "s", "$_max_size", "and", "the", "the", "flag", "is", "not", "set", "to", "Log", "::", "OVERWRITE", "this", "function", "does", "nothing", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.log.php#L397-L435
symphonycms/symphony-2
symphony/lib/core/class.log.php
Log.close
public function close() { $this->writeToLog('============================================', true); $this->writeToLog('Log Closed: ' . DateTimeObj::get('c'), true); $this->writeToLog("============================================" . PHP_EOL . PHP_EOL, true); }
php
public function close() { $this->writeToLog('============================================', true); $this->writeToLog('Log Closed: ' . DateTimeObj::get('c'), true); $this->writeToLog("============================================" . PHP_EOL . PHP_EOL, true); }
[ "public", "function", "close", "(", ")", "{", "$", "this", "->", "writeToLog", "(", "'============================================'", ",", "true", ")", ";", "$", "this", "->", "writeToLog", "(", "'Log Closed: '", ".", "DateTimeObj", "::", "get", "(", "'c'", ")", ",", "true", ")", ";", "$", "this", "->", "writeToLog", "(", "\"============================================\"", ".", "PHP_EOL", ".", "PHP_EOL", ",", "true", ")", ";", "}" ]
Writes a end of file block at the end of the log file with a datetime stamp of when the log file was closed.
[ "Writes", "a", "end", "of", "file", "block", "at", "the", "end", "of", "the", "log", "file", "with", "a", "datetime", "stamp", "of", "when", "the", "log", "file", "was", "closed", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.log.php#L441-L446
symphonycms/symphony-2
symphony/lib/core/class.log.php
Log.initialise
public function initialise($name) { $version = (is_null(Symphony::Configuration())) ? VERSION : Symphony::Configuration()->get('version', 'symphony'); $this->writeToLog($name, true); $this->writeToLog('Opened: '. DateTimeObj::get('c'), true); $this->writeToLog('Version: '. $version, true); $this->writeToLog('Domain: '. DOMAIN, true); $this->writeToLog('--------------------------------------------', true); }
php
public function initialise($name) { $version = (is_null(Symphony::Configuration())) ? VERSION : Symphony::Configuration()->get('version', 'symphony'); $this->writeToLog($name, true); $this->writeToLog('Opened: '. DateTimeObj::get('c'), true); $this->writeToLog('Version: '. $version, true); $this->writeToLog('Domain: '. DOMAIN, true); $this->writeToLog('--------------------------------------------', true); }
[ "public", "function", "initialise", "(", "$", "name", ")", "{", "$", "version", "=", "(", "is_null", "(", "Symphony", "::", "Configuration", "(", ")", ")", ")", "?", "VERSION", ":", "Symphony", "::", "Configuration", "(", ")", "->", "get", "(", "'version'", ",", "'symphony'", ")", ";", "$", "this", "->", "writeToLog", "(", "$", "name", ",", "true", ")", ";", "$", "this", "->", "writeToLog", "(", "'Opened: '", ".", "DateTimeObj", "::", "get", "(", "'c'", ")", ",", "true", ")", ";", "$", "this", "->", "writeToLog", "(", "'Version: '", ".", "$", "version", ",", "true", ")", ";", "$", "this", "->", "writeToLog", "(", "'Domain: '", ".", "DOMAIN", ",", "true", ")", ";", "$", "this", "->", "writeToLog", "(", "'--------------------------------------------'", ",", "true", ")", ";", "}" ]
/* Initialises the log file by writing into it the log name, the date of creation, the current Symphony version and the current domain. @param string $name The name of the log being initialised
[ "/", "*", "Initialises", "the", "log", "file", "by", "writing", "into", "it", "the", "log", "name", "the", "date", "of", "creation", "the", "current", "Symphony", "version", "and", "the", "current", "domain", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.log.php#L454-L463
symphonycms/symphony-2
symphony/lib/toolkit/class.datasourcemanager.php
DatasourceManager.__getClassPath
public static function __getClassPath($handle) { if (is_file(DATASOURCES . "/data.$handle.php")) { return DATASOURCES; } else { $extensions = Symphony::ExtensionManager()->listInstalledHandles(); if (is_array($extensions) && !empty($extensions)) { foreach ($extensions as $e) { if (is_file(EXTENSIONS . "/$e/data-sources/data.$handle.php")) { return EXTENSIONS . "/$e/data-sources"; } } } } return false; }
php
public static function __getClassPath($handle) { if (is_file(DATASOURCES . "/data.$handle.php")) { return DATASOURCES; } else { $extensions = Symphony::ExtensionManager()->listInstalledHandles(); if (is_array($extensions) && !empty($extensions)) { foreach ($extensions as $e) { if (is_file(EXTENSIONS . "/$e/data-sources/data.$handle.php")) { return EXTENSIONS . "/$e/data-sources"; } } } } return false; }
[ "public", "static", "function", "__getClassPath", "(", "$", "handle", ")", "{", "if", "(", "is_file", "(", "DATASOURCES", ".", "\"/data.$handle.php\"", ")", ")", "{", "return", "DATASOURCES", ";", "}", "else", "{", "$", "extensions", "=", "Symphony", "::", "ExtensionManager", "(", ")", "->", "listInstalledHandles", "(", ")", ";", "if", "(", "is_array", "(", "$", "extensions", ")", "&&", "!", "empty", "(", "$", "extensions", ")", ")", "{", "foreach", "(", "$", "extensions", "as", "$", "e", ")", "{", "if", "(", "is_file", "(", "EXTENSIONS", ".", "\"/$e/data-sources/data.$handle.php\"", ")", ")", "{", "return", "EXTENSIONS", ".", "\"/$e/data-sources\"", ";", "}", "}", "}", "}", "return", "false", ";", "}" ]
Finds a Datasource by name by searching the data-sources folder in the workspace and in all installed extension folders and returns the path to it's folder. @param string $handle The handle of the Datasource free from any Symphony conventions such as `data.*.php` @return string|boolean If the datasource is found, the function returns the path it's folder, otherwise false.
[ "Finds", "a", "Datasource", "by", "name", "by", "searching", "the", "data", "-", "sources", "folder", "in", "the", "workspace", "and", "in", "all", "installed", "extension", "folders", "and", "returns", "the", "path", "to", "it", "s", "folder", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.datasourcemanager.php#L53-L70
symphonycms/symphony-2
symphony/lib/toolkit/class.datasourcemanager.php
DatasourceManager.listAll
public static function listAll() { $result = array(); $structure = General::listStructure(DATASOURCES, '/data.[\\w-]+.php/', false, 'ASC', DATASOURCES); if (is_array($structure['filelist']) && !empty($structure['filelist'])) { foreach ($structure['filelist'] as $f) { $f = self::__getHandleFromFilename($f); if ($about = self::about($f)) { $classname = self::__getClassName($f); $env = array(); $class = new $classname($env, false); $about['can_parse'] = method_exists($class, 'allowEditorToParse') ? $class->allowEditorToParse() : false; $about['source'] = method_exists($class, 'getSource') ? $class->getSource() : null; $result[$f] = $about; } } } $extensions = Symphony::ExtensionManager()->listInstalledHandles(); if (is_array($extensions) && !empty($extensions)) { foreach ($extensions as $e) { if (!is_dir(EXTENSIONS . "/$e/data-sources")) { continue; } $tmp = General::listStructure(EXTENSIONS . "/$e/data-sources", '/data.[\\w-]+.php/', false, 'ASC', EXTENSIONS . "/$e/data-sources"); if (is_array($tmp['filelist']) && !empty($tmp['filelist'])) { foreach ($tmp['filelist'] as $f) { $f = self::__getHandleFromFilename($f); if ($about = self::about($f)) { $about['can_parse'] = false; $about['source'] = null; $result[$f] = $about; } } } } } ksort($result); return $result; }
php
public static function listAll() { $result = array(); $structure = General::listStructure(DATASOURCES, '/data.[\\w-]+.php/', false, 'ASC', DATASOURCES); if (is_array($structure['filelist']) && !empty($structure['filelist'])) { foreach ($structure['filelist'] as $f) { $f = self::__getHandleFromFilename($f); if ($about = self::about($f)) { $classname = self::__getClassName($f); $env = array(); $class = new $classname($env, false); $about['can_parse'] = method_exists($class, 'allowEditorToParse') ? $class->allowEditorToParse() : false; $about['source'] = method_exists($class, 'getSource') ? $class->getSource() : null; $result[$f] = $about; } } } $extensions = Symphony::ExtensionManager()->listInstalledHandles(); if (is_array($extensions) && !empty($extensions)) { foreach ($extensions as $e) { if (!is_dir(EXTENSIONS . "/$e/data-sources")) { continue; } $tmp = General::listStructure(EXTENSIONS . "/$e/data-sources", '/data.[\\w-]+.php/', false, 'ASC', EXTENSIONS . "/$e/data-sources"); if (is_array($tmp['filelist']) && !empty($tmp['filelist'])) { foreach ($tmp['filelist'] as $f) { $f = self::__getHandleFromFilename($f); if ($about = self::about($f)) { $about['can_parse'] = false; $about['source'] = null; $result[$f] = $about; } } } } } ksort($result); return $result; }
[ "public", "static", "function", "listAll", "(", ")", "{", "$", "result", "=", "array", "(", ")", ";", "$", "structure", "=", "General", "::", "listStructure", "(", "DATASOURCES", ",", "'/data.[\\\\w-]+.php/'", ",", "false", ",", "'ASC'", ",", "DATASOURCES", ")", ";", "if", "(", "is_array", "(", "$", "structure", "[", "'filelist'", "]", ")", "&&", "!", "empty", "(", "$", "structure", "[", "'filelist'", "]", ")", ")", "{", "foreach", "(", "$", "structure", "[", "'filelist'", "]", "as", "$", "f", ")", "{", "$", "f", "=", "self", "::", "__getHandleFromFilename", "(", "$", "f", ")", ";", "if", "(", "$", "about", "=", "self", "::", "about", "(", "$", "f", ")", ")", "{", "$", "classname", "=", "self", "::", "__getClassName", "(", "$", "f", ")", ";", "$", "env", "=", "array", "(", ")", ";", "$", "class", "=", "new", "$", "classname", "(", "$", "env", ",", "false", ")", ";", "$", "about", "[", "'can_parse'", "]", "=", "method_exists", "(", "$", "class", ",", "'allowEditorToParse'", ")", "?", "$", "class", "->", "allowEditorToParse", "(", ")", ":", "false", ";", "$", "about", "[", "'source'", "]", "=", "method_exists", "(", "$", "class", ",", "'getSource'", ")", "?", "$", "class", "->", "getSource", "(", ")", ":", "null", ";", "$", "result", "[", "$", "f", "]", "=", "$", "about", ";", "}", "}", "}", "$", "extensions", "=", "Symphony", "::", "ExtensionManager", "(", ")", "->", "listInstalledHandles", "(", ")", ";", "if", "(", "is_array", "(", "$", "extensions", ")", "&&", "!", "empty", "(", "$", "extensions", ")", ")", "{", "foreach", "(", "$", "extensions", "as", "$", "e", ")", "{", "if", "(", "!", "is_dir", "(", "EXTENSIONS", ".", "\"/$e/data-sources\"", ")", ")", "{", "continue", ";", "}", "$", "tmp", "=", "General", "::", "listStructure", "(", "EXTENSIONS", ".", "\"/$e/data-sources\"", ",", "'/data.[\\\\w-]+.php/'", ",", "false", ",", "'ASC'", ",", "EXTENSIONS", ".", "\"/$e/data-sources\"", ")", ";", "if", "(", "is_array", "(", "$", "tmp", "[", "'filelist'", "]", ")", "&&", "!", "empty", "(", "$", "tmp", "[", "'filelist'", "]", ")", ")", "{", "foreach", "(", "$", "tmp", "[", "'filelist'", "]", "as", "$", "f", ")", "{", "$", "f", "=", "self", "::", "__getHandleFromFilename", "(", "$", "f", ")", ";", "if", "(", "$", "about", "=", "self", "::", "about", "(", "$", "f", ")", ")", "{", "$", "about", "[", "'can_parse'", "]", "=", "false", ";", "$", "about", "[", "'source'", "]", "=", "null", ";", "$", "result", "[", "$", "f", "]", "=", "$", "about", ";", "}", "}", "}", "}", "}", "ksort", "(", "$", "result", ")", ";", "return", "$", "result", ";", "}" ]
Finds all available Datasources by searching the data-sources folder in the workspace and in all installed extension folders. Returns an associative array of data sources. @see toolkit.Manager#about() @return array Associative array of Datasources with the key being the handle of the Datasource and the value being the Datasource's `about()` information.
[ "Finds", "all", "available", "Datasources", "by", "searching", "the", "data", "-", "sources", "folder", "in", "the", "workspace", "and", "in", "all", "installed", "extension", "folders", ".", "Returns", "an", "associative", "array", "of", "data", "sources", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.datasourcemanager.php#L96-L149
symphonycms/symphony-2
symphony/lib/toolkit/class.extension.php
Extension.providerOf
public static function providerOf($type = null) { static::registerProviders(); if (is_null($type)) { return self::$provides; } if (!isset(self::$provides[$type])) { return array(); } return self::$provides[$type]; }
php
public static function providerOf($type = null) { static::registerProviders(); if (is_null($type)) { return self::$provides; } if (!isset(self::$provides[$type])) { return array(); } return self::$provides[$type]; }
[ "public", "static", "function", "providerOf", "(", "$", "type", "=", "null", ")", "{", "static", "::", "registerProviders", "(", ")", ";", "if", "(", "is_null", "(", "$", "type", ")", ")", "{", "return", "self", "::", "$", "provides", ";", "}", "if", "(", "!", "isset", "(", "self", "::", "$", "provides", "[", "$", "type", "]", ")", ")", "{", "return", "array", "(", ")", ";", "}", "return", "self", "::", "$", "provides", "[", "$", "type", "]", ";", "}" ]
Used by Symphony to ask this extension if it's able to provide any new objects as defined by `$type` @since Symphony 2.5.0 @param string $type One of the `iProvider` constants @return array
[ "Used", "by", "Symphony", "to", "ask", "this", "extension", "if", "it", "s", "able", "to", "provide", "any", "new", "objects", "as", "defined", "by", "$type" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.extension.php#L319-L332
symphonycms/symphony-2
install/lib/class.updater.php
Updater.initialiseLog
public static function initialiseLog($filename = null) { if (is_dir(INSTALL_LOGS) || General::realiseDirectory(INSTALL_LOGS, self::Configuration()->get('write_mode', 'directory'))) { parent::initialiseLog(INSTALL_LOGS . '/update'); } }
php
public static function initialiseLog($filename = null) { if (is_dir(INSTALL_LOGS) || General::realiseDirectory(INSTALL_LOGS, self::Configuration()->get('write_mode', 'directory'))) { parent::initialiseLog(INSTALL_LOGS . '/update'); } }
[ "public", "static", "function", "initialiseLog", "(", "$", "filename", "=", "null", ")", "{", "if", "(", "is_dir", "(", "INSTALL_LOGS", ")", "||", "General", "::", "realiseDirectory", "(", "INSTALL_LOGS", ",", "self", "::", "Configuration", "(", ")", "->", "get", "(", "'write_mode'", ",", "'directory'", ")", ")", ")", "{", "parent", "::", "initialiseLog", "(", "INSTALL_LOGS", ".", "'/update'", ")", ";", "}", "}" ]
Overrides the `initialiseLog()` method and writes logs to manifest/logs/update
[ "Overrides", "the", "initialiseLog", "()", "method", "and", "writes", "logs", "to", "manifest", "/", "logs", "/", "update" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/install/lib/class.updater.php#L43-L48
symphonycms/symphony-2
install/lib/class.updater.php
Updater.initialiseDatabase
public static function initialiseDatabase() { self::setDatabase(); $details = Symphony::Configuration()->get('database'); try { Symphony::Database()->connect( $details['host'], $details['user'], $details['password'], $details['port'], $details['db'] ); } catch (DatabaseException $e) { self::__abort( 'There was a problem while trying to establish a connection to the MySQL server. Please check your settings.', time() ); } // MySQL: Setting prefix & character encoding Symphony::Database()->setPrefix($details['tbl_prefix']); Symphony::Database()->setCharacterEncoding(); Symphony::Database()->setCharacterSet(); }
php
public static function initialiseDatabase() { self::setDatabase(); $details = Symphony::Configuration()->get('database'); try { Symphony::Database()->connect( $details['host'], $details['user'], $details['password'], $details['port'], $details['db'] ); } catch (DatabaseException $e) { self::__abort( 'There was a problem while trying to establish a connection to the MySQL server. Please check your settings.', time() ); } // MySQL: Setting prefix & character encoding Symphony::Database()->setPrefix($details['tbl_prefix']); Symphony::Database()->setCharacterEncoding(); Symphony::Database()->setCharacterSet(); }
[ "public", "static", "function", "initialiseDatabase", "(", ")", "{", "self", "::", "setDatabase", "(", ")", ";", "$", "details", "=", "Symphony", "::", "Configuration", "(", ")", "->", "get", "(", "'database'", ")", ";", "try", "{", "Symphony", "::", "Database", "(", ")", "->", "connect", "(", "$", "details", "[", "'host'", "]", ",", "$", "details", "[", "'user'", "]", ",", "$", "details", "[", "'password'", "]", ",", "$", "details", "[", "'port'", "]", ",", "$", "details", "[", "'db'", "]", ")", ";", "}", "catch", "(", "DatabaseException", "$", "e", ")", "{", "self", "::", "__abort", "(", "'There was a problem while trying to establish a connection to the MySQL server. Please check your settings.'", ",", "time", "(", ")", ")", ";", "}", "// MySQL: Setting prefix & character encoding", "Symphony", "::", "Database", "(", ")", "->", "setPrefix", "(", "$", "details", "[", "'tbl_prefix'", "]", ")", ";", "Symphony", "::", "Database", "(", ")", "->", "setCharacterEncoding", "(", ")", ";", "Symphony", "::", "Database", "(", ")", "->", "setCharacterSet", "(", ")", ";", "}" ]
Overrides the default `initialiseDatabase()` method This allows us to still use the normal accessor
[ "Overrides", "the", "default", "initialiseDatabase", "()", "method", "This", "allows", "us", "to", "still", "use", "the", "normal", "accessor" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/install/lib/class.updater.php#L54-L79
symphonycms/symphony-2
symphony/lib/toolkit/email-gateways/email.smtp.php
SMTPGateway.send
public function send() { $this->validate(); $settings = array(); $settings['helo_hostname'] = $this->_helo_hostname; if ($this->_auth) { $settings['username'] = $this->_user; $settings['password'] = $this->_pass; } $settings['secure'] = $this->_secure; try { if (!is_a($this->_SMTP, 'SMTP')) { $this->_SMTP = new SMTP($this->_host, $this->_port, $settings); } // Encode recipient names (but not any numeric array indexes) $recipients = array(); foreach ($this->_recipients as $name => $email) { // Support Bcc header if (isset($this->_header_fields['Bcc']) && $this->_header_fields['Bcc'] == $email) { continue; } // if the key is not numeric, qEncode the key. $name = General::intval($name) > -1 ? General::intval($name) : EmailHelper::qEncode($name); $recipients[$name] = $email; } // Combine keys and values into a recipient list (name <email>, name <email>). $recipient_list = EmailHelper::arrayToList($recipients); // Encode the subject $subject = EmailHelper::qEncode((string)$this->_subject); // Build the 'From' header field body $from = empty($this->_sender_name) ? $this->_sender_email_address : EmailHelper::qEncode($this->_sender_name) . ' <' . $this->_sender_email_address . '>'; // Build the 'Reply-To' header field body if (!empty($this->_reply_to_email_address)) { $reply_to = empty($this->_reply_to_name) ? $this->_reply_to_email_address : EmailHelper::qEncode($this->_reply_to_name) . ' <'.$this->_reply_to_email_address.'>'; } if (!empty($reply_to)) { $this->_header_fields = array_merge( $this->_header_fields, array( 'Reply-To' => $reply_to, ) ); } // Build the body text using attachments, html-text and plain-text. $this->prepareMessageBody(); // Build the header fields $this->_header_fields = array_merge( $this->_header_fields, array( 'Message-ID' => sprintf('<%s@%s>', md5(uniqid()), HTTP_HOST), 'Date' => date('r'), 'From' => $from, 'Subject' => $subject, 'To' => $recipient_list, 'MIME-Version' => '1.0' ) ); // Set header fields and fold header field bodies foreach ($this->_header_fields as $name => $body) { $this->_SMTP->setHeader($name, EmailHelper::fold($body)); } // Send the email command. If the envelope from variable is set, use that for the MAIL command. This improves bounce handling. $this->_SMTP->sendMail(is_null($this->_envelope_from)?$this->_sender_email_address:$this->_envelope_from, $this->_recipients, $this->_body); if ($this->_keepalive === false) { $this->closeConnection(); } $this->reset(); } catch (SMTPException $e) { throw new EmailGatewayException($e->getMessage()); } return true; }
php
public function send() { $this->validate(); $settings = array(); $settings['helo_hostname'] = $this->_helo_hostname; if ($this->_auth) { $settings['username'] = $this->_user; $settings['password'] = $this->_pass; } $settings['secure'] = $this->_secure; try { if (!is_a($this->_SMTP, 'SMTP')) { $this->_SMTP = new SMTP($this->_host, $this->_port, $settings); } // Encode recipient names (but not any numeric array indexes) $recipients = array(); foreach ($this->_recipients as $name => $email) { // Support Bcc header if (isset($this->_header_fields['Bcc']) && $this->_header_fields['Bcc'] == $email) { continue; } // if the key is not numeric, qEncode the key. $name = General::intval($name) > -1 ? General::intval($name) : EmailHelper::qEncode($name); $recipients[$name] = $email; } // Combine keys and values into a recipient list (name <email>, name <email>). $recipient_list = EmailHelper::arrayToList($recipients); // Encode the subject $subject = EmailHelper::qEncode((string)$this->_subject); // Build the 'From' header field body $from = empty($this->_sender_name) ? $this->_sender_email_address : EmailHelper::qEncode($this->_sender_name) . ' <' . $this->_sender_email_address . '>'; // Build the 'Reply-To' header field body if (!empty($this->_reply_to_email_address)) { $reply_to = empty($this->_reply_to_name) ? $this->_reply_to_email_address : EmailHelper::qEncode($this->_reply_to_name) . ' <'.$this->_reply_to_email_address.'>'; } if (!empty($reply_to)) { $this->_header_fields = array_merge( $this->_header_fields, array( 'Reply-To' => $reply_to, ) ); } // Build the body text using attachments, html-text and plain-text. $this->prepareMessageBody(); // Build the header fields $this->_header_fields = array_merge( $this->_header_fields, array( 'Message-ID' => sprintf('<%s@%s>', md5(uniqid()), HTTP_HOST), 'Date' => date('r'), 'From' => $from, 'Subject' => $subject, 'To' => $recipient_list, 'MIME-Version' => '1.0' ) ); // Set header fields and fold header field bodies foreach ($this->_header_fields as $name => $body) { $this->_SMTP->setHeader($name, EmailHelper::fold($body)); } // Send the email command. If the envelope from variable is set, use that for the MAIL command. This improves bounce handling. $this->_SMTP->sendMail(is_null($this->_envelope_from)?$this->_sender_email_address:$this->_envelope_from, $this->_recipients, $this->_body); if ($this->_keepalive === false) { $this->closeConnection(); } $this->reset(); } catch (SMTPException $e) { throw new EmailGatewayException($e->getMessage()); } return true; }
[ "public", "function", "send", "(", ")", "{", "$", "this", "->", "validate", "(", ")", ";", "$", "settings", "=", "array", "(", ")", ";", "$", "settings", "[", "'helo_hostname'", "]", "=", "$", "this", "->", "_helo_hostname", ";", "if", "(", "$", "this", "->", "_auth", ")", "{", "$", "settings", "[", "'username'", "]", "=", "$", "this", "->", "_user", ";", "$", "settings", "[", "'password'", "]", "=", "$", "this", "->", "_pass", ";", "}", "$", "settings", "[", "'secure'", "]", "=", "$", "this", "->", "_secure", ";", "try", "{", "if", "(", "!", "is_a", "(", "$", "this", "->", "_SMTP", ",", "'SMTP'", ")", ")", "{", "$", "this", "->", "_SMTP", "=", "new", "SMTP", "(", "$", "this", "->", "_host", ",", "$", "this", "->", "_port", ",", "$", "settings", ")", ";", "}", "// Encode recipient names (but not any numeric array indexes)", "$", "recipients", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "_recipients", "as", "$", "name", "=>", "$", "email", ")", "{", "// Support Bcc header", "if", "(", "isset", "(", "$", "this", "->", "_header_fields", "[", "'Bcc'", "]", ")", "&&", "$", "this", "->", "_header_fields", "[", "'Bcc'", "]", "==", "$", "email", ")", "{", "continue", ";", "}", "// if the key is not numeric, qEncode the key.", "$", "name", "=", "General", "::", "intval", "(", "$", "name", ")", ">", "-", "1", "?", "General", "::", "intval", "(", "$", "name", ")", ":", "EmailHelper", "::", "qEncode", "(", "$", "name", ")", ";", "$", "recipients", "[", "$", "name", "]", "=", "$", "email", ";", "}", "// Combine keys and values into a recipient list (name <email>, name <email>).", "$", "recipient_list", "=", "EmailHelper", "::", "arrayToList", "(", "$", "recipients", ")", ";", "// Encode the subject", "$", "subject", "=", "EmailHelper", "::", "qEncode", "(", "(", "string", ")", "$", "this", "->", "_subject", ")", ";", "// Build the 'From' header field body", "$", "from", "=", "empty", "(", "$", "this", "->", "_sender_name", ")", "?", "$", "this", "->", "_sender_email_address", ":", "EmailHelper", "::", "qEncode", "(", "$", "this", "->", "_sender_name", ")", ".", "' <'", ".", "$", "this", "->", "_sender_email_address", ".", "'>'", ";", "// Build the 'Reply-To' header field body", "if", "(", "!", "empty", "(", "$", "this", "->", "_reply_to_email_address", ")", ")", "{", "$", "reply_to", "=", "empty", "(", "$", "this", "->", "_reply_to_name", ")", "?", "$", "this", "->", "_reply_to_email_address", ":", "EmailHelper", "::", "qEncode", "(", "$", "this", "->", "_reply_to_name", ")", ".", "' <'", ".", "$", "this", "->", "_reply_to_email_address", ".", "'>'", ";", "}", "if", "(", "!", "empty", "(", "$", "reply_to", ")", ")", "{", "$", "this", "->", "_header_fields", "=", "array_merge", "(", "$", "this", "->", "_header_fields", ",", "array", "(", "'Reply-To'", "=>", "$", "reply_to", ",", ")", ")", ";", "}", "// Build the body text using attachments, html-text and plain-text.", "$", "this", "->", "prepareMessageBody", "(", ")", ";", "// Build the header fields", "$", "this", "->", "_header_fields", "=", "array_merge", "(", "$", "this", "->", "_header_fields", ",", "array", "(", "'Message-ID'", "=>", "sprintf", "(", "'<%s@%s>'", ",", "md5", "(", "uniqid", "(", ")", ")", ",", "HTTP_HOST", ")", ",", "'Date'", "=>", "date", "(", "'r'", ")", ",", "'From'", "=>", "$", "from", ",", "'Subject'", "=>", "$", "subject", ",", "'To'", "=>", "$", "recipient_list", ",", "'MIME-Version'", "=>", "'1.0'", ")", ")", ";", "// Set header fields and fold header field bodies", "foreach", "(", "$", "this", "->", "_header_fields", "as", "$", "name", "=>", "$", "body", ")", "{", "$", "this", "->", "_SMTP", "->", "setHeader", "(", "$", "name", ",", "EmailHelper", "::", "fold", "(", "$", "body", ")", ")", ";", "}", "// Send the email command. If the envelope from variable is set, use that for the MAIL command. This improves bounce handling.", "$", "this", "->", "_SMTP", "->", "sendMail", "(", "is_null", "(", "$", "this", "->", "_envelope_from", ")", "?", "$", "this", "->", "_sender_email_address", ":", "$", "this", "->", "_envelope_from", ",", "$", "this", "->", "_recipients", ",", "$", "this", "->", "_body", ")", ";", "if", "(", "$", "this", "->", "_keepalive", "===", "false", ")", "{", "$", "this", "->", "closeConnection", "(", ")", ";", "}", "$", "this", "->", "reset", "(", ")", ";", "}", "catch", "(", "SMTPException", "$", "e", ")", "{", "throw", "new", "EmailGatewayException", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "return", "true", ";", "}" ]
Send an email using an SMTP server @throws EmailGatewayException @throws EmailValidationException @throws Exception @return boolean
[ "Send", "an", "email", "using", "an", "SMTP", "server" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/email-gateways/email.smtp.php#L57-L148
symphonycms/symphony-2
symphony/lib/toolkit/email-gateways/email.smtp.php
SMTPGateway.reset
public function reset() { $this->_header_fields = array(); $this->_envelope_from = null; $this->_recipients = array(); $this->_subject = null; $this->_body = null; }
php
public function reset() { $this->_header_fields = array(); $this->_envelope_from = null; $this->_recipients = array(); $this->_subject = null; $this->_body = null; }
[ "public", "function", "reset", "(", ")", "{", "$", "this", "->", "_header_fields", "=", "array", "(", ")", ";", "$", "this", "->", "_envelope_from", "=", "null", ";", "$", "this", "->", "_recipients", "=", "array", "(", ")", ";", "$", "this", "->", "_subject", "=", "null", ";", "$", "this", "->", "_body", "=", "null", ";", "}" ]
Resets the headers, body, subject @return void
[ "Resets", "the", "headers", "body", "subject" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/email-gateways/email.smtp.php#L155-L162
symphonycms/symphony-2
symphony/lib/toolkit/email-gateways/email.smtp.php
SMTPGateway.setHost
public function setHost($host = null) { if ($host === null) { $host = '127.0.0.1'; } if (substr($host, 0, 6) == 'ssl://') { $this->_protocol = 'ssl'; $this->_secure = 'ssl'; $host = substr($host, 6); } $this->_host = $host; }
php
public function setHost($host = null) { if ($host === null) { $host = '127.0.0.1'; } if (substr($host, 0, 6) == 'ssl://') { $this->_protocol = 'ssl'; $this->_secure = 'ssl'; $host = substr($host, 6); } $this->_host = $host; }
[ "public", "function", "setHost", "(", "$", "host", "=", "null", ")", "{", "if", "(", "$", "host", "===", "null", ")", "{", "$", "host", "=", "'127.0.0.1'", ";", "}", "if", "(", "substr", "(", "$", "host", ",", "0", ",", "6", ")", "==", "'ssl://'", ")", "{", "$", "this", "->", "_protocol", "=", "'ssl'", ";", "$", "this", "->", "_secure", "=", "'ssl'", ";", "$", "host", "=", "substr", "(", "$", "host", ",", "6", ")", ";", "}", "$", "this", "->", "_host", "=", "$", "host", ";", "}" ]
Sets the host to connect to. @param null|string $host (optional) @return void
[ "Sets", "the", "host", "to", "connect", "to", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/email-gateways/email.smtp.php#L200-L212
symphonycms/symphony-2
symphony/lib/toolkit/email-gateways/email.smtp.php
SMTPGateway.setPort
public function setPort($port = null) { if (is_null($port)) { $port = ($this->_protocol == 'ssl') ? 465 : 25; } $this->_port = $port; }
php
public function setPort($port = null) { if (is_null($port)) { $port = ($this->_protocol == 'ssl') ? 465 : 25; } $this->_port = $port; }
[ "public", "function", "setPort", "(", "$", "port", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "port", ")", ")", "{", "$", "port", "=", "(", "$", "this", "->", "_protocol", "==", "'ssl'", ")", "?", "465", ":", "25", ";", "}", "$", "this", "->", "_port", "=", "$", "port", ";", "}" ]
Sets the port, used in the connection. @param null|int $port @return void
[ "Sets", "the", "port", "used", "in", "the", "connection", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/email-gateways/email.smtp.php#L220-L227
symphonycms/symphony-2
symphony/lib/toolkit/email-gateways/email.smtp.php
SMTPGateway.setSecure
public function setSecure($secure = null) { if ($secure == 'tls') { $this->_protocol = 'tcp'; $this->_secure = 'tls'; } elseif ($secure == 'ssl') { $this->_protocol = 'ssl'; $this->_secure = 'ssl'; } else { $this->_protocol = 'tcp'; $this->_secure = 'no'; } }
php
public function setSecure($secure = null) { if ($secure == 'tls') { $this->_protocol = 'tcp'; $this->_secure = 'tls'; } elseif ($secure == 'ssl') { $this->_protocol = 'ssl'; $this->_secure = 'ssl'; } else { $this->_protocol = 'tcp'; $this->_secure = 'no'; } }
[ "public", "function", "setSecure", "(", "$", "secure", "=", "null", ")", "{", "if", "(", "$", "secure", "==", "'tls'", ")", "{", "$", "this", "->", "_protocol", "=", "'tcp'", ";", "$", "this", "->", "_secure", "=", "'tls'", ";", "}", "elseif", "(", "$", "secure", "==", "'ssl'", ")", "{", "$", "this", "->", "_protocol", "=", "'ssl'", ";", "$", "this", "->", "_secure", "=", "'ssl'", ";", "}", "else", "{", "$", "this", "->", "_protocol", "=", "'tcp'", ";", "$", "this", "->", "_secure", "=", "'no'", ";", "}", "}" ]
Sets the encryption used. @param string $secure The encryption used. Can be 'ssl', 'tls'. Anything else defaults to a non secure TCP connection @return void
[ "Sets", "the", "encryption", "used", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/email-gateways/email.smtp.php#L270-L282
symphonycms/symphony-2
symphony/lib/toolkit/email-gateways/email.smtp.php
SMTPGateway.setEnvelopeFrom
public function setEnvelopeFrom($envelope_from = null) { if (preg_match('%[\r\n]%', $envelope_from)) { throw new EmailValidationException(__('The Envelope From Address can not contain carriage return or newlines.')); } $this->_envelope_from = $envelope_from; }
php
public function setEnvelopeFrom($envelope_from = null) { if (preg_match('%[\r\n]%', $envelope_from)) { throw new EmailValidationException(__('The Envelope From Address can not contain carriage return or newlines.')); } $this->_envelope_from = $envelope_from; }
[ "public", "function", "setEnvelopeFrom", "(", "$", "envelope_from", "=", "null", ")", "{", "if", "(", "preg_match", "(", "'%[\\r\\n]%'", ",", "$", "envelope_from", ")", ")", "{", "throw", "new", "EmailValidationException", "(", "__", "(", "'The Envelope From Address can not contain carriage return or newlines.'", ")", ")", ";", "}", "$", "this", "->", "_envelope_from", "=", "$", "envelope_from", ";", "}" ]
Sets the envelope_from address. This is only available via the API, as it is an expert-only feature. @since 2.3.1 @param null $envelope_from @throws EmailValidationException @return void
[ "Sets", "the", "envelope_from", "address", ".", "This", "is", "only", "available", "via", "the", "API", "as", "it", "is", "an", "expert", "-", "only", "feature", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/email-gateways/email.smtp.php#L292-L299
symphonycms/symphony-2
symphony/lib/toolkit/email-gateways/email.smtp.php
SMTPGateway.setConfiguration
public function setConfiguration($config) { $this->setHeloHostname($config['helo_hostname']); $this->setFrom($config['from_address'], $config['from_name']); $this->setHost($config['host']); $this->setPort($config['port']); $this->setSecure($config['secure']); $this->setAuth((int)$config['auth'] === 1); $this->setUser($config['username']); $this->setPass($config['password']); }
php
public function setConfiguration($config) { $this->setHeloHostname($config['helo_hostname']); $this->setFrom($config['from_address'], $config['from_name']); $this->setHost($config['host']); $this->setPort($config['port']); $this->setSecure($config['secure']); $this->setAuth((int)$config['auth'] === 1); $this->setUser($config['username']); $this->setPass($config['password']); }
[ "public", "function", "setConfiguration", "(", "$", "config", ")", "{", "$", "this", "->", "setHeloHostname", "(", "$", "config", "[", "'helo_hostname'", "]", ")", ";", "$", "this", "->", "setFrom", "(", "$", "config", "[", "'from_address'", "]", ",", "$", "config", "[", "'from_name'", "]", ")", ";", "$", "this", "->", "setHost", "(", "$", "config", "[", "'host'", "]", ")", ";", "$", "this", "->", "setPort", "(", "$", "config", "[", "'port'", "]", ")", ";", "$", "this", "->", "setSecure", "(", "$", "config", "[", "'secure'", "]", ")", ";", "$", "this", "->", "setAuth", "(", "(", "int", ")", "$", "config", "[", "'auth'", "]", "===", "1", ")", ";", "$", "this", "->", "setUser", "(", "$", "config", "[", "'username'", "]", ")", ";", "$", "this", "->", "setPass", "(", "$", "config", "[", "'password'", "]", ")", ";", "}" ]
Sets all configuration entries from an array. @param array $config All configuration entries stored in a single array. The array should have the format of the $_POST array created by the preferences HTML. @throws EmailValidationException @since 2.3.1 @return void
[ "Sets", "all", "configuration", "entries", "from", "an", "array", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/email-gateways/email.smtp.php#L311-L322
symphonycms/symphony-2
symphony/lib/toolkit/email-gateways/email.smtp.php
SMTPGateway.getPreferencesPane
public function getPreferencesPane() { parent::getPreferencesPane(); $group = new XMLElement('fieldset'); $group->setAttribute('class', 'settings condensed pickable'); $group->setAttribute('id', 'smtp'); $group->appendChild(new XMLElement('legend', __('Email: SMTP'))); $div = new XMLElement('div'); $readonly = array('readonly' => 'readonly'); $label = Widget::Label(__('HELO Hostname')); $label->appendChild(Widget::Input('settings[email_smtp][helo_hostname]', General::sanitize($this->_helo_hostname), 'text', $readonly)); $div->appendChild($label); $group->appendChild($div); $group->appendChild(new XMLElement('p', __('A fully qualified domain name (FQDN) of your server, e.g. "www.example.com". If left empty, Symphony will attempt to find an IP address for the EHLO/HELO greeting.'), array('class' => 'help'))); $div = new XMLElement('div'); $div->setAttribute('class', 'two columns'); $label = Widget::Label(__('From Name')); $label->setAttribute('class', 'column'); $label->appendChild(Widget::Input('settings[email_smtp][from_name]', General::sanitize($this->_sender_name), 'text', $readonly)); $div->appendChild($label); $label = Widget::Label(__('From Email Address')); $label->setAttribute('class', 'column'); $label->appendChild(Widget::Input('settings[email_smtp][from_address]', General::sanitize($this->_sender_email_address), 'text', $readonly)); $div->appendChild($label); $group->appendChild($div); $div = new XMLElement('div'); $div->setAttribute('class', 'two columns'); $label = Widget::Label(__('Host')); $label->setAttribute('class', 'column'); $label->appendChild(Widget::Input('settings[email_smtp][host]', General::sanitize($this->_host), 'text', $readonly)); $div->appendChild($label); $label = Widget::Label(__('Port')); $label->setAttribute('class', 'column'); $label->appendChild(Widget::Input('settings[email_smtp][port]', General::sanitize((string) $this->_port), 'text', $readonly)); $div->appendChild($label); $group->appendChild($div); $label = Widget::Label(); $label->setAttribute('class', 'column'); // To fix the issue with checkboxes that do not send a value when unchecked. $options = array( array('no',$this->_secure == 'no', __('No encryption')), array('ssl',$this->_secure == 'ssl', __('SSL encryption')), array('tls',$this->_secure == 'tls', __('TLS encryption')), ); $select = Widget::Select('settings[email_smtp][secure]', $options, $readonly); $label->appendChild($select); $group->appendChild($label); $group->appendChild(new XMLElement('p', __('For a secure connection, SSL and TLS are supported. Please check the manual of your email provider for more details.'), array('class' => 'help'))); $label = Widget::Label(); $label->setAttribute('class', 'column'); // To fix the issue with checkboxes that do not send a value when unchecked. $group->appendChild(Widget::Input('settings[email_smtp][auth]', '0', 'hidden')); $input = Widget::Input('settings[email_smtp][auth]', '1', 'checkbox', $readonly); if ($this->_auth === true) { $input->setAttribute('checked', 'checked'); } $label->setValue(__('%s Requires authentication', array($input->generate()))); $group->appendChild($label); $group->appendChild(new XMLElement('p', __('Some SMTP connections require authentication. If that is the case, enter the username/password combination below.'), array('class' => 'help'))); $div = new XMLElement('div'); $div->setAttribute('class', 'two columns'); $label = Widget::Label(__('Username')); $label->setAttribute('class', 'column'); $label->appendChild(Widget::Input('settings[email_smtp][username]', General::sanitize($this->_user), 'text', array_merge($readonly, array('autocomplete' => 'off')))); $div->appendChild($label); $label = Widget::Label(__('Password')); $label->setAttribute('class', 'column'); $label->appendChild(Widget::Input('settings[email_smtp][password]', General::sanitize($this->_pass), 'password', array_merge($readonly, array('autocomplete' => 'off')))); $div->appendChild($label); $group->appendChild($div); return $group; }
php
public function getPreferencesPane() { parent::getPreferencesPane(); $group = new XMLElement('fieldset'); $group->setAttribute('class', 'settings condensed pickable'); $group->setAttribute('id', 'smtp'); $group->appendChild(new XMLElement('legend', __('Email: SMTP'))); $div = new XMLElement('div'); $readonly = array('readonly' => 'readonly'); $label = Widget::Label(__('HELO Hostname')); $label->appendChild(Widget::Input('settings[email_smtp][helo_hostname]', General::sanitize($this->_helo_hostname), 'text', $readonly)); $div->appendChild($label); $group->appendChild($div); $group->appendChild(new XMLElement('p', __('A fully qualified domain name (FQDN) of your server, e.g. "www.example.com". If left empty, Symphony will attempt to find an IP address for the EHLO/HELO greeting.'), array('class' => 'help'))); $div = new XMLElement('div'); $div->setAttribute('class', 'two columns'); $label = Widget::Label(__('From Name')); $label->setAttribute('class', 'column'); $label->appendChild(Widget::Input('settings[email_smtp][from_name]', General::sanitize($this->_sender_name), 'text', $readonly)); $div->appendChild($label); $label = Widget::Label(__('From Email Address')); $label->setAttribute('class', 'column'); $label->appendChild(Widget::Input('settings[email_smtp][from_address]', General::sanitize($this->_sender_email_address), 'text', $readonly)); $div->appendChild($label); $group->appendChild($div); $div = new XMLElement('div'); $div->setAttribute('class', 'two columns'); $label = Widget::Label(__('Host')); $label->setAttribute('class', 'column'); $label->appendChild(Widget::Input('settings[email_smtp][host]', General::sanitize($this->_host), 'text', $readonly)); $div->appendChild($label); $label = Widget::Label(__('Port')); $label->setAttribute('class', 'column'); $label->appendChild(Widget::Input('settings[email_smtp][port]', General::sanitize((string) $this->_port), 'text', $readonly)); $div->appendChild($label); $group->appendChild($div); $label = Widget::Label(); $label->setAttribute('class', 'column'); // To fix the issue with checkboxes that do not send a value when unchecked. $options = array( array('no',$this->_secure == 'no', __('No encryption')), array('ssl',$this->_secure == 'ssl', __('SSL encryption')), array('tls',$this->_secure == 'tls', __('TLS encryption')), ); $select = Widget::Select('settings[email_smtp][secure]', $options, $readonly); $label->appendChild($select); $group->appendChild($label); $group->appendChild(new XMLElement('p', __('For a secure connection, SSL and TLS are supported. Please check the manual of your email provider for more details.'), array('class' => 'help'))); $label = Widget::Label(); $label->setAttribute('class', 'column'); // To fix the issue with checkboxes that do not send a value when unchecked. $group->appendChild(Widget::Input('settings[email_smtp][auth]', '0', 'hidden')); $input = Widget::Input('settings[email_smtp][auth]', '1', 'checkbox', $readonly); if ($this->_auth === true) { $input->setAttribute('checked', 'checked'); } $label->setValue(__('%s Requires authentication', array($input->generate()))); $group->appendChild($label); $group->appendChild(new XMLElement('p', __('Some SMTP connections require authentication. If that is the case, enter the username/password combination below.'), array('class' => 'help'))); $div = new XMLElement('div'); $div->setAttribute('class', 'two columns'); $label = Widget::Label(__('Username')); $label->setAttribute('class', 'column'); $label->appendChild(Widget::Input('settings[email_smtp][username]', General::sanitize($this->_user), 'text', array_merge($readonly, array('autocomplete' => 'off')))); $div->appendChild($label); $label = Widget::Label(__('Password')); $label->setAttribute('class', 'column'); $label->appendChild(Widget::Input('settings[email_smtp][password]', General::sanitize($this->_pass), 'password', array_merge($readonly, array('autocomplete' => 'off')))); $div->appendChild($label); $group->appendChild($div); return $group; }
[ "public", "function", "getPreferencesPane", "(", ")", "{", "parent", "::", "getPreferencesPane", "(", ")", ";", "$", "group", "=", "new", "XMLElement", "(", "'fieldset'", ")", ";", "$", "group", "->", "setAttribute", "(", "'class'", ",", "'settings condensed pickable'", ")", ";", "$", "group", "->", "setAttribute", "(", "'id'", ",", "'smtp'", ")", ";", "$", "group", "->", "appendChild", "(", "new", "XMLElement", "(", "'legend'", ",", "__", "(", "'Email: SMTP'", ")", ")", ")", ";", "$", "div", "=", "new", "XMLElement", "(", "'div'", ")", ";", "$", "readonly", "=", "array", "(", "'readonly'", "=>", "'readonly'", ")", ";", "$", "label", "=", "Widget", "::", "Label", "(", "__", "(", "'HELO Hostname'", ")", ")", ";", "$", "label", "->", "appendChild", "(", "Widget", "::", "Input", "(", "'settings[email_smtp][helo_hostname]'", ",", "General", "::", "sanitize", "(", "$", "this", "->", "_helo_hostname", ")", ",", "'text'", ",", "$", "readonly", ")", ")", ";", "$", "div", "->", "appendChild", "(", "$", "label", ")", ";", "$", "group", "->", "appendChild", "(", "$", "div", ")", ";", "$", "group", "->", "appendChild", "(", "new", "XMLElement", "(", "'p'", ",", "__", "(", "'A fully qualified domain name (FQDN) of your server, e.g. \"www.example.com\". If left empty, Symphony will attempt to find an IP address for the EHLO/HELO greeting.'", ")", ",", "array", "(", "'class'", "=>", "'help'", ")", ")", ")", ";", "$", "div", "=", "new", "XMLElement", "(", "'div'", ")", ";", "$", "div", "->", "setAttribute", "(", "'class'", ",", "'two columns'", ")", ";", "$", "label", "=", "Widget", "::", "Label", "(", "__", "(", "'From Name'", ")", ")", ";", "$", "label", "->", "setAttribute", "(", "'class'", ",", "'column'", ")", ";", "$", "label", "->", "appendChild", "(", "Widget", "::", "Input", "(", "'settings[email_smtp][from_name]'", ",", "General", "::", "sanitize", "(", "$", "this", "->", "_sender_name", ")", ",", "'text'", ",", "$", "readonly", ")", ")", ";", "$", "div", "->", "appendChild", "(", "$", "label", ")", ";", "$", "label", "=", "Widget", "::", "Label", "(", "__", "(", "'From Email Address'", ")", ")", ";", "$", "label", "->", "setAttribute", "(", "'class'", ",", "'column'", ")", ";", "$", "label", "->", "appendChild", "(", "Widget", "::", "Input", "(", "'settings[email_smtp][from_address]'", ",", "General", "::", "sanitize", "(", "$", "this", "->", "_sender_email_address", ")", ",", "'text'", ",", "$", "readonly", ")", ")", ";", "$", "div", "->", "appendChild", "(", "$", "label", ")", ";", "$", "group", "->", "appendChild", "(", "$", "div", ")", ";", "$", "div", "=", "new", "XMLElement", "(", "'div'", ")", ";", "$", "div", "->", "setAttribute", "(", "'class'", ",", "'two columns'", ")", ";", "$", "label", "=", "Widget", "::", "Label", "(", "__", "(", "'Host'", ")", ")", ";", "$", "label", "->", "setAttribute", "(", "'class'", ",", "'column'", ")", ";", "$", "label", "->", "appendChild", "(", "Widget", "::", "Input", "(", "'settings[email_smtp][host]'", ",", "General", "::", "sanitize", "(", "$", "this", "->", "_host", ")", ",", "'text'", ",", "$", "readonly", ")", ")", ";", "$", "div", "->", "appendChild", "(", "$", "label", ")", ";", "$", "label", "=", "Widget", "::", "Label", "(", "__", "(", "'Port'", ")", ")", ";", "$", "label", "->", "setAttribute", "(", "'class'", ",", "'column'", ")", ";", "$", "label", "->", "appendChild", "(", "Widget", "::", "Input", "(", "'settings[email_smtp][port]'", ",", "General", "::", "sanitize", "(", "(", "string", ")", "$", "this", "->", "_port", ")", ",", "'text'", ",", "$", "readonly", ")", ")", ";", "$", "div", "->", "appendChild", "(", "$", "label", ")", ";", "$", "group", "->", "appendChild", "(", "$", "div", ")", ";", "$", "label", "=", "Widget", "::", "Label", "(", ")", ";", "$", "label", "->", "setAttribute", "(", "'class'", ",", "'column'", ")", ";", "// To fix the issue with checkboxes that do not send a value when unchecked.", "$", "options", "=", "array", "(", "array", "(", "'no'", ",", "$", "this", "->", "_secure", "==", "'no'", ",", "__", "(", "'No encryption'", ")", ")", ",", "array", "(", "'ssl'", ",", "$", "this", "->", "_secure", "==", "'ssl'", ",", "__", "(", "'SSL encryption'", ")", ")", ",", "array", "(", "'tls'", ",", "$", "this", "->", "_secure", "==", "'tls'", ",", "__", "(", "'TLS encryption'", ")", ")", ",", ")", ";", "$", "select", "=", "Widget", "::", "Select", "(", "'settings[email_smtp][secure]'", ",", "$", "options", ",", "$", "readonly", ")", ";", "$", "label", "->", "appendChild", "(", "$", "select", ")", ";", "$", "group", "->", "appendChild", "(", "$", "label", ")", ";", "$", "group", "->", "appendChild", "(", "new", "XMLElement", "(", "'p'", ",", "__", "(", "'For a secure connection, SSL and TLS are supported. Please check the manual of your email provider for more details.'", ")", ",", "array", "(", "'class'", "=>", "'help'", ")", ")", ")", ";", "$", "label", "=", "Widget", "::", "Label", "(", ")", ";", "$", "label", "->", "setAttribute", "(", "'class'", ",", "'column'", ")", ";", "// To fix the issue with checkboxes that do not send a value when unchecked.", "$", "group", "->", "appendChild", "(", "Widget", "::", "Input", "(", "'settings[email_smtp][auth]'", ",", "'0'", ",", "'hidden'", ")", ")", ";", "$", "input", "=", "Widget", "::", "Input", "(", "'settings[email_smtp][auth]'", ",", "'1'", ",", "'checkbox'", ",", "$", "readonly", ")", ";", "if", "(", "$", "this", "->", "_auth", "===", "true", ")", "{", "$", "input", "->", "setAttribute", "(", "'checked'", ",", "'checked'", ")", ";", "}", "$", "label", "->", "setValue", "(", "__", "(", "'%s Requires authentication'", ",", "array", "(", "$", "input", "->", "generate", "(", ")", ")", ")", ")", ";", "$", "group", "->", "appendChild", "(", "$", "label", ")", ";", "$", "group", "->", "appendChild", "(", "new", "XMLElement", "(", "'p'", ",", "__", "(", "'Some SMTP connections require authentication. If that is the case, enter the username/password combination below.'", ")", ",", "array", "(", "'class'", "=>", "'help'", ")", ")", ")", ";", "$", "div", "=", "new", "XMLElement", "(", "'div'", ")", ";", "$", "div", "->", "setAttribute", "(", "'class'", ",", "'two columns'", ")", ";", "$", "label", "=", "Widget", "::", "Label", "(", "__", "(", "'Username'", ")", ")", ";", "$", "label", "->", "setAttribute", "(", "'class'", ",", "'column'", ")", ";", "$", "label", "->", "appendChild", "(", "Widget", "::", "Input", "(", "'settings[email_smtp][username]'", ",", "General", "::", "sanitize", "(", "$", "this", "->", "_user", ")", ",", "'text'", ",", "array_merge", "(", "$", "readonly", ",", "array", "(", "'autocomplete'", "=>", "'off'", ")", ")", ")", ")", ";", "$", "div", "->", "appendChild", "(", "$", "label", ")", ";", "$", "label", "=", "Widget", "::", "Label", "(", "__", "(", "'Password'", ")", ")", ";", "$", "label", "->", "setAttribute", "(", "'class'", ",", "'column'", ")", ";", "$", "label", "->", "appendChild", "(", "Widget", "::", "Input", "(", "'settings[email_smtp][password]'", ",", "General", "::", "sanitize", "(", "$", "this", "->", "_pass", ")", ",", "'password'", ",", "array_merge", "(", "$", "readonly", ",", "array", "(", "'autocomplete'", "=>", "'off'", ")", ")", ")", ")", ";", "$", "div", "->", "appendChild", "(", "$", "label", ")", ";", "$", "group", "->", "appendChild", "(", "$", "div", ")", ";", "return", "$", "group", ";", "}" ]
Builds the preferences pane, shown in the Symphony backend. @throws InvalidArgumentException @return XMLElement
[ "Builds", "the", "preferences", "pane", "shown", "in", "the", "Symphony", "backend", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/email-gateways/email.smtp.php#L330-L422
symphonycms/symphony-2
symphony/lib/toolkit/class.json.php
JSON.convertToXML
public static function convertToXML($json, $standalone = true) { self::$dom = new DomDocument('1.0', 'utf-8'); self::$dom->formatOutput = true; // remove callback functions from JSONP if (preg_match('/(\{|\[).*(\}|\])/s', $json, $matches)) { $json = $matches[0]; } else { throw new JSONException(__("JSON not formatted correctly")); } $data = json_decode($json); if (function_exists('json_last_error')) { if (json_last_error() !== JSON_ERROR_NONE) { throw new JSONException(__("JSON not formatted correctly"), json_last_error()); } } elseif (!$data) { throw new JSONException(__("JSON not formatted correctly")); } $data_element = self::_process($data, self::$dom->createElement('data')); self::$dom->appendChild($data_element); if ($standalone) { return self::$dom->saveXML(); } else { return self::$dom->saveXML(self::$dom->documentElement); } }
php
public static function convertToXML($json, $standalone = true) { self::$dom = new DomDocument('1.0', 'utf-8'); self::$dom->formatOutput = true; // remove callback functions from JSONP if (preg_match('/(\{|\[).*(\}|\])/s', $json, $matches)) { $json = $matches[0]; } else { throw new JSONException(__("JSON not formatted correctly")); } $data = json_decode($json); if (function_exists('json_last_error')) { if (json_last_error() !== JSON_ERROR_NONE) { throw new JSONException(__("JSON not formatted correctly"), json_last_error()); } } elseif (!$data) { throw new JSONException(__("JSON not formatted correctly")); } $data_element = self::_process($data, self::$dom->createElement('data')); self::$dom->appendChild($data_element); if ($standalone) { return self::$dom->saveXML(); } else { return self::$dom->saveXML(self::$dom->documentElement); } }
[ "public", "static", "function", "convertToXML", "(", "$", "json", ",", "$", "standalone", "=", "true", ")", "{", "self", "::", "$", "dom", "=", "new", "DomDocument", "(", "'1.0'", ",", "'utf-8'", ")", ";", "self", "::", "$", "dom", "->", "formatOutput", "=", "true", ";", "// remove callback functions from JSONP", "if", "(", "preg_match", "(", "'/(\\{|\\[).*(\\}|\\])/s'", ",", "$", "json", ",", "$", "matches", ")", ")", "{", "$", "json", "=", "$", "matches", "[", "0", "]", ";", "}", "else", "{", "throw", "new", "JSONException", "(", "__", "(", "\"JSON not formatted correctly\"", ")", ")", ";", "}", "$", "data", "=", "json_decode", "(", "$", "json", ")", ";", "if", "(", "function_exists", "(", "'json_last_error'", ")", ")", "{", "if", "(", "json_last_error", "(", ")", "!==", "JSON_ERROR_NONE", ")", "{", "throw", "new", "JSONException", "(", "__", "(", "\"JSON not formatted correctly\"", ")", ",", "json_last_error", "(", ")", ")", ";", "}", "}", "elseif", "(", "!", "$", "data", ")", "{", "throw", "new", "JSONException", "(", "__", "(", "\"JSON not formatted correctly\"", ")", ")", ";", "}", "$", "data_element", "=", "self", "::", "_process", "(", "$", "data", ",", "self", "::", "$", "dom", "->", "createElement", "(", "'data'", ")", ")", ";", "self", "::", "$", "dom", "->", "appendChild", "(", "$", "data_element", ")", ";", "if", "(", "$", "standalone", ")", "{", "return", "self", "::", "$", "dom", "->", "saveXML", "(", ")", ";", "}", "else", "{", "return", "self", "::", "$", "dom", "->", "saveXML", "(", "self", "::", "$", "dom", "->", "documentElement", ")", ";", "}", "}" ]
Given a JSON formatted string, this function will convert it to an equivalent XML version (either standalone or as a fragment). The JSON will be added under a root node of `<data>`. @throws JSONException @param string $json The JSON formatted class @param boolean $standalone If passed true (which is the default), this parameter will cause the function to return the XML with an XML declaration, otherwise the XML will be returned as a fragment. @return string Returns a XML string
[ "Given", "a", "JSON", "formatted", "string", "this", "function", "will", "convert", "it", "to", "an", "equivalent", "XML", "version", "(", "either", "standalone", "or", "as", "a", "fragment", ")", ".", "The", "JSON", "will", "be", "added", "under", "a", "root", "node", "of", "<data", ">", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.json.php#L86-L115
symphonycms/symphony-2
symphony/lib/toolkit/class.json.php
JSON._process
private static function _process($data, DOMElement $element) { if (is_array($data)) { foreach ($data as $item) { $item_element = self::_process($item, self::$dom->createElement('item')); $element->appendChild($item_element); } } elseif (is_object($data)) { $vars = get_object_vars($data); foreach ($vars as $key => $value) { $key = self::_valid_element_name($key); $var_element = self::_process($value, $key); $element->appendChild($var_element); } } else { $element->appendChild(self::$dom->createTextNode($data)); } return $element; }
php
private static function _process($data, DOMElement $element) { if (is_array($data)) { foreach ($data as $item) { $item_element = self::_process($item, self::$dom->createElement('item')); $element->appendChild($item_element); } } elseif (is_object($data)) { $vars = get_object_vars($data); foreach ($vars as $key => $value) { $key = self::_valid_element_name($key); $var_element = self::_process($value, $key); $element->appendChild($var_element); } } else { $element->appendChild(self::$dom->createTextNode($data)); } return $element; }
[ "private", "static", "function", "_process", "(", "$", "data", ",", "DOMElement", "$", "element", ")", "{", "if", "(", "is_array", "(", "$", "data", ")", ")", "{", "foreach", "(", "$", "data", "as", "$", "item", ")", "{", "$", "item_element", "=", "self", "::", "_process", "(", "$", "item", ",", "self", "::", "$", "dom", "->", "createElement", "(", "'item'", ")", ")", ";", "$", "element", "->", "appendChild", "(", "$", "item_element", ")", ";", "}", "}", "elseif", "(", "is_object", "(", "$", "data", ")", ")", "{", "$", "vars", "=", "get_object_vars", "(", "$", "data", ")", ";", "foreach", "(", "$", "vars", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "key", "=", "self", "::", "_valid_element_name", "(", "$", "key", ")", ";", "$", "var_element", "=", "self", "::", "_process", "(", "$", "value", ",", "$", "key", ")", ";", "$", "element", "->", "appendChild", "(", "$", "var_element", ")", ";", "}", "}", "else", "{", "$", "element", "->", "appendChild", "(", "self", "::", "$", "dom", "->", "createTextNode", "(", "$", "data", ")", ")", ";", "}", "return", "$", "element", ";", "}" ]
This function recursively iterates over `$data` and uses `self::$dom` to create an XML structure that mirrors the JSON. The results are added to `$element` and then returned. Any arrays that are encountered are added to 'item' elements. @param mixed $data The initial call to this function will be of `stdClass` and directly from `json_decode`. Recursive calls after that may be of `stdClass`, `array` or `string` types. @param DOMElement $element The `DOMElement` to append the data to. The root node is `<data>`. @return DOMElement
[ "This", "function", "recursively", "iterates", "over", "$data", "and", "uses", "self", "::", "$dom", "to", "create", "an", "XML", "structure", "that", "mirrors", "the", "JSON", ".", "The", "results", "are", "added", "to", "$element", "and", "then", "returned", ".", "Any", "arrays", "that", "are", "encountered", "are", "added", "to", "item", "elements", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.json.php#L131-L151
symphonycms/symphony-2
symphony/lib/toolkit/class.json.php
JSON._valid_element_name
private static function _valid_element_name($name) { if (Lang::isUnicodeCompiled()) { $valid_name = preg_match('/^[\p{L}]([0-9\p{L}\.\-\_]+)?$/u', $name); } else { $valid_name = preg_match('/^[A-z]([\w\d\-_\.]+)?$/i', $name); } if ($valid_name) { $xKey = self::$dom->createElement( Lang::createHandle($name) ); } else { $xKey = self::$dom->createElement('key'); } $xKey->setAttribute('handle', Lang::createHandle($name)); $xKey->setAttribute('value', General::sanitize($name)); return $xKey; }
php
private static function _valid_element_name($name) { if (Lang::isUnicodeCompiled()) { $valid_name = preg_match('/^[\p{L}]([0-9\p{L}\.\-\_]+)?$/u', $name); } else { $valid_name = preg_match('/^[A-z]([\w\d\-_\.]+)?$/i', $name); } if ($valid_name) { $xKey = self::$dom->createElement( Lang::createHandle($name) ); } else { $xKey = self::$dom->createElement('key'); } $xKey->setAttribute('handle', Lang::createHandle($name)); $xKey->setAttribute('value', General::sanitize($name)); return $xKey; }
[ "private", "static", "function", "_valid_element_name", "(", "$", "name", ")", "{", "if", "(", "Lang", "::", "isUnicodeCompiled", "(", ")", ")", "{", "$", "valid_name", "=", "preg_match", "(", "'/^[\\p{L}]([0-9\\p{L}\\.\\-\\_]+)?$/u'", ",", "$", "name", ")", ";", "}", "else", "{", "$", "valid_name", "=", "preg_match", "(", "'/^[A-z]([\\w\\d\\-_\\.]+)?$/i'", ",", "$", "name", ")", ";", "}", "if", "(", "$", "valid_name", ")", "{", "$", "xKey", "=", "self", "::", "$", "dom", "->", "createElement", "(", "Lang", "::", "createHandle", "(", "$", "name", ")", ")", ";", "}", "else", "{", "$", "xKey", "=", "self", "::", "$", "dom", "->", "createElement", "(", "'key'", ")", ";", "}", "$", "xKey", "->", "setAttribute", "(", "'handle'", ",", "Lang", "::", "createHandle", "(", "$", "name", ")", ")", ";", "$", "xKey", "->", "setAttribute", "(", "'value'", ",", "General", "::", "sanitize", "(", "$", "name", ")", ")", ";", "return", "$", "xKey", ";", "}" ]
This function takes a string and returns an empty DOMElement with a valid name. If the passed `$name` is a valid QName, the handle of this name will be the name of the element, otherwise this will fallback to 'key'. @see toolkit.Lang#createHandle @param string $name If the `$name` is not a valid QName it will be ignored and replaced with 'key'. If this happens, a `@value` attribute will be set with the original `$name`. If `$name` is a valid QName, it will be run through `Lang::createHandle` to create a handle for the element. @return DOMElement An empty DOMElement with `@handle` and `@value` attributes.
[ "This", "function", "takes", "a", "string", "and", "returns", "an", "empty", "DOMElement", "with", "a", "valid", "name", ".", "If", "the", "passed", "$name", "is", "a", "valid", "QName", "the", "handle", "of", "this", "name", "will", "be", "the", "name", "of", "the", "element", "otherwise", "this", "will", "fallback", "to", "key", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.json.php#L167-L187
symphonycms/symphony-2
symphony/content/content.publish.php
contentPublish.createFilteringInterface
public function createFilteringInterface() { //Check if section has filtering enabled $context = $this->getContext(); $handle = $context['section_handle']; $section_id = SectionManager::fetchIDFromHandle($handle); $section = SectionManager::fetch($section_id); $filter = $section->get('filter'); $count = EntryManager::fetchCount($section_id); if ($filter !== 'no' && $count > 1) { $drawer = Widget::Drawer('filtering-' . $section_id, __('Filter Entries'), $this->createFilteringDrawer($section)); $drawer->addClass('drawer-filtering'); $this->insertDrawer($drawer); } }
php
public function createFilteringInterface() { //Check if section has filtering enabled $context = $this->getContext(); $handle = $context['section_handle']; $section_id = SectionManager::fetchIDFromHandle($handle); $section = SectionManager::fetch($section_id); $filter = $section->get('filter'); $count = EntryManager::fetchCount($section_id); if ($filter !== 'no' && $count > 1) { $drawer = Widget::Drawer('filtering-' . $section_id, __('Filter Entries'), $this->createFilteringDrawer($section)); $drawer->addClass('drawer-filtering'); $this->insertDrawer($drawer); } }
[ "public", "function", "createFilteringInterface", "(", ")", "{", "//Check if section has filtering enabled", "$", "context", "=", "$", "this", "->", "getContext", "(", ")", ";", "$", "handle", "=", "$", "context", "[", "'section_handle'", "]", ";", "$", "section_id", "=", "SectionManager", "::", "fetchIDFromHandle", "(", "$", "handle", ")", ";", "$", "section", "=", "SectionManager", "::", "fetch", "(", "$", "section_id", ")", ";", "$", "filter", "=", "$", "section", "->", "get", "(", "'filter'", ")", ";", "$", "count", "=", "EntryManager", "::", "fetchCount", "(", "$", "section_id", ")", ";", "if", "(", "$", "filter", "!==", "'no'", "&&", "$", "count", ">", "1", ")", "{", "$", "drawer", "=", "Widget", "::", "Drawer", "(", "'filtering-'", ".", "$", "section_id", ",", "__", "(", "'Filter Entries'", ")", ",", "$", "this", "->", "createFilteringDrawer", "(", "$", "section", ")", ")", ";", "$", "drawer", "->", "addClass", "(", "'drawer-filtering'", ")", ";", "$", "this", "->", "insertDrawer", "(", "$", "drawer", ")", ";", "}", "}" ]
Append filtering interface
[ "Append", "filtering", "interface" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/content/content.publish.php#L71-L86
symphonycms/symphony-2
symphony/content/content.publish.php
contentPublish.createFilteringDrawer
public function createFilteringDrawer($section) { $this->filteringForm = Widget::Form(null, 'get', 'filtering'); $this->createFilteringDuplicator($section); return $this->filteringForm; }
php
public function createFilteringDrawer($section) { $this->filteringForm = Widget::Form(null, 'get', 'filtering'); $this->createFilteringDuplicator($section); return $this->filteringForm; }
[ "public", "function", "createFilteringDrawer", "(", "$", "section", ")", "{", "$", "this", "->", "filteringForm", "=", "Widget", "::", "Form", "(", "null", ",", "'get'", ",", "'filtering'", ")", ";", "$", "this", "->", "createFilteringDuplicator", "(", "$", "section", ")", ";", "return", "$", "this", "->", "filteringForm", ";", "}" ]
Create filtering drawer
[ "Create", "filtering", "drawer" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/content/content.publish.php#L91-L97
symphonycms/symphony-2
symphony/content/content.publish.php
contentPublish.__wrapFieldWithDiv
private function __wrapFieldWithDiv(Field $field, Entry $entry) { $is_hidden = $this->isFieldHidden($field); $div = new XMLElement('div', null, array('id' => 'field-' . $field->get('id'), 'class' => 'field field-'.$field->handle().($field->get('required') == 'yes' ? ' required' : '').($is_hidden === true ? ' irrelevant' : ''))); $field->setAssociationContext($div); $field->displayPublishPanel( $div, $entry->getData($field->get('id')), (isset($this->_errors[$field->get('id')]) ? $this->_errors[$field->get('id')] : null), null, null, (is_numeric($entry->get('id')) ? $entry->get('id') : null) ); /** * Allows developers modify the field before it is rendered in the publish * form. Passes the `Field` object, `Entry` object, the `XMLElement` div and * any errors for the entire `Entry`. Only the `$div` element * will be altered before appending to the page, the rest are read only. * * @since Symphony 2.5.0 * @delegate ModifyFieldPublishWidget * @param string $context * '/backend/' * @param Field $field * @param Entry $entry * @param array $errors * @param Widget $widget */ Symphony::ExtensionManager()->notifyMembers('ModifyFieldPublishWidget', '/backend/', array( 'field' => $field, 'entry' => $entry, 'errors' => $this->_errors, 'widget' => &$div )); return $div; }
php
private function __wrapFieldWithDiv(Field $field, Entry $entry) { $is_hidden = $this->isFieldHidden($field); $div = new XMLElement('div', null, array('id' => 'field-' . $field->get('id'), 'class' => 'field field-'.$field->handle().($field->get('required') == 'yes' ? ' required' : '').($is_hidden === true ? ' irrelevant' : ''))); $field->setAssociationContext($div); $field->displayPublishPanel( $div, $entry->getData($field->get('id')), (isset($this->_errors[$field->get('id')]) ? $this->_errors[$field->get('id')] : null), null, null, (is_numeric($entry->get('id')) ? $entry->get('id') : null) ); /** * Allows developers modify the field before it is rendered in the publish * form. Passes the `Field` object, `Entry` object, the `XMLElement` div and * any errors for the entire `Entry`. Only the `$div` element * will be altered before appending to the page, the rest are read only. * * @since Symphony 2.5.0 * @delegate ModifyFieldPublishWidget * @param string $context * '/backend/' * @param Field $field * @param Entry $entry * @param array $errors * @param Widget $widget */ Symphony::ExtensionManager()->notifyMembers('ModifyFieldPublishWidget', '/backend/', array( 'field' => $field, 'entry' => $entry, 'errors' => $this->_errors, 'widget' => &$div )); return $div; }
[ "private", "function", "__wrapFieldWithDiv", "(", "Field", "$", "field", ",", "Entry", "$", "entry", ")", "{", "$", "is_hidden", "=", "$", "this", "->", "isFieldHidden", "(", "$", "field", ")", ";", "$", "div", "=", "new", "XMLElement", "(", "'div'", ",", "null", ",", "array", "(", "'id'", "=>", "'field-'", ".", "$", "field", "->", "get", "(", "'id'", ")", ",", "'class'", "=>", "'field field-'", ".", "$", "field", "->", "handle", "(", ")", ".", "(", "$", "field", "->", "get", "(", "'required'", ")", "==", "'yes'", "?", "' required'", ":", "''", ")", ".", "(", "$", "is_hidden", "===", "true", "?", "' irrelevant'", ":", "''", ")", ")", ")", ";", "$", "field", "->", "setAssociationContext", "(", "$", "div", ")", ";", "$", "field", "->", "displayPublishPanel", "(", "$", "div", ",", "$", "entry", "->", "getData", "(", "$", "field", "->", "get", "(", "'id'", ")", ")", ",", "(", "isset", "(", "$", "this", "->", "_errors", "[", "$", "field", "->", "get", "(", "'id'", ")", "]", ")", "?", "$", "this", "->", "_errors", "[", "$", "field", "->", "get", "(", "'id'", ")", "]", ":", "null", ")", ",", "null", ",", "null", ",", "(", "is_numeric", "(", "$", "entry", "->", "get", "(", "'id'", ")", ")", "?", "$", "entry", "->", "get", "(", "'id'", ")", ":", "null", ")", ")", ";", "/**\n * Allows developers modify the field before it is rendered in the publish\n * form. Passes the `Field` object, `Entry` object, the `XMLElement` div and\n * any errors for the entire `Entry`. Only the `$div` element\n * will be altered before appending to the page, the rest are read only.\n *\n * @since Symphony 2.5.0\n * @delegate ModifyFieldPublishWidget\n * @param string $context\n * '/backend/'\n * @param Field $field\n * @param Entry $entry\n * @param array $errors\n * @param Widget $widget\n */", "Symphony", "::", "ExtensionManager", "(", ")", "->", "notifyMembers", "(", "'ModifyFieldPublishWidget'", ",", "'/backend/'", ",", "array", "(", "'field'", "=>", "$", "field", ",", "'entry'", "=>", "$", "entry", ",", "'errors'", "=>", "$", "this", "->", "_errors", ",", "'widget'", "=>", "&", "$", "div", ")", ")", ";", "return", "$", "div", ";", "}" ]
Given a Field and Entry object, this function will wrap the Field's displayPublishPanel result with a div that contains some contextual information such as the Field ID, the Field handle and whether it is required or not. @param Field $field @param Entry $entry @return XMLElement
[ "Given", "a", "Field", "and", "Entry", "object", "this", "function", "will", "wrap", "the", "Field", "s", "displayPublishPanel", "result", "with", "a", "div", "that", "contains", "some", "contextual", "information", "such", "as", "the", "Field", "ID", "the", "Field", "handle", "and", "whether", "it", "is", "required", "or", "not", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/content/content.publish.php#L1538-L1574
symphonycms/symphony-2
symphony/content/content.publish.php
contentPublish.isFieldHidden
public function isFieldHidden(Field $field) { if ($field->get('hide_when_prepopulated') == 'yes') { if (isset($_REQUEST['prepopulate'])) { foreach ($_REQUEST['prepopulate'] as $field_id => $value) { if ($field_id == $field->get('id')) { return true; } } } } return false; }
php
public function isFieldHidden(Field $field) { if ($field->get('hide_when_prepopulated') == 'yes') { if (isset($_REQUEST['prepopulate'])) { foreach ($_REQUEST['prepopulate'] as $field_id => $value) { if ($field_id == $field->get('id')) { return true; } } } } return false; }
[ "public", "function", "isFieldHidden", "(", "Field", "$", "field", ")", "{", "if", "(", "$", "field", "->", "get", "(", "'hide_when_prepopulated'", ")", "==", "'yes'", ")", "{", "if", "(", "isset", "(", "$", "_REQUEST", "[", "'prepopulate'", "]", ")", ")", "{", "foreach", "(", "$", "_REQUEST", "[", "'prepopulate'", "]", "as", "$", "field_id", "=>", "$", "value", ")", "{", "if", "(", "$", "field_id", "==", "$", "field", "->", "get", "(", "'id'", ")", ")", "{", "return", "true", ";", "}", "}", "}", "}", "return", "false", ";", "}" ]
Check whether the given `$field` will be hidden because it's been prepopulated. @param Field $field @return boolean
[ "Check", "whether", "the", "given", "$field", "will", "be", "hidden", "because", "it", "s", "been", "prepopulated", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/content/content.publish.php#L1583-L1596
symphonycms/symphony-2
symphony/content/content.publish.php
contentPublish.prepareAssociationsDrawer
private function prepareAssociationsDrawer($section) { $entry_id = (!is_null($this->_context['entry_id'])) ? $this->_context['entry_id'] : null; $show_entries = Symphony::Configuration()->get('association_maximum_rows', 'symphony'); if (is_null($entry_id) && !isset($_GET['prepopulate']) || is_null($show_entries) || $show_entries == 0) { return; } $parent_associations = SectionManager::fetchParentAssociations($section->get('id'), true); $child_associations = SectionManager::fetchChildAssociations($section->get('id'), true); $content = null; $drawer_position = 'vertical-right'; /** * Prepare Associations Drawer from an Extension * * @since Symphony 2.3.3 * @delegate PrepareAssociationsDrawer * @param string $context * '/publish/' * @param integer $entry_id * The entry ID or null * @param array $parent_associations * Array of Sections * @param array $child_associations * Array of Sections * @param string $drawer_position * The position of the Drawer, defaults to `vertical-right`. Available * values of `vertical-left, `vertical-right` and `horizontal` */ Symphony::ExtensionManager()->notifyMembers('PrepareAssociationsDrawer', '/publish/', array( 'entry_id' => $entry_id, 'parent_associations' => &$parent_associations, 'child_associations' => &$child_associations, 'content' => &$content, 'drawer-position' => &$drawer_position )); // If there are no associations, return now. if ( (is_null($parent_associations) || empty($parent_associations)) && (is_null($child_associations) || empty($child_associations)) ) { return; } if (!($content instanceof XMLElement)) { $content = new XMLElement('div', null, array('class' => 'content')); $content->setSelfClosingTag(false); // backup global sorting $sorting = EntryManager::getFetchSorting(); // Process Parent Associations if (!is_null($parent_associations) && !empty($parent_associations)) { $title = new XMLElement('h2', __('Linked to') . ':', array('class' => 'association-title')); $content->appendChild($title); foreach ($parent_associations as $as) { if (empty($as['parent_section_field_id'])) { continue; } if ($field = FieldManager::fetch($as['parent_section_field_id'])) { // Get the related section $parent_section = SectionManager::fetch($as['parent_section_id']); if (!($parent_section instanceof Section)) { continue; } // set global sorting for associated section EntryManager::setFetchSorting( $parent_section->getSortingField(), $parent_section->getSortingOrder() ); if (isset($_GET['prepopulate'])) { $prepopulate_field = key($_GET['prepopulate']); } // get associated entries if entry exists, if ($entry_id) { $relation_field = FieldManager::fetch($as['child_section_field_id']); $entry_ids = $relation_field->findParentRelatedEntries($as['parent_section_field_id'], $entry_id); // get prepopulated entry otherwise } elseif (isset($_GET['prepopulate']) && is_array($_GET['prepopulate']) && isset($_GET['prepopulate'][$as['child_section_field_id']])) { $entry_ids = array(intval($_GET['prepopulate'][$as['child_section_field_id']])); } else { $entry_ids = array(); } // Use $schema for perf reasons $schema = array($field->get('element_name')); $where = (!empty($entry_ids)) ? sprintf(' AND `e`.`id` IN (%s)', implode(', ', $entry_ids)) : null; $entries = (!empty($entry_ids) || isset($_GET['prepopulate']) && $field->get('id') === $prepopulate_field) ? EntryManager::fetchByPage(1, $as['parent_section_id'], $show_entries, $where, null, false, false, true, $schema) : array(); $has_entries = !empty($entries) && $entries['total-entries'] != 0; // Create link $link = SYMPHONY_URL . '/publish/' . $as['handle'] . '/'; $aname = General::sanitize($as['name']); if ($has_entries) { $aname .= ' <span>(' . $entries['total-entries'] . ')</span>'; } $a = new XMLElement('a', $aname, array( 'class' => 'association-section', 'href' => $link, 'title' => strip_tags($aname), )); if (!$has_entries) { unset($field); continue; } $element = new XMLElement('section', null, array('class' => 'association parent')); $header = new XMLElement('header'); $header->appendChild(new XMLElement('p', $a->generate())); $element->appendChild($header); $ul = new XMLElement('ul', null, array( 'class' => 'association-links', 'data-section-id' => $as['child_section_id'], 'data-association-ids' => implode(', ', $entry_ids) )); foreach ($entries['records'] as $e) { // let the field create the mark up $li = $field->prepareAssociationsDrawerXMLElement($e, $as); // add it to the unordered list $ul->appendChild($li); } $element->appendChild($ul); $content->appendChild($element); unset($field); } } } // Process Child Associations if (!is_null($child_associations) && !empty($child_associations)) { $title = new XMLElement('h2', __('Links in') . ':', array('class' => 'association-title')); $content->appendChild($title); foreach ($child_associations as $as) { // Get the related section $child_section = SectionManager::fetch($as['child_section_id']); if (!($child_section instanceof Section)) { continue; } // set global sorting for associated section EntryManager::setFetchSorting( $child_section->getSortingField(), $child_section->getSortingOrder() ); // Get the visible field instance (using the sorting field, this is more flexible than visibleColumns()) // Get the link field instance $visible_field = current($child_section->fetchVisibleColumns()); $relation_field = FieldManager::fetch($as['child_section_field_id']); $entry_ids = $relation_field->findRelatedEntries($entry_id, $as['parent_section_field_id']); $schema = $visible_field ? array($visible_field->get('element_name')) : array(); $where = sprintf(' AND `e`.`id` IN (%s)', implode(', ', $entry_ids)); $entries = (!empty($entry_ids)) ? EntryManager::fetchByPage(1, $as['child_section_id'], $show_entries, $where, null, false, false, true, $schema) : array(); $has_entries = !empty($entries) && $entries['total-entries'] != 0; // Build the HTML of the relationship $element = new XMLElement('section', null, array('class' => 'association child')); $header = new XMLElement('header'); // Get the search value for filters and prepopulate $filter = ''; $prepopulate = ''; $entry = current(EntryManager::fetch($entry_id)); if ($entry) { $search_value = $relation_field->fetchAssociatedEntrySearchValue( $entry->getData($as['parent_section_field_id']), $as['parent_section_field_id'], $entry_id ); if (is_array($search_value)) { $search_value = $entry_id; } $filter = '?filter[' . $relation_field->get('element_name') . ']=' . $search_value; $prepopulate = '?prepopulate[' . $as['child_section_field_id'] . ']=' . $search_value; } // Create link with filter or prepopulate $link = SYMPHONY_URL . '/publish/' . $as['handle'] . '/' . $filter; $aname = General::sanitize($as['name']); if ($has_entries) { $aname .= ' <span>(' . $entries['total-entries'] . ')</span>'; } $a = new XMLElement('a', $aname, array( 'class' => 'association-section', 'href' => $link, 'title' => strip_tags($aname), )); // Create new entries $create = new XMLElement('a', __('New'), array( 'class' => 'button association-new', 'href' => SYMPHONY_URL . '/publish/' . $as['handle'] . '/new/' . $prepopulate )); // Display existing entries if ($has_entries) { $header->appendChild(new XMLElement('p', $a->generate())); $ul = new XMLElement('ul', null, array( 'class' => 'association-links', 'data-section-id' => $as['child_section_id'], 'data-association-ids' => implode(', ', $entry_ids) )); foreach ($entries['records'] as $key => $e) { // let the first visible field create the mark up if ($visible_field) { $li = $visible_field->prepareAssociationsDrawerXMLElement($e, $as, $prepopulate); } // or use the system:id if no visible field exists. else { $li = Field::createAssociationsDrawerXMLElement($e->get('id'), $e, $as, $prepopulate); } // add it to the unordered list $ul->appendChild($li); } $element->appendChild($ul); // If we are only showing 'some' of the entries, then show this on the UI if ($entries['total-entries'] > $show_entries) { $pagination = new XMLElement('li', null, array( 'class' => 'association-more', 'data-current-page' => '1', 'data-total-pages' => ceil($entries['total-entries'] / $show_entries), 'data-total-entries' => $entries['total-entries'] )); $counts = new XMLElement('a', __('Show more entries'), array( 'href' => $link )); $pagination->appendChild($counts); $ul->appendChild($pagination); } // No entries } else { $element->setAttribute('class', 'association child empty'); $header->appendChild(new XMLElement('p', __('No links in %s', array($a->generate())))); } $header->appendChild($create); $element->prependChild($header); $content->appendChild($element); } } // reset global sorting EntryManager::setFetchSorting( $sorting->field, $sorting->direction ); } $drawer = Widget::Drawer('section-associations', __('Show Associations'), $content); $this->insertDrawer($drawer, $drawer_position, 'prepend'); }
php
private function prepareAssociationsDrawer($section) { $entry_id = (!is_null($this->_context['entry_id'])) ? $this->_context['entry_id'] : null; $show_entries = Symphony::Configuration()->get('association_maximum_rows', 'symphony'); if (is_null($entry_id) && !isset($_GET['prepopulate']) || is_null($show_entries) || $show_entries == 0) { return; } $parent_associations = SectionManager::fetchParentAssociations($section->get('id'), true); $child_associations = SectionManager::fetchChildAssociations($section->get('id'), true); $content = null; $drawer_position = 'vertical-right'; /** * Prepare Associations Drawer from an Extension * * @since Symphony 2.3.3 * @delegate PrepareAssociationsDrawer * @param string $context * '/publish/' * @param integer $entry_id * The entry ID or null * @param array $parent_associations * Array of Sections * @param array $child_associations * Array of Sections * @param string $drawer_position * The position of the Drawer, defaults to `vertical-right`. Available * values of `vertical-left, `vertical-right` and `horizontal` */ Symphony::ExtensionManager()->notifyMembers('PrepareAssociationsDrawer', '/publish/', array( 'entry_id' => $entry_id, 'parent_associations' => &$parent_associations, 'child_associations' => &$child_associations, 'content' => &$content, 'drawer-position' => &$drawer_position )); // If there are no associations, return now. if ( (is_null($parent_associations) || empty($parent_associations)) && (is_null($child_associations) || empty($child_associations)) ) { return; } if (!($content instanceof XMLElement)) { $content = new XMLElement('div', null, array('class' => 'content')); $content->setSelfClosingTag(false); // backup global sorting $sorting = EntryManager::getFetchSorting(); // Process Parent Associations if (!is_null($parent_associations) && !empty($parent_associations)) { $title = new XMLElement('h2', __('Linked to') . ':', array('class' => 'association-title')); $content->appendChild($title); foreach ($parent_associations as $as) { if (empty($as['parent_section_field_id'])) { continue; } if ($field = FieldManager::fetch($as['parent_section_field_id'])) { // Get the related section $parent_section = SectionManager::fetch($as['parent_section_id']); if (!($parent_section instanceof Section)) { continue; } // set global sorting for associated section EntryManager::setFetchSorting( $parent_section->getSortingField(), $parent_section->getSortingOrder() ); if (isset($_GET['prepopulate'])) { $prepopulate_field = key($_GET['prepopulate']); } // get associated entries if entry exists, if ($entry_id) { $relation_field = FieldManager::fetch($as['child_section_field_id']); $entry_ids = $relation_field->findParentRelatedEntries($as['parent_section_field_id'], $entry_id); // get prepopulated entry otherwise } elseif (isset($_GET['prepopulate']) && is_array($_GET['prepopulate']) && isset($_GET['prepopulate'][$as['child_section_field_id']])) { $entry_ids = array(intval($_GET['prepopulate'][$as['child_section_field_id']])); } else { $entry_ids = array(); } // Use $schema for perf reasons $schema = array($field->get('element_name')); $where = (!empty($entry_ids)) ? sprintf(' AND `e`.`id` IN (%s)', implode(', ', $entry_ids)) : null; $entries = (!empty($entry_ids) || isset($_GET['prepopulate']) && $field->get('id') === $prepopulate_field) ? EntryManager::fetchByPage(1, $as['parent_section_id'], $show_entries, $where, null, false, false, true, $schema) : array(); $has_entries = !empty($entries) && $entries['total-entries'] != 0; // Create link $link = SYMPHONY_URL . '/publish/' . $as['handle'] . '/'; $aname = General::sanitize($as['name']); if ($has_entries) { $aname .= ' <span>(' . $entries['total-entries'] . ')</span>'; } $a = new XMLElement('a', $aname, array( 'class' => 'association-section', 'href' => $link, 'title' => strip_tags($aname), )); if (!$has_entries) { unset($field); continue; } $element = new XMLElement('section', null, array('class' => 'association parent')); $header = new XMLElement('header'); $header->appendChild(new XMLElement('p', $a->generate())); $element->appendChild($header); $ul = new XMLElement('ul', null, array( 'class' => 'association-links', 'data-section-id' => $as['child_section_id'], 'data-association-ids' => implode(', ', $entry_ids) )); foreach ($entries['records'] as $e) { // let the field create the mark up $li = $field->prepareAssociationsDrawerXMLElement($e, $as); // add it to the unordered list $ul->appendChild($li); } $element->appendChild($ul); $content->appendChild($element); unset($field); } } } // Process Child Associations if (!is_null($child_associations) && !empty($child_associations)) { $title = new XMLElement('h2', __('Links in') . ':', array('class' => 'association-title')); $content->appendChild($title); foreach ($child_associations as $as) { // Get the related section $child_section = SectionManager::fetch($as['child_section_id']); if (!($child_section instanceof Section)) { continue; } // set global sorting for associated section EntryManager::setFetchSorting( $child_section->getSortingField(), $child_section->getSortingOrder() ); // Get the visible field instance (using the sorting field, this is more flexible than visibleColumns()) // Get the link field instance $visible_field = current($child_section->fetchVisibleColumns()); $relation_field = FieldManager::fetch($as['child_section_field_id']); $entry_ids = $relation_field->findRelatedEntries($entry_id, $as['parent_section_field_id']); $schema = $visible_field ? array($visible_field->get('element_name')) : array(); $where = sprintf(' AND `e`.`id` IN (%s)', implode(', ', $entry_ids)); $entries = (!empty($entry_ids)) ? EntryManager::fetchByPage(1, $as['child_section_id'], $show_entries, $where, null, false, false, true, $schema) : array(); $has_entries = !empty($entries) && $entries['total-entries'] != 0; // Build the HTML of the relationship $element = new XMLElement('section', null, array('class' => 'association child')); $header = new XMLElement('header'); // Get the search value for filters and prepopulate $filter = ''; $prepopulate = ''; $entry = current(EntryManager::fetch($entry_id)); if ($entry) { $search_value = $relation_field->fetchAssociatedEntrySearchValue( $entry->getData($as['parent_section_field_id']), $as['parent_section_field_id'], $entry_id ); if (is_array($search_value)) { $search_value = $entry_id; } $filter = '?filter[' . $relation_field->get('element_name') . ']=' . $search_value; $prepopulate = '?prepopulate[' . $as['child_section_field_id'] . ']=' . $search_value; } // Create link with filter or prepopulate $link = SYMPHONY_URL . '/publish/' . $as['handle'] . '/' . $filter; $aname = General::sanitize($as['name']); if ($has_entries) { $aname .= ' <span>(' . $entries['total-entries'] . ')</span>'; } $a = new XMLElement('a', $aname, array( 'class' => 'association-section', 'href' => $link, 'title' => strip_tags($aname), )); // Create new entries $create = new XMLElement('a', __('New'), array( 'class' => 'button association-new', 'href' => SYMPHONY_URL . '/publish/' . $as['handle'] . '/new/' . $prepopulate )); // Display existing entries if ($has_entries) { $header->appendChild(new XMLElement('p', $a->generate())); $ul = new XMLElement('ul', null, array( 'class' => 'association-links', 'data-section-id' => $as['child_section_id'], 'data-association-ids' => implode(', ', $entry_ids) )); foreach ($entries['records'] as $key => $e) { // let the first visible field create the mark up if ($visible_field) { $li = $visible_field->prepareAssociationsDrawerXMLElement($e, $as, $prepopulate); } // or use the system:id if no visible field exists. else { $li = Field::createAssociationsDrawerXMLElement($e->get('id'), $e, $as, $prepopulate); } // add it to the unordered list $ul->appendChild($li); } $element->appendChild($ul); // If we are only showing 'some' of the entries, then show this on the UI if ($entries['total-entries'] > $show_entries) { $pagination = new XMLElement('li', null, array( 'class' => 'association-more', 'data-current-page' => '1', 'data-total-pages' => ceil($entries['total-entries'] / $show_entries), 'data-total-entries' => $entries['total-entries'] )); $counts = new XMLElement('a', __('Show more entries'), array( 'href' => $link )); $pagination->appendChild($counts); $ul->appendChild($pagination); } // No entries } else { $element->setAttribute('class', 'association child empty'); $header->appendChild(new XMLElement('p', __('No links in %s', array($a->generate())))); } $header->appendChild($create); $element->prependChild($header); $content->appendChild($element); } } // reset global sorting EntryManager::setFetchSorting( $sorting->field, $sorting->direction ); } $drawer = Widget::Drawer('section-associations', __('Show Associations'), $content); $this->insertDrawer($drawer, $drawer_position, 'prepend'); }
[ "private", "function", "prepareAssociationsDrawer", "(", "$", "section", ")", "{", "$", "entry_id", "=", "(", "!", "is_null", "(", "$", "this", "->", "_context", "[", "'entry_id'", "]", ")", ")", "?", "$", "this", "->", "_context", "[", "'entry_id'", "]", ":", "null", ";", "$", "show_entries", "=", "Symphony", "::", "Configuration", "(", ")", "->", "get", "(", "'association_maximum_rows'", ",", "'symphony'", ")", ";", "if", "(", "is_null", "(", "$", "entry_id", ")", "&&", "!", "isset", "(", "$", "_GET", "[", "'prepopulate'", "]", ")", "||", "is_null", "(", "$", "show_entries", ")", "||", "$", "show_entries", "==", "0", ")", "{", "return", ";", "}", "$", "parent_associations", "=", "SectionManager", "::", "fetchParentAssociations", "(", "$", "section", "->", "get", "(", "'id'", ")", ",", "true", ")", ";", "$", "child_associations", "=", "SectionManager", "::", "fetchChildAssociations", "(", "$", "section", "->", "get", "(", "'id'", ")", ",", "true", ")", ";", "$", "content", "=", "null", ";", "$", "drawer_position", "=", "'vertical-right'", ";", "/**\n * Prepare Associations Drawer from an Extension\n *\n * @since Symphony 2.3.3\n * @delegate PrepareAssociationsDrawer\n * @param string $context\n * '/publish/'\n * @param integer $entry_id\n * The entry ID or null\n * @param array $parent_associations\n * Array of Sections\n * @param array $child_associations\n * Array of Sections\n * @param string $drawer_position\n * The position of the Drawer, defaults to `vertical-right`. Available\n * values of `vertical-left, `vertical-right` and `horizontal`\n */", "Symphony", "::", "ExtensionManager", "(", ")", "->", "notifyMembers", "(", "'PrepareAssociationsDrawer'", ",", "'/publish/'", ",", "array", "(", "'entry_id'", "=>", "$", "entry_id", ",", "'parent_associations'", "=>", "&", "$", "parent_associations", ",", "'child_associations'", "=>", "&", "$", "child_associations", ",", "'content'", "=>", "&", "$", "content", ",", "'drawer-position'", "=>", "&", "$", "drawer_position", ")", ")", ";", "// If there are no associations, return now.", "if", "(", "(", "is_null", "(", "$", "parent_associations", ")", "||", "empty", "(", "$", "parent_associations", ")", ")", "&&", "(", "is_null", "(", "$", "child_associations", ")", "||", "empty", "(", "$", "child_associations", ")", ")", ")", "{", "return", ";", "}", "if", "(", "!", "(", "$", "content", "instanceof", "XMLElement", ")", ")", "{", "$", "content", "=", "new", "XMLElement", "(", "'div'", ",", "null", ",", "array", "(", "'class'", "=>", "'content'", ")", ")", ";", "$", "content", "->", "setSelfClosingTag", "(", "false", ")", ";", "// backup global sorting", "$", "sorting", "=", "EntryManager", "::", "getFetchSorting", "(", ")", ";", "// Process Parent Associations", "if", "(", "!", "is_null", "(", "$", "parent_associations", ")", "&&", "!", "empty", "(", "$", "parent_associations", ")", ")", "{", "$", "title", "=", "new", "XMLElement", "(", "'h2'", ",", "__", "(", "'Linked to'", ")", ".", "':'", ",", "array", "(", "'class'", "=>", "'association-title'", ")", ")", ";", "$", "content", "->", "appendChild", "(", "$", "title", ")", ";", "foreach", "(", "$", "parent_associations", "as", "$", "as", ")", "{", "if", "(", "empty", "(", "$", "as", "[", "'parent_section_field_id'", "]", ")", ")", "{", "continue", ";", "}", "if", "(", "$", "field", "=", "FieldManager", "::", "fetch", "(", "$", "as", "[", "'parent_section_field_id'", "]", ")", ")", "{", "// Get the related section", "$", "parent_section", "=", "SectionManager", "::", "fetch", "(", "$", "as", "[", "'parent_section_id'", "]", ")", ";", "if", "(", "!", "(", "$", "parent_section", "instanceof", "Section", ")", ")", "{", "continue", ";", "}", "// set global sorting for associated section", "EntryManager", "::", "setFetchSorting", "(", "$", "parent_section", "->", "getSortingField", "(", ")", ",", "$", "parent_section", "->", "getSortingOrder", "(", ")", ")", ";", "if", "(", "isset", "(", "$", "_GET", "[", "'prepopulate'", "]", ")", ")", "{", "$", "prepopulate_field", "=", "key", "(", "$", "_GET", "[", "'prepopulate'", "]", ")", ";", "}", "// get associated entries if entry exists,", "if", "(", "$", "entry_id", ")", "{", "$", "relation_field", "=", "FieldManager", "::", "fetch", "(", "$", "as", "[", "'child_section_field_id'", "]", ")", ";", "$", "entry_ids", "=", "$", "relation_field", "->", "findParentRelatedEntries", "(", "$", "as", "[", "'parent_section_field_id'", "]", ",", "$", "entry_id", ")", ";", "// get prepopulated entry otherwise", "}", "elseif", "(", "isset", "(", "$", "_GET", "[", "'prepopulate'", "]", ")", "&&", "is_array", "(", "$", "_GET", "[", "'prepopulate'", "]", ")", "&&", "isset", "(", "$", "_GET", "[", "'prepopulate'", "]", "[", "$", "as", "[", "'child_section_field_id'", "]", "]", ")", ")", "{", "$", "entry_ids", "=", "array", "(", "intval", "(", "$", "_GET", "[", "'prepopulate'", "]", "[", "$", "as", "[", "'child_section_field_id'", "]", "]", ")", ")", ";", "}", "else", "{", "$", "entry_ids", "=", "array", "(", ")", ";", "}", "// Use $schema for perf reasons", "$", "schema", "=", "array", "(", "$", "field", "->", "get", "(", "'element_name'", ")", ")", ";", "$", "where", "=", "(", "!", "empty", "(", "$", "entry_ids", ")", ")", "?", "sprintf", "(", "' AND `e`.`id` IN (%s)'", ",", "implode", "(", "', '", ",", "$", "entry_ids", ")", ")", ":", "null", ";", "$", "entries", "=", "(", "!", "empty", "(", "$", "entry_ids", ")", "||", "isset", "(", "$", "_GET", "[", "'prepopulate'", "]", ")", "&&", "$", "field", "->", "get", "(", "'id'", ")", "===", "$", "prepopulate_field", ")", "?", "EntryManager", "::", "fetchByPage", "(", "1", ",", "$", "as", "[", "'parent_section_id'", "]", ",", "$", "show_entries", ",", "$", "where", ",", "null", ",", "false", ",", "false", ",", "true", ",", "$", "schema", ")", ":", "array", "(", ")", ";", "$", "has_entries", "=", "!", "empty", "(", "$", "entries", ")", "&&", "$", "entries", "[", "'total-entries'", "]", "!=", "0", ";", "// Create link", "$", "link", "=", "SYMPHONY_URL", ".", "'/publish/'", ".", "$", "as", "[", "'handle'", "]", ".", "'/'", ";", "$", "aname", "=", "General", "::", "sanitize", "(", "$", "as", "[", "'name'", "]", ")", ";", "if", "(", "$", "has_entries", ")", "{", "$", "aname", ".=", "' <span>('", ".", "$", "entries", "[", "'total-entries'", "]", ".", "')</span>'", ";", "}", "$", "a", "=", "new", "XMLElement", "(", "'a'", ",", "$", "aname", ",", "array", "(", "'class'", "=>", "'association-section'", ",", "'href'", "=>", "$", "link", ",", "'title'", "=>", "strip_tags", "(", "$", "aname", ")", ",", ")", ")", ";", "if", "(", "!", "$", "has_entries", ")", "{", "unset", "(", "$", "field", ")", ";", "continue", ";", "}", "$", "element", "=", "new", "XMLElement", "(", "'section'", ",", "null", ",", "array", "(", "'class'", "=>", "'association parent'", ")", ")", ";", "$", "header", "=", "new", "XMLElement", "(", "'header'", ")", ";", "$", "header", "->", "appendChild", "(", "new", "XMLElement", "(", "'p'", ",", "$", "a", "->", "generate", "(", ")", ")", ")", ";", "$", "element", "->", "appendChild", "(", "$", "header", ")", ";", "$", "ul", "=", "new", "XMLElement", "(", "'ul'", ",", "null", ",", "array", "(", "'class'", "=>", "'association-links'", ",", "'data-section-id'", "=>", "$", "as", "[", "'child_section_id'", "]", ",", "'data-association-ids'", "=>", "implode", "(", "', '", ",", "$", "entry_ids", ")", ")", ")", ";", "foreach", "(", "$", "entries", "[", "'records'", "]", "as", "$", "e", ")", "{", "// let the field create the mark up", "$", "li", "=", "$", "field", "->", "prepareAssociationsDrawerXMLElement", "(", "$", "e", ",", "$", "as", ")", ";", "// add it to the unordered list", "$", "ul", "->", "appendChild", "(", "$", "li", ")", ";", "}", "$", "element", "->", "appendChild", "(", "$", "ul", ")", ";", "$", "content", "->", "appendChild", "(", "$", "element", ")", ";", "unset", "(", "$", "field", ")", ";", "}", "}", "}", "// Process Child Associations", "if", "(", "!", "is_null", "(", "$", "child_associations", ")", "&&", "!", "empty", "(", "$", "child_associations", ")", ")", "{", "$", "title", "=", "new", "XMLElement", "(", "'h2'", ",", "__", "(", "'Links in'", ")", ".", "':'", ",", "array", "(", "'class'", "=>", "'association-title'", ")", ")", ";", "$", "content", "->", "appendChild", "(", "$", "title", ")", ";", "foreach", "(", "$", "child_associations", "as", "$", "as", ")", "{", "// Get the related section", "$", "child_section", "=", "SectionManager", "::", "fetch", "(", "$", "as", "[", "'child_section_id'", "]", ")", ";", "if", "(", "!", "(", "$", "child_section", "instanceof", "Section", ")", ")", "{", "continue", ";", "}", "// set global sorting for associated section", "EntryManager", "::", "setFetchSorting", "(", "$", "child_section", "->", "getSortingField", "(", ")", ",", "$", "child_section", "->", "getSortingOrder", "(", ")", ")", ";", "// Get the visible field instance (using the sorting field, this is more flexible than visibleColumns())", "// Get the link field instance", "$", "visible_field", "=", "current", "(", "$", "child_section", "->", "fetchVisibleColumns", "(", ")", ")", ";", "$", "relation_field", "=", "FieldManager", "::", "fetch", "(", "$", "as", "[", "'child_section_field_id'", "]", ")", ";", "$", "entry_ids", "=", "$", "relation_field", "->", "findRelatedEntries", "(", "$", "entry_id", ",", "$", "as", "[", "'parent_section_field_id'", "]", ")", ";", "$", "schema", "=", "$", "visible_field", "?", "array", "(", "$", "visible_field", "->", "get", "(", "'element_name'", ")", ")", ":", "array", "(", ")", ";", "$", "where", "=", "sprintf", "(", "' AND `e`.`id` IN (%s)'", ",", "implode", "(", "', '", ",", "$", "entry_ids", ")", ")", ";", "$", "entries", "=", "(", "!", "empty", "(", "$", "entry_ids", ")", ")", "?", "EntryManager", "::", "fetchByPage", "(", "1", ",", "$", "as", "[", "'child_section_id'", "]", ",", "$", "show_entries", ",", "$", "where", ",", "null", ",", "false", ",", "false", ",", "true", ",", "$", "schema", ")", ":", "array", "(", ")", ";", "$", "has_entries", "=", "!", "empty", "(", "$", "entries", ")", "&&", "$", "entries", "[", "'total-entries'", "]", "!=", "0", ";", "// Build the HTML of the relationship", "$", "element", "=", "new", "XMLElement", "(", "'section'", ",", "null", ",", "array", "(", "'class'", "=>", "'association child'", ")", ")", ";", "$", "header", "=", "new", "XMLElement", "(", "'header'", ")", ";", "// Get the search value for filters and prepopulate", "$", "filter", "=", "''", ";", "$", "prepopulate", "=", "''", ";", "$", "entry", "=", "current", "(", "EntryManager", "::", "fetch", "(", "$", "entry_id", ")", ")", ";", "if", "(", "$", "entry", ")", "{", "$", "search_value", "=", "$", "relation_field", "->", "fetchAssociatedEntrySearchValue", "(", "$", "entry", "->", "getData", "(", "$", "as", "[", "'parent_section_field_id'", "]", ")", ",", "$", "as", "[", "'parent_section_field_id'", "]", ",", "$", "entry_id", ")", ";", "if", "(", "is_array", "(", "$", "search_value", ")", ")", "{", "$", "search_value", "=", "$", "entry_id", ";", "}", "$", "filter", "=", "'?filter['", ".", "$", "relation_field", "->", "get", "(", "'element_name'", ")", ".", "']='", ".", "$", "search_value", ";", "$", "prepopulate", "=", "'?prepopulate['", ".", "$", "as", "[", "'child_section_field_id'", "]", ".", "']='", ".", "$", "search_value", ";", "}", "// Create link with filter or prepopulate", "$", "link", "=", "SYMPHONY_URL", ".", "'/publish/'", ".", "$", "as", "[", "'handle'", "]", ".", "'/'", ".", "$", "filter", ";", "$", "aname", "=", "General", "::", "sanitize", "(", "$", "as", "[", "'name'", "]", ")", ";", "if", "(", "$", "has_entries", ")", "{", "$", "aname", ".=", "' <span>('", ".", "$", "entries", "[", "'total-entries'", "]", ".", "')</span>'", ";", "}", "$", "a", "=", "new", "XMLElement", "(", "'a'", ",", "$", "aname", ",", "array", "(", "'class'", "=>", "'association-section'", ",", "'href'", "=>", "$", "link", ",", "'title'", "=>", "strip_tags", "(", "$", "aname", ")", ",", ")", ")", ";", "// Create new entries", "$", "create", "=", "new", "XMLElement", "(", "'a'", ",", "__", "(", "'New'", ")", ",", "array", "(", "'class'", "=>", "'button association-new'", ",", "'href'", "=>", "SYMPHONY_URL", ".", "'/publish/'", ".", "$", "as", "[", "'handle'", "]", ".", "'/new/'", ".", "$", "prepopulate", ")", ")", ";", "// Display existing entries", "if", "(", "$", "has_entries", ")", "{", "$", "header", "->", "appendChild", "(", "new", "XMLElement", "(", "'p'", ",", "$", "a", "->", "generate", "(", ")", ")", ")", ";", "$", "ul", "=", "new", "XMLElement", "(", "'ul'", ",", "null", ",", "array", "(", "'class'", "=>", "'association-links'", ",", "'data-section-id'", "=>", "$", "as", "[", "'child_section_id'", "]", ",", "'data-association-ids'", "=>", "implode", "(", "', '", ",", "$", "entry_ids", ")", ")", ")", ";", "foreach", "(", "$", "entries", "[", "'records'", "]", "as", "$", "key", "=>", "$", "e", ")", "{", "// let the first visible field create the mark up", "if", "(", "$", "visible_field", ")", "{", "$", "li", "=", "$", "visible_field", "->", "prepareAssociationsDrawerXMLElement", "(", "$", "e", ",", "$", "as", ",", "$", "prepopulate", ")", ";", "}", "// or use the system:id if no visible field exists.", "else", "{", "$", "li", "=", "Field", "::", "createAssociationsDrawerXMLElement", "(", "$", "e", "->", "get", "(", "'id'", ")", ",", "$", "e", ",", "$", "as", ",", "$", "prepopulate", ")", ";", "}", "// add it to the unordered list", "$", "ul", "->", "appendChild", "(", "$", "li", ")", ";", "}", "$", "element", "->", "appendChild", "(", "$", "ul", ")", ";", "// If we are only showing 'some' of the entries, then show this on the UI", "if", "(", "$", "entries", "[", "'total-entries'", "]", ">", "$", "show_entries", ")", "{", "$", "pagination", "=", "new", "XMLElement", "(", "'li'", ",", "null", ",", "array", "(", "'class'", "=>", "'association-more'", ",", "'data-current-page'", "=>", "'1'", ",", "'data-total-pages'", "=>", "ceil", "(", "$", "entries", "[", "'total-entries'", "]", "/", "$", "show_entries", ")", ",", "'data-total-entries'", "=>", "$", "entries", "[", "'total-entries'", "]", ")", ")", ";", "$", "counts", "=", "new", "XMLElement", "(", "'a'", ",", "__", "(", "'Show more entries'", ")", ",", "array", "(", "'href'", "=>", "$", "link", ")", ")", ";", "$", "pagination", "->", "appendChild", "(", "$", "counts", ")", ";", "$", "ul", "->", "appendChild", "(", "$", "pagination", ")", ";", "}", "// No entries", "}", "else", "{", "$", "element", "->", "setAttribute", "(", "'class'", ",", "'association child empty'", ")", ";", "$", "header", "->", "appendChild", "(", "new", "XMLElement", "(", "'p'", ",", "__", "(", "'No links in %s'", ",", "array", "(", "$", "a", "->", "generate", "(", ")", ")", ")", ")", ")", ";", "}", "$", "header", "->", "appendChild", "(", "$", "create", ")", ";", "$", "element", "->", "prependChild", "(", "$", "header", ")", ";", "$", "content", "->", "appendChild", "(", "$", "element", ")", ";", "}", "}", "// reset global sorting", "EntryManager", "::", "setFetchSorting", "(", "$", "sorting", "->", "field", ",", "$", "sorting", "->", "direction", ")", ";", "}", "$", "drawer", "=", "Widget", "::", "Drawer", "(", "'section-associations'", ",", "__", "(", "'Show Associations'", ")", ",", "$", "content", ")", ";", "$", "this", "->", "insertDrawer", "(", "$", "drawer", ",", "$", "drawer_position", ",", "'prepend'", ")", ";", "}" ]
Prepare a Drawer to visualize section associations @param Section $section The current Section object @throws InvalidArgumentException @throws Exception
[ "Prepare", "a", "Drawer", "to", "visualize", "section", "associations" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/content/content.publish.php#L1605-L1883
symphonycms/symphony-2
symphony/content/content.publish.php
contentPublish.getPrepopulateString
public function getPrepopulateString() { $prepopulate_querystring = ''; if (isset($_REQUEST['prepopulate']) && is_array($_REQUEST['prepopulate'])) { foreach ($_REQUEST['prepopulate'] as $field_id => $value) { // Properly decode and re-encode value for output $value = rawurlencode(rawurldecode($value)); $prepopulate_querystring .= sprintf("prepopulate[%s]=%s&", $field_id, $value); } $prepopulate_querystring = trim($prepopulate_querystring, '&'); } // This is to prevent the value being interpreted as an additional GET // parameter. eg. prepopulate[cat]=Minx&June, would come through as: // $_GET['cat'] = Minx // $_GET['June'] = '' $prepopulate_querystring = preg_replace("/&amp;$/", '', $prepopulate_querystring); return $prepopulate_querystring ? '?' . $prepopulate_querystring : null; }
php
public function getPrepopulateString() { $prepopulate_querystring = ''; if (isset($_REQUEST['prepopulate']) && is_array($_REQUEST['prepopulate'])) { foreach ($_REQUEST['prepopulate'] as $field_id => $value) { // Properly decode and re-encode value for output $value = rawurlencode(rawurldecode($value)); $prepopulate_querystring .= sprintf("prepopulate[%s]=%s&", $field_id, $value); } $prepopulate_querystring = trim($prepopulate_querystring, '&'); } // This is to prevent the value being interpreted as an additional GET // parameter. eg. prepopulate[cat]=Minx&June, would come through as: // $_GET['cat'] = Minx // $_GET['June'] = '' $prepopulate_querystring = preg_replace("/&amp;$/", '', $prepopulate_querystring); return $prepopulate_querystring ? '?' . $prepopulate_querystring : null; }
[ "public", "function", "getPrepopulateString", "(", ")", "{", "$", "prepopulate_querystring", "=", "''", ";", "if", "(", "isset", "(", "$", "_REQUEST", "[", "'prepopulate'", "]", ")", "&&", "is_array", "(", "$", "_REQUEST", "[", "'prepopulate'", "]", ")", ")", "{", "foreach", "(", "$", "_REQUEST", "[", "'prepopulate'", "]", "as", "$", "field_id", "=>", "$", "value", ")", "{", "// Properly decode and re-encode value for output", "$", "value", "=", "rawurlencode", "(", "rawurldecode", "(", "$", "value", ")", ")", ";", "$", "prepopulate_querystring", ".=", "sprintf", "(", "\"prepopulate[%s]=%s&\"", ",", "$", "field_id", ",", "$", "value", ")", ";", "}", "$", "prepopulate_querystring", "=", "trim", "(", "$", "prepopulate_querystring", ",", "'&'", ")", ";", "}", "// This is to prevent the value being interpreted as an additional GET", "// parameter. eg. prepopulate[cat]=Minx&June, would come through as:", "// $_GET['cat'] = Minx", "// $_GET['June'] = ''", "$", "prepopulate_querystring", "=", "preg_replace", "(", "\"/&amp;$/\"", ",", "''", ",", "$", "prepopulate_querystring", ")", ";", "return", "$", "prepopulate_querystring", "?", "'?'", ".", "$", "prepopulate_querystring", ":", "null", ";", "}" ]
If this entry is being prepopulated, this function will return the prepopulated fields and values as a query string. @since Symphony 2.5.2 @return string
[ "If", "this", "entry", "is", "being", "prepopulated", "this", "function", "will", "return", "the", "prepopulated", "fields", "and", "values", "as", "a", "query", "string", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/content/content.publish.php#L1892-L1912
symphonycms/symphony-2
symphony/content/content.publish.php
contentPublish.getFilterString
public function getFilterString() { $filter_querystring = ''; if (isset($_REQUEST['prepopulate']) && is_array($_REQUEST['prepopulate'])) { foreach ($_REQUEST['prepopulate'] as $field_id => $value) { $handle = FieldManager::fetchHandleFromID($field_id); // Properly decode and re-encode value for output $value = rawurlencode(rawurldecode($value)); $filter_querystring .= sprintf('filter[%s]=%s&', $handle, $value); } $filter_querystring = trim($filter_querystring, '&'); } // This is to prevent the value being interpreted as an additional GET // parameter. eg. filter[cat]=Minx&June, would come through as: // $_GET['cat'] = Minx // $_GET['June'] = '' $filter_querystring = preg_replace("/&amp;$/", '', $filter_querystring); return $filter_querystring ? '?' . $filter_querystring : null; }
php
public function getFilterString() { $filter_querystring = ''; if (isset($_REQUEST['prepopulate']) && is_array($_REQUEST['prepopulate'])) { foreach ($_REQUEST['prepopulate'] as $field_id => $value) { $handle = FieldManager::fetchHandleFromID($field_id); // Properly decode and re-encode value for output $value = rawurlencode(rawurldecode($value)); $filter_querystring .= sprintf('filter[%s]=%s&', $handle, $value); } $filter_querystring = trim($filter_querystring, '&'); } // This is to prevent the value being interpreted as an additional GET // parameter. eg. filter[cat]=Minx&June, would come through as: // $_GET['cat'] = Minx // $_GET['June'] = '' $filter_querystring = preg_replace("/&amp;$/", '', $filter_querystring); return $filter_querystring ? '?' . $filter_querystring : null; }
[ "public", "function", "getFilterString", "(", ")", "{", "$", "filter_querystring", "=", "''", ";", "if", "(", "isset", "(", "$", "_REQUEST", "[", "'prepopulate'", "]", ")", "&&", "is_array", "(", "$", "_REQUEST", "[", "'prepopulate'", "]", ")", ")", "{", "foreach", "(", "$", "_REQUEST", "[", "'prepopulate'", "]", "as", "$", "field_id", "=>", "$", "value", ")", "{", "$", "handle", "=", "FieldManager", "::", "fetchHandleFromID", "(", "$", "field_id", ")", ";", "// Properly decode and re-encode value for output", "$", "value", "=", "rawurlencode", "(", "rawurldecode", "(", "$", "value", ")", ")", ";", "$", "filter_querystring", ".=", "sprintf", "(", "'filter[%s]=%s&'", ",", "$", "handle", ",", "$", "value", ")", ";", "}", "$", "filter_querystring", "=", "trim", "(", "$", "filter_querystring", ",", "'&'", ")", ";", "}", "// This is to prevent the value being interpreted as an additional GET", "// parameter. eg. filter[cat]=Minx&June, would come through as:", "// $_GET['cat'] = Minx", "// $_GET['June'] = ''", "$", "filter_querystring", "=", "preg_replace", "(", "\"/&amp;$/\"", ",", "''", ",", "$", "filter_querystring", ")", ";", "return", "$", "filter_querystring", "?", "'?'", ".", "$", "filter_querystring", ":", "null", ";", "}" ]
If the entry is being prepopulated, we may want to filter other views by this entry's value. This function will create that filter query string. @since Symphony 2.5.2 @return string
[ "If", "the", "entry", "is", "being", "prepopulated", "we", "may", "want", "to", "filter", "other", "views", "by", "this", "entry", "s", "value", ".", "This", "function", "will", "create", "that", "filter", "query", "string", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/content/content.publish.php#L1921-L1942
symphonycms/symphony-2
symphony/content/content.publish.php
contentPublish.validateTimestamp
protected function validateTimestamp($entry_id, $checkMissing = false) { if (!isset($_POST['action']['ignore-timestamp'])) { if ($checkMissing && !isset($_POST['action']['timestamp'])) { if (isset($this->_errors) && is_array($this->_errors)) { $this->_errors['timestamp'] = __('The entry could not be saved due to conflicting changes'); } return false; } elseif (isset($_POST['action']['timestamp'])) { $tv = new TimestampValidator('entries'); if (!$tv->check($entry_id, $_POST['action']['timestamp'])) { if (isset($this->_errors) && is_array($this->_errors)) { $this->_errors['timestamp'] = __('The entry could not be saved due to conflicting changes'); } return false; } } } return true; }
php
protected function validateTimestamp($entry_id, $checkMissing = false) { if (!isset($_POST['action']['ignore-timestamp'])) { if ($checkMissing && !isset($_POST['action']['timestamp'])) { if (isset($this->_errors) && is_array($this->_errors)) { $this->_errors['timestamp'] = __('The entry could not be saved due to conflicting changes'); } return false; } elseif (isset($_POST['action']['timestamp'])) { $tv = new TimestampValidator('entries'); if (!$tv->check($entry_id, $_POST['action']['timestamp'])) { if (isset($this->_errors) && is_array($this->_errors)) { $this->_errors['timestamp'] = __('The entry could not be saved due to conflicting changes'); } return false; } } } return true; }
[ "protected", "function", "validateTimestamp", "(", "$", "entry_id", ",", "$", "checkMissing", "=", "false", ")", "{", "if", "(", "!", "isset", "(", "$", "_POST", "[", "'action'", "]", "[", "'ignore-timestamp'", "]", ")", ")", "{", "if", "(", "$", "checkMissing", "&&", "!", "isset", "(", "$", "_POST", "[", "'action'", "]", "[", "'timestamp'", "]", ")", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "_errors", ")", "&&", "is_array", "(", "$", "this", "->", "_errors", ")", ")", "{", "$", "this", "->", "_errors", "[", "'timestamp'", "]", "=", "__", "(", "'The entry could not be saved due to conflicting changes'", ")", ";", "}", "return", "false", ";", "}", "elseif", "(", "isset", "(", "$", "_POST", "[", "'action'", "]", "[", "'timestamp'", "]", ")", ")", "{", "$", "tv", "=", "new", "TimestampValidator", "(", "'entries'", ")", ";", "if", "(", "!", "$", "tv", "->", "check", "(", "$", "entry_id", ",", "$", "_POST", "[", "'action'", "]", "[", "'timestamp'", "]", ")", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "_errors", ")", "&&", "is_array", "(", "$", "this", "->", "_errors", ")", ")", "{", "$", "this", "->", "_errors", "[", "'timestamp'", "]", "=", "__", "(", "'The entry could not be saved due to conflicting changes'", ")", ";", "}", "return", "false", ";", "}", "}", "}", "return", "true", ";", "}" ]
Given $_POST values, this function will validate the current timestamp and set the proper error messages. @since Symphony 2.7.0 @param int $entry_id The entry id to validate @return boolean true if the timestamp is valid
[ "Given", "$_POST", "values", "this", "function", "will", "validate", "the", "current", "timestamp", "and", "set", "the", "proper", "error", "messages", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/content/content.publish.php#L1954-L1973
symphonycms/symphony-2
symphony/content/content.blueprintsdatasources.php
contentBlueprintsDatasources.__isValidURL
public static function __isValidURL($url, $timeout = 6, &$error) { if (!filter_var($url, FILTER_VALIDATE_URL)) { $error = __('Invalid URL'); return false; } // Check that URL was provided $gateway = new Gateway; $gateway->init($url); $gateway->setopt('TIMEOUT', $timeout); $data = $gateway->exec(); $info = $gateway->getInfoLast(); // 28 is CURLE_OPERATION_TIMEDOUT if ($info['curl_error'] == 28) { $error = __('Request timed out. %d second limit reached.', array($timeout)); return false; } elseif ($data === false || $info['http_code'] != 200) { $error = __('Failed to load URL, status code %d was returned.', array($info['http_code'])); return false; } return array('data' => $data); }
php
public static function __isValidURL($url, $timeout = 6, &$error) { if (!filter_var($url, FILTER_VALIDATE_URL)) { $error = __('Invalid URL'); return false; } // Check that URL was provided $gateway = new Gateway; $gateway->init($url); $gateway->setopt('TIMEOUT', $timeout); $data = $gateway->exec(); $info = $gateway->getInfoLast(); // 28 is CURLE_OPERATION_TIMEDOUT if ($info['curl_error'] == 28) { $error = __('Request timed out. %d second limit reached.', array($timeout)); return false; } elseif ($data === false || $info['http_code'] != 200) { $error = __('Failed to load URL, status code %d was returned.', array($info['http_code'])); return false; } return array('data' => $data); }
[ "public", "static", "function", "__isValidURL", "(", "$", "url", ",", "$", "timeout", "=", "6", ",", "&", "$", "error", ")", "{", "if", "(", "!", "filter_var", "(", "$", "url", ",", "FILTER_VALIDATE_URL", ")", ")", "{", "$", "error", "=", "__", "(", "'Invalid URL'", ")", ";", "return", "false", ";", "}", "// Check that URL was provided", "$", "gateway", "=", "new", "Gateway", ";", "$", "gateway", "->", "init", "(", "$", "url", ")", ";", "$", "gateway", "->", "setopt", "(", "'TIMEOUT'", ",", "$", "timeout", ")", ";", "$", "data", "=", "$", "gateway", "->", "exec", "(", ")", ";", "$", "info", "=", "$", "gateway", "->", "getInfoLast", "(", ")", ";", "// 28 is CURLE_OPERATION_TIMEDOUT", "if", "(", "$", "info", "[", "'curl_error'", "]", "==", "28", ")", "{", "$", "error", "=", "__", "(", "'Request timed out. %d second limit reached.'", ",", "array", "(", "$", "timeout", ")", ")", ";", "return", "false", ";", "}", "elseif", "(", "$", "data", "===", "false", "||", "$", "info", "[", "'http_code'", "]", "!=", "200", ")", "{", "$", "error", "=", "__", "(", "'Failed to load URL, status code %d was returned.'", ",", "array", "(", "$", "info", "[", "'http_code'", "]", ")", ")", ";", "return", "false", ";", "}", "return", "array", "(", "'data'", "=>", "$", "data", ")", ";", "}" ]
Given a `$url` and `$timeout`, this function will use the `Gateway` class to determine that it is a valid URL and returns successfully before the `$timeout`. If it does not, an error message will be returned, otherwise true. @since Symphony 2.3 @param string $url @param integer $timeout If not provided, this will default to 6 seconds @param string $error If this function returns false, this variable will be populated with the error message. @return array|boolean Returns an array with the 'data' if it is a valid URL, otherwise a string containing an error message.
[ "Given", "a", "$url", "and", "$timeout", "this", "function", "will", "use", "the", "Gateway", "class", "to", "determine", "that", "it", "is", "a", "valid", "URL", "and", "returns", "successfully", "before", "the", "$timeout", ".", "If", "it", "does", "not", "an", "error", "message", "will", "be", "returned", "otherwise", "true", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/content/content.blueprintsdatasources.php#L1639-L1664
symphonycms/symphony-2
symphony/lib/toolkit/class.alert.php
Alert.asXML
public function asXML() { $p = new XMLElement('p', $this->message, array('role' => 'alert')); $p->setAttribute('class', 'notice'); if ($this->type !== self::NOTICE) { $p->setAttribute('class', 'notice ' . $this->type); } return $p; }
php
public function asXML() { $p = new XMLElement('p', $this->message, array('role' => 'alert')); $p->setAttribute('class', 'notice'); if ($this->type !== self::NOTICE) { $p->setAttribute('class', 'notice ' . $this->type); } return $p; }
[ "public", "function", "asXML", "(", ")", "{", "$", "p", "=", "new", "XMLElement", "(", "'p'", ",", "$", "this", "->", "message", ",", "array", "(", "'role'", "=>", "'alert'", ")", ")", ";", "$", "p", "->", "setAttribute", "(", "'class'", ",", "'notice'", ")", ";", "if", "(", "$", "this", "->", "type", "!==", "self", "::", "NOTICE", ")", "{", "$", "p", "->", "setAttribute", "(", "'class'", ",", "'notice '", ".", "$", "this", "->", "type", ")", ";", "}", "return", "$", "p", ";", "}" ]
Generates as XMLElement representation of this Alert @return XMLElement
[ "Generates", "as", "XMLElement", "representation", "of", "this", "Alert" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.alert.php#L113-L123
symphonycms/symphony-2
symphony/lib/toolkit/class.mutex.php
Mutex.acquire
public static function acquire($id, $ttl = 5, $path = '.') { $lockFile = self::__generateLockFileName($id, $path); // If this thread already has acquired the lock, return true. if (isset(self::$lockFiles[$lockFile])) { $age = time() - self::$lockFiles[$lockFile]['time']; return ($age < $ttl ? false : true); } // Disable log temporarily because we actually depend on fopen() // failing with E_WARNING here and we do not want Symphony to throw // errors or spam logfiles. try { GenericErrorHandler::$logDisabled = true; $lock = fopen($lockFile, 'xb'); GenericErrorHandler::$logDisabled = false; self::$lockFiles[$lockFile] = array('time' => time(), 'ttl' => $ttl); fclose($lock); return true; } catch (Exception $ex) { // If, for some reason, lock file was not unlinked before, // remove it if it is old enough. if (file_exists($lockFile)) { $age = time() - filemtime($lockFile); if ($age > $ttl) { unlink($lockFile); } } // Return false anyway - just in case two or more threads // do the same check and unlink at the same time. return false; } }
php
public static function acquire($id, $ttl = 5, $path = '.') { $lockFile = self::__generateLockFileName($id, $path); // If this thread already has acquired the lock, return true. if (isset(self::$lockFiles[$lockFile])) { $age = time() - self::$lockFiles[$lockFile]['time']; return ($age < $ttl ? false : true); } // Disable log temporarily because we actually depend on fopen() // failing with E_WARNING here and we do not want Symphony to throw // errors or spam logfiles. try { GenericErrorHandler::$logDisabled = true; $lock = fopen($lockFile, 'xb'); GenericErrorHandler::$logDisabled = false; self::$lockFiles[$lockFile] = array('time' => time(), 'ttl' => $ttl); fclose($lock); return true; } catch (Exception $ex) { // If, for some reason, lock file was not unlinked before, // remove it if it is old enough. if (file_exists($lockFile)) { $age = time() - filemtime($lockFile); if ($age > $ttl) { unlink($lockFile); } } // Return false anyway - just in case two or more threads // do the same check and unlink at the same time. return false; } }
[ "public", "static", "function", "acquire", "(", "$", "id", ",", "$", "ttl", "=", "5", ",", "$", "path", "=", "'.'", ")", "{", "$", "lockFile", "=", "self", "::", "__generateLockFileName", "(", "$", "id", ",", "$", "path", ")", ";", "// If this thread already has acquired the lock, return true.", "if", "(", "isset", "(", "self", "::", "$", "lockFiles", "[", "$", "lockFile", "]", ")", ")", "{", "$", "age", "=", "time", "(", ")", "-", "self", "::", "$", "lockFiles", "[", "$", "lockFile", "]", "[", "'time'", "]", ";", "return", "(", "$", "age", "<", "$", "ttl", "?", "false", ":", "true", ")", ";", "}", "// Disable log temporarily because we actually depend on fopen()", "// failing with E_WARNING here and we do not want Symphony to throw", "// errors or spam logfiles.", "try", "{", "GenericErrorHandler", "::", "$", "logDisabled", "=", "true", ";", "$", "lock", "=", "fopen", "(", "$", "lockFile", ",", "'xb'", ")", ";", "GenericErrorHandler", "::", "$", "logDisabled", "=", "false", ";", "self", "::", "$", "lockFiles", "[", "$", "lockFile", "]", "=", "array", "(", "'time'", "=>", "time", "(", ")", ",", "'ttl'", "=>", "$", "ttl", ")", ";", "fclose", "(", "$", "lock", ")", ";", "return", "true", ";", "}", "catch", "(", "Exception", "$", "ex", ")", "{", "// If, for some reason, lock file was not unlinked before,", "// remove it if it is old enough.", "if", "(", "file_exists", "(", "$", "lockFile", ")", ")", "{", "$", "age", "=", "time", "(", ")", "-", "filemtime", "(", "$", "lockFile", ")", ";", "if", "(", "$", "age", ">", "$", "ttl", ")", "{", "unlink", "(", "$", "lockFile", ")", ";", "}", "}", "// Return false anyway - just in case two or more threads", "// do the same check and unlink at the same time.", "return", "false", ";", "}", "}" ]
Creates a lock file if one does not already exist with a certain time to live (TTL) at a specific path. If a lock already exists, false will be returned otherwise boolean depending if a lock file was created successfully or not. @param string $id The name of the lock file, which gets obfuscated using generateLockFileName. @param integer $ttl The length, in seconds, that the lock should exist for. Defaults to 5. @param string $path The path the lock should be written, defaults to the current working directory @return boolean
[ "Creates", "a", "lock", "file", "if", "one", "does", "not", "already", "exist", "with", "a", "certain", "time", "to", "live", "(", "TTL", ")", "at", "a", "specific", "path", ".", "If", "a", "lock", "already", "exists", "false", "will", "be", "returned", "otherwise", "boolean", "depending", "if", "a", "lock", "file", "was", "created", "successfully", "or", "not", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.mutex.php#L37-L74
symphonycms/symphony-2
symphony/lib/toolkit/class.mutex.php
Mutex.release
public static function release($id, $path = '.') { $lockFile = self::__generateLockFileName($id, $path); if (!empty(self::$lockFiles[$lockFile])) { unset(self::$lockFiles[$lockFile]); return General::deleteFile($lockFile, false); } return false; }
php
public static function release($id, $path = '.') { $lockFile = self::__generateLockFileName($id, $path); if (!empty(self::$lockFiles[$lockFile])) { unset(self::$lockFiles[$lockFile]); return General::deleteFile($lockFile, false); } return false; }
[ "public", "static", "function", "release", "(", "$", "id", ",", "$", "path", "=", "'.'", ")", "{", "$", "lockFile", "=", "self", "::", "__generateLockFileName", "(", "$", "id", ",", "$", "path", ")", ";", "if", "(", "!", "empty", "(", "self", "::", "$", "lockFiles", "[", "$", "lockFile", "]", ")", ")", "{", "unset", "(", "self", "::", "$", "lockFiles", "[", "$", "lockFile", "]", ")", ";", "return", "General", "::", "deleteFile", "(", "$", "lockFile", ",", "false", ")", ";", "}", "return", "false", ";", "}" ]
Removes a lock file. This is the only way a lock file can be removed @param string $id The original name of the lock file (note that this will be different from the name of the file saved on the file system) @param string $path The path to the lock, defaults to the current working directory @return boolean
[ "Removes", "a", "lock", "file", ".", "This", "is", "the", "only", "way", "a", "lock", "file", "can", "be", "removed" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.mutex.php#L86-L96
symphonycms/symphony-2
symphony/lib/toolkit/class.mutex.php
Mutex.refresh
public static function refresh($id, $ttl = 5, $path = '.') { return touch(self::__generateLockFileName($id, $path), time() + $ttl, time()); }
php
public static function refresh($id, $ttl = 5, $path = '.') { return touch(self::__generateLockFileName($id, $path), time() + $ttl, time()); }
[ "public", "static", "function", "refresh", "(", "$", "id", ",", "$", "ttl", "=", "5", ",", "$", "path", "=", "'.'", ")", "{", "return", "touch", "(", "self", "::", "__generateLockFileName", "(", "$", "id", ",", "$", "path", ")", ",", "time", "(", ")", "+", "$", "ttl", ",", "time", "(", ")", ")", ";", "}" ]
Updates a lock file to 'keep alive' for another 'x' seconds. @param string $id The name of the lock file, which gets obfuscated using `__generateLockFileName()`. @param integer $ttl The length, in seconds, that the lock should be extended by. Defaults to 5. @param string $path The path to the lock, defaults to the current working directory @return boolean
[ "Updates", "a", "lock", "file", "to", "keep", "alive", "for", "another", "x", "seconds", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.mutex.php#L111-L114
symphonycms/symphony-2
symphony/lib/toolkit/class.mutex.php
Mutex.lockExists
public static function lockExists($id, $path) { $lockFile = self::__generateLockFileName($id, $path); return file_exists($lockFile); }
php
public static function lockExists($id, $path) { $lockFile = self::__generateLockFileName($id, $path); return file_exists($lockFile); }
[ "public", "static", "function", "lockExists", "(", "$", "id", ",", "$", "path", ")", "{", "$", "lockFile", "=", "self", "::", "__generateLockFileName", "(", "$", "id", ",", "$", "path", ")", ";", "return", "file_exists", "(", "$", "lockFile", ")", ";", "}" ]
Checks if a lock exists, purely on the presence on the lock file. This function takes the unobfuscated lock name Others should not depend on value returned by this function, because by the time it returns, the lock file can be created or deleted by another thread. @since Symphony 2.2 @param string $id The name of the lock file, which gets obfuscated using generateLockFileName. @param string $path The path the lock should be written, defaults to the current working directory @return boolean
[ "Checks", "if", "a", "lock", "exists", "purely", "on", "the", "presence", "on", "the", "lock", "file", ".", "This", "function", "takes", "the", "unobfuscated", "lock", "name", "Others", "should", "not", "depend", "on", "value", "returned", "by", "this", "function", "because", "by", "the", "time", "it", "returns", "the", "lock", "file", "can", "be", "created", "or", "deleted", "by", "another", "thread", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.mutex.php#L132-L137
symphonycms/symphony-2
symphony/lib/toolkit/class.mutex.php
Mutex.__generateLockFileName
private static function __generateLockFileName($id, $path = null) { // This function is called from all others, so it is a good point to initialize Mutex handling. if (!is_array(self::$lockFiles)) { self::$lockFiles = array(); register_shutdown_function(array(__CLASS__, '__shutdownCleanup')); } if (is_null($path)) { $path = sys_get_temp_dir(); } // Use realpath, because shutdown function may operate in different working directory. // So we need to be sure that path is absolute. return rtrim(realpath($path), '/') . '/' . md5($id) . '.lock'; }
php
private static function __generateLockFileName($id, $path = null) { // This function is called from all others, so it is a good point to initialize Mutex handling. if (!is_array(self::$lockFiles)) { self::$lockFiles = array(); register_shutdown_function(array(__CLASS__, '__shutdownCleanup')); } if (is_null($path)) { $path = sys_get_temp_dir(); } // Use realpath, because shutdown function may operate in different working directory. // So we need to be sure that path is absolute. return rtrim(realpath($path), '/') . '/' . md5($id) . '.lock'; }
[ "private", "static", "function", "__generateLockFileName", "(", "$", "id", ",", "$", "path", "=", "null", ")", "{", "// This function is called from all others, so it is a good point to initialize Mutex handling.", "if", "(", "!", "is_array", "(", "self", "::", "$", "lockFiles", ")", ")", "{", "self", "::", "$", "lockFiles", "=", "array", "(", ")", ";", "register_shutdown_function", "(", "array", "(", "__CLASS__", ",", "'__shutdownCleanup'", ")", ")", ";", "}", "if", "(", "is_null", "(", "$", "path", ")", ")", "{", "$", "path", "=", "sys_get_temp_dir", "(", ")", ";", "}", "// Use realpath, because shutdown function may operate in different working directory.", "// So we need to be sure that path is absolute.", "return", "rtrim", "(", "realpath", "(", "$", "path", ")", ",", "'/'", ")", ".", "'/'", ".", "md5", "(", "$", "id", ")", ".", "'.lock'", ";", "}" ]
Generates a lock filename using an MD5 hash of the `$id` and `$path`. Lock files are given a .lock extension @param string $id The name of the lock file to be obfuscated @param string $path The path the lock should be written @return string
[ "Generates", "a", "lock", "filename", "using", "an", "MD5", "hash", "of", "the", "$id", "and", "$path", ".", "Lock", "files", "are", "given", "a", ".", "lock", "extension" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.mutex.php#L149-L164
symphonycms/symphony-2
symphony/lib/toolkit/class.mutex.php
Mutex.__shutdownCleanup
public static function __shutdownCleanup() { $now = time(); if (is_array(self::$lockFiles)) { foreach (self::$lockFiles as $lockFile => $meta) { if (($now - $meta['time'] > $meta['ttl']) && file_exists($lockFile)) { unlink($lockFile); } } } }
php
public static function __shutdownCleanup() { $now = time(); if (is_array(self::$lockFiles)) { foreach (self::$lockFiles as $lockFile => $meta) { if (($now - $meta['time'] > $meta['ttl']) && file_exists($lockFile)) { unlink($lockFile); } } } }
[ "public", "static", "function", "__shutdownCleanup", "(", ")", "{", "$", "now", "=", "time", "(", ")", ";", "if", "(", "is_array", "(", "self", "::", "$", "lockFiles", ")", ")", "{", "foreach", "(", "self", "::", "$", "lockFiles", "as", "$", "lockFile", "=>", "$", "meta", ")", "{", "if", "(", "(", "$", "now", "-", "$", "meta", "[", "'time'", "]", ">", "$", "meta", "[", "'ttl'", "]", ")", "&&", "file_exists", "(", "$", "lockFile", ")", ")", "{", "unlink", "(", "$", "lockFile", ")", ";", "}", "}", "}", "}" ]
Releases all locks on expired files. @since Symphony 2.2.2
[ "Releases", "all", "locks", "on", "expired", "files", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.mutex.php#L171-L182
symphonycms/symphony-2
symphony/lib/toolkit/class.resourcespage.php
ResourcesPage.sort
public function sort(&$sort, &$order, array $params) { $type = $params['type']; if (!is_null($sort)) { General::sanitize($sort); } // If `?unsort` is appended to the URL, then sorting information are reverted // to their defaults if (isset($params['unsort'])) { ResourceManager::setSortingField($type, 'name', false); ResourceManager::setSortingOrder($type, 'asc'); redirect(Administration::instance()->getCurrentPageURL()); } // By default, sorting information are retrieved from // the filesystem and stored inside the `Configuration` object if (is_null($sort) && is_null($order)) { $sort = ResourceManager::getSortingField($type); $order = ResourceManager::getSortingOrder($type); // If the sorting field or order differs from what is saved, // update the config file and reload the page } elseif ($sort !== ResourceManager::getSortingField($type) || $order !== ResourceManager::getSortingOrder($type)) { ResourceManager::setSortingField($type, $sort, false); ResourceManager::setSortingOrder($type, $order); redirect(Administration::instance()->getCurrentPageURL()); } return ResourceManager::fetch($params['type'], array(), array(), $sort . ' ' . $order); }
php
public function sort(&$sort, &$order, array $params) { $type = $params['type']; if (!is_null($sort)) { General::sanitize($sort); } // If `?unsort` is appended to the URL, then sorting information are reverted // to their defaults if (isset($params['unsort'])) { ResourceManager::setSortingField($type, 'name', false); ResourceManager::setSortingOrder($type, 'asc'); redirect(Administration::instance()->getCurrentPageURL()); } // By default, sorting information are retrieved from // the filesystem and stored inside the `Configuration` object if (is_null($sort) && is_null($order)) { $sort = ResourceManager::getSortingField($type); $order = ResourceManager::getSortingOrder($type); // If the sorting field or order differs from what is saved, // update the config file and reload the page } elseif ($sort !== ResourceManager::getSortingField($type) || $order !== ResourceManager::getSortingOrder($type)) { ResourceManager::setSortingField($type, $sort, false); ResourceManager::setSortingOrder($type, $order); redirect(Administration::instance()->getCurrentPageURL()); } return ResourceManager::fetch($params['type'], array(), array(), $sort . ' ' . $order); }
[ "public", "function", "sort", "(", "&", "$", "sort", ",", "&", "$", "order", ",", "array", "$", "params", ")", "{", "$", "type", "=", "$", "params", "[", "'type'", "]", ";", "if", "(", "!", "is_null", "(", "$", "sort", ")", ")", "{", "General", "::", "sanitize", "(", "$", "sort", ")", ";", "}", "// If `?unsort` is appended to the URL, then sorting information are reverted", "// to their defaults", "if", "(", "isset", "(", "$", "params", "[", "'unsort'", "]", ")", ")", "{", "ResourceManager", "::", "setSortingField", "(", "$", "type", ",", "'name'", ",", "false", ")", ";", "ResourceManager", "::", "setSortingOrder", "(", "$", "type", ",", "'asc'", ")", ";", "redirect", "(", "Administration", "::", "instance", "(", ")", "->", "getCurrentPageURL", "(", ")", ")", ";", "}", "// By default, sorting information are retrieved from", "// the filesystem and stored inside the `Configuration` object", "if", "(", "is_null", "(", "$", "sort", ")", "&&", "is_null", "(", "$", "order", ")", ")", "{", "$", "sort", "=", "ResourceManager", "::", "getSortingField", "(", "$", "type", ")", ";", "$", "order", "=", "ResourceManager", "::", "getSortingOrder", "(", "$", "type", ")", ";", "// If the sorting field or order differs from what is saved,", "// update the config file and reload the page", "}", "elseif", "(", "$", "sort", "!==", "ResourceManager", "::", "getSortingField", "(", "$", "type", ")", "||", "$", "order", "!==", "ResourceManager", "::", "getSortingOrder", "(", "$", "type", ")", ")", "{", "ResourceManager", "::", "setSortingField", "(", "$", "type", ",", "$", "sort", ",", "false", ")", ";", "ResourceManager", "::", "setSortingOrder", "(", "$", "type", ",", "$", "order", ")", ";", "redirect", "(", "Administration", "::", "instance", "(", ")", "->", "getCurrentPageURL", "(", ")", ")", ";", "}", "return", "ResourceManager", "::", "fetch", "(", "$", "params", "[", "'type'", "]", ",", "array", "(", ")", ",", "array", "(", ")", ",", "$", "sort", ".", "' '", ".", "$", "order", ")", ";", "}" ]
This method is invoked from the `Sortable` class and it contains the logic for sorting (or unsorting) the resource index. It provides a basic wrapper to the `ResourceManager`'s `fetch()` method. @see toolkit.ResourceManager#getSortingField @see toolkit.ResourceManager#getSortingOrder @see toolkit.ResourceManager#fetch @param string $sort The field to sort on which should match one of the table's column names. If this is not provided the default will be determined by `ResourceManager::getSortingField` @param string $order The direction to sort in, either 'asc' or 'desc'. If this is not provided the value will be determined by `ResourceManager::getSortingOrder`. @param array $params An associative array of params (usually populated from the URL) that this function uses. The current implementation will use `type` and `unsort` keys @throws Exception @throws SymphonyErrorPage @return array An associative of the resource as determined by `ResourceManager::fetch`
[ "This", "method", "is", "invoked", "from", "the", "Sortable", "class", "and", "it", "contains", "the", "logic", "for", "sorting", "(", "or", "unsorting", ")", "the", "resource", "index", ".", "It", "provides", "a", "basic", "wrapper", "to", "the", "ResourceManager", "s", "fetch", "()", "method", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.resourcespage.php#L40-L73
symphonycms/symphony-2
symphony/lib/toolkit/class.resourcespage.php
ResourcesPage.pagesFlatView
public function pagesFlatView() { $pages = PageManager::fetch(false, array('id')); foreach ($pages as &$p) { $p['title'] = PageManager::resolvePageTitle($p['id']); } return $pages; }
php
public function pagesFlatView() { $pages = PageManager::fetch(false, array('id')); foreach ($pages as &$p) { $p['title'] = PageManager::resolvePageTitle($p['id']); } return $pages; }
[ "public", "function", "pagesFlatView", "(", ")", "{", "$", "pages", "=", "PageManager", "::", "fetch", "(", "false", ",", "array", "(", "'id'", ")", ")", ";", "foreach", "(", "$", "pages", "as", "&", "$", "p", ")", "{", "$", "p", "[", "'title'", "]", "=", "PageManager", "::", "resolvePageTitle", "(", "$", "p", "[", "'id'", "]", ")", ";", "}", "return", "$", "pages", ";", "}" ]
This function creates an array of all page titles in the system. @return array An array of page titles
[ "This", "function", "creates", "an", "array", "of", "all", "page", "titles", "in", "the", "system", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.resourcespage.php#L81-L90
symphonycms/symphony-2
symphony/lib/toolkit/class.resourcespage.php
ResourcesPage.__viewIndex
public function __viewIndex($resource_type) { $manager = ResourceManager::getManagerFromType($resource_type); $friendly_resource = ($resource_type === ResourceManager::RESOURCE_TYPE_EVENT) ? __('Event') : __('DataSource'); $this->setPageType('table'); Sortable::initialize($this, $resources, $sort, $order, array( 'type' => $resource_type, )); $columns = array( array( 'label' => __('Name'), 'sortable' => true, 'handle' => 'name' ), array( 'label' => __('Source'), 'sortable' => true, 'handle' => 'source' ), array( 'label' => __('Pages'), 'sortable' => false, ), array( 'label' => __('Author'), 'sortable' => true, 'handle' => 'author' ) ); $aTableHead = Sortable::buildTableHeaders($columns, $sort, $order, (isset($_REQUEST['filter']) ? '&amp;filter=' . $_REQUEST['filter'] : '')); $aTableBody = array(); if (!is_array($resources) || empty($resources)) { $aTableBody = array(Widget::TableRow(array(Widget::TableData(__('None found.'), 'inactive', null, count($aTableHead))), 'odd')); } else { $context = Administration::instance()->getPageCallback(); foreach ($resources as $r) { $action = 'edit'; $status = null; $locked = null; // Locked resources if ( isset($r['can_parse']) && $r['can_parse'] !== true || ($resource_type === ResourceManager::RESOURCE_TYPE_DS && $r['source']['name'] === 'Dynamic_xml') ) { $action = 'info'; $status = 'status-notice'; $locked = array( 'data-status' => ' — ' . __('read only') ); } $name = Widget::TableData( Widget::Anchor( stripslashes($r['name']), SYMPHONY_URL . $context['pageroot'] . $action . '/' . $r['handle'] . '/', $r['handle'], 'resource-' . $action, null, $locked ) ); $name->appendChild(Widget::Label(__('Select ' . $friendly_resource . ' %s', array($r['name'])), null, 'accessible', null, array( 'for' => 'resource-' . $r['handle'] ))); $name->appendChild(Widget::Input('items['.$r['handle'].']', 'on', 'checkbox', array( 'id' => 'resource-' . $r['handle'] ))); // Resource type/source if (isset($r['source'], $r['source']['id'])) { $section = Widget::TableData( Widget::Anchor( $r['source']['name'], SYMPHONY_URL . '/blueprints/sections/edit/' . $r['source']['id'] . '/', $r['source']['handle'] ) ); } elseif (isset($r['source']) && class_exists($r['source']['name']) && method_exists($r['source']['name'], 'getSourceColumn')) { $class = call_user_func(array($manager, '__getClassName'), $r['handle']); $section = Widget::TableData(call_user_func(array($class, 'getSourceColumn'), $r['handle'])); } elseif (isset($r['source'], $r['source']['name'])) { $section = Widget::TableData(stripslashes($r['source']['name'])); } else { $section = Widget::TableData(__('Unknown'), 'inactive'); } // Attached pages $pages = ResourceManager::getAttachedPages($resource_type, $r['handle']); $pagelinks = array(); $i = 0; foreach ($pages as $p) { ++$i; $pagelinks[] = Widget::Anchor( General::sanitize($p['title']), SYMPHONY_URL . '/blueprints/pages/edit/' . $p['id'] . '/' )->generate() . (count($pages) > $i ? (($i % 10) == 0 ? '<br />' : ', ') : ''); } $pages = implode('', $pagelinks); if ($pages == '') { $pagelinks = Widget::TableData(__('None'), 'inactive'); } else { $pagelinks = Widget::TableData($pages, 'pages'); } // Authors $author = $r['author']['name']; if ($author) { if (isset($r['author']['website'])) { $author = Widget::Anchor($r['author']['name'], General::validateURL($r['author']['website'])); } elseif (isset($r['author']['email'])) { $author = Widget::Anchor($r['author']['name'], 'mailto:' . $r['author']['email']); } } $author = Widget::TableData($author); $aTableBody[] = Widget::TableRow(array($name, $section, $pagelinks, $author), $status); } } $table = Widget::Table( Widget::TableHead($aTableHead), null, Widget::TableBody($aTableBody), 'selectable', null, array('role' => 'directory', 'aria-labelledby' => 'symphony-subheading', 'data-interactive' => 'data-interactive') ); $this->Form->appendChild($table); $version = new XMLElement('p', 'Symphony ' . Symphony::Configuration()->get('version', 'symphony'), array( 'id' => 'version' )); $this->Form->appendChild($version); $tableActions = new XMLElement('div'); $tableActions->setAttribute('class', 'actions'); $options = array( array(null, false, __('With Selected...')), array('delete', false, __('Delete'), 'confirm'), ); $pages = $this->pagesFlatView(); $group_attach = array('label' => __('Attach to Page'), 'options' => array()); $group_detach = array('label' => __('Detach from Page'), 'options' => array()); $group_attach['options'][] = array('attach-all-pages', false, __('All')); $group_detach['options'][] = array('detach-all-pages', false, __('All')); foreach ($pages as $p) { $group_attach['options'][] = array('attach-to-page-' . $p['id'], false, General::sanitize($p['title'])); $group_detach['options'][] = array('detach-from-page-' . $p['id'], false, General::sanitize($p['title'])); } $options[] = $group_attach; $options[] = $group_detach; /** * Allows an extension to modify the existing options for this page's * With Selected menu. If the `$options` parameter is an empty array, * the 'With Selected' menu will not be rendered. * * @delegate AddCustomActions * @since Symphony 2.3.2 * @param string $context * '/blueprints/datasources/' or '/blueprints/events/' * @param array $options * An array of arrays, where each child array represents an option * in the With Selected menu. Options should follow the same format * expected by `Widget::__SelectBuildOption`. Passed by reference. */ Symphony::ExtensionManager()->notifyMembers('AddCustomActions', $context['pageroot'], array( 'options' => &$options )); if (!empty($options)) { $tableActions->appendChild(Widget::Apply($options)); $this->Form->appendChild($tableActions); } }
php
public function __viewIndex($resource_type) { $manager = ResourceManager::getManagerFromType($resource_type); $friendly_resource = ($resource_type === ResourceManager::RESOURCE_TYPE_EVENT) ? __('Event') : __('DataSource'); $this->setPageType('table'); Sortable::initialize($this, $resources, $sort, $order, array( 'type' => $resource_type, )); $columns = array( array( 'label' => __('Name'), 'sortable' => true, 'handle' => 'name' ), array( 'label' => __('Source'), 'sortable' => true, 'handle' => 'source' ), array( 'label' => __('Pages'), 'sortable' => false, ), array( 'label' => __('Author'), 'sortable' => true, 'handle' => 'author' ) ); $aTableHead = Sortable::buildTableHeaders($columns, $sort, $order, (isset($_REQUEST['filter']) ? '&amp;filter=' . $_REQUEST['filter'] : '')); $aTableBody = array(); if (!is_array($resources) || empty($resources)) { $aTableBody = array(Widget::TableRow(array(Widget::TableData(__('None found.'), 'inactive', null, count($aTableHead))), 'odd')); } else { $context = Administration::instance()->getPageCallback(); foreach ($resources as $r) { $action = 'edit'; $status = null; $locked = null; // Locked resources if ( isset($r['can_parse']) && $r['can_parse'] !== true || ($resource_type === ResourceManager::RESOURCE_TYPE_DS && $r['source']['name'] === 'Dynamic_xml') ) { $action = 'info'; $status = 'status-notice'; $locked = array( 'data-status' => ' — ' . __('read only') ); } $name = Widget::TableData( Widget::Anchor( stripslashes($r['name']), SYMPHONY_URL . $context['pageroot'] . $action . '/' . $r['handle'] . '/', $r['handle'], 'resource-' . $action, null, $locked ) ); $name->appendChild(Widget::Label(__('Select ' . $friendly_resource . ' %s', array($r['name'])), null, 'accessible', null, array( 'for' => 'resource-' . $r['handle'] ))); $name->appendChild(Widget::Input('items['.$r['handle'].']', 'on', 'checkbox', array( 'id' => 'resource-' . $r['handle'] ))); // Resource type/source if (isset($r['source'], $r['source']['id'])) { $section = Widget::TableData( Widget::Anchor( $r['source']['name'], SYMPHONY_URL . '/blueprints/sections/edit/' . $r['source']['id'] . '/', $r['source']['handle'] ) ); } elseif (isset($r['source']) && class_exists($r['source']['name']) && method_exists($r['source']['name'], 'getSourceColumn')) { $class = call_user_func(array($manager, '__getClassName'), $r['handle']); $section = Widget::TableData(call_user_func(array($class, 'getSourceColumn'), $r['handle'])); } elseif (isset($r['source'], $r['source']['name'])) { $section = Widget::TableData(stripslashes($r['source']['name'])); } else { $section = Widget::TableData(__('Unknown'), 'inactive'); } // Attached pages $pages = ResourceManager::getAttachedPages($resource_type, $r['handle']); $pagelinks = array(); $i = 0; foreach ($pages as $p) { ++$i; $pagelinks[] = Widget::Anchor( General::sanitize($p['title']), SYMPHONY_URL . '/blueprints/pages/edit/' . $p['id'] . '/' )->generate() . (count($pages) > $i ? (($i % 10) == 0 ? '<br />' : ', ') : ''); } $pages = implode('', $pagelinks); if ($pages == '') { $pagelinks = Widget::TableData(__('None'), 'inactive'); } else { $pagelinks = Widget::TableData($pages, 'pages'); } // Authors $author = $r['author']['name']; if ($author) { if (isset($r['author']['website'])) { $author = Widget::Anchor($r['author']['name'], General::validateURL($r['author']['website'])); } elseif (isset($r['author']['email'])) { $author = Widget::Anchor($r['author']['name'], 'mailto:' . $r['author']['email']); } } $author = Widget::TableData($author); $aTableBody[] = Widget::TableRow(array($name, $section, $pagelinks, $author), $status); } } $table = Widget::Table( Widget::TableHead($aTableHead), null, Widget::TableBody($aTableBody), 'selectable', null, array('role' => 'directory', 'aria-labelledby' => 'symphony-subheading', 'data-interactive' => 'data-interactive') ); $this->Form->appendChild($table); $version = new XMLElement('p', 'Symphony ' . Symphony::Configuration()->get('version', 'symphony'), array( 'id' => 'version' )); $this->Form->appendChild($version); $tableActions = new XMLElement('div'); $tableActions->setAttribute('class', 'actions'); $options = array( array(null, false, __('With Selected...')), array('delete', false, __('Delete'), 'confirm'), ); $pages = $this->pagesFlatView(); $group_attach = array('label' => __('Attach to Page'), 'options' => array()); $group_detach = array('label' => __('Detach from Page'), 'options' => array()); $group_attach['options'][] = array('attach-all-pages', false, __('All')); $group_detach['options'][] = array('detach-all-pages', false, __('All')); foreach ($pages as $p) { $group_attach['options'][] = array('attach-to-page-' . $p['id'], false, General::sanitize($p['title'])); $group_detach['options'][] = array('detach-from-page-' . $p['id'], false, General::sanitize($p['title'])); } $options[] = $group_attach; $options[] = $group_detach; /** * Allows an extension to modify the existing options for this page's * With Selected menu. If the `$options` parameter is an empty array, * the 'With Selected' menu will not be rendered. * * @delegate AddCustomActions * @since Symphony 2.3.2 * @param string $context * '/blueprints/datasources/' or '/blueprints/events/' * @param array $options * An array of arrays, where each child array represents an option * in the With Selected menu. Options should follow the same format * expected by `Widget::__SelectBuildOption`. Passed by reference. */ Symphony::ExtensionManager()->notifyMembers('AddCustomActions', $context['pageroot'], array( 'options' => &$options )); if (!empty($options)) { $tableActions->appendChild(Widget::Apply($options)); $this->Form->appendChild($tableActions); } }
[ "public", "function", "__viewIndex", "(", "$", "resource_type", ")", "{", "$", "manager", "=", "ResourceManager", "::", "getManagerFromType", "(", "$", "resource_type", ")", ";", "$", "friendly_resource", "=", "(", "$", "resource_type", "===", "ResourceManager", "::", "RESOURCE_TYPE_EVENT", ")", "?", "__", "(", "'Event'", ")", ":", "__", "(", "'DataSource'", ")", ";", "$", "this", "->", "setPageType", "(", "'table'", ")", ";", "Sortable", "::", "initialize", "(", "$", "this", ",", "$", "resources", ",", "$", "sort", ",", "$", "order", ",", "array", "(", "'type'", "=>", "$", "resource_type", ",", ")", ")", ";", "$", "columns", "=", "array", "(", "array", "(", "'label'", "=>", "__", "(", "'Name'", ")", ",", "'sortable'", "=>", "true", ",", "'handle'", "=>", "'name'", ")", ",", "array", "(", "'label'", "=>", "__", "(", "'Source'", ")", ",", "'sortable'", "=>", "true", ",", "'handle'", "=>", "'source'", ")", ",", "array", "(", "'label'", "=>", "__", "(", "'Pages'", ")", ",", "'sortable'", "=>", "false", ",", ")", ",", "array", "(", "'label'", "=>", "__", "(", "'Author'", ")", ",", "'sortable'", "=>", "true", ",", "'handle'", "=>", "'author'", ")", ")", ";", "$", "aTableHead", "=", "Sortable", "::", "buildTableHeaders", "(", "$", "columns", ",", "$", "sort", ",", "$", "order", ",", "(", "isset", "(", "$", "_REQUEST", "[", "'filter'", "]", ")", "?", "'&amp;filter='", ".", "$", "_REQUEST", "[", "'filter'", "]", ":", "''", ")", ")", ";", "$", "aTableBody", "=", "array", "(", ")", ";", "if", "(", "!", "is_array", "(", "$", "resources", ")", "||", "empty", "(", "$", "resources", ")", ")", "{", "$", "aTableBody", "=", "array", "(", "Widget", "::", "TableRow", "(", "array", "(", "Widget", "::", "TableData", "(", "__", "(", "'None found.'", ")", ",", "'inactive'", ",", "null", ",", "count", "(", "$", "aTableHead", ")", ")", ")", ",", "'odd'", ")", ")", ";", "}", "else", "{", "$", "context", "=", "Administration", "::", "instance", "(", ")", "->", "getPageCallback", "(", ")", ";", "foreach", "(", "$", "resources", "as", "$", "r", ")", "{", "$", "action", "=", "'edit'", ";", "$", "status", "=", "null", ";", "$", "locked", "=", "null", ";", "// Locked resources", "if", "(", "isset", "(", "$", "r", "[", "'can_parse'", "]", ")", "&&", "$", "r", "[", "'can_parse'", "]", "!==", "true", "||", "(", "$", "resource_type", "===", "ResourceManager", "::", "RESOURCE_TYPE_DS", "&&", "$", "r", "[", "'source'", "]", "[", "'name'", "]", "===", "'Dynamic_xml'", ")", ")", "{", "$", "action", "=", "'info'", ";", "$", "status", "=", "'status-notice'", ";", "$", "locked", "=", "array", "(", "'data-status'", "=>", "' — ' .", "_", "('", "r", "ead only')", "", ")", ";", "}", "$", "name", "=", "Widget", "::", "TableData", "(", "Widget", "::", "Anchor", "(", "stripslashes", "(", "$", "r", "[", "'name'", "]", ")", ",", "SYMPHONY_URL", ".", "$", "context", "[", "'pageroot'", "]", ".", "$", "action", ".", "'/'", ".", "$", "r", "[", "'handle'", "]", ".", "'/'", ",", "$", "r", "[", "'handle'", "]", ",", "'resource-'", ".", "$", "action", ",", "null", ",", "$", "locked", ")", ")", ";", "$", "name", "->", "appendChild", "(", "Widget", "::", "Label", "(", "__", "(", "'Select '", ".", "$", "friendly_resource", ".", "' %s'", ",", "array", "(", "$", "r", "[", "'name'", "]", ")", ")", ",", "null", ",", "'accessible'", ",", "null", ",", "array", "(", "'for'", "=>", "'resource-'", ".", "$", "r", "[", "'handle'", "]", ")", ")", ")", ";", "$", "name", "->", "appendChild", "(", "Widget", "::", "Input", "(", "'items['", ".", "$", "r", "[", "'handle'", "]", ".", "']'", ",", "'on'", ",", "'checkbox'", ",", "array", "(", "'id'", "=>", "'resource-'", ".", "$", "r", "[", "'handle'", "]", ")", ")", ")", ";", "// Resource type/source", "if", "(", "isset", "(", "$", "r", "[", "'source'", "]", ",", "$", "r", "[", "'source'", "]", "[", "'id'", "]", ")", ")", "{", "$", "section", "=", "Widget", "::", "TableData", "(", "Widget", "::", "Anchor", "(", "$", "r", "[", "'source'", "]", "[", "'name'", "]", ",", "SYMPHONY_URL", ".", "'/blueprints/sections/edit/'", ".", "$", "r", "[", "'source'", "]", "[", "'id'", "]", ".", "'/'", ",", "$", "r", "[", "'source'", "]", "[", "'handle'", "]", ")", ")", ";", "}", "elseif", "(", "isset", "(", "$", "r", "[", "'source'", "]", ")", "&&", "class_exists", "(", "$", "r", "[", "'source'", "]", "[", "'name'", "]", ")", "&&", "method_exists", "(", "$", "r", "[", "'source'", "]", "[", "'name'", "]", ",", "'getSourceColumn'", ")", ")", "{", "$", "class", "=", "call_user_func", "(", "array", "(", "$", "manager", ",", "'__getClassName'", ")", ",", "$", "r", "[", "'handle'", "]", ")", ";", "$", "section", "=", "Widget", "::", "TableData", "(", "call_user_func", "(", "array", "(", "$", "class", ",", "'getSourceColumn'", ")", ",", "$", "r", "[", "'handle'", "]", ")", ")", ";", "}", "elseif", "(", "isset", "(", "$", "r", "[", "'source'", "]", ",", "$", "r", "[", "'source'", "]", "[", "'name'", "]", ")", ")", "{", "$", "section", "=", "Widget", "::", "TableData", "(", "stripslashes", "(", "$", "r", "[", "'source'", "]", "[", "'name'", "]", ")", ")", ";", "}", "else", "{", "$", "section", "=", "Widget", "::", "TableData", "(", "__", "(", "'Unknown'", ")", ",", "'inactive'", ")", ";", "}", "// Attached pages", "$", "pages", "=", "ResourceManager", "::", "getAttachedPages", "(", "$", "resource_type", ",", "$", "r", "[", "'handle'", "]", ")", ";", "$", "pagelinks", "=", "array", "(", ")", ";", "$", "i", "=", "0", ";", "foreach", "(", "$", "pages", "as", "$", "p", ")", "{", "++", "$", "i", ";", "$", "pagelinks", "[", "]", "=", "Widget", "::", "Anchor", "(", "General", "::", "sanitize", "(", "$", "p", "[", "'title'", "]", ")", ",", "SYMPHONY_URL", ".", "'/blueprints/pages/edit/'", ".", "$", "p", "[", "'id'", "]", ".", "'/'", ")", "->", "generate", "(", ")", ".", "(", "count", "(", "$", "pages", ")", ">", "$", "i", "?", "(", "(", "$", "i", "%", "10", ")", "==", "0", "?", "'<br />'", ":", "', '", ")", ":", "''", ")", ";", "}", "$", "pages", "=", "implode", "(", "''", ",", "$", "pagelinks", ")", ";", "if", "(", "$", "pages", "==", "''", ")", "{", "$", "pagelinks", "=", "Widget", "::", "TableData", "(", "__", "(", "'None'", ")", ",", "'inactive'", ")", ";", "}", "else", "{", "$", "pagelinks", "=", "Widget", "::", "TableData", "(", "$", "pages", ",", "'pages'", ")", ";", "}", "// Authors", "$", "author", "=", "$", "r", "[", "'author'", "]", "[", "'name'", "]", ";", "if", "(", "$", "author", ")", "{", "if", "(", "isset", "(", "$", "r", "[", "'author'", "]", "[", "'website'", "]", ")", ")", "{", "$", "author", "=", "Widget", "::", "Anchor", "(", "$", "r", "[", "'author'", "]", "[", "'name'", "]", ",", "General", "::", "validateURL", "(", "$", "r", "[", "'author'", "]", "[", "'website'", "]", ")", ")", ";", "}", "elseif", "(", "isset", "(", "$", "r", "[", "'author'", "]", "[", "'email'", "]", ")", ")", "{", "$", "author", "=", "Widget", "::", "Anchor", "(", "$", "r", "[", "'author'", "]", "[", "'name'", "]", ",", "'mailto:'", ".", "$", "r", "[", "'author'", "]", "[", "'email'", "]", ")", ";", "}", "}", "$", "author", "=", "Widget", "::", "TableData", "(", "$", "author", ")", ";", "$", "aTableBody", "[", "]", "=", "Widget", "::", "TableRow", "(", "array", "(", "$", "name", ",", "$", "section", ",", "$", "pagelinks", ",", "$", "author", ")", ",", "$", "status", ")", ";", "}", "}", "$", "table", "=", "Widget", "::", "Table", "(", "Widget", "::", "TableHead", "(", "$", "aTableHead", ")", ",", "null", ",", "Widget", "::", "TableBody", "(", "$", "aTableBody", ")", ",", "'selectable'", ",", "null", ",", "array", "(", "'role'", "=>", "'directory'", ",", "'aria-labelledby'", "=>", "'symphony-subheading'", ",", "'data-interactive'", "=>", "'data-interactive'", ")", ")", ";", "$", "this", "->", "Form", "->", "appendChild", "(", "$", "table", ")", ";", "$", "version", "=", "new", "XMLElement", "(", "'p'", ",", "'Symphony '", ".", "Symphony", "::", "Configuration", "(", ")", "->", "get", "(", "'version'", ",", "'symphony'", ")", ",", "array", "(", "'id'", "=>", "'version'", ")", ")", ";", "$", "this", "->", "Form", "->", "appendChild", "(", "$", "version", ")", ";", "$", "tableActions", "=", "new", "XMLElement", "(", "'div'", ")", ";", "$", "tableActions", "->", "setAttribute", "(", "'class'", ",", "'actions'", ")", ";", "$", "options", "=", "array", "(", "array", "(", "null", ",", "false", ",", "__", "(", "'With Selected...'", ")", ")", ",", "array", "(", "'delete'", ",", "false", ",", "__", "(", "'Delete'", ")", ",", "'confirm'", ")", ",", ")", ";", "$", "pages", "=", "$", "this", "->", "pagesFlatView", "(", ")", ";", "$", "group_attach", "=", "array", "(", "'label'", "=>", "__", "(", "'Attach to Page'", ")", ",", "'options'", "=>", "array", "(", ")", ")", ";", "$", "group_detach", "=", "array", "(", "'label'", "=>", "__", "(", "'Detach from Page'", ")", ",", "'options'", "=>", "array", "(", ")", ")", ";", "$", "group_attach", "[", "'options'", "]", "[", "]", "=", "array", "(", "'attach-all-pages'", ",", "false", ",", "__", "(", "'All'", ")", ")", ";", "$", "group_detach", "[", "'options'", "]", "[", "]", "=", "array", "(", "'detach-all-pages'", ",", "false", ",", "__", "(", "'All'", ")", ")", ";", "foreach", "(", "$", "pages", "as", "$", "p", ")", "{", "$", "group_attach", "[", "'options'", "]", "[", "]", "=", "array", "(", "'attach-to-page-'", ".", "$", "p", "[", "'id'", "]", ",", "false", ",", "General", "::", "sanitize", "(", "$", "p", "[", "'title'", "]", ")", ")", ";", "$", "group_detach", "[", "'options'", "]", "[", "]", "=", "array", "(", "'detach-from-page-'", ".", "$", "p", "[", "'id'", "]", ",", "false", ",", "General", "::", "sanitize", "(", "$", "p", "[", "'title'", "]", ")", ")", ";", "}", "$", "options", "[", "]", "=", "$", "group_attach", ";", "$", "options", "[", "]", "=", "$", "group_detach", ";", "/**\n * Allows an extension to modify the existing options for this page's\n * With Selected menu. If the `$options` parameter is an empty array,\n * the 'With Selected' menu will not be rendered.\n *\n * @delegate AddCustomActions\n * @since Symphony 2.3.2\n * @param string $context\n * '/blueprints/datasources/' or '/blueprints/events/'\n * @param array $options\n * An array of arrays, where each child array represents an option\n * in the With Selected menu. Options should follow the same format\n * expected by `Widget::__SelectBuildOption`. Passed by reference.\n */", "Symphony", "::", "ExtensionManager", "(", ")", "->", "notifyMembers", "(", "'AddCustomActions'", ",", "$", "context", "[", "'pageroot'", "]", ",", "array", "(", "'options'", "=>", "&", "$", "options", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "options", ")", ")", "{", "$", "tableActions", "->", "appendChild", "(", "Widget", "::", "Apply", "(", "$", "options", ")", ")", ";", "$", "this", "->", "Form", "->", "appendChild", "(", "$", "tableActions", ")", ";", "}", "}" ]
This function contains the minimal amount of logic for generating the index table of a given `$resource_type`. The table has name, source, pages release date and author columns. The values for these columns are determined by the resource's `about()` method. As Datasources types can be installed using Providers, the Source column can be overridden with a Datasource's `getSourceColumn` method (if it exists). @param integer $resource_type Either `ResourceManager::RESOURCE_TYPE_EVENT` or `ResourceManager::RESOURCE_TYPE_DATASOURCE` @throws InvalidArgumentException
[ "This", "function", "contains", "the", "minimal", "amount", "of", "logic", "for", "generating", "the", "index", "table", "of", "a", "given", "$resource_type", ".", "The", "table", "has", "name", "source", "pages", "release", "date", "and", "author", "columns", ".", "The", "values", "for", "these", "columns", "are", "determined", "by", "the", "resource", "s", "about", "()", "method", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.resourcespage.php#L105-L301
symphonycms/symphony-2
symphony/lib/toolkit/class.resourcespage.php
ResourcesPage.__actionIndex
public function __actionIndex($resource_type) { $manager = ResourceManager::getManagerFromType($resource_type); $checked = (is_array($_POST['items'])) ? array_keys($_POST['items']) : null; $context = Administration::instance()->getPageCallback(); if (isset($_POST['action']) && is_array($_POST['action'])) { /** * Extensions can listen for any custom actions that were added * through `AddCustomPreferenceFieldsets` or `AddCustomActions` * delegates. * * @delegate CustomActions * @since Symphony 2.3.2 * @param string $context * '/blueprints/datasources/' or '/blueprints/events/' * @param array $checked * An array of the selected rows. The value is usually the ID of the * the associated object. */ Symphony::ExtensionManager()->notifyMembers('CustomActions', $context['pageroot'], array( 'checked' => $checked )); if (is_array($checked) && !empty($checked)) { if ($_POST['with-selected'] == 'delete') { $canProceed = true; foreach ($checked as $handle) { $path = call_user_func(array($manager, '__getDriverPath'), $handle); // Don't allow Extension resources to be deleted. RE: #2027 if (stripos($path, EXTENSIONS) === 0) { continue; } elseif (!General::deleteFile($path)) { $folder = str_replace(DOCROOT, '', $path); $folder = str_replace('/' . basename($path), '', $folder); $this->pageAlert( __('Failed to delete %s.', array('<code>' . basename($path) . '</code>')) . ' ' . __('Please check permissions on %s', array('<code>' . $folder . '</code>')), Alert::ERROR ); $canProceed = false; } else { $pages = ResourceManager::getAttachedPages($resource_type, $handle); foreach ($pages as $page) { ResourceManager::detach($resource_type, $handle, $page['id']); } } } if ($canProceed) { redirect(Administration::instance()->getCurrentPageURL()); } } elseif (preg_match('/^(at|de)?tach-(to|from)-page-/', $_POST['with-selected'])) { if (substr($_POST['with-selected'], 0, 6) == 'detach') { $page = str_replace('detach-from-page-', '', $_POST['with-selected']); foreach ($checked as $handle) { ResourceManager::detach($resource_type, $handle, $page); } } else { $page = str_replace('attach-to-page-', '', $_POST['with-selected']); foreach ($checked as $handle) { ResourceManager::attach($resource_type, $handle, $page); } } if ($canProceed) { redirect(Administration::instance()->getCurrentPageURL()); } } elseif (preg_match('/^(at|de)?tach-all-pages$/', $_POST['with-selected'])) { $pages = PageManager::fetch(false, array('id')); if (substr($_POST['with-selected'], 0, 6) == 'detach') { foreach ($checked as $handle) { foreach ($pages as $page) { ResourceManager::detach($resource_type, $handle, $page['id']); } } } else { foreach ($checked as $handle) { foreach ($pages as $page) { ResourceManager::attach($resource_type, $handle, $page['id']); } } } redirect(Administration::instance()->getCurrentPageURL()); } } } }
php
public function __actionIndex($resource_type) { $manager = ResourceManager::getManagerFromType($resource_type); $checked = (is_array($_POST['items'])) ? array_keys($_POST['items']) : null; $context = Administration::instance()->getPageCallback(); if (isset($_POST['action']) && is_array($_POST['action'])) { /** * Extensions can listen for any custom actions that were added * through `AddCustomPreferenceFieldsets` or `AddCustomActions` * delegates. * * @delegate CustomActions * @since Symphony 2.3.2 * @param string $context * '/blueprints/datasources/' or '/blueprints/events/' * @param array $checked * An array of the selected rows. The value is usually the ID of the * the associated object. */ Symphony::ExtensionManager()->notifyMembers('CustomActions', $context['pageroot'], array( 'checked' => $checked )); if (is_array($checked) && !empty($checked)) { if ($_POST['with-selected'] == 'delete') { $canProceed = true; foreach ($checked as $handle) { $path = call_user_func(array($manager, '__getDriverPath'), $handle); // Don't allow Extension resources to be deleted. RE: #2027 if (stripos($path, EXTENSIONS) === 0) { continue; } elseif (!General::deleteFile($path)) { $folder = str_replace(DOCROOT, '', $path); $folder = str_replace('/' . basename($path), '', $folder); $this->pageAlert( __('Failed to delete %s.', array('<code>' . basename($path) . '</code>')) . ' ' . __('Please check permissions on %s', array('<code>' . $folder . '</code>')), Alert::ERROR ); $canProceed = false; } else { $pages = ResourceManager::getAttachedPages($resource_type, $handle); foreach ($pages as $page) { ResourceManager::detach($resource_type, $handle, $page['id']); } } } if ($canProceed) { redirect(Administration::instance()->getCurrentPageURL()); } } elseif (preg_match('/^(at|de)?tach-(to|from)-page-/', $_POST['with-selected'])) { if (substr($_POST['with-selected'], 0, 6) == 'detach') { $page = str_replace('detach-from-page-', '', $_POST['with-selected']); foreach ($checked as $handle) { ResourceManager::detach($resource_type, $handle, $page); } } else { $page = str_replace('attach-to-page-', '', $_POST['with-selected']); foreach ($checked as $handle) { ResourceManager::attach($resource_type, $handle, $page); } } if ($canProceed) { redirect(Administration::instance()->getCurrentPageURL()); } } elseif (preg_match('/^(at|de)?tach-all-pages$/', $_POST['with-selected'])) { $pages = PageManager::fetch(false, array('id')); if (substr($_POST['with-selected'], 0, 6) == 'detach') { foreach ($checked as $handle) { foreach ($pages as $page) { ResourceManager::detach($resource_type, $handle, $page['id']); } } } else { foreach ($checked as $handle) { foreach ($pages as $page) { ResourceManager::attach($resource_type, $handle, $page['id']); } } } redirect(Administration::instance()->getCurrentPageURL()); } } } }
[ "public", "function", "__actionIndex", "(", "$", "resource_type", ")", "{", "$", "manager", "=", "ResourceManager", "::", "getManagerFromType", "(", "$", "resource_type", ")", ";", "$", "checked", "=", "(", "is_array", "(", "$", "_POST", "[", "'items'", "]", ")", ")", "?", "array_keys", "(", "$", "_POST", "[", "'items'", "]", ")", ":", "null", ";", "$", "context", "=", "Administration", "::", "instance", "(", ")", "->", "getPageCallback", "(", ")", ";", "if", "(", "isset", "(", "$", "_POST", "[", "'action'", "]", ")", "&&", "is_array", "(", "$", "_POST", "[", "'action'", "]", ")", ")", "{", "/**\n * Extensions can listen for any custom actions that were added\n * through `AddCustomPreferenceFieldsets` or `AddCustomActions`\n * delegates.\n *\n * @delegate CustomActions\n * @since Symphony 2.3.2\n * @param string $context\n * '/blueprints/datasources/' or '/blueprints/events/'\n * @param array $checked\n * An array of the selected rows. The value is usually the ID of the\n * the associated object.\n */", "Symphony", "::", "ExtensionManager", "(", ")", "->", "notifyMembers", "(", "'CustomActions'", ",", "$", "context", "[", "'pageroot'", "]", ",", "array", "(", "'checked'", "=>", "$", "checked", ")", ")", ";", "if", "(", "is_array", "(", "$", "checked", ")", "&&", "!", "empty", "(", "$", "checked", ")", ")", "{", "if", "(", "$", "_POST", "[", "'with-selected'", "]", "==", "'delete'", ")", "{", "$", "canProceed", "=", "true", ";", "foreach", "(", "$", "checked", "as", "$", "handle", ")", "{", "$", "path", "=", "call_user_func", "(", "array", "(", "$", "manager", ",", "'__getDriverPath'", ")", ",", "$", "handle", ")", ";", "// Don't allow Extension resources to be deleted. RE: #2027", "if", "(", "stripos", "(", "$", "path", ",", "EXTENSIONS", ")", "===", "0", ")", "{", "continue", ";", "}", "elseif", "(", "!", "General", "::", "deleteFile", "(", "$", "path", ")", ")", "{", "$", "folder", "=", "str_replace", "(", "DOCROOT", ",", "''", ",", "$", "path", ")", ";", "$", "folder", "=", "str_replace", "(", "'/'", ".", "basename", "(", "$", "path", ")", ",", "''", ",", "$", "folder", ")", ";", "$", "this", "->", "pageAlert", "(", "__", "(", "'Failed to delete %s.'", ",", "array", "(", "'<code>'", ".", "basename", "(", "$", "path", ")", ".", "'</code>'", ")", ")", ".", "' '", ".", "__", "(", "'Please check permissions on %s'", ",", "array", "(", "'<code>'", ".", "$", "folder", ".", "'</code>'", ")", ")", ",", "Alert", "::", "ERROR", ")", ";", "$", "canProceed", "=", "false", ";", "}", "else", "{", "$", "pages", "=", "ResourceManager", "::", "getAttachedPages", "(", "$", "resource_type", ",", "$", "handle", ")", ";", "foreach", "(", "$", "pages", "as", "$", "page", ")", "{", "ResourceManager", "::", "detach", "(", "$", "resource_type", ",", "$", "handle", ",", "$", "page", "[", "'id'", "]", ")", ";", "}", "}", "}", "if", "(", "$", "canProceed", ")", "{", "redirect", "(", "Administration", "::", "instance", "(", ")", "->", "getCurrentPageURL", "(", ")", ")", ";", "}", "}", "elseif", "(", "preg_match", "(", "'/^(at|de)?tach-(to|from)-page-/'", ",", "$", "_POST", "[", "'with-selected'", "]", ")", ")", "{", "if", "(", "substr", "(", "$", "_POST", "[", "'with-selected'", "]", ",", "0", ",", "6", ")", "==", "'detach'", ")", "{", "$", "page", "=", "str_replace", "(", "'detach-from-page-'", ",", "''", ",", "$", "_POST", "[", "'with-selected'", "]", ")", ";", "foreach", "(", "$", "checked", "as", "$", "handle", ")", "{", "ResourceManager", "::", "detach", "(", "$", "resource_type", ",", "$", "handle", ",", "$", "page", ")", ";", "}", "}", "else", "{", "$", "page", "=", "str_replace", "(", "'attach-to-page-'", ",", "''", ",", "$", "_POST", "[", "'with-selected'", "]", ")", ";", "foreach", "(", "$", "checked", "as", "$", "handle", ")", "{", "ResourceManager", "::", "attach", "(", "$", "resource_type", ",", "$", "handle", ",", "$", "page", ")", ";", "}", "}", "if", "(", "$", "canProceed", ")", "{", "redirect", "(", "Administration", "::", "instance", "(", ")", "->", "getCurrentPageURL", "(", ")", ")", ";", "}", "}", "elseif", "(", "preg_match", "(", "'/^(at|de)?tach-all-pages$/'", ",", "$", "_POST", "[", "'with-selected'", "]", ")", ")", "{", "$", "pages", "=", "PageManager", "::", "fetch", "(", "false", ",", "array", "(", "'id'", ")", ")", ";", "if", "(", "substr", "(", "$", "_POST", "[", "'with-selected'", "]", ",", "0", ",", "6", ")", "==", "'detach'", ")", "{", "foreach", "(", "$", "checked", "as", "$", "handle", ")", "{", "foreach", "(", "$", "pages", "as", "$", "page", ")", "{", "ResourceManager", "::", "detach", "(", "$", "resource_type", ",", "$", "handle", ",", "$", "page", "[", "'id'", "]", ")", ";", "}", "}", "}", "else", "{", "foreach", "(", "$", "checked", "as", "$", "handle", ")", "{", "foreach", "(", "$", "pages", "as", "$", "page", ")", "{", "ResourceManager", "::", "attach", "(", "$", "resource_type", ",", "$", "handle", ",", "$", "page", "[", "'id'", "]", ")", ";", "}", "}", "}", "redirect", "(", "Administration", "::", "instance", "(", ")", "->", "getCurrentPageURL", "(", ")", ")", ";", "}", "}", "}", "}" ]
This function is called from the resources index when a user uses the With Selected, or Apply, menu. The type of resource is given by `$resource_type`. At this time the only two valid values, `ResourceManager::RESOURCE_TYPE_EVENT` or `ResourceManager::RESOURCE_TYPE_DATASOURCE`. The function handles 'delete', 'attach', 'detach', 'attach all', 'detach all' actions. @param integer $resource_type Either `ResourceManager::RESOURCE_TYPE_EVENT` or `ResourceManager::RESOURCE_TYPE_DATASOURCE` @throws Exception
[ "This", "function", "is", "called", "from", "the", "resources", "index", "when", "a", "user", "uses", "the", "With", "Selected", "or", "Apply", "menu", ".", "The", "type", "of", "resource", "is", "given", "by", "$resource_type", ".", "At", "this", "time", "the", "only", "two", "valid", "values", "ResourceManager", "::", "RESOURCE_TYPE_EVENT", "or", "ResourceManager", "::", "RESOURCE_TYPE_DATASOURCE", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.resourcespage.php#L316-L411
symphonycms/symphony-2
symphony/lib/toolkit/class.eventmanager.php
EventManager.create
public static function create($handle, array $env = null) { $classname = self::__getClassName($handle); $path = self::__getDriverPath($handle); if (!is_file($path)) { throw new Exception( __('Could not find Event %s.', array('<code>' . $handle . '</code>')) . ' ' . __('If it was provided by an Extension, ensure that it is installed, and enabled.') ); } if (!class_exists($classname)) { require_once $path; } return new $classname($env); }
php
public static function create($handle, array $env = null) { $classname = self::__getClassName($handle); $path = self::__getDriverPath($handle); if (!is_file($path)) { throw new Exception( __('Could not find Event %s.', array('<code>' . $handle . '</code>')) . ' ' . __('If it was provided by an Extension, ensure that it is installed, and enabled.') ); } if (!class_exists($classname)) { require_once $path; } return new $classname($env); }
[ "public", "static", "function", "create", "(", "$", "handle", ",", "array", "$", "env", "=", "null", ")", "{", "$", "classname", "=", "self", "::", "__getClassName", "(", "$", "handle", ")", ";", "$", "path", "=", "self", "::", "__getDriverPath", "(", "$", "handle", ")", ";", "if", "(", "!", "is_file", "(", "$", "path", ")", ")", "{", "throw", "new", "Exception", "(", "__", "(", "'Could not find Event %s.'", ",", "array", "(", "'<code>'", ".", "$", "handle", ".", "'</code>'", ")", ")", ".", "' '", ".", "__", "(", "'If it was provided by an Extension, ensure that it is installed, and enabled.'", ")", ")", ";", "}", "if", "(", "!", "class_exists", "(", "$", "classname", ")", ")", "{", "require_once", "$", "path", ";", "}", "return", "new", "$", "classname", "(", "$", "env", ")", ";", "}" ]
Creates an instance of a given class and returns it. @param string $handle The handle of the Event to create @param array $env The environment variables from the Frontend class which includes any params set by Symphony or Datasources or by other Events @throws Exception @return Event
[ "Creates", "an", "instance", "of", "a", "given", "class", "and", "returns", "it", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.eventmanager.php#L183-L200
symphonycms/symphony-2
symphony/lib/toolkit/class.emailgatewaymanager.php
EmailGatewayManager.setDefaultGateway
public static function setDefaultGateway($name) { if (self::__getClassPath($name)) { Symphony::Configuration()->set('default_gateway', $name, 'Email'); Symphony::Configuration()->write(); } else { throw new EmailGatewayException(__('This gateway can not be found. Can not save as default.')); } }
php
public static function setDefaultGateway($name) { if (self::__getClassPath($name)) { Symphony::Configuration()->set('default_gateway', $name, 'Email'); Symphony::Configuration()->write(); } else { throw new EmailGatewayException(__('This gateway can not be found. Can not save as default.')); } }
[ "public", "static", "function", "setDefaultGateway", "(", "$", "name", ")", "{", "if", "(", "self", "::", "__getClassPath", "(", "$", "name", ")", ")", "{", "Symphony", "::", "Configuration", "(", ")", "->", "set", "(", "'default_gateway'", ",", "$", "name", ",", "'Email'", ")", ";", "Symphony", "::", "Configuration", "(", ")", "->", "write", "(", ")", ";", "}", "else", "{", "throw", "new", "EmailGatewayException", "(", "__", "(", "'This gateway can not be found. Can not save as default.'", ")", ")", ";", "}", "}" ]
Sets the default gateway. Will throw an exception if the gateway can not be found. @throws EmailGatewayException @param string $name @return void
[ "Sets", "the", "default", "gateway", ".", "Will", "throw", "an", "exception", "if", "the", "gateway", "can", "not", "be", "found", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.emailgatewaymanager.php#L30-L38
symphonycms/symphony-2
symphony/lib/toolkit/class.emailgatewaymanager.php
EmailGatewayManager.__getClassPath
public static function __getClassPath($name) { if (is_file(EMAILGATEWAYS . "/email.$name.php")) { return EMAILGATEWAYS; } else { $extensions = Symphony::ExtensionManager()->listInstalledHandles(); if (is_array($extensions) && !empty($extensions)) { foreach ($extensions as $e) { if (is_file(EXTENSIONS . "/$e/email-gateways/email.$name.php")) { return EXTENSIONS . "/$e/email-gateways"; } } } } return false; }
php
public static function __getClassPath($name) { if (is_file(EMAILGATEWAYS . "/email.$name.php")) { return EMAILGATEWAYS; } else { $extensions = Symphony::ExtensionManager()->listInstalledHandles(); if (is_array($extensions) && !empty($extensions)) { foreach ($extensions as $e) { if (is_file(EXTENSIONS . "/$e/email-gateways/email.$name.php")) { return EXTENSIONS . "/$e/email-gateways"; } } } } return false; }
[ "public", "static", "function", "__getClassPath", "(", "$", "name", ")", "{", "if", "(", "is_file", "(", "EMAILGATEWAYS", ".", "\"/email.$name.php\"", ")", ")", "{", "return", "EMAILGATEWAYS", ";", "}", "else", "{", "$", "extensions", "=", "Symphony", "::", "ExtensionManager", "(", ")", "->", "listInstalledHandles", "(", ")", ";", "if", "(", "is_array", "(", "$", "extensions", ")", "&&", "!", "empty", "(", "$", "extensions", ")", ")", "{", "foreach", "(", "$", "extensions", "as", "$", "e", ")", "{", "if", "(", "is_file", "(", "EXTENSIONS", ".", "\"/$e/email-gateways/email.$name.php\"", ")", ")", "{", "return", "EXTENSIONS", ".", "\"/$e/email-gateways\"", ";", "}", "}", "}", "}", "return", "false", ";", "}" ]
Finds the gateway by name @param string $name The gateway to look for @return string|boolean If the gateway is found, the path to the folder containing the gateway is returned. If the gateway is not found, false is returned.
[ "Finds", "the", "gateway", "by", "name" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.emailgatewaymanager.php#L79-L96
symphonycms/symphony-2
symphony/lib/toolkit/class.emailgatewaymanager.php
EmailGatewayManager.listAll
public static function listAll() { $result = array(); $structure = General::listStructure(EMAILGATEWAYS, '/email.[\\w-]+.php/', false, 'ASC', EMAILGATEWAYS); if (is_array($structure['filelist']) && !empty($structure['filelist'])) { foreach ($structure['filelist'] as $f) { $f = str_replace(array('email.', '.php'), '', $f); $result[$f] = self::about($f); } } $extensions = Symphony::ExtensionManager()->listInstalledHandles(); if (is_array($extensions) && !empty($extensions)) { foreach ($extensions as $e) { if (!is_dir(EXTENSIONS . "/$e/email-gateways")) { continue; } $tmp = General::listStructure(EXTENSIONS . "/$e/email-gateways", '/email.[\\w-]+.php/', false, 'ASC', EXTENSIONS . "/$e/email-gateways"); if (is_array($tmp['filelist']) && !empty($tmp['filelist'])) { foreach ($tmp['filelist'] as $f) { $f = preg_replace(array('/^email./i', '/.php$/i'), '', $f); $result[$f] = self::about($f); } } } } ksort($result); return $result; }
php
public static function listAll() { $result = array(); $structure = General::listStructure(EMAILGATEWAYS, '/email.[\\w-]+.php/', false, 'ASC', EMAILGATEWAYS); if (is_array($structure['filelist']) && !empty($structure['filelist'])) { foreach ($structure['filelist'] as $f) { $f = str_replace(array('email.', '.php'), '', $f); $result[$f] = self::about($f); } } $extensions = Symphony::ExtensionManager()->listInstalledHandles(); if (is_array($extensions) && !empty($extensions)) { foreach ($extensions as $e) { if (!is_dir(EXTENSIONS . "/$e/email-gateways")) { continue; } $tmp = General::listStructure(EXTENSIONS . "/$e/email-gateways", '/email.[\\w-]+.php/', false, 'ASC', EXTENSIONS . "/$e/email-gateways"); if (is_array($tmp['filelist']) && !empty($tmp['filelist'])) { foreach ($tmp['filelist'] as $f) { $f = preg_replace(array('/^email./i', '/.php$/i'), '', $f); $result[$f] = self::about($f); } } } } ksort($result); return $result; }
[ "public", "static", "function", "listAll", "(", ")", "{", "$", "result", "=", "array", "(", ")", ";", "$", "structure", "=", "General", "::", "listStructure", "(", "EMAILGATEWAYS", ",", "'/email.[\\\\w-]+.php/'", ",", "false", ",", "'ASC'", ",", "EMAILGATEWAYS", ")", ";", "if", "(", "is_array", "(", "$", "structure", "[", "'filelist'", "]", ")", "&&", "!", "empty", "(", "$", "structure", "[", "'filelist'", "]", ")", ")", "{", "foreach", "(", "$", "structure", "[", "'filelist'", "]", "as", "$", "f", ")", "{", "$", "f", "=", "str_replace", "(", "array", "(", "'email.'", ",", "'.php'", ")", ",", "''", ",", "$", "f", ")", ";", "$", "result", "[", "$", "f", "]", "=", "self", "::", "about", "(", "$", "f", ")", ";", "}", "}", "$", "extensions", "=", "Symphony", "::", "ExtensionManager", "(", ")", "->", "listInstalledHandles", "(", ")", ";", "if", "(", "is_array", "(", "$", "extensions", ")", "&&", "!", "empty", "(", "$", "extensions", ")", ")", "{", "foreach", "(", "$", "extensions", "as", "$", "e", ")", "{", "if", "(", "!", "is_dir", "(", "EXTENSIONS", ".", "\"/$e/email-gateways\"", ")", ")", "{", "continue", ";", "}", "$", "tmp", "=", "General", "::", "listStructure", "(", "EXTENSIONS", ".", "\"/$e/email-gateways\"", ",", "'/email.[\\\\w-]+.php/'", ",", "false", ",", "'ASC'", ",", "EXTENSIONS", ".", "\"/$e/email-gateways\"", ")", ";", "if", "(", "is_array", "(", "$", "tmp", "[", "'filelist'", "]", ")", "&&", "!", "empty", "(", "$", "tmp", "[", "'filelist'", "]", ")", ")", "{", "foreach", "(", "$", "tmp", "[", "'filelist'", "]", "as", "$", "f", ")", "{", "$", "f", "=", "preg_replace", "(", "array", "(", "'/^email./i'", ",", "'/.php$/i'", ")", ",", "''", ",", "$", "f", ")", ";", "$", "result", "[", "$", "f", "]", "=", "self", "::", "about", "(", "$", "f", ")", ";", "}", "}", "}", "}", "ksort", "(", "$", "result", ")", ";", "return", "$", "result", ";", "}" ]
Returns an array of all gateways. Each item in the array will contain the return value of the about() function of each gateway. @return array
[ "Returns", "an", "array", "of", "all", "gateways", ".", "Each", "item", "in", "the", "array", "will", "contain", "the", "return", "value", "of", "the", "about", "()", "function", "of", "each", "gateway", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.emailgatewaymanager.php#L130-L163
symphonycms/symphony-2
symphony/lib/toolkit/class.emailgatewaymanager.php
EmailGatewayManager.create
public static function create($name) { $name = strtolower($name); $classname = self::__getClassName($name); $path = self::__getDriverPath($name); if (!is_file($path)) { throw new Exception( __('Could not find Email Gateway %s.', array('<code>' . $name . '</code>')) . ' ' . __('If it was provided by an Extension, ensure that it is installed, and enabled.') ); } if (!class_exists($classname)) { require_once $path; } return new $classname; }
php
public static function create($name) { $name = strtolower($name); $classname = self::__getClassName($name); $path = self::__getDriverPath($name); if (!is_file($path)) { throw new Exception( __('Could not find Email Gateway %s.', array('<code>' . $name . '</code>')) . ' ' . __('If it was provided by an Extension, ensure that it is installed, and enabled.') ); } if (!class_exists($classname)) { require_once $path; } return new $classname; }
[ "public", "static", "function", "create", "(", "$", "name", ")", "{", "$", "name", "=", "strtolower", "(", "$", "name", ")", ";", "$", "classname", "=", "self", "::", "__getClassName", "(", "$", "name", ")", ";", "$", "path", "=", "self", "::", "__getDriverPath", "(", "$", "name", ")", ";", "if", "(", "!", "is_file", "(", "$", "path", ")", ")", "{", "throw", "new", "Exception", "(", "__", "(", "'Could not find Email Gateway %s.'", ",", "array", "(", "'<code>'", ".", "$", "name", ".", "'</code>'", ")", ")", ".", "' '", ".", "__", "(", "'If it was provided by an Extension, ensure that it is installed, and enabled.'", ")", ")", ";", "}", "if", "(", "!", "class_exists", "(", "$", "classname", ")", ")", "{", "require_once", "$", "path", ";", "}", "return", "new", "$", "classname", ";", "}" ]
Creates a new object from a gateway name. @param string $name The gateway to look for @throws Exception @return EmailGateway If the gateway is found, an instantiated object is returned. If the gateway is not found, an error is triggered.
[ "Creates", "a", "new", "object", "from", "a", "gateway", "name", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.emailgatewaymanager.php#L196-L214
symphonycms/symphony-2
symphony/lib/toolkit/class.emailhelper.php
EmailHelper.qEncode
public static function qEncode($input, $max_length = 75) { // Don't encode empty strings if (empty($input)) { return $input; } // Don't encode if all code points are in ASCII range 0-127 if (!preg_match('/[\\x80-\\xff]+/', $input)) { return $input; } $qpHexDigits = '0123456789ABCDEF'; $input_length = strlen($input); // Substract delimiters, character set and encoding $line_limit = $max_length - 12; $line_length = 0; $output = '=?UTF-8?Q?'; for ($i=0; $i < $input_length; $i++) { $char = $input[$i]; $ascii = ord($char); // No encoding for all 62 alphanumeric characters if (48 <= $ascii && $ascii <= 57 || 65 <= $ascii && $ascii <= 90 || 97 <= $ascii && $ascii <= 122) { $replace_length = 1; $replace_char = $char; // Encode space as underscore (means better readability for humans) } elseif ($ascii == 32) { $replace_length = 1; $replace_char = '_'; // Encode } else { $replace_length = 3; // Bit operation is around 10 percent faster // than 'strtoupper(dechex($ascii))' $replace_char = '=' . $qpHexDigits[$ascii >> 4] . $qpHexDigits[$ascii & 0x0f]; // Account for following bytes of UTF8-multi-byte // sequence (max. length is 4 octets, RFC3629) $lookahead_limit = min($i+4, $input_length); for ($lookahead = $i+1; $lookahead < $lookahead_limit; $lookahead++) { $ascii_ff = ord($input[$lookahead]); if (128 <= $ascii_ff && $ascii_ff <= 191) { $replace_char .= '=' . $qpHexDigits[$ascii_ff >> 4] . $qpHexDigits[$ascii_ff & 0x0f]; $replace_length += 3; $i++; } else { break; } } } // Would the line become too long? if ($line_length + $replace_length > $line_limit) { $output .= "?= =?UTF-8?Q?"; $line_length = 0; } $output .= $replace_char; $line_length += $replace_length; } $output .= '?='; return $output; }
php
public static function qEncode($input, $max_length = 75) { // Don't encode empty strings if (empty($input)) { return $input; } // Don't encode if all code points are in ASCII range 0-127 if (!preg_match('/[\\x80-\\xff]+/', $input)) { return $input; } $qpHexDigits = '0123456789ABCDEF'; $input_length = strlen($input); // Substract delimiters, character set and encoding $line_limit = $max_length - 12; $line_length = 0; $output = '=?UTF-8?Q?'; for ($i=0; $i < $input_length; $i++) { $char = $input[$i]; $ascii = ord($char); // No encoding for all 62 alphanumeric characters if (48 <= $ascii && $ascii <= 57 || 65 <= $ascii && $ascii <= 90 || 97 <= $ascii && $ascii <= 122) { $replace_length = 1; $replace_char = $char; // Encode space as underscore (means better readability for humans) } elseif ($ascii == 32) { $replace_length = 1; $replace_char = '_'; // Encode } else { $replace_length = 3; // Bit operation is around 10 percent faster // than 'strtoupper(dechex($ascii))' $replace_char = '=' . $qpHexDigits[$ascii >> 4] . $qpHexDigits[$ascii & 0x0f]; // Account for following bytes of UTF8-multi-byte // sequence (max. length is 4 octets, RFC3629) $lookahead_limit = min($i+4, $input_length); for ($lookahead = $i+1; $lookahead < $lookahead_limit; $lookahead++) { $ascii_ff = ord($input[$lookahead]); if (128 <= $ascii_ff && $ascii_ff <= 191) { $replace_char .= '=' . $qpHexDigits[$ascii_ff >> 4] . $qpHexDigits[$ascii_ff & 0x0f]; $replace_length += 3; $i++; } else { break; } } } // Would the line become too long? if ($line_length + $replace_length > $line_limit) { $output .= "?= =?UTF-8?Q?"; $line_length = 0; } $output .= $replace_char; $line_length += $replace_length; } $output .= '?='; return $output; }
[ "public", "static", "function", "qEncode", "(", "$", "input", ",", "$", "max_length", "=", "75", ")", "{", "// Don't encode empty strings", "if", "(", "empty", "(", "$", "input", ")", ")", "{", "return", "$", "input", ";", "}", "// Don't encode if all code points are in ASCII range 0-127", "if", "(", "!", "preg_match", "(", "'/[\\\\x80-\\\\xff]+/'", ",", "$", "input", ")", ")", "{", "return", "$", "input", ";", "}", "$", "qpHexDigits", "=", "'0123456789ABCDEF'", ";", "$", "input_length", "=", "strlen", "(", "$", "input", ")", ";", "// Substract delimiters, character set and encoding", "$", "line_limit", "=", "$", "max_length", "-", "12", ";", "$", "line_length", "=", "0", ";", "$", "output", "=", "'=?UTF-8?Q?'", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "input_length", ";", "$", "i", "++", ")", "{", "$", "char", "=", "$", "input", "[", "$", "i", "]", ";", "$", "ascii", "=", "ord", "(", "$", "char", ")", ";", "// No encoding for all 62 alphanumeric characters", "if", "(", "48", "<=", "$", "ascii", "&&", "$", "ascii", "<=", "57", "||", "65", "<=", "$", "ascii", "&&", "$", "ascii", "<=", "90", "||", "97", "<=", "$", "ascii", "&&", "$", "ascii", "<=", "122", ")", "{", "$", "replace_length", "=", "1", ";", "$", "replace_char", "=", "$", "char", ";", "// Encode space as underscore (means better readability for humans)", "}", "elseif", "(", "$", "ascii", "==", "32", ")", "{", "$", "replace_length", "=", "1", ";", "$", "replace_char", "=", "'_'", ";", "// Encode", "}", "else", "{", "$", "replace_length", "=", "3", ";", "// Bit operation is around 10 percent faster", "// than 'strtoupper(dechex($ascii))'", "$", "replace_char", "=", "'='", ".", "$", "qpHexDigits", "[", "$", "ascii", ">>", "4", "]", ".", "$", "qpHexDigits", "[", "$", "ascii", "&", "0x0f", "]", ";", "// Account for following bytes of UTF8-multi-byte", "// sequence (max. length is 4 octets, RFC3629)", "$", "lookahead_limit", "=", "min", "(", "$", "i", "+", "4", ",", "$", "input_length", ")", ";", "for", "(", "$", "lookahead", "=", "$", "i", "+", "1", ";", "$", "lookahead", "<", "$", "lookahead_limit", ";", "$", "lookahead", "++", ")", "{", "$", "ascii_ff", "=", "ord", "(", "$", "input", "[", "$", "lookahead", "]", ")", ";", "if", "(", "128", "<=", "$", "ascii_ff", "&&", "$", "ascii_ff", "<=", "191", ")", "{", "$", "replace_char", ".=", "'='", ".", "$", "qpHexDigits", "[", "$", "ascii_ff", ">>", "4", "]", ".", "$", "qpHexDigits", "[", "$", "ascii_ff", "&", "0x0f", "]", ";", "$", "replace_length", "+=", "3", ";", "$", "i", "++", ";", "}", "else", "{", "break", ";", "}", "}", "}", "// Would the line become too long?", "if", "(", "$", "line_length", "+", "$", "replace_length", ">", "$", "line_limit", ")", "{", "$", "output", ".=", "\"?= =?UTF-8?Q?\"", ";", "$", "line_length", "=", "0", ";", "}", "$", "output", ".=", "$", "replace_char", ";", "$", "line_length", "+=", "$", "replace_length", ";", "}", "$", "output", ".=", "'?='", ";", "return", "$", "output", ";", "}" ]
Q-encoding of a header field 'text' token or 'word' entity within a 'phrase', according to RFC2047. The output is called an 'encoded-word'; it must not be longer than 75 characters. This might be achieved with PHP's `mbstring` functions, but `mbstring` is a non-default extension. For simplicity reasons this function encodes every character except upper and lower case letters and decimal digits. RFC: 'While there is no limit to the length of a multiple-line header field, each line of a header field that contains one or more 'encoded-word's is limited to 76 characters.' The required 'folding' will not be done here, but in another helper function. This function must be 'multi-byte-sensitive' in a way that it must never scatter a multi-byte character representation across multiple encoded-words. So a 'lookahead' has been implemented, based on the fact that for UTF-8 encoded characters any byte except the first byte will have a leading '10' bit pattern, which means an ASCII value >=128 and <=191. @author Elmar Bartel @author Michael Eichelsdoerfer @param string $input string to encode @param integer $max_length maximum line length (default: 75 chars) @return string $output encoded string
[ "Q", "-", "encoding", "of", "a", "header", "field", "text", "token", "or", "word", "entity", "within", "a", "phrase", "according", "to", "RFC2047", ".", "The", "output", "is", "called", "an", "encoded", "-", "word", ";", "it", "must", "not", "be", "longer", "than", "75", "characters", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.emailhelper.php#L60-L133
symphonycms/symphony-2
symphony/lib/toolkit/class.emailhelper.php
EmailHelper.qpContentTransferEncode
public static function qpContentTransferEncode($input, $max_length = 76) { $qpHexDigits = '0123456789ABCDEF'; $input_length = strlen($input); $line_limit = $max_length; $line_length = 0; $output = ''; $blank = false; for ($i=0; $i < $input_length; $i++) { $char = $input[$i]; $ascii = ord($char); // No encoding for spaces and tabs if ($ascii == 9 || $ascii == 32) { $blank = true; $replace_length = 1; $replace_char = $char; // CR and LF } elseif ($ascii == 13 || $ascii == 10) { // Use existing offset only. if ($i+1 < $input_length) { if (($ascii == 13 && ord($input[$i+1]) == 10) || ($ascii == 10 && ord($input[$i+1]) == 13)) { $i++; } } if ($blank) { /** * Any tab or space characters on an encoded line MUST * be followed on that line by a printable character. * This character may as well be the soft line break * indicator. * * So if the preceding character is a space or a * tab, we may simply insert a soft line break * here, followed by a literal line break. * Basically this means that we are appending * an empty line (nada). */ $output .= "=\r\n\r\n"; } else { $output .= "\r\n"; } $blank = false; $line_length = 0; continue; // No encoding within ascii range 33 to 126 (exception: 61) } elseif (32 < $ascii && $ascii < 127 && $char !== '=') { $replace_length = 1; $replace_char = $char; $blank = false; // Encode } else { $replace_length = 3; // bit operation is around 10 percent faster // than 'strtoupper(dechex($ascii))' $replace_char = '=' . $qpHexDigits[$ascii >> 4] . $qpHexDigits[$ascii & 0x0f]; $blank = false; } // Would the line become too long? if ($line_length + $replace_length > $line_limit - 1) { $output .= "=\r\n"; $line_length = 0; } $output .= $replace_char; $line_length += $replace_length; } return $output; }
php
public static function qpContentTransferEncode($input, $max_length = 76) { $qpHexDigits = '0123456789ABCDEF'; $input_length = strlen($input); $line_limit = $max_length; $line_length = 0; $output = ''; $blank = false; for ($i=0; $i < $input_length; $i++) { $char = $input[$i]; $ascii = ord($char); // No encoding for spaces and tabs if ($ascii == 9 || $ascii == 32) { $blank = true; $replace_length = 1; $replace_char = $char; // CR and LF } elseif ($ascii == 13 || $ascii == 10) { // Use existing offset only. if ($i+1 < $input_length) { if (($ascii == 13 && ord($input[$i+1]) == 10) || ($ascii == 10 && ord($input[$i+1]) == 13)) { $i++; } } if ($blank) { /** * Any tab or space characters on an encoded line MUST * be followed on that line by a printable character. * This character may as well be the soft line break * indicator. * * So if the preceding character is a space or a * tab, we may simply insert a soft line break * here, followed by a literal line break. * Basically this means that we are appending * an empty line (nada). */ $output .= "=\r\n\r\n"; } else { $output .= "\r\n"; } $blank = false; $line_length = 0; continue; // No encoding within ascii range 33 to 126 (exception: 61) } elseif (32 < $ascii && $ascii < 127 && $char !== '=') { $replace_length = 1; $replace_char = $char; $blank = false; // Encode } else { $replace_length = 3; // bit operation is around 10 percent faster // than 'strtoupper(dechex($ascii))' $replace_char = '=' . $qpHexDigits[$ascii >> 4] . $qpHexDigits[$ascii & 0x0f]; $blank = false; } // Would the line become too long? if ($line_length + $replace_length > $line_limit - 1) { $output .= "=\r\n"; $line_length = 0; } $output .= $replace_char; $line_length += $replace_length; } return $output; }
[ "public", "static", "function", "qpContentTransferEncode", "(", "$", "input", ",", "$", "max_length", "=", "76", ")", "{", "$", "qpHexDigits", "=", "'0123456789ABCDEF'", ";", "$", "input_length", "=", "strlen", "(", "$", "input", ")", ";", "$", "line_limit", "=", "$", "max_length", ";", "$", "line_length", "=", "0", ";", "$", "output", "=", "''", ";", "$", "blank", "=", "false", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "input_length", ";", "$", "i", "++", ")", "{", "$", "char", "=", "$", "input", "[", "$", "i", "]", ";", "$", "ascii", "=", "ord", "(", "$", "char", ")", ";", "// No encoding for spaces and tabs", "if", "(", "$", "ascii", "==", "9", "||", "$", "ascii", "==", "32", ")", "{", "$", "blank", "=", "true", ";", "$", "replace_length", "=", "1", ";", "$", "replace_char", "=", "$", "char", ";", "// CR and LF", "}", "elseif", "(", "$", "ascii", "==", "13", "||", "$", "ascii", "==", "10", ")", "{", "// Use existing offset only.", "if", "(", "$", "i", "+", "1", "<", "$", "input_length", ")", "{", "if", "(", "(", "$", "ascii", "==", "13", "&&", "ord", "(", "$", "input", "[", "$", "i", "+", "1", "]", ")", "==", "10", ")", "||", "(", "$", "ascii", "==", "10", "&&", "ord", "(", "$", "input", "[", "$", "i", "+", "1", "]", ")", "==", "13", ")", ")", "{", "$", "i", "++", ";", "}", "}", "if", "(", "$", "blank", ")", "{", "/**\n * Any tab or space characters on an encoded line MUST\n * be followed on that line by a printable character.\n * This character may as well be the soft line break\n * indicator.\n *\n * So if the preceding character is a space or a\n * tab, we may simply insert a soft line break\n * here, followed by a literal line break.\n * Basically this means that we are appending\n * an empty line (nada).\n */", "$", "output", ".=", "\"=\\r\\n\\r\\n\"", ";", "}", "else", "{", "$", "output", ".=", "\"\\r\\n\"", ";", "}", "$", "blank", "=", "false", ";", "$", "line_length", "=", "0", ";", "continue", ";", "// No encoding within ascii range 33 to 126 (exception: 61)", "}", "elseif", "(", "32", "<", "$", "ascii", "&&", "$", "ascii", "<", "127", "&&", "$", "char", "!==", "'='", ")", "{", "$", "replace_length", "=", "1", ";", "$", "replace_char", "=", "$", "char", ";", "$", "blank", "=", "false", ";", "// Encode", "}", "else", "{", "$", "replace_length", "=", "3", ";", "// bit operation is around 10 percent faster", "// than 'strtoupper(dechex($ascii))'", "$", "replace_char", "=", "'='", ".", "$", "qpHexDigits", "[", "$", "ascii", ">>", "4", "]", ".", "$", "qpHexDigits", "[", "$", "ascii", "&", "0x0f", "]", ";", "$", "blank", "=", "false", ";", "}", "// Would the line become too long?", "if", "(", "$", "line_length", "+", "$", "replace_length", ">", "$", "line_limit", "-", "1", ")", "{", "$", "output", ".=", "\"=\\r\\n\"", ";", "$", "line_length", "=", "0", ";", "}", "$", "output", ".=", "$", "replace_char", ";", "$", "line_length", "+=", "$", "replace_length", ";", "}", "return", "$", "output", ";", "}" ]
Quoted-printable encoding of a message body (part), according to RFC2045. This function handles <CR>, <LF>, <CR><LF> and <LF><CR> sequences as 'user relevant' line breaks and encodes them as RFC822 line breaks as required by RFC2045. @author Elmar Bartel @author Michael Eichelsdoerfer @param string $input string to encode @param integer $max_length maximum line length (default: 76 chars) @return string $output encoded string
[ "Quoted", "-", "printable", "encoding", "of", "a", "message", "body", "(", "part", ")", "according", "to", "RFC2045", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.emailhelper.php#L152-L229
symphonycms/symphony-2
symphony/lib/toolkit/class.emailhelper.php
EmailHelper.arrayToList
public static function arrayToList(array $array = array()) { $return = array(); foreach ($array as $name => $email) { $return[] = empty($name) || General::intval($name) > -1 ? $email : $name . ' <' . $email . '>'; } return implode(', ', $return); }
php
public static function arrayToList(array $array = array()) { $return = array(); foreach ($array as $name => $email) { $return[] = empty($name) || General::intval($name) > -1 ? $email : $name . ' <' . $email . '>'; } return implode(', ', $return); }
[ "public", "static", "function", "arrayToList", "(", "array", "$", "array", "=", "array", "(", ")", ")", "{", "$", "return", "=", "array", "(", ")", ";", "foreach", "(", "$", "array", "as", "$", "name", "=>", "$", "email", ")", "{", "$", "return", "[", "]", "=", "empty", "(", "$", "name", ")", "||", "General", "::", "intval", "(", "$", "name", ")", ">", "-", "1", "?", "$", "email", ":", "$", "name", ".", "' <'", ".", "$", "email", ".", "'>'", ";", "}", "return", "implode", "(", "', '", ",", "$", "return", ")", ";", "}" ]
Implodes an associative array or straight array to a comma-separated string @param array $array @return string
[ "Implodes", "an", "associative", "array", "or", "straight", "array", "to", "a", "comma", "-", "separated", "string" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.emailhelper.php#L254-L264
symphonycms/symphony-2
symphony/lib/toolkit/cache/cache.database.php
CacheDatabase.read
public function read($hash, $namespace = null) { $data = false; // Check namespace first if (!is_null($namespace) && is_null($hash)) { $data = $this->Database->fetch(" SELECT SQL_NO_CACHE * FROM `tbl_cache` WHERE `namespace` = '$namespace' AND (`expiry` IS NULL OR UNIX_TIMESTAMP() <= `expiry`) "); } // Then check hash if (!is_null($hash)) { $data = $this->Database->fetchRow(0, " SELECT SQL_NO_CACHE * FROM `tbl_cache` WHERE `hash` = '$hash' AND (`expiry` IS NULL OR UNIX_TIMESTAMP() <= `expiry`) LIMIT 1 "); } // If the data exists, see if it's still valid if ($data) { if (!$data['data'] = Cacheable::decompressData($data['data'])) { $this->delete($hash, $namespace); return false; } return $data; } $this->delete(null, $namespace); return false; }
php
public function read($hash, $namespace = null) { $data = false; // Check namespace first if (!is_null($namespace) && is_null($hash)) { $data = $this->Database->fetch(" SELECT SQL_NO_CACHE * FROM `tbl_cache` WHERE `namespace` = '$namespace' AND (`expiry` IS NULL OR UNIX_TIMESTAMP() <= `expiry`) "); } // Then check hash if (!is_null($hash)) { $data = $this->Database->fetchRow(0, " SELECT SQL_NO_CACHE * FROM `tbl_cache` WHERE `hash` = '$hash' AND (`expiry` IS NULL OR UNIX_TIMESTAMP() <= `expiry`) LIMIT 1 "); } // If the data exists, see if it's still valid if ($data) { if (!$data['data'] = Cacheable::decompressData($data['data'])) { $this->delete($hash, $namespace); return false; } return $data; } $this->delete(null, $namespace); return false; }
[ "public", "function", "read", "(", "$", "hash", ",", "$", "namespace", "=", "null", ")", "{", "$", "data", "=", "false", ";", "// Check namespace first", "if", "(", "!", "is_null", "(", "$", "namespace", ")", "&&", "is_null", "(", "$", "hash", ")", ")", "{", "$", "data", "=", "$", "this", "->", "Database", "->", "fetch", "(", "\"\n SELECT SQL_NO_CACHE *\n FROM `tbl_cache`\n WHERE `namespace` = '$namespace'\n AND (`expiry` IS NULL OR UNIX_TIMESTAMP() <= `expiry`)\n \"", ")", ";", "}", "// Then check hash", "if", "(", "!", "is_null", "(", "$", "hash", ")", ")", "{", "$", "data", "=", "$", "this", "->", "Database", "->", "fetchRow", "(", "0", ",", "\"\n SELECT SQL_NO_CACHE *\n FROM `tbl_cache`\n WHERE `hash` = '$hash'\n AND (`expiry` IS NULL OR UNIX_TIMESTAMP() <= `expiry`)\n LIMIT 1\n \"", ")", ";", "}", "// If the data exists, see if it's still valid", "if", "(", "$", "data", ")", "{", "if", "(", "!", "$", "data", "[", "'data'", "]", "=", "Cacheable", "::", "decompressData", "(", "$", "data", "[", "'data'", "]", ")", ")", "{", "$", "this", "->", "delete", "(", "$", "hash", ",", "$", "namespace", ")", ";", "return", "false", ";", "}", "return", "$", "data", ";", "}", "$", "this", "->", "delete", "(", "null", ",", "$", "namespace", ")", ";", "return", "false", ";", "}" ]
Given the hash of a some data, check to see whether it exists in `tbl_cache`. If no cached object is found, this function will return false, otherwise the cached object will be returned as an array. @param string $hash The hash of the Cached object, as defined by the user @param string $namespace The namespace allows a group of data to be retrieved at once @return array|boolean An associative array of the cached object including the creation time, expiry time, the hash and the data. If the object is not found, false will be returned.
[ "Given", "the", "hash", "of", "a", "some", "data", "check", "to", "see", "whether", "it", "exists", "in", "tbl_cache", ".", "If", "no", "cached", "object", "is", "found", "this", "function", "will", "return", "false", "otherwise", "the", "cached", "object", "will", "be", "returned", "as", "an", "array", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/cache/cache.database.php#L78-L117
symphonycms/symphony-2
symphony/lib/toolkit/cache/cache.database.php
CacheDatabase.write
public function write($hash, $data, $ttl = null, $namespace = null) { if (!Mutex::acquire($hash, 2, TMP)) { return false; } $creation = time(); $expiry = null; $ttl = intval($ttl); if ($ttl > 0) { $expiry = $creation + ($ttl * 60); } if (!$data = Cacheable::compressData($data)) { return false; } $this->delete($hash, $namespace); $this->Database->insert(array( 'hash' => $hash, 'creation' => $creation, 'expiry' => $expiry, 'data' => $data, 'namespace' => $namespace ), 'tbl_cache'); Mutex::release($hash, TMP); return true; }
php
public function write($hash, $data, $ttl = null, $namespace = null) { if (!Mutex::acquire($hash, 2, TMP)) { return false; } $creation = time(); $expiry = null; $ttl = intval($ttl); if ($ttl > 0) { $expiry = $creation + ($ttl * 60); } if (!$data = Cacheable::compressData($data)) { return false; } $this->delete($hash, $namespace); $this->Database->insert(array( 'hash' => $hash, 'creation' => $creation, 'expiry' => $expiry, 'data' => $data, 'namespace' => $namespace ), 'tbl_cache'); Mutex::release($hash, TMP); return true; }
[ "public", "function", "write", "(", "$", "hash", ",", "$", "data", ",", "$", "ttl", "=", "null", ",", "$", "namespace", "=", "null", ")", "{", "if", "(", "!", "Mutex", "::", "acquire", "(", "$", "hash", ",", "2", ",", "TMP", ")", ")", "{", "return", "false", ";", "}", "$", "creation", "=", "time", "(", ")", ";", "$", "expiry", "=", "null", ";", "$", "ttl", "=", "intval", "(", "$", "ttl", ")", ";", "if", "(", "$", "ttl", ">", "0", ")", "{", "$", "expiry", "=", "$", "creation", "+", "(", "$", "ttl", "*", "60", ")", ";", "}", "if", "(", "!", "$", "data", "=", "Cacheable", "::", "compressData", "(", "$", "data", ")", ")", "{", "return", "false", ";", "}", "$", "this", "->", "delete", "(", "$", "hash", ",", "$", "namespace", ")", ";", "$", "this", "->", "Database", "->", "insert", "(", "array", "(", "'hash'", "=>", "$", "hash", ",", "'creation'", "=>", "$", "creation", ",", "'expiry'", "=>", "$", "expiry", ",", "'data'", "=>", "$", "data", ",", "'namespace'", "=>", "$", "namespace", ")", ",", "'tbl_cache'", ")", ";", "Mutex", "::", "release", "(", "$", "hash", ",", "TMP", ")", ";", "return", "true", ";", "}" ]
This function will compress data for storage in `tbl_cache`. It is left to the user to define a unique hash for this data so that it can be retrieved in the future. Optionally, a `$ttl` parameter can be passed for this data. If this is omitted, it data is considered to be valid forever. This function utilizes the Mutex class to act as a crude locking mechanism. @see toolkit.Mutex @throws DatabaseException @param string $hash The hash of the Cached object, as defined by the user @param string $data The data to be cached, this will be compressed prior to saving. @param integer $ttl A integer representing how long the data should be valid for in minutes. By default this is null, meaning the data is valid forever @param string $namespace The namespace allows data to be grouped and saved so it can be retrieved later. @return boolean If an error occurs, this function will return false otherwise true
[ "This", "function", "will", "compress", "data", "for", "storage", "in", "tbl_cache", ".", "It", "is", "left", "to", "the", "user", "to", "define", "a", "unique", "hash", "for", "this", "data", "so", "that", "it", "can", "be", "retrieved", "in", "the", "future", ".", "Optionally", "a", "$ttl", "parameter", "can", "be", "passed", "for", "this", "data", ".", "If", "this", "is", "omitted", "it", "data", "is", "considered", "to", "be", "valid", "forever", ".", "This", "function", "utilizes", "the", "Mutex", "class", "to", "act", "as", "a", "crude", "locking", "mechanism", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/cache/cache.database.php#L142-L172
symphonycms/symphony-2
symphony/lib/toolkit/cache/cache.database.php
CacheDatabase.delete
public function delete($hash = null, $namespace = null) { if (!is_null($hash)) { $this->Database->delete('tbl_cache', sprintf("`hash` = '%s'", $hash)); } elseif (!is_null($namespace)) { $this->Database->delete('tbl_cache', sprintf("`namespace` = '%s'", $namespace)); } else { $this->Database->delete('tbl_cache', "UNIX_TIMESTAMP() > `expiry`"); } $this->__optimise(); }
php
public function delete($hash = null, $namespace = null) { if (!is_null($hash)) { $this->Database->delete('tbl_cache', sprintf("`hash` = '%s'", $hash)); } elseif (!is_null($namespace)) { $this->Database->delete('tbl_cache', sprintf("`namespace` = '%s'", $namespace)); } else { $this->Database->delete('tbl_cache', "UNIX_TIMESTAMP() > `expiry`"); } $this->__optimise(); }
[ "public", "function", "delete", "(", "$", "hash", "=", "null", ",", "$", "namespace", "=", "null", ")", "{", "if", "(", "!", "is_null", "(", "$", "hash", ")", ")", "{", "$", "this", "->", "Database", "->", "delete", "(", "'tbl_cache'", ",", "sprintf", "(", "\"`hash` = '%s'\"", ",", "$", "hash", ")", ")", ";", "}", "elseif", "(", "!", "is_null", "(", "$", "namespace", ")", ")", "{", "$", "this", "->", "Database", "->", "delete", "(", "'tbl_cache'", ",", "sprintf", "(", "\"`namespace` = '%s'\"", ",", "$", "namespace", ")", ")", ";", "}", "else", "{", "$", "this", "->", "Database", "->", "delete", "(", "'tbl_cache'", ",", "\"UNIX_TIMESTAMP() > `expiry`\"", ")", ";", "}", "$", "this", "->", "__optimise", "(", ")", ";", "}" ]
Given the hash of a cacheable object, remove it from `tbl_cache` regardless of if it has expired or not. If no $hash is given, this removes all cache objects from `tbl_cache` that have expired. After removing, the function uses the `__optimise` function @see core.Cacheable#optimise() @throws DatabaseException @param string $hash The hash of the Cached object, as defined by the user @param string $namespace The namespace allows similar data to be deleted quickly.
[ "Given", "the", "hash", "of", "a", "cacheable", "object", "remove", "it", "from", "tbl_cache", "regardless", "of", "if", "it", "has", "expired", "or", "not", ".", "If", "no", "$hash", "is", "given", "this", "removes", "all", "cache", "objects", "from", "tbl_cache", "that", "have", "expired", ".", "After", "removing", "the", "function", "uses", "the", "__optimise", "function" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/cache/cache.database.php#L187-L198
symphonycms/symphony-2
symphony/lib/toolkit/class.entry.php
Entry.get
public function get($setting = null) { if (is_null($setting)) { return $this->_fields; } if (!isset($this->_fields[$setting])) { return null; } return $this->_fields[$setting]; }
php
public function get($setting = null) { if (is_null($setting)) { return $this->_fields; } if (!isset($this->_fields[$setting])) { return null; } return $this->_fields[$setting]; }
[ "public", "function", "get", "(", "$", "setting", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "setting", ")", ")", "{", "return", "$", "this", "->", "_fields", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "_fields", "[", "$", "setting", "]", ")", ")", "{", "return", "null", ";", "}", "return", "$", "this", "->", "_fields", "[", "$", "setting", "]", ";", "}" ]
Accessor to the a setting by name. If no setting is provided all the settings of this Entry instance are returned. @param string $setting (optional) the name of the setting to access the value for. This is optional and defaults to null in which case all settings are returned. @return null|mixed|array the value of the setting if there is one, all settings if the input setting was omitted or null if the setting was supplied but there is no value for that setting.
[ "Accessor", "to", "the", "a", "setting", "by", "name", ".", "If", "no", "setting", "is", "provided", "all", "the", "settings", "of", "this", "Entry", "instance", "are", "returned", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.entry.php#L79-L90
symphonycms/symphony-2
symphony/lib/toolkit/class.entry.php
Entry.assignEntryId
public function assignEntryId() { $fields = $this->get(); $fields['creation_date'] = $fields['modification_date'] = DateTimeObj::get('Y-m-d H:i:s'); $fields['creation_date_gmt'] = $fields['modification_date_gmt'] = DateTimeObj::getGMT('Y-m-d H:i:s'); $fields['author_id'] = is_null($this->get('author_id')) ? 1 : (int)$this->get('author_id'); // Author_id cannot be null $fields['modification_author_id'] = is_null($this->get('modification_author_id')) ? $fields['author_id'] : (int)$this->get('modification_author_id'); Symphony::Database()->insert($fields, 'tbl_entries'); if (!$entry_id = Symphony::Database()->getInsertID()) { return null; } $this->set('id', $entry_id); return $entry_id; }
php
public function assignEntryId() { $fields = $this->get(); $fields['creation_date'] = $fields['modification_date'] = DateTimeObj::get('Y-m-d H:i:s'); $fields['creation_date_gmt'] = $fields['modification_date_gmt'] = DateTimeObj::getGMT('Y-m-d H:i:s'); $fields['author_id'] = is_null($this->get('author_id')) ? 1 : (int)$this->get('author_id'); // Author_id cannot be null $fields['modification_author_id'] = is_null($this->get('modification_author_id')) ? $fields['author_id'] : (int)$this->get('modification_author_id'); Symphony::Database()->insert($fields, 'tbl_entries'); if (!$entry_id = Symphony::Database()->getInsertID()) { return null; } $this->set('id', $entry_id); return $entry_id; }
[ "public", "function", "assignEntryId", "(", ")", "{", "$", "fields", "=", "$", "this", "->", "get", "(", ")", ";", "$", "fields", "[", "'creation_date'", "]", "=", "$", "fields", "[", "'modification_date'", "]", "=", "DateTimeObj", "::", "get", "(", "'Y-m-d H:i:s'", ")", ";", "$", "fields", "[", "'creation_date_gmt'", "]", "=", "$", "fields", "[", "'modification_date_gmt'", "]", "=", "DateTimeObj", "::", "getGMT", "(", "'Y-m-d H:i:s'", ")", ";", "$", "fields", "[", "'author_id'", "]", "=", "is_null", "(", "$", "this", "->", "get", "(", "'author_id'", ")", ")", "?", "1", ":", "(", "int", ")", "$", "this", "->", "get", "(", "'author_id'", ")", ";", "// Author_id cannot be null", "$", "fields", "[", "'modification_author_id'", "]", "=", "is_null", "(", "$", "this", "->", "get", "(", "'modification_author_id'", ")", ")", "?", "$", "fields", "[", "'author_id'", "]", ":", "(", "int", ")", "$", "this", "->", "get", "(", "'modification_author_id'", ")", ";", "Symphony", "::", "Database", "(", ")", "->", "insert", "(", "$", "fields", ",", "'tbl_entries'", ")", ";", "if", "(", "!", "$", "entry_id", "=", "Symphony", "::", "Database", "(", ")", "->", "getInsertID", "(", ")", ")", "{", "return", "null", ";", "}", "$", "this", "->", "set", "(", "'id'", ",", "$", "entry_id", ")", ";", "return", "$", "entry_id", ";", "}" ]
Creates the initial entry row in tbl_entries and returns the resulting Entry ID using `getInsertID()`. @see toolkit.MySQL#getInsertID() @throws DatabaseException @return integer
[ "Creates", "the", "initial", "entry", "row", "in", "tbl_entries", "and", "returns", "the", "resulting", "Entry", "ID", "using", "getInsertID", "()", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.entry.php#L100-L117
symphonycms/symphony-2
symphony/lib/toolkit/class.entry.php
Entry.setDataFromPost
public function setDataFromPost($data, &$errors = null, $simulate = false, $ignore_missing_fields = false) { $status = Entry::__ENTRY_OK__; // Entry has no ID, create it: if (!$this->get('id') && $simulate === false) { $entry_id = $this->assignEntryId(); if (is_null($entry_id)) { return Entry::__ENTRY_FIELD_ERROR__; } } $section = SectionManager::fetch($this->get('section_id')); $schema = $section->fetchFieldsSchema(); foreach ($schema as $info) { $message = null; $field = FieldManager::fetch($info['id']); if ($ignore_missing_fields && !isset($data[$field->get('element_name')])) { continue; } $result = $field->processRawFieldData((isset($data[$info['element_name']]) ? $data[$info['element_name']] : null), $s, $message, $simulate, $this->get('id')); if ($s !== Field::__OK__) { $status = Entry::__ENTRY_FIELD_ERROR__; $errors[$info['id']] = $message; } $this->setData($info['id'], $result); } // Failed to create entry, cleanup if ($status !== Entry::__ENTRY_OK__ && !is_null($entry_id)) { Symphony::Database()->delete('tbl_entries', sprintf(" `id` = %d ", $entry_id)); } return $status; }
php
public function setDataFromPost($data, &$errors = null, $simulate = false, $ignore_missing_fields = false) { $status = Entry::__ENTRY_OK__; // Entry has no ID, create it: if (!$this->get('id') && $simulate === false) { $entry_id = $this->assignEntryId(); if (is_null($entry_id)) { return Entry::__ENTRY_FIELD_ERROR__; } } $section = SectionManager::fetch($this->get('section_id')); $schema = $section->fetchFieldsSchema(); foreach ($schema as $info) { $message = null; $field = FieldManager::fetch($info['id']); if ($ignore_missing_fields && !isset($data[$field->get('element_name')])) { continue; } $result = $field->processRawFieldData((isset($data[$info['element_name']]) ? $data[$info['element_name']] : null), $s, $message, $simulate, $this->get('id')); if ($s !== Field::__OK__) { $status = Entry::__ENTRY_FIELD_ERROR__; $errors[$info['id']] = $message; } $this->setData($info['id'], $result); } // Failed to create entry, cleanup if ($status !== Entry::__ENTRY_OK__ && !is_null($entry_id)) { Symphony::Database()->delete('tbl_entries', sprintf(" `id` = %d ", $entry_id)); } return $status; }
[ "public", "function", "setDataFromPost", "(", "$", "data", ",", "&", "$", "errors", "=", "null", ",", "$", "simulate", "=", "false", ",", "$", "ignore_missing_fields", "=", "false", ")", "{", "$", "status", "=", "Entry", "::", "__ENTRY_OK__", ";", "// Entry has no ID, create it:", "if", "(", "!", "$", "this", "->", "get", "(", "'id'", ")", "&&", "$", "simulate", "===", "false", ")", "{", "$", "entry_id", "=", "$", "this", "->", "assignEntryId", "(", ")", ";", "if", "(", "is_null", "(", "$", "entry_id", ")", ")", "{", "return", "Entry", "::", "__ENTRY_FIELD_ERROR__", ";", "}", "}", "$", "section", "=", "SectionManager", "::", "fetch", "(", "$", "this", "->", "get", "(", "'section_id'", ")", ")", ";", "$", "schema", "=", "$", "section", "->", "fetchFieldsSchema", "(", ")", ";", "foreach", "(", "$", "schema", "as", "$", "info", ")", "{", "$", "message", "=", "null", ";", "$", "field", "=", "FieldManager", "::", "fetch", "(", "$", "info", "[", "'id'", "]", ")", ";", "if", "(", "$", "ignore_missing_fields", "&&", "!", "isset", "(", "$", "data", "[", "$", "field", "->", "get", "(", "'element_name'", ")", "]", ")", ")", "{", "continue", ";", "}", "$", "result", "=", "$", "field", "->", "processRawFieldData", "(", "(", "isset", "(", "$", "data", "[", "$", "info", "[", "'element_name'", "]", "]", ")", "?", "$", "data", "[", "$", "info", "[", "'element_name'", "]", "]", ":", "null", ")", ",", "$", "s", ",", "$", "message", ",", "$", "simulate", ",", "$", "this", "->", "get", "(", "'id'", ")", ")", ";", "if", "(", "$", "s", "!==", "Field", "::", "__OK__", ")", "{", "$", "status", "=", "Entry", "::", "__ENTRY_FIELD_ERROR__", ";", "$", "errors", "[", "$", "info", "[", "'id'", "]", "]", "=", "$", "message", ";", "}", "$", "this", "->", "setData", "(", "$", "info", "[", "'id'", "]", ",", "$", "result", ")", ";", "}", "// Failed to create entry, cleanup", "if", "(", "$", "status", "!==", "Entry", "::", "__ENTRY_OK__", "&&", "!", "is_null", "(", "$", "entry_id", ")", ")", "{", "Symphony", "::", "Database", "(", ")", "->", "delete", "(", "'tbl_entries'", ",", "sprintf", "(", "\" `id` = %d \"", ",", "$", "entry_id", ")", ")", ";", "}", "return", "$", "status", ";", "}" ]
When an entry is saved from a form (either Frontend/Backend) this function will find all the fields in this set and loop over them, setting the data to each of the fields for processing. If any errors occur during this, `_ENTRY_FIELD_ERROR_` is returned, and an array is available with the errors. @param array $data An associative array of the data for this entry where they key is the Field's handle for this Section and the value is the data from the form @param array $errors An associative array of errors, by reference. The key is the `field_id`, the value is the message text. Defaults to an empty array @param boolean $simulate If $simulate is given as true, a dry run of this function will occur, where regardless of errors, an Entry will not be saved in the database. Defaults to false @param boolean $ignore_missing_fields This parameter allows Entries to be updated, rather than replaced. This is useful if the input form only contains a couple of the fields for this Entry. Defaults to false, which will set Fields to their default values if they are not provided in the $data @throws DatabaseException @throws Exception @return integer Either `Entry::__ENTRY_OK__` or `Entry::__ENTRY_FIELD_ERROR__`
[ "When", "an", "entry", "is", "saved", "from", "a", "form", "(", "either", "Frontend", "/", "Backend", ")", "this", "function", "will", "find", "all", "the", "fields", "in", "this", "set", "and", "loop", "over", "them", "setting", "the", "data", "to", "each", "of", "the", "fields", "for", "processing", ".", "If", "any", "errors", "occur", "during", "this", "_ENTRY_FIELD_ERROR_", "is", "returned", "and", "an", "array", "is", "available", "with", "the", "errors", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.entry.php#L159-L199