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.xmlelement.php
XMLElement.convertNode
private static function convertNode(XMLElement $element, DOMNode $node) { if ($node->hasAttributes()) { foreach ($node->attributes as $name => $attrEl) { $element->setAttribute($name, General::sanitize($attrEl->value)); } } if ($node->hasChildNodes()) { foreach ($node->childNodes as $childNode) { if ($childNode instanceof DOMCdataSection) { $element->setValue(General::wrapInCDATA($childNode->data)); } elseif ($childNode instanceof DOMText) { if ($childNode->isWhitespaceInElementContent() === false) { $element->setValue(General::sanitize($childNode->data)); } } elseif ($childNode instanceof DOMElement) { self::convert($element, $childNode); } } } }
php
private static function convertNode(XMLElement $element, DOMNode $node) { if ($node->hasAttributes()) { foreach ($node->attributes as $name => $attrEl) { $element->setAttribute($name, General::sanitize($attrEl->value)); } } if ($node->hasChildNodes()) { foreach ($node->childNodes as $childNode) { if ($childNode instanceof DOMCdataSection) { $element->setValue(General::wrapInCDATA($childNode->data)); } elseif ($childNode instanceof DOMText) { if ($childNode->isWhitespaceInElementContent() === false) { $element->setValue(General::sanitize($childNode->data)); } } elseif ($childNode instanceof DOMElement) { self::convert($element, $childNode); } } } }
[ "private", "static", "function", "convertNode", "(", "XMLElement", "$", "element", ",", "DOMNode", "$", "node", ")", "{", "if", "(", "$", "node", "->", "hasAttributes", "(", ")", ")", "{", "foreach", "(", "$", "node", "->", "attributes", "as", "$", "name", "=>", "$", "attrEl", ")", "{", "$", "element", "->", "setAttribute", "(", "$", "name", ",", "General", "::", "sanitize", "(", "$", "attrEl", "->", "value", ")", ")", ";", "}", "}", "if", "(", "$", "node", "->", "hasChildNodes", "(", ")", ")", "{", "foreach", "(", "$", "node", "->", "childNodes", "as", "$", "childNode", ")", "{", "if", "(", "$", "childNode", "instanceof", "DOMCdataSection", ")", "{", "$", "element", "->", "setValue", "(", "General", "::", "wrapInCDATA", "(", "$", "childNode", "->", "data", ")", ")", ";", "}", "elseif", "(", "$", "childNode", "instanceof", "DOMText", ")", "{", "if", "(", "$", "childNode", "->", "isWhitespaceInElementContent", "(", ")", "===", "false", ")", "{", "$", "element", "->", "setValue", "(", "General", "::", "sanitize", "(", "$", "childNode", "->", "data", ")", ")", ";", "}", "}", "elseif", "(", "$", "childNode", "instanceof", "DOMElement", ")", "{", "self", "::", "convert", "(", "$", "element", ",", "$", "childNode", ")", ";", "}", "}", "}", "}" ]
Given a DOMNode, this function will help replicate it as an XMLElement object @since Symphony 2.5.2 @param XMLElement $element @param DOMNode $node
[ "Given", "a", "DOMNode", "this", "function", "will", "help", "replicate", "it", "as", "an", "XMLElement", "object" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.xmlelement.php#L899-L920
symphonycms/symphony-2
symphony/lib/toolkit/class.profiler.php
Profiler.sample
public function sample($msg, $type = PROFILE_RUNNING_TOTAL, $group = 'General', $queries = null) { if ($type == PROFILE_RUNNING_TOTAL) { Profiler::$_samples[] = array($msg, precision_timer('stop', Profiler::$_starttime), precision_timer(), $group, $queries, memory_get_usage()); } else { if (!is_null(Profiler::$_seed)) { $start = Profiler::$_seed; Profiler::$_seed = null; } else { $start = null; } $prev = Profiler::retrieveLast(); Profiler::$_samples[] = array($msg, precision_timer('stop', ($start ? $start : $prev[2])), precision_timer(), $group, $queries, memory_get_usage()); } }
php
public function sample($msg, $type = PROFILE_RUNNING_TOTAL, $group = 'General', $queries = null) { if ($type == PROFILE_RUNNING_TOTAL) { Profiler::$_samples[] = array($msg, precision_timer('stop', Profiler::$_starttime), precision_timer(), $group, $queries, memory_get_usage()); } else { if (!is_null(Profiler::$_seed)) { $start = Profiler::$_seed; Profiler::$_seed = null; } else { $start = null; } $prev = Profiler::retrieveLast(); Profiler::$_samples[] = array($msg, precision_timer('stop', ($start ? $start : $prev[2])), precision_timer(), $group, $queries, memory_get_usage()); } }
[ "public", "function", "sample", "(", "$", "msg", ",", "$", "type", "=", "PROFILE_RUNNING_TOTAL", ",", "$", "group", "=", "'General'", ",", "$", "queries", "=", "null", ")", "{", "if", "(", "$", "type", "==", "PROFILE_RUNNING_TOTAL", ")", "{", "Profiler", "::", "$", "_samples", "[", "]", "=", "array", "(", "$", "msg", ",", "precision_timer", "(", "'stop'", ",", "Profiler", "::", "$", "_starttime", ")", ",", "precision_timer", "(", ")", ",", "$", "group", ",", "$", "queries", ",", "memory_get_usage", "(", ")", ")", ";", "}", "else", "{", "if", "(", "!", "is_null", "(", "Profiler", "::", "$", "_seed", ")", ")", "{", "$", "start", "=", "Profiler", "::", "$", "_seed", ";", "Profiler", "::", "$", "_seed", "=", "null", ";", "}", "else", "{", "$", "start", "=", "null", ";", "}", "$", "prev", "=", "Profiler", "::", "retrieveLast", "(", ")", ";", "Profiler", "::", "$", "_samples", "[", "]", "=", "array", "(", "$", "msg", ",", "precision_timer", "(", "'stop'", ",", "(", "$", "start", "?", "$", "start", ":", "$", "prev", "[", "2", "]", ")", ")", ",", "precision_timer", "(", ")", ",", "$", "group", ",", "$", "queries", ",", "memory_get_usage", "(", ")", ")", ";", "}", "}" ]
This function creates a new report in the `$_samples` array where the message is the name of this report. By default, all samples are compared to the `$_starttime` but if the `PROFILE_LAP` constant is passed, it will be compared to specific `$_seed` timestamp. Samples can grouped by type (ie. Datasources, Events), but by default are grouped by 'General'. Optionally, the number of SQL queries that have occurred since either `$_starttime` or `$_seed` can be passed. Memory usage is taken with each sample which measures the amount of memory used by this script by PHP at the time of sampling. @param string $msg A description for this sample @param integer $type Either `PROFILE_RUNNING_TOTAL` or `PROFILE_LAP` @param string $group Allows samples to be grouped together, defaults to General. @param integer $queries The number of MySQL queries that occurred since the `$_starttime` or `$_seed`
[ "This", "function", "creates", "a", "new", "report", "in", "the", "$_samples", "array", "where", "the", "message", "is", "the", "name", "of", "this", "report", ".", "By", "default", "all", "samples", "are", "compared", "to", "the", "$_starttime", "but", "if", "the", "PROFILE_LAP", "constant", "is", "passed", "it", "will", "be", "compared", "to", "specific", "$_seed", "timestamp", ".", "Samples", "can", "grouped", "by", "type", "(", "ie", ".", "Datasources", "Events", ")", "but", "by", "default", "are", "grouped", "by", "General", ".", "Optionally", "the", "number", "of", "SQL", "queries", "that", "have", "occurred", "since", "either", "$_starttime", "or", "$_seed", "can", "be", "passed", ".", "Memory", "usage", "is", "taken", "with", "each", "sample", "which", "measures", "the", "amount", "of", "memory", "used", "by", "this", "script", "by", "PHP", "at", "the", "time", "of", "sampling", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.profiler.php#L97-L112
symphonycms/symphony-2
symphony/lib/toolkit/class.profiler.php
Profiler.retrieve
public function retrieve($index = null) { return !is_null($index) ? Profiler::$_samples[$index] : Profiler::$_samples; }
php
public function retrieve($index = null) { return !is_null($index) ? Profiler::$_samples[$index] : Profiler::$_samples; }
[ "public", "function", "retrieve", "(", "$", "index", "=", "null", ")", "{", "return", "!", "is_null", "(", "$", "index", ")", "?", "Profiler", "::", "$", "_samples", "[", "$", "index", "]", ":", "Profiler", "::", "$", "_samples", ";", "}" ]
Given an index, return the sample at that position otherwise just return all samples. @param integer $index The array index to return the sample for @return array If no `$index` is passed an array of all the sample arrays are returned otherwise just the sample at the given `$index` will be returned.
[ "Given", "an", "index", "return", "the", "sample", "at", "that", "position", "otherwise", "just", "return", "all", "samples", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.profiler.php#L124-L127
symphonycms/symphony-2
symphony/lib/toolkit/class.profiler.php
Profiler.retrieveGroup
public function retrieveGroup($group) { $result = array(); foreach (Profiler::$_samples as $record) { if ($record[3] == $group) { $result[] = $record; } } return $result; }
php
public function retrieveGroup($group) { $result = array(); foreach (Profiler::$_samples as $record) { if ($record[3] == $group) { $result[] = $record; } } return $result; }
[ "public", "function", "retrieveGroup", "(", "$", "group", ")", "{", "$", "result", "=", "array", "(", ")", ";", "foreach", "(", "Profiler", "::", "$", "_samples", "as", "$", "record", ")", "{", "if", "(", "$", "record", "[", "3", "]", "==", "$", "group", ")", "{", "$", "result", "[", "]", "=", "$", "record", ";", "}", "}", "return", "$", "result", ";", "}" ]
Returns all the samples that belong to a particular group. @param string $group @return array
[ "Returns", "all", "the", "samples", "that", "belong", "to", "a", "particular", "group", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.profiler.php#L154-L165
symphonycms/symphony-2
symphony/lib/toolkit/class.profiler.php
Profiler.retrieveTotalMemoryUsage
public function retrieveTotalMemoryUsage() { $base = $this->retrieve(0); $total = $last = 0; foreach ($this->retrieve() as $item) { $total += max(0, (($item[5]-$base[5]) - $last)); $last = $item[5]-$base[5]; } return $total; }
php
public function retrieveTotalMemoryUsage() { $base = $this->retrieve(0); $total = $last = 0; foreach ($this->retrieve() as $item) { $total += max(0, (($item[5]-$base[5]) - $last)); $last = $item[5]-$base[5]; } return $total; }
[ "public", "function", "retrieveTotalMemoryUsage", "(", ")", "{", "$", "base", "=", "$", "this", "->", "retrieve", "(", "0", ")", ";", "$", "total", "=", "$", "last", "=", "0", ";", "foreach", "(", "$", "this", "->", "retrieve", "(", ")", "as", "$", "item", ")", "{", "$", "total", "+=", "max", "(", "0", ",", "(", "(", "$", "item", "[", "5", "]", "-", "$", "base", "[", "5", "]", ")", "-", "$", "last", ")", ")", ";", "$", "last", "=", "$", "item", "[", "5", "]", "-", "$", "base", "[", "5", "]", ";", "}", "return", "$", "total", ";", "}" ]
Returns the total memory usage from all samples taken by comparing each sample to the base memory sample. @return integer Memory usage in bytes.
[ "Returns", "the", "total", "memory", "usage", "from", "all", "samples", "taken", "by", "comparing", "each", "sample", "to", "the", "base", "memory", "sample", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.profiler.php#L195-L206
symphonycms/symphony-2
symphony/lib/toolkit/class.xsrf.php
XSRF.getSessionToken
public static function getSessionToken() { $token = null; if (isset($_SESSION[__SYM_COOKIE_PREFIX__]['xsrf-token'])) { $token = $_SESSION[__SYM_COOKIE_PREFIX__]['xsrf-token']; } if (is_array($token)) { $token = key($token); } return is_null($token) ? null : $token; }
php
public static function getSessionToken() { $token = null; if (isset($_SESSION[__SYM_COOKIE_PREFIX__]['xsrf-token'])) { $token = $_SESSION[__SYM_COOKIE_PREFIX__]['xsrf-token']; } if (is_array($token)) { $token = key($token); } return is_null($token) ? null : $token; }
[ "public", "static", "function", "getSessionToken", "(", ")", "{", "$", "token", "=", "null", ";", "if", "(", "isset", "(", "$", "_SESSION", "[", "__SYM_COOKIE_PREFIX__", "]", "[", "'xsrf-token'", "]", ")", ")", "{", "$", "token", "=", "$", "_SESSION", "[", "__SYM_COOKIE_PREFIX__", "]", "[", "'xsrf-token'", "]", ";", "}", "if", "(", "is_array", "(", "$", "token", ")", ")", "{", "$", "token", "=", "key", "(", "$", "token", ")", ";", "}", "return", "is_null", "(", "$", "token", ")", "?", "null", ":", "$", "token", ";", "}" ]
Return's the location of the XSRF tokens in the Session @return string|null
[ "Return", "s", "the", "location", "of", "the", "XSRF", "tokens", "in", "the", "Session" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.xsrf.php#L24-L37
symphonycms/symphony-2
symphony/lib/toolkit/class.xsrf.php
XSRF.generateNonce
public static function generateNonce($length = 30) { $random = null; if ($length < 1) { throw new Exception('$length must be greater than 0'); } // Use the new PHP 7 random_bytes call, if available if (!$random && function_exists('random_bytes')) { $random = random_bytes($length); } // Get some random binary data from open ssl, if available if (!$random && function_exists('openssl_random_pseudo_bytes')) { $random = openssl_random_pseudo_bytes($length); } // Fallback to /dev/urandom if (!$random && is_readable('/dev/urandom')) { if (($handle = @fopen('/dev/urandom', 'rb')) !== false) { $random = @fread($handle, $length); @fclose($handle); } } // Fallback if no random bytes were found if (!$random) { $random = microtime(); for ($i = 0; $i < 1000; $i += $length) { $random = sha1(microtime() . $random); } } // Convert to base64 $random = base64_encode($random); // Replace unsafe chars $random = strtr($random, '+/', '-_'); $random = str_replace('=', '', $random); // Truncate the string to specified lengh $random = substr($random, 0, $length); return $random; }
php
public static function generateNonce($length = 30) { $random = null; if ($length < 1) { throw new Exception('$length must be greater than 0'); } // Use the new PHP 7 random_bytes call, if available if (!$random && function_exists('random_bytes')) { $random = random_bytes($length); } // Get some random binary data from open ssl, if available if (!$random && function_exists('openssl_random_pseudo_bytes')) { $random = openssl_random_pseudo_bytes($length); } // Fallback to /dev/urandom if (!$random && is_readable('/dev/urandom')) { if (($handle = @fopen('/dev/urandom', 'rb')) !== false) { $random = @fread($handle, $length); @fclose($handle); } } // Fallback if no random bytes were found if (!$random) { $random = microtime(); for ($i = 0; $i < 1000; $i += $length) { $random = sha1(microtime() . $random); } } // Convert to base64 $random = base64_encode($random); // Replace unsafe chars $random = strtr($random, '+/', '-_'); $random = str_replace('=', '', $random); // Truncate the string to specified lengh $random = substr($random, 0, $length); return $random; }
[ "public", "static", "function", "generateNonce", "(", "$", "length", "=", "30", ")", "{", "$", "random", "=", "null", ";", "if", "(", "$", "length", "<", "1", ")", "{", "throw", "new", "Exception", "(", "'$length must be greater than 0'", ")", ";", "}", "// Use the new PHP 7 random_bytes call, if available", "if", "(", "!", "$", "random", "&&", "function_exists", "(", "'random_bytes'", ")", ")", "{", "$", "random", "=", "random_bytes", "(", "$", "length", ")", ";", "}", "// Get some random binary data from open ssl, if available", "if", "(", "!", "$", "random", "&&", "function_exists", "(", "'openssl_random_pseudo_bytes'", ")", ")", "{", "$", "random", "=", "openssl_random_pseudo_bytes", "(", "$", "length", ")", ";", "}", "// Fallback to /dev/urandom", "if", "(", "!", "$", "random", "&&", "is_readable", "(", "'/dev/urandom'", ")", ")", "{", "if", "(", "(", "$", "handle", "=", "@", "fopen", "(", "'/dev/urandom'", ",", "'rb'", ")", ")", "!==", "false", ")", "{", "$", "random", "=", "@", "fread", "(", "$", "handle", ",", "$", "length", ")", ";", "@", "fclose", "(", "$", "handle", ")", ";", "}", "}", "// Fallback if no random bytes were found", "if", "(", "!", "$", "random", ")", "{", "$", "random", "=", "microtime", "(", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "1000", ";", "$", "i", "+=", "$", "length", ")", "{", "$", "random", "=", "sha1", "(", "microtime", "(", ")", ".", "$", "random", ")", ";", "}", "}", "// Convert to base64", "$", "random", "=", "base64_encode", "(", "$", "random", ")", ";", "// Replace unsafe chars", "$", "random", "=", "strtr", "(", "$", "random", ",", "'+/'", ",", "'-_'", ")", ";", "$", "random", "=", "str_replace", "(", "'='", ",", "''", ",", "$", "random", ")", ";", "// Truncate the string to specified lengh", "$", "random", "=", "substr", "(", "$", "random", ",", "0", ",", "$", "length", ")", ";", "return", "$", "random", ";", "}" ]
Generates nonce to a desired `$length` using `openssl` where available, falling back to using `/dev/urandom` and a microtime implementation otherwise @param integer $length optional. By default, 30. @return string base64 encoded, url safe
[ "Generates", "nonce", "to", "a", "desired", "$length", "using", "openssl", "where", "available", "falling", "back", "to", "using", "/", "dev", "/", "urandom", "and", "a", "microtime", "implementation", "otherwise" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.xsrf.php#L72-L117
symphonycms/symphony-2
symphony/lib/toolkit/class.xsrf.php
XSRF.formToken
public static function formToken() { // <input type="hidden" name="xsrf" value=" . self::getToken() . " /> $obj = new XMLElement("input"); $obj->setAttribute("type", "hidden"); $obj->setAttribute("name", "xsrf"); $obj->setAttribute("value", self::getToken()); return $obj; }
php
public static function formToken() { // <input type="hidden" name="xsrf" value=" . self::getToken() . " /> $obj = new XMLElement("input"); $obj->setAttribute("type", "hidden"); $obj->setAttribute("name", "xsrf"); $obj->setAttribute("value", self::getToken()); return $obj; }
[ "public", "static", "function", "formToken", "(", ")", "{", "// <input type=\"hidden\" name=\"xsrf\" value=\" . self::getToken() . \" />", "$", "obj", "=", "new", "XMLElement", "(", "\"input\"", ")", ";", "$", "obj", "->", "setAttribute", "(", "\"type\"", ",", "\"hidden\"", ")", ";", "$", "obj", "->", "setAttribute", "(", "\"name\"", ",", "\"xsrf\"", ")", ";", "$", "obj", "->", "setAttribute", "(", "\"value\"", ",", "self", "::", "getToken", "(", ")", ")", ";", "return", "$", "obj", ";", "}" ]
Creates the form input to use to house the token @return XMLElement
[ "Creates", "the", "form", "input", "to", "use", "to", "house", "the", "token" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.xsrf.php#L124-L132
symphonycms/symphony-2
symphony/lib/toolkit/class.xsrf.php
XSRF.getToken
public static function getToken() { $token = self::getSessionToken(); if (is_null($token)) { $nonce = self::generateNonce(); self::setSessionToken($nonce); // Handle old tokens (< 2.6.0) } elseif (is_array($token)) { $nonce = key($token); self::setSessionToken($nonce); // New style tokens } else { $nonce = $token; } return $nonce; }
php
public static function getToken() { $token = self::getSessionToken(); if (is_null($token)) { $nonce = self::generateNonce(); self::setSessionToken($nonce); // Handle old tokens (< 2.6.0) } elseif (is_array($token)) { $nonce = key($token); self::setSessionToken($nonce); // New style tokens } else { $nonce = $token; } return $nonce; }
[ "public", "static", "function", "getToken", "(", ")", "{", "$", "token", "=", "self", "::", "getSessionToken", "(", ")", ";", "if", "(", "is_null", "(", "$", "token", ")", ")", "{", "$", "nonce", "=", "self", "::", "generateNonce", "(", ")", ";", "self", "::", "setSessionToken", "(", "$", "nonce", ")", ";", "// Handle old tokens (< 2.6.0)", "}", "elseif", "(", "is_array", "(", "$", "token", ")", ")", "{", "$", "nonce", "=", "key", "(", "$", "token", ")", ";", "self", "::", "setSessionToken", "(", "$", "nonce", ")", ";", "// New style tokens", "}", "else", "{", "$", "nonce", "=", "$", "token", ";", "}", "return", "$", "nonce", ";", "}" ]
This is the nonce used to stop CSRF/XSRF attacks. It's stored in the user session. @return string
[ "This", "is", "the", "nonce", "used", "to", "stop", "CSRF", "/", "XSRF", "attacks", ".", "It", "s", "stored", "in", "the", "user", "session", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.xsrf.php#L139-L157
symphonycms/symphony-2
symphony/lib/toolkit/class.xsrf.php
XSRF.validateRequest
public static function validateRequest($silent = false) { // Only care if we have a POST request. if (count($_POST) > 0) { if (!self::validateToken($_POST["xsrf"])) { // Token was invalid, show an error page. if (!$silent) { self::throwXSRFException(); } else { return false; } } } }
php
public static function validateRequest($silent = false) { // Only care if we have a POST request. if (count($_POST) > 0) { if (!self::validateToken($_POST["xsrf"])) { // Token was invalid, show an error page. if (!$silent) { self::throwXSRFException(); } else { return false; } } } }
[ "public", "static", "function", "validateRequest", "(", "$", "silent", "=", "false", ")", "{", "// Only care if we have a POST request.", "if", "(", "count", "(", "$", "_POST", ")", ">", "0", ")", "{", "if", "(", "!", "self", "::", "validateToken", "(", "$", "_POST", "[", "\"xsrf\"", "]", ")", ")", "{", "// Token was invalid, show an error page.", "if", "(", "!", "$", "silent", ")", "{", "self", "::", "throwXSRFException", "(", ")", ";", "}", "else", "{", "return", "false", ";", "}", "}", "}", "}" ]
This will validate a request has a good token. @throws SymphonyErrorPage @param boolean $silent If true, this function will return false if the request fails, otherwise it will throw an Exception. By default this function will thrown an exception if the request is invalid. @return false|void
[ "This", "will", "validate", "a", "request", "has", "a", "good", "token", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.xsrf.php#L183-L196
symphonycms/symphony-2
symphony/lib/toolkit/class.timestampvalidator.php
TimestampValidator.check
public function check($id, $timestamp) { $id = General::intval(MySQL::cleanValue($id)); if ($id < 1) { return false; } $timestamp = MySQL::cleanValue($timestamp); $sql = " SELECT `id` FROM `{$this->table}` WHERE `id` = $id AND `modification_date` = '$timestamp' "; $results = Symphony::Database()->fetchVar('id', 0, $sql); return !empty($results) && General::intval($results) === $id; }
php
public function check($id, $timestamp) { $id = General::intval(MySQL::cleanValue($id)); if ($id < 1) { return false; } $timestamp = MySQL::cleanValue($timestamp); $sql = " SELECT `id` FROM `{$this->table}` WHERE `id` = $id AND `modification_date` = '$timestamp' "; $results = Symphony::Database()->fetchVar('id', 0, $sql); return !empty($results) && General::intval($results) === $id; }
[ "public", "function", "check", "(", "$", "id", ",", "$", "timestamp", ")", "{", "$", "id", "=", "General", "::", "intval", "(", "MySQL", "::", "cleanValue", "(", "$", "id", ")", ")", ";", "if", "(", "$", "id", "<", "1", ")", "{", "return", "false", ";", "}", "$", "timestamp", "=", "MySQL", "::", "cleanValue", "(", "$", "timestamp", ")", ";", "$", "sql", "=", "\"\n SELECT `id` FROM `{$this->table}`\n WHERE `id` = $id\n AND `modification_date` = '$timestamp'\n \"", ";", "$", "results", "=", "Symphony", "::", "Database", "(", ")", "->", "fetchVar", "(", "'id'", ",", "0", ",", "$", "sql", ")", ";", "return", "!", "empty", "(", "$", "results", ")", "&&", "General", "::", "intval", "(", "$", "results", ")", "===", "$", "id", ";", "}" ]
Checks if the modified date of the record identified with $id if equal to the supplied $timestamp @param int|string $id The record id to check @param string $timestamp The user supplied timestamp @return boolean true if the $timestamp is the latest or the $id is invalid, false other wise
[ "Checks", "if", "the", "modified", "date", "of", "the", "record", "identified", "with", "$id", "if", "equal", "to", "the", "supplied", "$timestamp" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.timestampvalidator.php#L47-L61
symphonycms/symphony-2
symphony/lib/toolkit/class.entrymanager.php
EntryManager.setFetchSortingDirection
public static function setFetchSortingDirection($direction) { $direction = strtoupper($direction); if ($direction == 'RANDOM') { $direction = 'RAND'; } self::$_fetchSortDirection = (in_array($direction, array('RAND', 'ASC', 'DESC')) ? $direction : null); }
php
public static function setFetchSortingDirection($direction) { $direction = strtoupper($direction); if ($direction == 'RANDOM') { $direction = 'RAND'; } self::$_fetchSortDirection = (in_array($direction, array('RAND', 'ASC', 'DESC')) ? $direction : null); }
[ "public", "static", "function", "setFetchSortingDirection", "(", "$", "direction", ")", "{", "$", "direction", "=", "strtoupper", "(", "$", "direction", ")", ";", "if", "(", "$", "direction", "==", "'RANDOM'", ")", "{", "$", "direction", "=", "'RAND'", ";", "}", "self", "::", "$", "_fetchSortDirection", "=", "(", "in_array", "(", "$", "direction", ",", "array", "(", "'RAND'", ",", "'ASC'", ",", "'DESC'", ")", ")", "?", "$", "direction", ":", "null", ")", ";", "}" ]
Setter function for the default sorting direction of the Fetch function. Available options are RAND, ASC or DESC. @param string $direction The direction that entries should be sorted in, available options are RAND, ASC or DESC.
[ "Setter", "function", "for", "the", "default", "sorting", "direction", "of", "the", "Fetch", "function", ".", "Available", "options", "are", "RAND", "ASC", "or", "DESC", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.entrymanager.php#L41-L50
symphonycms/symphony-2
symphony/lib/toolkit/class.entrymanager.php
EntryManager.saveFieldData
protected static function saveFieldData($entry_id, $field_id, $field) { // Check that we have a field id if (empty($field_id)) { return; } // Ignore parameter when not an array if (!is_array($field)) { $field = array(); } $did_lock = false; $exception = null; try { // Check if table exists $table_name = 'tbl_entries_data_' . General::intval($field_id); if (!Symphony::Database()->tableExists($table_name)) { return; } // Lock the table for write $did_lock = Symphony::Database()->query("LOCK TABLES `$table_name` WRITE"); // Delete old data Symphony::Database()->delete($table_name, sprintf(" `entry_id` = %d", $entry_id )); // Insert new data $data = array( 'entry_id' => $entry_id ); $fields = array(); foreach ($field as $key => $value) { if (is_array($value)) { foreach ($value as $ii => $v) { $fields[$ii][$key] = $v; } } else { $fields[max(0, count($fields) - 1)][$key] = $value; } } foreach ($fields as $index => $field_data) { $fields[$index] = array_merge($data, $field_data); } // Insert only if we have field data if (!empty($fields)) { Symphony::Database()->insert($fields, $table_name); } } catch (Exception $ex) { $exception = $ex; Symphony::Log()->pushExceptionToLog($ex, true); } if ($did_lock) { Symphony::Database()->query('UNLOCK TABLES'); } if ($exception) { throw $exception; } }
php
protected static function saveFieldData($entry_id, $field_id, $field) { // Check that we have a field id if (empty($field_id)) { return; } // Ignore parameter when not an array if (!is_array($field)) { $field = array(); } $did_lock = false; $exception = null; try { // Check if table exists $table_name = 'tbl_entries_data_' . General::intval($field_id); if (!Symphony::Database()->tableExists($table_name)) { return; } // Lock the table for write $did_lock = Symphony::Database()->query("LOCK TABLES `$table_name` WRITE"); // Delete old data Symphony::Database()->delete($table_name, sprintf(" `entry_id` = %d", $entry_id )); // Insert new data $data = array( 'entry_id' => $entry_id ); $fields = array(); foreach ($field as $key => $value) { if (is_array($value)) { foreach ($value as $ii => $v) { $fields[$ii][$key] = $v; } } else { $fields[max(0, count($fields) - 1)][$key] = $value; } } foreach ($fields as $index => $field_data) { $fields[$index] = array_merge($data, $field_data); } // Insert only if we have field data if (!empty($fields)) { Symphony::Database()->insert($fields, $table_name); } } catch (Exception $ex) { $exception = $ex; Symphony::Log()->pushExceptionToLog($ex, true); } if ($did_lock) { Symphony::Database()->query('UNLOCK TABLES'); } if ($exception) { throw $exception; } }
[ "protected", "static", "function", "saveFieldData", "(", "$", "entry_id", ",", "$", "field_id", ",", "$", "field", ")", "{", "// Check that we have a field id", "if", "(", "empty", "(", "$", "field_id", ")", ")", "{", "return", ";", "}", "// Ignore parameter when not an array", "if", "(", "!", "is_array", "(", "$", "field", ")", ")", "{", "$", "field", "=", "array", "(", ")", ";", "}", "$", "did_lock", "=", "false", ";", "$", "exception", "=", "null", ";", "try", "{", "// Check if table exists", "$", "table_name", "=", "'tbl_entries_data_'", ".", "General", "::", "intval", "(", "$", "field_id", ")", ";", "if", "(", "!", "Symphony", "::", "Database", "(", ")", "->", "tableExists", "(", "$", "table_name", ")", ")", "{", "return", ";", "}", "// Lock the table for write", "$", "did_lock", "=", "Symphony", "::", "Database", "(", ")", "->", "query", "(", "\"LOCK TABLES `$table_name` WRITE\"", ")", ";", "// Delete old data", "Symphony", "::", "Database", "(", ")", "->", "delete", "(", "$", "table_name", ",", "sprintf", "(", "\"\n `entry_id` = %d\"", ",", "$", "entry_id", ")", ")", ";", "// Insert new data", "$", "data", "=", "array", "(", "'entry_id'", "=>", "$", "entry_id", ")", ";", "$", "fields", "=", "array", "(", ")", ";", "foreach", "(", "$", "field", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "foreach", "(", "$", "value", "as", "$", "ii", "=>", "$", "v", ")", "{", "$", "fields", "[", "$", "ii", "]", "[", "$", "key", "]", "=", "$", "v", ";", "}", "}", "else", "{", "$", "fields", "[", "max", "(", "0", ",", "count", "(", "$", "fields", ")", "-", "1", ")", "]", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}", "foreach", "(", "$", "fields", "as", "$", "index", "=>", "$", "field_data", ")", "{", "$", "fields", "[", "$", "index", "]", "=", "array_merge", "(", "$", "data", ",", "$", "field_data", ")", ";", "}", "// Insert only if we have field data", "if", "(", "!", "empty", "(", "$", "fields", ")", ")", "{", "Symphony", "::", "Database", "(", ")", "->", "insert", "(", "$", "fields", ",", "$", "table_name", ")", ";", "}", "}", "catch", "(", "Exception", "$", "ex", ")", "{", "$", "exception", "=", "$", "ex", ";", "Symphony", "::", "Log", "(", ")", "->", "pushExceptionToLog", "(", "$", "ex", ",", "true", ")", ";", "}", "if", "(", "$", "did_lock", ")", "{", "Symphony", "::", "Database", "(", ")", "->", "query", "(", "'UNLOCK TABLES'", ")", ";", "}", "if", "(", "$", "exception", ")", "{", "throw", "$", "exception", ";", "}", "}" ]
Executes the SQL queries need to save a field's data for the specified entry id. It first locks the table for writes, it then deletes existing data and then it inserts a new row for the data. Errors are discarded and the lock is released, if it was acquired. @param int $entry_id The entry id to save the data for @param int $field_id The field id to save the data for @param array $field The field data to save
[ "Executes", "the", "SQL", "queries", "need", "to", "save", "a", "field", "s", "data", "for", "the", "specified", "entry", "id", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.entrymanager.php#L111-L178
symphonycms/symphony-2
symphony/lib/toolkit/class.entrymanager.php
EntryManager.add
public static function add(Entry $entry) { $fields = $entry->get(); Symphony::Database()->insert($fields, 'tbl_entries'); if (!$entry_id = Symphony::Database()->getInsertID()) { return false; } // Iterate over all data for this entry foreach ($entry->getData() as $field_id => $field) { // Write data static::saveFieldData($entry_id, $field_id, $field); } $entry->set('id', $entry_id); return true; }
php
public static function add(Entry $entry) { $fields = $entry->get(); Symphony::Database()->insert($fields, 'tbl_entries'); if (!$entry_id = Symphony::Database()->getInsertID()) { return false; } // Iterate over all data for this entry foreach ($entry->getData() as $field_id => $field) { // Write data static::saveFieldData($entry_id, $field_id, $field); } $entry->set('id', $entry_id); return true; }
[ "public", "static", "function", "add", "(", "Entry", "$", "entry", ")", "{", "$", "fields", "=", "$", "entry", "->", "get", "(", ")", ";", "Symphony", "::", "Database", "(", ")", "->", "insert", "(", "$", "fields", ",", "'tbl_entries'", ")", ";", "if", "(", "!", "$", "entry_id", "=", "Symphony", "::", "Database", "(", ")", "->", "getInsertID", "(", ")", ")", "{", "return", "false", ";", "}", "// Iterate over all data for this entry", "foreach", "(", "$", "entry", "->", "getData", "(", ")", "as", "$", "field_id", "=>", "$", "field", ")", "{", "// Write data", "static", "::", "saveFieldData", "(", "$", "entry_id", ",", "$", "field_id", ",", "$", "field", ")", ";", "}", "$", "entry", "->", "set", "(", "'id'", ",", "$", "entry_id", ")", ";", "return", "true", ";", "}" ]
Given an Entry object, iterate over all of the fields in that object an insert them into their relevant entry tables. @see EntryManager::saveFieldData() @param Entry $entry An Entry object to insert into the database @throws DatabaseException @return boolean
[ "Given", "an", "Entry", "object", "iterate", "over", "all", "of", "the", "fields", "in", "that", "object", "an", "insert", "them", "into", "their", "relevant", "entry", "tables", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.entrymanager.php#L190-L208
symphonycms/symphony-2
symphony/lib/toolkit/class.entrymanager.php
EntryManager.edit
public static function edit(Entry $entry) { // Update modification date and modification author. Symphony::Database()->update( array( 'modification_author_id' => $entry->get('modification_author_id'), 'modification_date' => $entry->get('modification_date'), 'modification_date_gmt' => $entry->get('modification_date_gmt') ), 'tbl_entries', sprintf(' `id` = %d', (int)$entry->get('id')) ); // Iterate over all data for this entry foreach ($entry->getData() as $field_id => $field) { // Write data static::saveFieldData($entry->get('id'), $field_id, $field); } return true; }
php
public static function edit(Entry $entry) { // Update modification date and modification author. Symphony::Database()->update( array( 'modification_author_id' => $entry->get('modification_author_id'), 'modification_date' => $entry->get('modification_date'), 'modification_date_gmt' => $entry->get('modification_date_gmt') ), 'tbl_entries', sprintf(' `id` = %d', (int)$entry->get('id')) ); // Iterate over all data for this entry foreach ($entry->getData() as $field_id => $field) { // Write data static::saveFieldData($entry->get('id'), $field_id, $field); } return true; }
[ "public", "static", "function", "edit", "(", "Entry", "$", "entry", ")", "{", "// Update modification date and modification author.", "Symphony", "::", "Database", "(", ")", "->", "update", "(", "array", "(", "'modification_author_id'", "=>", "$", "entry", "->", "get", "(", "'modification_author_id'", ")", ",", "'modification_date'", "=>", "$", "entry", "->", "get", "(", "'modification_date'", ")", ",", "'modification_date_gmt'", "=>", "$", "entry", "->", "get", "(", "'modification_date_gmt'", ")", ")", ",", "'tbl_entries'", ",", "sprintf", "(", "' `id` = %d'", ",", "(", "int", ")", "$", "entry", "->", "get", "(", "'id'", ")", ")", ")", ";", "// Iterate over all data for this entry", "foreach", "(", "$", "entry", "->", "getData", "(", ")", "as", "$", "field_id", "=>", "$", "field", ")", "{", "// Write data", "static", "::", "saveFieldData", "(", "$", "entry", "->", "get", "(", "'id'", ")", ",", "$", "field_id", ",", "$", "field", ")", ";", "}", "return", "true", ";", "}" ]
Update an existing Entry object given an Entry object @see EntryManager::saveFieldData() @param Entry $entry An Entry object @throws DatabaseException @return boolean
[ "Update", "an", "existing", "Entry", "object", "given", "an", "Entry", "object" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.entrymanager.php#L219-L239
symphonycms/symphony-2
symphony/lib/toolkit/class.entrymanager.php
EntryManager.delete
public static function delete($entries, $section_id = null) { $needs_data = true; if (!is_array($entries)) { $entries = array($entries); } // Get the section's schema if (!is_null($section_id)) { $section = SectionManager::fetch($section_id); if ($section instanceof Section) { $fields = $section->fetchFields(); $data = array(); foreach ($fields as $field) { $reflection = new ReflectionClass($field); // This field overrides the default implementation, so pass it data. $data[$field->get('element_name')] = $reflection->getMethod('entryDataCleanup')->class == 'Field' ? false : true; } $data = array_filter($data); if (empty($data)) { $needs_data = false; } } } // We'll split $entries into blocks of 2500 (random number) // and process the deletion in chunks. $chunks = array_chunk($entries, 2500); foreach ($chunks as $chunk) { $entry_list = implode("', '", $chunk); // If we weren't given a `section_id` we'll have to process individually // If we don't need data for any field, we can process the whole chunk // without building Entry objects, otherwise we'll need to build // Entry objects with data if (is_null($section_id) || !$needs_data) { $entries = $chunk; } elseif ($needs_data) { $entries = self::fetch($chunk, $section_id); } if ($needs_data) { foreach ($entries as $id) { // Handles the case where `section_id` was not provided if (is_null($section_id)) { $e = self::fetch($id); if (!is_array($e)) { continue; } $e = current($e); if (!$e instanceof Entry) { continue; } // If we needed data, whole Entry objects will exist } elseif ($needs_data) { $e = $id; $id = $e->get('id'); } // Time to loop over it and send it to the fields. // Note we can't rely on the `$fields` array as we may // also be dealing with the case where `section_id` hasn't // been provided $entry_data = $e->getData(); foreach ($entry_data as $field_id => $data) { $field = FieldManager::fetch($field_id); $field->entryDataCleanup($id, $data); } } } else { foreach ($fields as $field) { $field->entryDataCleanup($chunk); } } Symphony::Database()->delete('tbl_entries', " `id` IN ('$entry_list') "); } return true; }
php
public static function delete($entries, $section_id = null) { $needs_data = true; if (!is_array($entries)) { $entries = array($entries); } // Get the section's schema if (!is_null($section_id)) { $section = SectionManager::fetch($section_id); if ($section instanceof Section) { $fields = $section->fetchFields(); $data = array(); foreach ($fields as $field) { $reflection = new ReflectionClass($field); // This field overrides the default implementation, so pass it data. $data[$field->get('element_name')] = $reflection->getMethod('entryDataCleanup')->class == 'Field' ? false : true; } $data = array_filter($data); if (empty($data)) { $needs_data = false; } } } // We'll split $entries into blocks of 2500 (random number) // and process the deletion in chunks. $chunks = array_chunk($entries, 2500); foreach ($chunks as $chunk) { $entry_list = implode("', '", $chunk); // If we weren't given a `section_id` we'll have to process individually // If we don't need data for any field, we can process the whole chunk // without building Entry objects, otherwise we'll need to build // Entry objects with data if (is_null($section_id) || !$needs_data) { $entries = $chunk; } elseif ($needs_data) { $entries = self::fetch($chunk, $section_id); } if ($needs_data) { foreach ($entries as $id) { // Handles the case where `section_id` was not provided if (is_null($section_id)) { $e = self::fetch($id); if (!is_array($e)) { continue; } $e = current($e); if (!$e instanceof Entry) { continue; } // If we needed data, whole Entry objects will exist } elseif ($needs_data) { $e = $id; $id = $e->get('id'); } // Time to loop over it and send it to the fields. // Note we can't rely on the `$fields` array as we may // also be dealing with the case where `section_id` hasn't // been provided $entry_data = $e->getData(); foreach ($entry_data as $field_id => $data) { $field = FieldManager::fetch($field_id); $field->entryDataCleanup($id, $data); } } } else { foreach ($fields as $field) { $field->entryDataCleanup($chunk); } } Symphony::Database()->delete('tbl_entries', " `id` IN ('$entry_list') "); } return true; }
[ "public", "static", "function", "delete", "(", "$", "entries", ",", "$", "section_id", "=", "null", ")", "{", "$", "needs_data", "=", "true", ";", "if", "(", "!", "is_array", "(", "$", "entries", ")", ")", "{", "$", "entries", "=", "array", "(", "$", "entries", ")", ";", "}", "// Get the section's schema", "if", "(", "!", "is_null", "(", "$", "section_id", ")", ")", "{", "$", "section", "=", "SectionManager", "::", "fetch", "(", "$", "section_id", ")", ";", "if", "(", "$", "section", "instanceof", "Section", ")", "{", "$", "fields", "=", "$", "section", "->", "fetchFields", "(", ")", ";", "$", "data", "=", "array", "(", ")", ";", "foreach", "(", "$", "fields", "as", "$", "field", ")", "{", "$", "reflection", "=", "new", "ReflectionClass", "(", "$", "field", ")", ";", "// This field overrides the default implementation, so pass it data.", "$", "data", "[", "$", "field", "->", "get", "(", "'element_name'", ")", "]", "=", "$", "reflection", "->", "getMethod", "(", "'entryDataCleanup'", ")", "->", "class", "==", "'Field'", "?", "false", ":", "true", ";", "}", "$", "data", "=", "array_filter", "(", "$", "data", ")", ";", "if", "(", "empty", "(", "$", "data", ")", ")", "{", "$", "needs_data", "=", "false", ";", "}", "}", "}", "// We'll split $entries into blocks of 2500 (random number)", "// and process the deletion in chunks.", "$", "chunks", "=", "array_chunk", "(", "$", "entries", ",", "2500", ")", ";", "foreach", "(", "$", "chunks", "as", "$", "chunk", ")", "{", "$", "entry_list", "=", "implode", "(", "\"', '\"", ",", "$", "chunk", ")", ";", "// If we weren't given a `section_id` we'll have to process individually", "// If we don't need data for any field, we can process the whole chunk", "// without building Entry objects, otherwise we'll need to build", "// Entry objects with data", "if", "(", "is_null", "(", "$", "section_id", ")", "||", "!", "$", "needs_data", ")", "{", "$", "entries", "=", "$", "chunk", ";", "}", "elseif", "(", "$", "needs_data", ")", "{", "$", "entries", "=", "self", "::", "fetch", "(", "$", "chunk", ",", "$", "section_id", ")", ";", "}", "if", "(", "$", "needs_data", ")", "{", "foreach", "(", "$", "entries", "as", "$", "id", ")", "{", "// Handles the case where `section_id` was not provided", "if", "(", "is_null", "(", "$", "section_id", ")", ")", "{", "$", "e", "=", "self", "::", "fetch", "(", "$", "id", ")", ";", "if", "(", "!", "is_array", "(", "$", "e", ")", ")", "{", "continue", ";", "}", "$", "e", "=", "current", "(", "$", "e", ")", ";", "if", "(", "!", "$", "e", "instanceof", "Entry", ")", "{", "continue", ";", "}", "// If we needed data, whole Entry objects will exist", "}", "elseif", "(", "$", "needs_data", ")", "{", "$", "e", "=", "$", "id", ";", "$", "id", "=", "$", "e", "->", "get", "(", "'id'", ")", ";", "}", "// Time to loop over it and send it to the fields.", "// Note we can't rely on the `$fields` array as we may", "// also be dealing with the case where `section_id` hasn't", "// been provided", "$", "entry_data", "=", "$", "e", "->", "getData", "(", ")", ";", "foreach", "(", "$", "entry_data", "as", "$", "field_id", "=>", "$", "data", ")", "{", "$", "field", "=", "FieldManager", "::", "fetch", "(", "$", "field_id", ")", ";", "$", "field", "->", "entryDataCleanup", "(", "$", "id", ",", "$", "data", ")", ";", "}", "}", "}", "else", "{", "foreach", "(", "$", "fields", "as", "$", "field", ")", "{", "$", "field", "->", "entryDataCleanup", "(", "$", "chunk", ")", ";", "}", "}", "Symphony", "::", "Database", "(", ")", "->", "delete", "(", "'tbl_entries'", ",", "\" `id` IN ('$entry_list') \"", ")", ";", "}", "return", "true", ";", "}" ]
Given an Entry ID, or an array of Entry ID's, delete all data associated with this Entry using a Field's `entryDataCleanup()` function, and then remove this Entry from `tbl_entries`. If the `$entries` all belong to the same section, passing `$section_id` will improve performance @param array|integer $entries An entry_id, or an array of entry id's to delete @param integer $section_id (optional) If possible, the `$section_id` of the the `$entries`. This parameter should be left as null if the `$entries` array contains entry_id's for multiple sections. @throws DatabaseException @throws Exception @return boolean
[ "Given", "an", "Entry", "ID", "or", "an", "array", "of", "Entry", "ID", "s", "delete", "all", "data", "associated", "with", "this", "Entry", "using", "a", "Field", "s", "entryDataCleanup", "()", "function", "and", "then", "remove", "this", "Entry", "from", "tbl_entries", ".", "If", "the", "$entries", "all", "belong", "to", "the", "same", "section", "passing", "$section_id", "will", "improve", "performance" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.entrymanager.php#L258-L348
symphonycms/symphony-2
symphony/lib/toolkit/class.entrymanager.php
EntryManager.fetch
public static function fetch($entry_id = null, $section_id = null, $limit = null, $start = null, $where = null, $joins = null, $group = false, $buildentries = true, $element_names = null, $enable_sort = true) { $sort = null; $sortSelectClause = null; if (!$entry_id && !$section_id) { return array(); } if (!$section_id) { $section_id = self::fetchEntrySectionID($entry_id); } $section = SectionManager::fetch($section_id); if (!is_object($section)) { return array(); } // SORTING // A single $entry_id doesn't need to be sorted on, or if it's explicitly disabled if ((!is_array($entry_id) && General::intval($entry_id) > 0) || !$enable_sort) { $sort = null; // Check for RAND first, since this works independently of any specific field } elseif (self::$_fetchSortDirection == 'RAND') { $sort = 'ORDER BY RAND() '; // Handle Creation Date or the old Date sorting } elseif (self::$_fetchSortField === 'system:creation-date' || self::$_fetchSortField === 'date') { $sort = sprintf('ORDER BY `e`.`creation_date` %s', self::$_fetchSortDirection); // Handle Modification Date sorting } elseif (self::$_fetchSortField === 'system:modification-date') { $sort = sprintf('ORDER BY `e`.`modification_date` %s', self::$_fetchSortDirection); // Handle sorting for System ID } elseif (self::$_fetchSortField == 'system:id' || self::$_fetchSortField == 'id') { $sort = sprintf('ORDER BY `e`.`id` %s', self::$_fetchSortDirection); // Handle when the sort field is an actual Field } elseif (self::$_fetchSortField && $field = FieldManager::fetch(self::$_fetchSortField)) { if ($field->isSortable()) { $field->buildSortingSQL($joins, $where, $sort, self::$_fetchSortDirection); $sortSelectClause = $field->buildSortingSelectSQL($sort, self::$_fetchSortDirection); } // Handle if the section has a default sorting field } elseif ($section->getSortingField() && $field = FieldManager::fetch($section->getSortingField())) { if ($field->isSortable()) { $field->buildSortingSQL($joins, $where, $sort, $section->getSortingOrder()); $sortSelectClause = $field->buildSortingSelectSQL($sort, $section->getSortingOrder()); } // No sort specified, so just sort on system id } else { $sort = sprintf('ORDER BY `e`.`id` %s', self::$_fetchSortDirection); } if ($field && !$group) { $group = $field->requiresSQLGrouping(); } if ($entry_id && !is_array($entry_id)) { // The entry ID may be a comma-separated string, so explode it to make it // a proper array $entry_id = explode(',', $entry_id); } // An existing entry ID will be an array now, and we can force integer values if ($entry_id) { $entry_id = array_map(array('General', 'intval'), $entry_id); } $sql = sprintf(" SELECT %s`e`.`id`, `e`.section_id, `e`.`author_id`, `e`.`modification_author_id`, `e`.`creation_date` AS `creation_date`, `e`.`modification_date` AS `modification_date` %s FROM `tbl_entries` AS `e` %s WHERE 1 %s %s %s %s %s ", $group ? 'DISTINCT ' : '', $sortSelectClause ? ', ' . $sortSelectClause : '', $joins, $entry_id ? "AND `e`.`id` IN ('".implode("', '", $entry_id)."') " : '', $section_id ? sprintf("AND `e`.`section_id` = %d", $section_id) : '', $where, $sort, $limit ? sprintf('LIMIT %d, %d', $start, $limit) : '' ); $rows = Symphony::Database()->fetch($sql); // Create UNIX timestamps, as it has always been (Re: #2501) foreach ($rows as &$entry) { $entry['creation_date'] = DateTimeObj::get('U', $entry['creation_date']); $entry['modification_date'] = DateTimeObj::get('U', $entry['modification_date']); } unset($entry); return ($buildentries && (is_array($rows) && !empty($rows)) ? self::__buildEntries($rows, $section_id, $element_names) : $rows); }
php
public static function fetch($entry_id = null, $section_id = null, $limit = null, $start = null, $where = null, $joins = null, $group = false, $buildentries = true, $element_names = null, $enable_sort = true) { $sort = null; $sortSelectClause = null; if (!$entry_id && !$section_id) { return array(); } if (!$section_id) { $section_id = self::fetchEntrySectionID($entry_id); } $section = SectionManager::fetch($section_id); if (!is_object($section)) { return array(); } // SORTING // A single $entry_id doesn't need to be sorted on, or if it's explicitly disabled if ((!is_array($entry_id) && General::intval($entry_id) > 0) || !$enable_sort) { $sort = null; // Check for RAND first, since this works independently of any specific field } elseif (self::$_fetchSortDirection == 'RAND') { $sort = 'ORDER BY RAND() '; // Handle Creation Date or the old Date sorting } elseif (self::$_fetchSortField === 'system:creation-date' || self::$_fetchSortField === 'date') { $sort = sprintf('ORDER BY `e`.`creation_date` %s', self::$_fetchSortDirection); // Handle Modification Date sorting } elseif (self::$_fetchSortField === 'system:modification-date') { $sort = sprintf('ORDER BY `e`.`modification_date` %s', self::$_fetchSortDirection); // Handle sorting for System ID } elseif (self::$_fetchSortField == 'system:id' || self::$_fetchSortField == 'id') { $sort = sprintf('ORDER BY `e`.`id` %s', self::$_fetchSortDirection); // Handle when the sort field is an actual Field } elseif (self::$_fetchSortField && $field = FieldManager::fetch(self::$_fetchSortField)) { if ($field->isSortable()) { $field->buildSortingSQL($joins, $where, $sort, self::$_fetchSortDirection); $sortSelectClause = $field->buildSortingSelectSQL($sort, self::$_fetchSortDirection); } // Handle if the section has a default sorting field } elseif ($section->getSortingField() && $field = FieldManager::fetch($section->getSortingField())) { if ($field->isSortable()) { $field->buildSortingSQL($joins, $where, $sort, $section->getSortingOrder()); $sortSelectClause = $field->buildSortingSelectSQL($sort, $section->getSortingOrder()); } // No sort specified, so just sort on system id } else { $sort = sprintf('ORDER BY `e`.`id` %s', self::$_fetchSortDirection); } if ($field && !$group) { $group = $field->requiresSQLGrouping(); } if ($entry_id && !is_array($entry_id)) { // The entry ID may be a comma-separated string, so explode it to make it // a proper array $entry_id = explode(',', $entry_id); } // An existing entry ID will be an array now, and we can force integer values if ($entry_id) { $entry_id = array_map(array('General', 'intval'), $entry_id); } $sql = sprintf(" SELECT %s`e`.`id`, `e`.section_id, `e`.`author_id`, `e`.`modification_author_id`, `e`.`creation_date` AS `creation_date`, `e`.`modification_date` AS `modification_date` %s FROM `tbl_entries` AS `e` %s WHERE 1 %s %s %s %s %s ", $group ? 'DISTINCT ' : '', $sortSelectClause ? ', ' . $sortSelectClause : '', $joins, $entry_id ? "AND `e`.`id` IN ('".implode("', '", $entry_id)."') " : '', $section_id ? sprintf("AND `e`.`section_id` = %d", $section_id) : '', $where, $sort, $limit ? sprintf('LIMIT %d, %d', $start, $limit) : '' ); $rows = Symphony::Database()->fetch($sql); // Create UNIX timestamps, as it has always been (Re: #2501) foreach ($rows as &$entry) { $entry['creation_date'] = DateTimeObj::get('U', $entry['creation_date']); $entry['modification_date'] = DateTimeObj::get('U', $entry['modification_date']); } unset($entry); return ($buildentries && (is_array($rows) && !empty($rows)) ? self::__buildEntries($rows, $section_id, $element_names) : $rows); }
[ "public", "static", "function", "fetch", "(", "$", "entry_id", "=", "null", ",", "$", "section_id", "=", "null", ",", "$", "limit", "=", "null", ",", "$", "start", "=", "null", ",", "$", "where", "=", "null", ",", "$", "joins", "=", "null", ",", "$", "group", "=", "false", ",", "$", "buildentries", "=", "true", ",", "$", "element_names", "=", "null", ",", "$", "enable_sort", "=", "true", ")", "{", "$", "sort", "=", "null", ";", "$", "sortSelectClause", "=", "null", ";", "if", "(", "!", "$", "entry_id", "&&", "!", "$", "section_id", ")", "{", "return", "array", "(", ")", ";", "}", "if", "(", "!", "$", "section_id", ")", "{", "$", "section_id", "=", "self", "::", "fetchEntrySectionID", "(", "$", "entry_id", ")", ";", "}", "$", "section", "=", "SectionManager", "::", "fetch", "(", "$", "section_id", ")", ";", "if", "(", "!", "is_object", "(", "$", "section", ")", ")", "{", "return", "array", "(", ")", ";", "}", "// SORTING", "// A single $entry_id doesn't need to be sorted on, or if it's explicitly disabled", "if", "(", "(", "!", "is_array", "(", "$", "entry_id", ")", "&&", "General", "::", "intval", "(", "$", "entry_id", ")", ">", "0", ")", "||", "!", "$", "enable_sort", ")", "{", "$", "sort", "=", "null", ";", "// Check for RAND first, since this works independently of any specific field", "}", "elseif", "(", "self", "::", "$", "_fetchSortDirection", "==", "'RAND'", ")", "{", "$", "sort", "=", "'ORDER BY RAND() '", ";", "// Handle Creation Date or the old Date sorting", "}", "elseif", "(", "self", "::", "$", "_fetchSortField", "===", "'system:creation-date'", "||", "self", "::", "$", "_fetchSortField", "===", "'date'", ")", "{", "$", "sort", "=", "sprintf", "(", "'ORDER BY `e`.`creation_date` %s'", ",", "self", "::", "$", "_fetchSortDirection", ")", ";", "// Handle Modification Date sorting", "}", "elseif", "(", "self", "::", "$", "_fetchSortField", "===", "'system:modification-date'", ")", "{", "$", "sort", "=", "sprintf", "(", "'ORDER BY `e`.`modification_date` %s'", ",", "self", "::", "$", "_fetchSortDirection", ")", ";", "// Handle sorting for System ID", "}", "elseif", "(", "self", "::", "$", "_fetchSortField", "==", "'system:id'", "||", "self", "::", "$", "_fetchSortField", "==", "'id'", ")", "{", "$", "sort", "=", "sprintf", "(", "'ORDER BY `e`.`id` %s'", ",", "self", "::", "$", "_fetchSortDirection", ")", ";", "// Handle when the sort field is an actual Field", "}", "elseif", "(", "self", "::", "$", "_fetchSortField", "&&", "$", "field", "=", "FieldManager", "::", "fetch", "(", "self", "::", "$", "_fetchSortField", ")", ")", "{", "if", "(", "$", "field", "->", "isSortable", "(", ")", ")", "{", "$", "field", "->", "buildSortingSQL", "(", "$", "joins", ",", "$", "where", ",", "$", "sort", ",", "self", "::", "$", "_fetchSortDirection", ")", ";", "$", "sortSelectClause", "=", "$", "field", "->", "buildSortingSelectSQL", "(", "$", "sort", ",", "self", "::", "$", "_fetchSortDirection", ")", ";", "}", "// Handle if the section has a default sorting field", "}", "elseif", "(", "$", "section", "->", "getSortingField", "(", ")", "&&", "$", "field", "=", "FieldManager", "::", "fetch", "(", "$", "section", "->", "getSortingField", "(", ")", ")", ")", "{", "if", "(", "$", "field", "->", "isSortable", "(", ")", ")", "{", "$", "field", "->", "buildSortingSQL", "(", "$", "joins", ",", "$", "where", ",", "$", "sort", ",", "$", "section", "->", "getSortingOrder", "(", ")", ")", ";", "$", "sortSelectClause", "=", "$", "field", "->", "buildSortingSelectSQL", "(", "$", "sort", ",", "$", "section", "->", "getSortingOrder", "(", ")", ")", ";", "}", "// No sort specified, so just sort on system id", "}", "else", "{", "$", "sort", "=", "sprintf", "(", "'ORDER BY `e`.`id` %s'", ",", "self", "::", "$", "_fetchSortDirection", ")", ";", "}", "if", "(", "$", "field", "&&", "!", "$", "group", ")", "{", "$", "group", "=", "$", "field", "->", "requiresSQLGrouping", "(", ")", ";", "}", "if", "(", "$", "entry_id", "&&", "!", "is_array", "(", "$", "entry_id", ")", ")", "{", "// The entry ID may be a comma-separated string, so explode it to make it", "// a proper array", "$", "entry_id", "=", "explode", "(", "','", ",", "$", "entry_id", ")", ";", "}", "// An existing entry ID will be an array now, and we can force integer values", "if", "(", "$", "entry_id", ")", "{", "$", "entry_id", "=", "array_map", "(", "array", "(", "'General'", ",", "'intval'", ")", ",", "$", "entry_id", ")", ";", "}", "$", "sql", "=", "sprintf", "(", "\"\n SELECT %s`e`.`id`, `e`.section_id,\n `e`.`author_id`, `e`.`modification_author_id`,\n `e`.`creation_date` AS `creation_date`,\n `e`.`modification_date` AS `modification_date`\n %s\n FROM `tbl_entries` AS `e`\n %s\n WHERE 1\n %s\n %s\n %s\n %s\n %s\n \"", ",", "$", "group", "?", "'DISTINCT '", ":", "''", ",", "$", "sortSelectClause", "?", "', '", ".", "$", "sortSelectClause", ":", "''", ",", "$", "joins", ",", "$", "entry_id", "?", "\"AND `e`.`id` IN ('\"", ".", "implode", "(", "\"', '\"", ",", "$", "entry_id", ")", ".", "\"') \"", ":", "''", ",", "$", "section_id", "?", "sprintf", "(", "\"AND `e`.`section_id` = %d\"", ",", "$", "section_id", ")", ":", "''", ",", "$", "where", ",", "$", "sort", ",", "$", "limit", "?", "sprintf", "(", "'LIMIT %d, %d'", ",", "$", "start", ",", "$", "limit", ")", ":", "''", ")", ";", "$", "rows", "=", "Symphony", "::", "Database", "(", ")", "->", "fetch", "(", "$", "sql", ")", ";", "// Create UNIX timestamps, as it has always been (Re: #2501)", "foreach", "(", "$", "rows", "as", "&", "$", "entry", ")", "{", "$", "entry", "[", "'creation_date'", "]", "=", "DateTimeObj", "::", "get", "(", "'U'", ",", "$", "entry", "[", "'creation_date'", "]", ")", ";", "$", "entry", "[", "'modification_date'", "]", "=", "DateTimeObj", "::", "get", "(", "'U'", ",", "$", "entry", "[", "'modification_date'", "]", ")", ";", "}", "unset", "(", "$", "entry", ")", ";", "return", "(", "$", "buildentries", "&&", "(", "is_array", "(", "$", "rows", ")", "&&", "!", "empty", "(", "$", "rows", ")", ")", "?", "self", "::", "__buildEntries", "(", "$", "rows", ",", "$", "section_id", ",", "$", "element_names", ")", ":", "$", "rows", ")", ";", "}" ]
This function will return an array of Entry objects given an ID or an array of ID's. Do not provide `$entry_id` as an array if not specifying the `$section_id`. This function is commonly passed custom SQL statements through the `$where` and `$join` parameters that is generated by the fields of this section. @since Symphony 2.7.0 it will also call a new method on fields, `buildSortingSelectSQL()`, to make sure fields can add ordering columns in the SELECT clause. This is required on MySQL 5.7+ strict mode. @param integer|array $entry_id An array of Entry ID's or an Entry ID to return @param integer $section_id The ID of the Section that these entries are contained in @param integer $limit The limit of entries to return @param integer $start The starting offset of the entries to return @param string $where Any custom WHERE clauses. The tbl_entries alias is `e` @param string $joins Any custom JOIN's @param boolean $group Whether the entries need to be grouped by Entry ID or not @param boolean $buildentries Whether to return an array of entry ID's or Entry objects. Defaults to true, which will return Entry objects @param array $element_names Choose whether to get data from a subset of fields or all fields in a section, by providing an array of field names. Defaults to null, which will load data from all fields in a section. @param boolean $enable_sort Defaults to true, if false this function will not apply any sorting @throws Exception @return array If `$buildentries` is true, this function will return an array of Entry objects, otherwise it will return an associative array of Entry data from `tbl_entries`
[ "This", "function", "will", "return", "an", "array", "of", "Entry", "objects", "given", "an", "ID", "or", "an", "array", "of", "ID", "s", ".", "Do", "not", "provide", "$entry_id", "as", "an", "array", "if", "not", "specifying", "the", "$section_id", ".", "This", "function", "is", "commonly", "passed", "custom", "SQL", "statements", "through", "the", "$where", "and", "$join", "parameters", "that", "is", "generated", "by", "the", "fields", "of", "this", "section", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.entrymanager.php#L388-L496
symphonycms/symphony-2
symphony/lib/toolkit/class.entrymanager.php
EntryManager.__buildEntries
public static function __buildEntries(array $rows, $section_id, $element_names = null) { $entries = array(); if (empty($rows)) { return $entries; } $schema = FieldManager::fetchFieldIDFromElementName($element_names, $section_id); if (is_int($schema)) { $schema = array($schema); } $raw = array(); $rows_string = ''; // Append meta data: foreach ($rows as $entry) { $raw[$entry['id']]['meta'] = $entry; $rows_string .= $entry['id'] . ','; } $rows_string = trim($rows_string, ','); // Append field data: if (is_array($schema)) { foreach ($schema as $field_id) { try { $row = Symphony::Database()->fetch("SELECT * FROM `tbl_entries_data_{$field_id}` WHERE `entry_id` IN ($rows_string) ORDER BY `id` ASC"); } catch (Exception $e) { // No data due to error continue; } if (!is_array($row) || empty($row)) { continue; } foreach ($row as $r) { $entry_id = $r['entry_id']; unset($r['id']); unset($r['entry_id']); if (!isset($raw[$entry_id]['fields'][$field_id])) { $raw[$entry_id]['fields'][$field_id] = $r; } else { foreach (array_keys($r) as $key) { // If this field already has been set, we need to take the existing // value and make it array, adding the current value to it as well // There is a special check incase the the field's value has been // purposely set to null in the database. if ( ( isset($raw[$entry_id]['fields'][$field_id][$key]) || is_null($raw[$entry_id]['fields'][$field_id][$key]) ) && !is_array($raw[$entry_id]['fields'][$field_id][$key]) ) { $raw[$entry_id]['fields'][$field_id][$key] = array( $raw[$entry_id]['fields'][$field_id][$key], $r[$key] ); // This key/value hasn't been set previously, so set it } elseif (!isset($raw[$entry_id]['fields'][$field_id][$key])) { $raw[$entry_id]['fields'][$field_id] = array($r[$key]); // This key has been set and it's an array, so just append // this value onto the array } else { $raw[$entry_id]['fields'][$field_id][$key][] = $r[$key]; } } } } } } // Loop over the array of entry data and convert it to an array of Entry objects foreach ($raw as $entry) { $obj = self::create(); $obj->set('id', $entry['meta']['id']); $obj->set('author_id', $entry['meta']['author_id']); $obj->set('modification_author_id', $entry['meta']['modification_author_id']); $obj->set('section_id', $entry['meta']['section_id']); $obj->set('creation_date', DateTimeObj::get('c', $entry['meta']['creation_date'])); if (isset($entry['meta']['modification_date'])) { $obj->set('modification_date', DateTimeObj::get('c', $entry['meta']['modification_date'])); } else { $obj->set('modification_date', $obj->get('creation_date')); } $obj->creationDate = $obj->get('creation_date'); if (isset($entry['fields']) && is_array($entry['fields'])) { foreach ($entry['fields'] as $field_id => $data) { $obj->setData($field_id, $data); } } $entries[] = $obj; } return $entries; }
php
public static function __buildEntries(array $rows, $section_id, $element_names = null) { $entries = array(); if (empty($rows)) { return $entries; } $schema = FieldManager::fetchFieldIDFromElementName($element_names, $section_id); if (is_int($schema)) { $schema = array($schema); } $raw = array(); $rows_string = ''; // Append meta data: foreach ($rows as $entry) { $raw[$entry['id']]['meta'] = $entry; $rows_string .= $entry['id'] . ','; } $rows_string = trim($rows_string, ','); // Append field data: if (is_array($schema)) { foreach ($schema as $field_id) { try { $row = Symphony::Database()->fetch("SELECT * FROM `tbl_entries_data_{$field_id}` WHERE `entry_id` IN ($rows_string) ORDER BY `id` ASC"); } catch (Exception $e) { // No data due to error continue; } if (!is_array($row) || empty($row)) { continue; } foreach ($row as $r) { $entry_id = $r['entry_id']; unset($r['id']); unset($r['entry_id']); if (!isset($raw[$entry_id]['fields'][$field_id])) { $raw[$entry_id]['fields'][$field_id] = $r; } else { foreach (array_keys($r) as $key) { // If this field already has been set, we need to take the existing // value and make it array, adding the current value to it as well // There is a special check incase the the field's value has been // purposely set to null in the database. if ( ( isset($raw[$entry_id]['fields'][$field_id][$key]) || is_null($raw[$entry_id]['fields'][$field_id][$key]) ) && !is_array($raw[$entry_id]['fields'][$field_id][$key]) ) { $raw[$entry_id]['fields'][$field_id][$key] = array( $raw[$entry_id]['fields'][$field_id][$key], $r[$key] ); // This key/value hasn't been set previously, so set it } elseif (!isset($raw[$entry_id]['fields'][$field_id][$key])) { $raw[$entry_id]['fields'][$field_id] = array($r[$key]); // This key has been set and it's an array, so just append // this value onto the array } else { $raw[$entry_id]['fields'][$field_id][$key][] = $r[$key]; } } } } } } // Loop over the array of entry data and convert it to an array of Entry objects foreach ($raw as $entry) { $obj = self::create(); $obj->set('id', $entry['meta']['id']); $obj->set('author_id', $entry['meta']['author_id']); $obj->set('modification_author_id', $entry['meta']['modification_author_id']); $obj->set('section_id', $entry['meta']['section_id']); $obj->set('creation_date', DateTimeObj::get('c', $entry['meta']['creation_date'])); if (isset($entry['meta']['modification_date'])) { $obj->set('modification_date', DateTimeObj::get('c', $entry['meta']['modification_date'])); } else { $obj->set('modification_date', $obj->get('creation_date')); } $obj->creationDate = $obj->get('creation_date'); if (isset($entry['fields']) && is_array($entry['fields'])) { foreach ($entry['fields'] as $field_id => $data) { $obj->setData($field_id, $data); } } $entries[] = $obj; } return $entries; }
[ "public", "static", "function", "__buildEntries", "(", "array", "$", "rows", ",", "$", "section_id", ",", "$", "element_names", "=", "null", ")", "{", "$", "entries", "=", "array", "(", ")", ";", "if", "(", "empty", "(", "$", "rows", ")", ")", "{", "return", "$", "entries", ";", "}", "$", "schema", "=", "FieldManager", "::", "fetchFieldIDFromElementName", "(", "$", "element_names", ",", "$", "section_id", ")", ";", "if", "(", "is_int", "(", "$", "schema", ")", ")", "{", "$", "schema", "=", "array", "(", "$", "schema", ")", ";", "}", "$", "raw", "=", "array", "(", ")", ";", "$", "rows_string", "=", "''", ";", "// Append meta data:", "foreach", "(", "$", "rows", "as", "$", "entry", ")", "{", "$", "raw", "[", "$", "entry", "[", "'id'", "]", "]", "[", "'meta'", "]", "=", "$", "entry", ";", "$", "rows_string", ".=", "$", "entry", "[", "'id'", "]", ".", "','", ";", "}", "$", "rows_string", "=", "trim", "(", "$", "rows_string", ",", "','", ")", ";", "// Append field data:", "if", "(", "is_array", "(", "$", "schema", ")", ")", "{", "foreach", "(", "$", "schema", "as", "$", "field_id", ")", "{", "try", "{", "$", "row", "=", "Symphony", "::", "Database", "(", ")", "->", "fetch", "(", "\"SELECT * FROM `tbl_entries_data_{$field_id}` WHERE `entry_id` IN ($rows_string) ORDER BY `id` ASC\"", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "// No data due to error", "continue", ";", "}", "if", "(", "!", "is_array", "(", "$", "row", ")", "||", "empty", "(", "$", "row", ")", ")", "{", "continue", ";", "}", "foreach", "(", "$", "row", "as", "$", "r", ")", "{", "$", "entry_id", "=", "$", "r", "[", "'entry_id'", "]", ";", "unset", "(", "$", "r", "[", "'id'", "]", ")", ";", "unset", "(", "$", "r", "[", "'entry_id'", "]", ")", ";", "if", "(", "!", "isset", "(", "$", "raw", "[", "$", "entry_id", "]", "[", "'fields'", "]", "[", "$", "field_id", "]", ")", ")", "{", "$", "raw", "[", "$", "entry_id", "]", "[", "'fields'", "]", "[", "$", "field_id", "]", "=", "$", "r", ";", "}", "else", "{", "foreach", "(", "array_keys", "(", "$", "r", ")", "as", "$", "key", ")", "{", "// If this field already has been set, we need to take the existing", "// value and make it array, adding the current value to it as well", "// There is a special check incase the the field's value has been", "// purposely set to null in the database.", "if", "(", "(", "isset", "(", "$", "raw", "[", "$", "entry_id", "]", "[", "'fields'", "]", "[", "$", "field_id", "]", "[", "$", "key", "]", ")", "||", "is_null", "(", "$", "raw", "[", "$", "entry_id", "]", "[", "'fields'", "]", "[", "$", "field_id", "]", "[", "$", "key", "]", ")", ")", "&&", "!", "is_array", "(", "$", "raw", "[", "$", "entry_id", "]", "[", "'fields'", "]", "[", "$", "field_id", "]", "[", "$", "key", "]", ")", ")", "{", "$", "raw", "[", "$", "entry_id", "]", "[", "'fields'", "]", "[", "$", "field_id", "]", "[", "$", "key", "]", "=", "array", "(", "$", "raw", "[", "$", "entry_id", "]", "[", "'fields'", "]", "[", "$", "field_id", "]", "[", "$", "key", "]", ",", "$", "r", "[", "$", "key", "]", ")", ";", "// This key/value hasn't been set previously, so set it", "}", "elseif", "(", "!", "isset", "(", "$", "raw", "[", "$", "entry_id", "]", "[", "'fields'", "]", "[", "$", "field_id", "]", "[", "$", "key", "]", ")", ")", "{", "$", "raw", "[", "$", "entry_id", "]", "[", "'fields'", "]", "[", "$", "field_id", "]", "=", "array", "(", "$", "r", "[", "$", "key", "]", ")", ";", "// This key has been set and it's an array, so just append", "// this value onto the array", "}", "else", "{", "$", "raw", "[", "$", "entry_id", "]", "[", "'fields'", "]", "[", "$", "field_id", "]", "[", "$", "key", "]", "[", "]", "=", "$", "r", "[", "$", "key", "]", ";", "}", "}", "}", "}", "}", "}", "// Loop over the array of entry data and convert it to an array of Entry objects", "foreach", "(", "$", "raw", "as", "$", "entry", ")", "{", "$", "obj", "=", "self", "::", "create", "(", ")", ";", "$", "obj", "->", "set", "(", "'id'", ",", "$", "entry", "[", "'meta'", "]", "[", "'id'", "]", ")", ";", "$", "obj", "->", "set", "(", "'author_id'", ",", "$", "entry", "[", "'meta'", "]", "[", "'author_id'", "]", ")", ";", "$", "obj", "->", "set", "(", "'modification_author_id'", ",", "$", "entry", "[", "'meta'", "]", "[", "'modification_author_id'", "]", ")", ";", "$", "obj", "->", "set", "(", "'section_id'", ",", "$", "entry", "[", "'meta'", "]", "[", "'section_id'", "]", ")", ";", "$", "obj", "->", "set", "(", "'creation_date'", ",", "DateTimeObj", "::", "get", "(", "'c'", ",", "$", "entry", "[", "'meta'", "]", "[", "'creation_date'", "]", ")", ")", ";", "if", "(", "isset", "(", "$", "entry", "[", "'meta'", "]", "[", "'modification_date'", "]", ")", ")", "{", "$", "obj", "->", "set", "(", "'modification_date'", ",", "DateTimeObj", "::", "get", "(", "'c'", ",", "$", "entry", "[", "'meta'", "]", "[", "'modification_date'", "]", ")", ")", ";", "}", "else", "{", "$", "obj", "->", "set", "(", "'modification_date'", ",", "$", "obj", "->", "get", "(", "'creation_date'", ")", ")", ";", "}", "$", "obj", "->", "creationDate", "=", "$", "obj", "->", "get", "(", "'creation_date'", ")", ";", "if", "(", "isset", "(", "$", "entry", "[", "'fields'", "]", ")", "&&", "is_array", "(", "$", "entry", "[", "'fields'", "]", ")", ")", "{", "foreach", "(", "$", "entry", "[", "'fields'", "]", "as", "$", "field_id", "=>", "$", "data", ")", "{", "$", "obj", "->", "setData", "(", "$", "field_id", ",", "$", "data", ")", ";", "}", "}", "$", "entries", "[", "]", "=", "$", "obj", ";", "}", "return", "$", "entries", ";", "}" ]
Given an array of Entry data from `tbl_entries` and a section ID, return an array of Entry objects. For performance reasons, it's possible to pass an array of field handles via `$element_names`, so that only a subset of the section schema will be queried. This function currently only supports Entry from one section at a time. @param array $rows An array of Entry data from `tbl_entries` including the Entry ID, Entry section, the ID of the Author who created the Entry, and a Unix timestamp of creation @param integer $section_id The section ID of the entries in the `$rows` @param array $element_names Choose whether to get data from a subset of fields or all fields in a section, by providing an array of field names. Defaults to null, which will load data from all fields in a section. @throws DatabaseException @return array An array of Entry objects
[ "Given", "an", "array", "of", "Entry", "data", "from", "tbl_entries", "and", "a", "section", "ID", "return", "an", "array", "of", "Entry", "objects", ".", "For", "performance", "reasons", "it", "s", "possible", "to", "pass", "an", "array", "of", "field", "handles", "via", "$element_names", "so", "that", "only", "a", "subset", "of", "the", "section", "schema", "will", "be", "queried", ".", "This", "function", "currently", "only", "supports", "Entry", "from", "one", "section", "at", "a", "time", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.entrymanager.php#L518-L626
symphonycms/symphony-2
symphony/lib/toolkit/class.entrymanager.php
EntryManager.fetchCount
public static function fetchCount($section_id = null, $where = null, $joins = null, $group = false) { if (is_null($section_id)) { return false; } $section = SectionManager::fetch($section_id); if (!is_object($section)) { return false; } return Symphony::Database()->fetchVar('count', 0, sprintf(" SELECT COUNT(%s`e`.id) as `count` FROM `tbl_entries` AS `e` %s WHERE `e`.`section_id` = %d %s ", $group ? 'DISTINCT ' : '', $joins, $section_id, $where )); }
php
public static function fetchCount($section_id = null, $where = null, $joins = null, $group = false) { if (is_null($section_id)) { return false; } $section = SectionManager::fetch($section_id); if (!is_object($section)) { return false; } return Symphony::Database()->fetchVar('count', 0, sprintf(" SELECT COUNT(%s`e`.id) as `count` FROM `tbl_entries` AS `e` %s WHERE `e`.`section_id` = %d %s ", $group ? 'DISTINCT ' : '', $joins, $section_id, $where )); }
[ "public", "static", "function", "fetchCount", "(", "$", "section_id", "=", "null", ",", "$", "where", "=", "null", ",", "$", "joins", "=", "null", ",", "$", "group", "=", "false", ")", "{", "if", "(", "is_null", "(", "$", "section_id", ")", ")", "{", "return", "false", ";", "}", "$", "section", "=", "SectionManager", "::", "fetch", "(", "$", "section_id", ")", ";", "if", "(", "!", "is_object", "(", "$", "section", ")", ")", "{", "return", "false", ";", "}", "return", "Symphony", "::", "Database", "(", ")", "->", "fetchVar", "(", "'count'", ",", "0", ",", "sprintf", "(", "\"\n SELECT COUNT(%s`e`.id) as `count`\n FROM `tbl_entries` AS `e`\n %s\n WHERE `e`.`section_id` = %d\n %s\n \"", ",", "$", "group", "?", "'DISTINCT '", ":", "''", ",", "$", "joins", ",", "$", "section_id", ",", "$", "where", ")", ")", ";", "}" ]
Return the count of the number of entries in a particular section. @param integer $section_id The ID of the Section where the Entries are to be counted @param string $where Any custom WHERE clauses @param string $joins Any custom JOIN's @param boolean $group Whether the entries need to be grouped by Entry ID or not @return integer
[ "Return", "the", "count", "of", "the", "number", "of", "entries", "in", "a", "particular", "section", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.entrymanager.php#L658-L682
symphonycms/symphony-2
symphony/lib/toolkit/class.entrymanager.php
EntryManager.fetchByPage
public static function fetchByPage($page = 1, $section_id, $entriesPerPage, $where = null, $joins = null, $group = false, $records_only = false, $buildentries = true, array $element_names = null) { if ($entriesPerPage != null && !is_string($entriesPerPage) && !is_numeric($entriesPerPage)) { throw new Exception(__('Entry limit specified was not a valid type. String or Integer expected.')); } elseif ($entriesPerPage == null) { $records = self::fetch(null, $section_id, null, null, $where, $joins, $group, $buildentries, $element_names); $count = self::fetchCount($section_id, $where, $joins, $group); $entries = array( 'total-entries' => $count, 'total-pages' => 1, 'remaining-pages' => 0, 'remaining-entries' => 0, 'start' => 1, 'limit' => $count, 'records' => $records ); return $entries; } else { $start = (max(1, $page) - 1) * $entriesPerPage; $records = ($entriesPerPage == '0' ? null : self::fetch(null, $section_id, $entriesPerPage, $start, $where, $joins, $group, $buildentries, $element_names)); if ($records_only) { return array('records' => $records); } $entries = array( 'total-entries' => self::fetchCount($section_id, $where, $joins, $group), 'records' => $records, 'start' => max(1, $start), 'limit' => $entriesPerPage ); $entries['remaining-entries'] = max(0, $entries['total-entries'] - ($start + $entriesPerPage)); $entries['total-pages'] = max(1, ceil($entries['total-entries'] * (1 / $entriesPerPage))); $entries['remaining-pages'] = max(0, $entries['total-pages'] - $page); return $entries; } }
php
public static function fetchByPage($page = 1, $section_id, $entriesPerPage, $where = null, $joins = null, $group = false, $records_only = false, $buildentries = true, array $element_names = null) { if ($entriesPerPage != null && !is_string($entriesPerPage) && !is_numeric($entriesPerPage)) { throw new Exception(__('Entry limit specified was not a valid type. String or Integer expected.')); } elseif ($entriesPerPage == null) { $records = self::fetch(null, $section_id, null, null, $where, $joins, $group, $buildentries, $element_names); $count = self::fetchCount($section_id, $where, $joins, $group); $entries = array( 'total-entries' => $count, 'total-pages' => 1, 'remaining-pages' => 0, 'remaining-entries' => 0, 'start' => 1, 'limit' => $count, 'records' => $records ); return $entries; } else { $start = (max(1, $page) - 1) * $entriesPerPage; $records = ($entriesPerPage == '0' ? null : self::fetch(null, $section_id, $entriesPerPage, $start, $where, $joins, $group, $buildentries, $element_names)); if ($records_only) { return array('records' => $records); } $entries = array( 'total-entries' => self::fetchCount($section_id, $where, $joins, $group), 'records' => $records, 'start' => max(1, $start), 'limit' => $entriesPerPage ); $entries['remaining-entries'] = max(0, $entries['total-entries'] - ($start + $entriesPerPage)); $entries['total-pages'] = max(1, ceil($entries['total-entries'] * (1 / $entriesPerPage))); $entries['remaining-pages'] = max(0, $entries['total-pages'] - $page); return $entries; } }
[ "public", "static", "function", "fetchByPage", "(", "$", "page", "=", "1", ",", "$", "section_id", ",", "$", "entriesPerPage", ",", "$", "where", "=", "null", ",", "$", "joins", "=", "null", ",", "$", "group", "=", "false", ",", "$", "records_only", "=", "false", ",", "$", "buildentries", "=", "true", ",", "array", "$", "element_names", "=", "null", ")", "{", "if", "(", "$", "entriesPerPage", "!=", "null", "&&", "!", "is_string", "(", "$", "entriesPerPage", ")", "&&", "!", "is_numeric", "(", "$", "entriesPerPage", ")", ")", "{", "throw", "new", "Exception", "(", "__", "(", "'Entry limit specified was not a valid type. String or Integer expected.'", ")", ")", ";", "}", "elseif", "(", "$", "entriesPerPage", "==", "null", ")", "{", "$", "records", "=", "self", "::", "fetch", "(", "null", ",", "$", "section_id", ",", "null", ",", "null", ",", "$", "where", ",", "$", "joins", ",", "$", "group", ",", "$", "buildentries", ",", "$", "element_names", ")", ";", "$", "count", "=", "self", "::", "fetchCount", "(", "$", "section_id", ",", "$", "where", ",", "$", "joins", ",", "$", "group", ")", ";", "$", "entries", "=", "array", "(", "'total-entries'", "=>", "$", "count", ",", "'total-pages'", "=>", "1", ",", "'remaining-pages'", "=>", "0", ",", "'remaining-entries'", "=>", "0", ",", "'start'", "=>", "1", ",", "'limit'", "=>", "$", "count", ",", "'records'", "=>", "$", "records", ")", ";", "return", "$", "entries", ";", "}", "else", "{", "$", "start", "=", "(", "max", "(", "1", ",", "$", "page", ")", "-", "1", ")", "*", "$", "entriesPerPage", ";", "$", "records", "=", "(", "$", "entriesPerPage", "==", "'0'", "?", "null", ":", "self", "::", "fetch", "(", "null", ",", "$", "section_id", ",", "$", "entriesPerPage", ",", "$", "start", ",", "$", "where", ",", "$", "joins", ",", "$", "group", ",", "$", "buildentries", ",", "$", "element_names", ")", ")", ";", "if", "(", "$", "records_only", ")", "{", "return", "array", "(", "'records'", "=>", "$", "records", ")", ";", "}", "$", "entries", "=", "array", "(", "'total-entries'", "=>", "self", "::", "fetchCount", "(", "$", "section_id", ",", "$", "where", ",", "$", "joins", ",", "$", "group", ")", ",", "'records'", "=>", "$", "records", ",", "'start'", "=>", "max", "(", "1", ",", "$", "start", ")", ",", "'limit'", "=>", "$", "entriesPerPage", ")", ";", "$", "entries", "[", "'remaining-entries'", "]", "=", "max", "(", "0", ",", "$", "entries", "[", "'total-entries'", "]", "-", "(", "$", "start", "+", "$", "entriesPerPage", ")", ")", ";", "$", "entries", "[", "'total-pages'", "]", "=", "max", "(", "1", ",", "ceil", "(", "$", "entries", "[", "'total-entries'", "]", "*", "(", "1", "/", "$", "entriesPerPage", ")", ")", ")", ";", "$", "entries", "[", "'remaining-pages'", "]", "=", "max", "(", "0", ",", "$", "entries", "[", "'total-pages'", "]", "-", "$", "page", ")", ";", "return", "$", "entries", ";", "}", "}" ]
Returns an array of Entry objects, with some basic pagination given the number of Entry's to return and the current starting offset. This function in turn calls the fetch function that does alot of the heavy lifting. For instance, if there are 60 entries in a section and the pagination dictates that per page, 15 entries are to be returned, by passing 2 to the $page parameter you could return entries 15-30 @param integer $page The page to return, defaults to 1 @param integer $section_id The ID of the Section that these entries are contained in @param integer $entriesPerPage The number of entries to return per page. @param string $where Any custom WHERE clauses @param string $joins Any custom JOIN's @param boolean $group Whether the entries need to be grouped by Entry ID or not @param boolean $records_only If this is set to true, an array of Entry objects will be returned without any basic pagination information. Defaults to false @param boolean $buildentries Whether to return an array of entry ID's or Entry objects. Defaults to true, which will return Entry objects @param array $element_names Choose whether to get data from a subset of fields or all fields in a section, by providing an array of field names. Defaults to null, which will load data from all fields in a section. @throws Exception @return array Either an array of Entry objects, or an associative array containing the total entries, the start position, the entries per page and the Entry objects
[ "Returns", "an", "array", "of", "Entry", "objects", "with", "some", "basic", "pagination", "given", "the", "number", "of", "Entry", "s", "to", "return", "and", "the", "current", "starting", "offset", ".", "This", "function", "in", "turn", "calls", "the", "fetch", "function", "that", "does", "alot", "of", "the", "heavy", "lifting", ".", "For", "instance", "if", "there", "are", "60", "entries", "in", "a", "section", "and", "the", "pagination", "dictates", "that", "per", "page", "15", "entries", "are", "to", "be", "returned", "by", "passing", "2", "to", "the", "$page", "parameter", "you", "could", "return", "entries", "15", "-", "30" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.entrymanager.php#L720-L762
symphonycms/symphony-2
symphony/lib/toolkit/class.xsltprocess.php
XsltProcess.process
public function process($xml = null, $xsl = null, array $parameters = array(), array $register_functions = array()) { if ($xml) { $this->_xml = $xml; } if ($xsl) { $this->_xsl = $xsl; } // dont let process continue if no xsl functionality exists if (!XsltProcess::isXSLTProcessorAvailable()) { return false; } $XSLProc = new XsltProcessor; if (!empty($register_functions)) { $XSLProc->registerPHPFunctions($register_functions); } $result = @$this->__process( $XSLProc, $this->_xml, $this->_xsl, $parameters ); unset($XSLProc); return $result; }
php
public function process($xml = null, $xsl = null, array $parameters = array(), array $register_functions = array()) { if ($xml) { $this->_xml = $xml; } if ($xsl) { $this->_xsl = $xsl; } // dont let process continue if no xsl functionality exists if (!XsltProcess::isXSLTProcessorAvailable()) { return false; } $XSLProc = new XsltProcessor; if (!empty($register_functions)) { $XSLProc->registerPHPFunctions($register_functions); } $result = @$this->__process( $XSLProc, $this->_xml, $this->_xsl, $parameters ); unset($XSLProc); return $result; }
[ "public", "function", "process", "(", "$", "xml", "=", "null", ",", "$", "xsl", "=", "null", ",", "array", "$", "parameters", "=", "array", "(", ")", ",", "array", "$", "register_functions", "=", "array", "(", ")", ")", "{", "if", "(", "$", "xml", ")", "{", "$", "this", "->", "_xml", "=", "$", "xml", ";", "}", "if", "(", "$", "xsl", ")", "{", "$", "this", "->", "_xsl", "=", "$", "xsl", ";", "}", "// dont let process continue if no xsl functionality exists", "if", "(", "!", "XsltProcess", "::", "isXSLTProcessorAvailable", "(", ")", ")", "{", "return", "false", ";", "}", "$", "XSLProc", "=", "new", "XsltProcessor", ";", "if", "(", "!", "empty", "(", "$", "register_functions", ")", ")", "{", "$", "XSLProc", "->", "registerPHPFunctions", "(", "$", "register_functions", ")", ";", "}", "$", "result", "=", "@", "$", "this", "->", "__process", "(", "$", "XSLProc", ",", "$", "this", "->", "_xml", ",", "$", "this", "->", "_xsl", ",", "$", "parameters", ")", ";", "unset", "(", "$", "XSLProc", ")", ";", "return", "$", "result", ";", "}" ]
This function will take a given XML file, a stylesheet and apply the transformation. Any errors will call the error function to log them into the `$_errors` array @see toolkit.XSLTProcess#__error() @see toolkit.XSLTProcess#__process() @param string $xml The XML for the transformation to be applied to @param string $xsl The XSL for the transformation @param array $parameters An array of available parameters the XSL will have access to @param array $register_functions An array of available PHP functions that the XSL can use @return string|boolean The string of the resulting transform, or false if there was an error
[ "This", "function", "will", "take", "a", "given", "XML", "file", "a", "stylesheet", "and", "apply", "the", "transformation", ".", "Any", "errors", "will", "call", "the", "error", "function", "to", "log", "them", "into", "the", "$_errors", "array" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.xsltprocess.php#L78-L109
symphonycms/symphony-2
symphony/lib/toolkit/class.xsltprocess.php
XsltProcess.__process
private function __process(XsltProcessor $XSLProc, $xml, $xsl, array $parameters = array()) { // Create instances of the DomDocument class $xmlDoc = new DomDocument; $xslDoc= new DomDocument; // Set up error handling if (function_exists('ini_set')) { $ehOLD = ini_set('html_errors', false); } // Load the xml document set_error_handler(array($this, 'trapXMLError')); // Prevent remote entities from being loaded, RE: #1939 $elOLD = libxml_disable_entity_loader(true); // Remove null bytes from XML $xml = str_replace(chr(0), '', $xml); $xmlDoc->loadXML($xml, LIBXML_NONET | LIBXML_DTDLOAD | LIBXML_DTDATTR | defined('LIBXML_COMPACT') ? LIBXML_COMPACT : 0); libxml_disable_entity_loader($elOLD); // Must restore the error handler to avoid problems restore_error_handler(); // Load the xsl document set_error_handler(array($this, 'trapXSLError')); // Ensure that the XSLT can be loaded with `false`. RE: #1939 // Note that `true` will cause `<xsl:import />` to fail. $elOLD = libxml_disable_entity_loader(false); $xslDoc->loadXML($xsl, LIBXML_NONET | LIBXML_DTDLOAD | LIBXML_DTDATTR | defined('LIBXML_COMPACT') ? LIBXML_COMPACT : 0); libxml_disable_entity_loader($elOLD); // Load the xsl template $XSLProc->importStyleSheet($xslDoc); // Set parameters when defined if (!empty($parameters)) { General::flattenArray($parameters); $XSLProc->setParameter('', $parameters); } // Must restore the error handler to avoid problems restore_error_handler(); // Start the transformation set_error_handler(array($this, 'trapXMLError')); $processed = $XSLProc->transformToXML($xmlDoc); // Restore error handling if (function_exists('ini_set') && isset($ehOLD)) { ini_set('html_errors', $ehOLD); } // Must restore the error handler to avoid problems restore_error_handler(); return $processed; }
php
private function __process(XsltProcessor $XSLProc, $xml, $xsl, array $parameters = array()) { // Create instances of the DomDocument class $xmlDoc = new DomDocument; $xslDoc= new DomDocument; // Set up error handling if (function_exists('ini_set')) { $ehOLD = ini_set('html_errors', false); } // Load the xml document set_error_handler(array($this, 'trapXMLError')); // Prevent remote entities from being loaded, RE: #1939 $elOLD = libxml_disable_entity_loader(true); // Remove null bytes from XML $xml = str_replace(chr(0), '', $xml); $xmlDoc->loadXML($xml, LIBXML_NONET | LIBXML_DTDLOAD | LIBXML_DTDATTR | defined('LIBXML_COMPACT') ? LIBXML_COMPACT : 0); libxml_disable_entity_loader($elOLD); // Must restore the error handler to avoid problems restore_error_handler(); // Load the xsl document set_error_handler(array($this, 'trapXSLError')); // Ensure that the XSLT can be loaded with `false`. RE: #1939 // Note that `true` will cause `<xsl:import />` to fail. $elOLD = libxml_disable_entity_loader(false); $xslDoc->loadXML($xsl, LIBXML_NONET | LIBXML_DTDLOAD | LIBXML_DTDATTR | defined('LIBXML_COMPACT') ? LIBXML_COMPACT : 0); libxml_disable_entity_loader($elOLD); // Load the xsl template $XSLProc->importStyleSheet($xslDoc); // Set parameters when defined if (!empty($parameters)) { General::flattenArray($parameters); $XSLProc->setParameter('', $parameters); } // Must restore the error handler to avoid problems restore_error_handler(); // Start the transformation set_error_handler(array($this, 'trapXMLError')); $processed = $XSLProc->transformToXML($xmlDoc); // Restore error handling if (function_exists('ini_set') && isset($ehOLD)) { ini_set('html_errors', $ehOLD); } // Must restore the error handler to avoid problems restore_error_handler(); return $processed; }
[ "private", "function", "__process", "(", "XsltProcessor", "$", "XSLProc", ",", "$", "xml", ",", "$", "xsl", ",", "array", "$", "parameters", "=", "array", "(", ")", ")", "{", "// Create instances of the DomDocument class", "$", "xmlDoc", "=", "new", "DomDocument", ";", "$", "xslDoc", "=", "new", "DomDocument", ";", "// Set up error handling", "if", "(", "function_exists", "(", "'ini_set'", ")", ")", "{", "$", "ehOLD", "=", "ini_set", "(", "'html_errors'", ",", "false", ")", ";", "}", "// Load the xml document", "set_error_handler", "(", "array", "(", "$", "this", ",", "'trapXMLError'", ")", ")", ";", "// Prevent remote entities from being loaded, RE: #1939", "$", "elOLD", "=", "libxml_disable_entity_loader", "(", "true", ")", ";", "// Remove null bytes from XML", "$", "xml", "=", "str_replace", "(", "chr", "(", "0", ")", ",", "''", ",", "$", "xml", ")", ";", "$", "xmlDoc", "->", "loadXML", "(", "$", "xml", ",", "LIBXML_NONET", "|", "LIBXML_DTDLOAD", "|", "LIBXML_DTDATTR", "|", "defined", "(", "'LIBXML_COMPACT'", ")", "?", "LIBXML_COMPACT", ":", "0", ")", ";", "libxml_disable_entity_loader", "(", "$", "elOLD", ")", ";", "// Must restore the error handler to avoid problems", "restore_error_handler", "(", ")", ";", "// Load the xsl document", "set_error_handler", "(", "array", "(", "$", "this", ",", "'trapXSLError'", ")", ")", ";", "// Ensure that the XSLT can be loaded with `false`. RE: #1939", "// Note that `true` will cause `<xsl:import />` to fail.", "$", "elOLD", "=", "libxml_disable_entity_loader", "(", "false", ")", ";", "$", "xslDoc", "->", "loadXML", "(", "$", "xsl", ",", "LIBXML_NONET", "|", "LIBXML_DTDLOAD", "|", "LIBXML_DTDATTR", "|", "defined", "(", "'LIBXML_COMPACT'", ")", "?", "LIBXML_COMPACT", ":", "0", ")", ";", "libxml_disable_entity_loader", "(", "$", "elOLD", ")", ";", "// Load the xsl template", "$", "XSLProc", "->", "importStyleSheet", "(", "$", "xslDoc", ")", ";", "// Set parameters when defined", "if", "(", "!", "empty", "(", "$", "parameters", ")", ")", "{", "General", "::", "flattenArray", "(", "$", "parameters", ")", ";", "$", "XSLProc", "->", "setParameter", "(", "''", ",", "$", "parameters", ")", ";", "}", "// Must restore the error handler to avoid problems", "restore_error_handler", "(", ")", ";", "// Start the transformation", "set_error_handler", "(", "array", "(", "$", "this", ",", "'trapXMLError'", ")", ")", ";", "$", "processed", "=", "$", "XSLProc", "->", "transformToXML", "(", "$", "xmlDoc", ")", ";", "// Restore error handling", "if", "(", "function_exists", "(", "'ini_set'", ")", "&&", "isset", "(", "$", "ehOLD", ")", ")", "{", "ini_set", "(", "'html_errors'", ",", "$", "ehOLD", ")", ";", "}", "// Must restore the error handler to avoid problems", "restore_error_handler", "(", ")", ";", "return", "$", "processed", ";", "}" ]
Uses `DomDocument` to transform the document. Any errors that occur are trapped by custom error handlers, `trapXMLError` or `trapXSLError`. @param XsltProcessor $XSLProc An instance of `XsltProcessor` @param string $xml The XML for the transformation to be applied to @param string $xsl The XSL for the transformation @param array $parameters An array of available parameters the XSL will have access to @return string
[ "Uses", "DomDocument", "to", "transform", "the", "document", ".", "Any", "errors", "that", "occur", "are", "trapped", "by", "custom", "error", "handlers", "trapXMLError", "or", "trapXSLError", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.xsltprocess.php#L126-L183
symphonycms/symphony-2
symphony/lib/toolkit/class.xsltprocess.php
XsltProcess.validate
public function validate($xsd, $xml = null) { if (is_null($xml) && !is_null($this->_xml)) { $xml = $this->_xml; } if (is_null($xsd) || is_null($xml)) { return false; } // Create instances of the DomDocument class $xmlDoc = new DomDocument; // Set up error handling if (function_exists('ini_set')) { $ehOLD = ini_set('html_errors', false); } // Load the xml document set_error_handler(array($this, 'trapXMLError')); $elOLD = libxml_disable_entity_loader(true); $xmlDoc->loadXML($xml, LIBXML_NONET | LIBXML_DTDLOAD | LIBXML_DTDATTR | defined('LIBXML_COMPACT') ? LIBXML_COMPACT : 0); libxml_disable_entity_loader($elOLD); // Must restore the error handler to avoid problems restore_error_handler(); // Validate the XML against the XSD set_error_handler(array($this, 'trapXSDError')); $result = $xmlDoc->schemaValidateSource($xsd); // Restore error handling if (function_exists('ini_set') && isset($ehOLD)) { ini_set('html_errors', $ehOLD); } // Must restore the error handler to avoid problems restore_error_handler(); return $result; }
php
public function validate($xsd, $xml = null) { if (is_null($xml) && !is_null($this->_xml)) { $xml = $this->_xml; } if (is_null($xsd) || is_null($xml)) { return false; } // Create instances of the DomDocument class $xmlDoc = new DomDocument; // Set up error handling if (function_exists('ini_set')) { $ehOLD = ini_set('html_errors', false); } // Load the xml document set_error_handler(array($this, 'trapXMLError')); $elOLD = libxml_disable_entity_loader(true); $xmlDoc->loadXML($xml, LIBXML_NONET | LIBXML_DTDLOAD | LIBXML_DTDATTR | defined('LIBXML_COMPACT') ? LIBXML_COMPACT : 0); libxml_disable_entity_loader($elOLD); // Must restore the error handler to avoid problems restore_error_handler(); // Validate the XML against the XSD set_error_handler(array($this, 'trapXSDError')); $result = $xmlDoc->schemaValidateSource($xsd); // Restore error handling if (function_exists('ini_set') && isset($ehOLD)) { ini_set('html_errors', $ehOLD); } // Must restore the error handler to avoid problems restore_error_handler(); return $result; }
[ "public", "function", "validate", "(", "$", "xsd", ",", "$", "xml", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "xml", ")", "&&", "!", "is_null", "(", "$", "this", "->", "_xml", ")", ")", "{", "$", "xml", "=", "$", "this", "->", "_xml", ";", "}", "if", "(", "is_null", "(", "$", "xsd", ")", "||", "is_null", "(", "$", "xml", ")", ")", "{", "return", "false", ";", "}", "// Create instances of the DomDocument class", "$", "xmlDoc", "=", "new", "DomDocument", ";", "// Set up error handling", "if", "(", "function_exists", "(", "'ini_set'", ")", ")", "{", "$", "ehOLD", "=", "ini_set", "(", "'html_errors'", ",", "false", ")", ";", "}", "// Load the xml document", "set_error_handler", "(", "array", "(", "$", "this", ",", "'trapXMLError'", ")", ")", ";", "$", "elOLD", "=", "libxml_disable_entity_loader", "(", "true", ")", ";", "$", "xmlDoc", "->", "loadXML", "(", "$", "xml", ",", "LIBXML_NONET", "|", "LIBXML_DTDLOAD", "|", "LIBXML_DTDATTR", "|", "defined", "(", "'LIBXML_COMPACT'", ")", "?", "LIBXML_COMPACT", ":", "0", ")", ";", "libxml_disable_entity_loader", "(", "$", "elOLD", ")", ";", "// Must restore the error handler to avoid problems", "restore_error_handler", "(", ")", ";", "// Validate the XML against the XSD", "set_error_handler", "(", "array", "(", "$", "this", ",", "'trapXSDError'", ")", ")", ";", "$", "result", "=", "$", "xmlDoc", "->", "schemaValidateSource", "(", "$", "xsd", ")", ";", "// Restore error handling", "if", "(", "function_exists", "(", "'ini_set'", ")", "&&", "isset", "(", "$", "ehOLD", ")", ")", "{", "ini_set", "(", "'html_errors'", ",", "$", "ehOLD", ")", ";", "}", "// Must restore the error handler to avoid problems", "restore_error_handler", "(", ")", ";", "return", "$", "result", ";", "}" ]
That validate function takes an XSD to valid against `$this->_xml` returning boolean. Optionally, a second parameter `$xml` can be passed that will be used instead of `$this->_xml`. @since Symphony 2.3 @param string $xsd The XSD to validate `$this->_xml` against @param string $xml (optional) If provided, this function will use this `$xml` instead of `$this->_xml`. @return boolean Returns true if the `$xml` validates against `$xsd`, false otherwise. If false is returned, the errors can be obtained with `XSLTProcess->getErrors()`
[ "That", "validate", "function", "takes", "an", "XSD", "to", "valid", "against", "$this", "-", ">", "_xml", "returning", "boolean", ".", "Optionally", "a", "second", "parameter", "$xml", "can", "be", "passed", "that", "will", "be", "used", "instead", "of", "$this", "-", ">", "_xml", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.xsltprocess.php#L200-L240
symphonycms/symphony-2
symphony/lib/toolkit/class.xsltprocess.php
XsltProcess.trapXMLError
public function trapXMLError($errno, $errstr, $errfile, $errline) { $this->__error($errno, str_replace('DOMDocument::', null, $errstr), $errfile, $errline, 'xml'); }
php
public function trapXMLError($errno, $errstr, $errfile, $errline) { $this->__error($errno, str_replace('DOMDocument::', null, $errstr), $errfile, $errline, 'xml'); }
[ "public", "function", "trapXMLError", "(", "$", "errno", ",", "$", "errstr", ",", "$", "errfile", ",", "$", "errline", ")", "{", "$", "this", "->", "__error", "(", "$", "errno", ",", "str_replace", "(", "'DOMDocument::'", ",", "null", ",", "$", "errstr", ")", ",", "$", "errfile", ",", "$", "errline", ",", "'xml'", ")", ";", "}" ]
A custom error handler especially for XML errors. @link http://au.php.net/manual/en/function.set-error-handler.php @param integer $errno @param integer $errstr @param integer $errfile @param integer $errline
[ "A", "custom", "error", "handler", "especially", "for", "XML", "errors", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.xsltprocess.php#L251-L254
symphonycms/symphony-2
symphony/lib/toolkit/class.xsltprocess.php
XsltProcess.__error
public function __error($number, $message, $file = null, $line = null, $type = null) { $context = null; if ($type == 'xml' || $type == 'xsd') { $context = $this->_xml; } if ($type == 'xsl') { $context = $this->_xsl; } $this->_errors[] = array( 'number' => $number, 'message' => $message, 'file' => $file, 'line' => $line, 'type' => $type, 'context' => $context ); }
php
public function __error($number, $message, $file = null, $line = null, $type = null) { $context = null; if ($type == 'xml' || $type == 'xsd') { $context = $this->_xml; } if ($type == 'xsl') { $context = $this->_xsl; } $this->_errors[] = array( 'number' => $number, 'message' => $message, 'file' => $file, 'line' => $line, 'type' => $type, 'context' => $context ); }
[ "public", "function", "__error", "(", "$", "number", ",", "$", "message", ",", "$", "file", "=", "null", ",", "$", "line", "=", "null", ",", "$", "type", "=", "null", ")", "{", "$", "context", "=", "null", ";", "if", "(", "$", "type", "==", "'xml'", "||", "$", "type", "==", "'xsd'", ")", "{", "$", "context", "=", "$", "this", "->", "_xml", ";", "}", "if", "(", "$", "type", "==", "'xsl'", ")", "{", "$", "context", "=", "$", "this", "->", "_xsl", ";", "}", "$", "this", "->", "_errors", "[", "]", "=", "array", "(", "'number'", "=>", "$", "number", ",", "'message'", "=>", "$", "message", ",", "'file'", "=>", "$", "file", ",", "'line'", "=>", "$", "line", ",", "'type'", "=>", "$", "type", ",", "'context'", "=>", "$", "context", ")", ";", "}" ]
Writes an error to the `$_errors` array, which contains the error information and some basic debugging information. @link http://au.php.net/manual/en/function.set-error-handler.php @param integer $number @param string $message @param string $file @param string $line @param string $type Where the error occurred, can be either 'xml', 'xsl' or `xsd`
[ "Writes", "an", "error", "to", "the", "$_errors", "array", "which", "contains", "the", "error", "information", "and", "some", "basic", "debugging", "information", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.xsltprocess.php#L297-L317
symphonycms/symphony-2
symphony/lib/toolkit/class.xsltprocess.php
XsltProcess.getError
public function getError($all = false, $rewind = false) { if ($rewind) { reset($this->_errors); } return ($all ? $this->_errors : each($this->_errors)); }
php
public function getError($all = false, $rewind = false) { if ($rewind) { reset($this->_errors); } return ($all ? $this->_errors : each($this->_errors)); }
[ "public", "function", "getError", "(", "$", "all", "=", "false", ",", "$", "rewind", "=", "false", ")", "{", "if", "(", "$", "rewind", ")", "{", "reset", "(", "$", "this", "->", "_errors", ")", ";", "}", "return", "(", "$", "all", "?", "$", "this", "->", "_errors", ":", "each", "(", "$", "this", "->", "_errors", ")", ")", ";", "}" ]
Provides an Iterator interface to return an error from the `$_errors` array. Repeat calls to this function to get all errors @param boolean $all If true, return all errors instead of one by one. Defaults to false @param boolean $rewind If rewind is true, resets the internal array pointer to the start of the `$_errors` array. Defaults to false. @return array Either an array of error array's or just an error array
[ "Provides", "an", "Iterator", "interface", "to", "return", "an", "error", "from", "the", "$_errors", "array", ".", "Repeat", "calls", "to", "this", "function", "to", "get", "all", "errors" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.xsltprocess.php#L342-L349
symphonycms/symphony-2
symphony/lib/toolkit/class.email.php
Email.create
public static function create($gateway = null) { $email_gateway_manager = new EmailGatewayManager; if ($gateway) { return $email_gateway_manager->create($gateway); } else { return $email_gateway_manager->create($email_gateway_manager->getDefaultGateway()); } }
php
public static function create($gateway = null) { $email_gateway_manager = new EmailGatewayManager; if ($gateway) { return $email_gateway_manager->create($gateway); } else { return $email_gateway_manager->create($email_gateway_manager->getDefaultGateway()); } }
[ "public", "static", "function", "create", "(", "$", "gateway", "=", "null", ")", "{", "$", "email_gateway_manager", "=", "new", "EmailGatewayManager", ";", "if", "(", "$", "gateway", ")", "{", "return", "$", "email_gateway_manager", "->", "create", "(", "$", "gateway", ")", ";", "}", "else", "{", "return", "$", "email_gateway_manager", "->", "create", "(", "$", "email_gateway_manager", "->", "getDefaultGateway", "(", ")", ")", ";", "}", "}" ]
Returns the EmailGateway to send emails with. Calling this function multiple times will return unique objects. @param string $gateway The name of the gateway to use. Please only supply if specific gateway functions are being used. If the gateway is not found, it will throw an EmailException @throws Exception @return EmailGateway
[ "Returns", "the", "EmailGateway", "to", "send", "emails", "with", ".", "Calling", "this", "function", "multiple", "times", "will", "return", "unique", "objects", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.email.php#L32-L41
symphonycms/symphony-2
symphony/lib/toolkit/fields/field.checkbox.php
FieldCheckbox.displayPublishPanel
public function displayPublishPanel(XMLElement &$wrapper, $data = null, $flagWithError = null, $fieldnamePrefix = null, $fieldnamePostfix = null, $entry_id = null) { if (!$data) { // TODO: Don't rely on $_POST if (isset($_POST) && !empty($_POST)) { $value = 'no'; } elseif ($this->get('default_state') == 'on') { $value = 'yes'; } else { $value = 'no'; } } else { $value = ($data['value'] === 'yes' ? 'yes' : 'no'); } $label = Widget::Label(); if ($this->get('required') !== 'yes') { $label->appendChild(new XMLElement('i', __('Optional'))); } $input = Widget::Input('fields'.$fieldnamePrefix.'['.$this->get('element_name').']'.$fieldnamePostfix, 'yes', 'checkbox', ($value === 'yes' ? array('checked' => 'checked') : null)); $label->setValue($input->generate(false) . ' ' . $this->get('label')); if ($flagWithError != null) { $wrapper->appendChild(Widget::Error($label, $flagWithError)); } else { $wrapper->appendChild($label); } }
php
public function displayPublishPanel(XMLElement &$wrapper, $data = null, $flagWithError = null, $fieldnamePrefix = null, $fieldnamePostfix = null, $entry_id = null) { if (!$data) { // TODO: Don't rely on $_POST if (isset($_POST) && !empty($_POST)) { $value = 'no'; } elseif ($this->get('default_state') == 'on') { $value = 'yes'; } else { $value = 'no'; } } else { $value = ($data['value'] === 'yes' ? 'yes' : 'no'); } $label = Widget::Label(); if ($this->get('required') !== 'yes') { $label->appendChild(new XMLElement('i', __('Optional'))); } $input = Widget::Input('fields'.$fieldnamePrefix.'['.$this->get('element_name').']'.$fieldnamePostfix, 'yes', 'checkbox', ($value === 'yes' ? array('checked' => 'checked') : null)); $label->setValue($input->generate(false) . ' ' . $this->get('label')); if ($flagWithError != null) { $wrapper->appendChild(Widget::Error($label, $flagWithError)); } else { $wrapper->appendChild($label); } }
[ "public", "function", "displayPublishPanel", "(", "XMLElement", "&", "$", "wrapper", ",", "$", "data", "=", "null", ",", "$", "flagWithError", "=", "null", ",", "$", "fieldnamePrefix", "=", "null", ",", "$", "fieldnamePostfix", "=", "null", ",", "$", "entry_id", "=", "null", ")", "{", "if", "(", "!", "$", "data", ")", "{", "// TODO: Don't rely on $_POST", "if", "(", "isset", "(", "$", "_POST", ")", "&&", "!", "empty", "(", "$", "_POST", ")", ")", "{", "$", "value", "=", "'no'", ";", "}", "elseif", "(", "$", "this", "->", "get", "(", "'default_state'", ")", "==", "'on'", ")", "{", "$", "value", "=", "'yes'", ";", "}", "else", "{", "$", "value", "=", "'no'", ";", "}", "}", "else", "{", "$", "value", "=", "(", "$", "data", "[", "'value'", "]", "===", "'yes'", "?", "'yes'", ":", "'no'", ")", ";", "}", "$", "label", "=", "Widget", "::", "Label", "(", ")", ";", "if", "(", "$", "this", "->", "get", "(", "'required'", ")", "!==", "'yes'", ")", "{", "$", "label", "->", "appendChild", "(", "new", "XMLElement", "(", "'i'", ",", "__", "(", "'Optional'", ")", ")", ")", ";", "}", "$", "input", "=", "Widget", "::", "Input", "(", "'fields'", ".", "$", "fieldnamePrefix", ".", "'['", ".", "$", "this", "->", "get", "(", "'element_name'", ")", ".", "']'", ".", "$", "fieldnamePostfix", ",", "'yes'", ",", "'checkbox'", ",", "(", "$", "value", "===", "'yes'", "?", "array", "(", "'checked'", "=>", "'checked'", ")", ":", "null", ")", ")", ";", "$", "label", "->", "setValue", "(", "$", "input", "->", "generate", "(", "false", ")", ".", "' '", ".", "$", "this", "->", "get", "(", "'label'", ")", ")", ";", "if", "(", "$", "flagWithError", "!=", "null", ")", "{", "$", "wrapper", "->", "appendChild", "(", "Widget", "::", "Error", "(", "$", "label", ",", "$", "flagWithError", ")", ")", ";", "}", "else", "{", "$", "wrapper", "->", "appendChild", "(", "$", "label", ")", ";", "}", "}" ]
/*------------------------------------------------------------------------- Publish: -------------------------------------------------------------------------
[ "/", "*", "-------------------------------------------------------------------------", "Publish", ":", "-------------------------------------------------------------------------" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/fields/field.checkbox.php#L153-L183
symphonycms/symphony-2
symphony/lib/toolkit/fields/field.checkbox.php
FieldCheckbox.appendFormattedElement
public function appendFormattedElement(XMLElement &$wrapper, $data, $encode = false, $mode = null, $entry_id = null) { $value = ($data['value'] === 'yes' ? 'Yes' : 'No'); $wrapper->appendChild(new XMLElement($this->get('element_name'), ($encode ? General::sanitize($value) : $value))); }
php
public function appendFormattedElement(XMLElement &$wrapper, $data, $encode = false, $mode = null, $entry_id = null) { $value = ($data['value'] === 'yes' ? 'Yes' : 'No'); $wrapper->appendChild(new XMLElement($this->get('element_name'), ($encode ? General::sanitize($value) : $value))); }
[ "public", "function", "appendFormattedElement", "(", "XMLElement", "&", "$", "wrapper", ",", "$", "data", ",", "$", "encode", "=", "false", ",", "$", "mode", "=", "null", ",", "$", "entry_id", "=", "null", ")", "{", "$", "value", "=", "(", "$", "data", "[", "'value'", "]", "===", "'yes'", "?", "'Yes'", ":", "'No'", ")", ";", "$", "wrapper", "->", "appendChild", "(", "new", "XMLElement", "(", "$", "this", "->", "get", "(", "'element_name'", ")", ",", "(", "$", "encode", "?", "General", "::", "sanitize", "(", "$", "value", ")", ":", "$", "value", ")", ")", ")", ";", "}" ]
/*------------------------------------------------------------------------- Output: -------------------------------------------------------------------------
[ "/", "*", "-------------------------------------------------------------------------", "Output", ":", "-------------------------------------------------------------------------" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/fields/field.checkbox.php#L217-L222
symphonycms/symphony-2
symphony/lib/toolkit/fields/field.checkbox.php
FieldCheckbox.prepareExportValue
public function prepareExportValue($data, $mode, $entry_id = null) { $modes = (object)$this->getExportModes(); // Export unformatted: if ($mode === $modes->getPostdata) { return ( isset($data['value']) && $data['value'] === 'yes' ? 'yes' : 'no' ); // Export formatted: } elseif ($mode === $modes->getValue) { return ( isset($data['value']) && $data['value'] === 'yes' ? __('Yes') : __('No') ); // Export boolean: } elseif ($mode === $modes->getBoolean) { return ( isset($data['value']) && $data['value'] === 'yes' ); } return null; }
php
public function prepareExportValue($data, $mode, $entry_id = null) { $modes = (object)$this->getExportModes(); // Export unformatted: if ($mode === $modes->getPostdata) { return ( isset($data['value']) && $data['value'] === 'yes' ? 'yes' : 'no' ); // Export formatted: } elseif ($mode === $modes->getValue) { return ( isset($data['value']) && $data['value'] === 'yes' ? __('Yes') : __('No') ); // Export boolean: } elseif ($mode === $modes->getBoolean) { return ( isset($data['value']) && $data['value'] === 'yes' ); } return null; }
[ "public", "function", "prepareExportValue", "(", "$", "data", ",", "$", "mode", ",", "$", "entry_id", "=", "null", ")", "{", "$", "modes", "=", "(", "object", ")", "$", "this", "->", "getExportModes", "(", ")", ";", "// Export unformatted:", "if", "(", "$", "mode", "===", "$", "modes", "->", "getPostdata", ")", "{", "return", "(", "isset", "(", "$", "data", "[", "'value'", "]", ")", "&&", "$", "data", "[", "'value'", "]", "===", "'yes'", "?", "'yes'", ":", "'no'", ")", ";", "// Export formatted:", "}", "elseif", "(", "$", "mode", "===", "$", "modes", "->", "getValue", ")", "{", "return", "(", "isset", "(", "$", "data", "[", "'value'", "]", ")", "&&", "$", "data", "[", "'value'", "]", "===", "'yes'", "?", "__", "(", "'Yes'", ")", ":", "__", "(", "'No'", ")", ")", ";", "// Export boolean:", "}", "elseif", "(", "$", "mode", "===", "$", "modes", "->", "getBoolean", ")", "{", "return", "(", "isset", "(", "$", "data", "[", "'value'", "]", ")", "&&", "$", "data", "[", "'value'", "]", "===", "'yes'", ")", ";", "}", "return", "null", ";", "}" ]
Give the field some data and ask it to return a value using one of many possible modes. @param mixed $data @param integer $mode @param integer $entry_id @return string|boolean|null
[ "Give", "the", "field", "some", "data", "and", "ask", "it", "to", "return", "a", "value", "using", "one", "of", "many", "possible", "modes", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/fields/field.checkbox.php#L288-L319
symphonycms/symphony-2
symphony/lib/toolkit/fields/field.checkbox.php
FieldCheckbox.displayFilteringOptions
public function displayFilteringOptions(XMLElement &$wrapper) { $existing_options = array('yes', 'no'); if (is_array($existing_options) && !empty($existing_options)) { $optionlist = new XMLElement('ul'); $optionlist->setAttribute('class', 'tags'); $optionlist->setAttribute('data-interactive', 'data-interactive'); foreach ($existing_options as $option) { $optionlist->appendChild(new XMLElement('li', $option)); } $wrapper->appendChild($optionlist); } }
php
public function displayFilteringOptions(XMLElement &$wrapper) { $existing_options = array('yes', 'no'); if (is_array($existing_options) && !empty($existing_options)) { $optionlist = new XMLElement('ul'); $optionlist->setAttribute('class', 'tags'); $optionlist->setAttribute('data-interactive', 'data-interactive'); foreach ($existing_options as $option) { $optionlist->appendChild(new XMLElement('li', $option)); } $wrapper->appendChild($optionlist); } }
[ "public", "function", "displayFilteringOptions", "(", "XMLElement", "&", "$", "wrapper", ")", "{", "$", "existing_options", "=", "array", "(", "'yes'", ",", "'no'", ")", ";", "if", "(", "is_array", "(", "$", "existing_options", ")", "&&", "!", "empty", "(", "$", "existing_options", ")", ")", "{", "$", "optionlist", "=", "new", "XMLElement", "(", "'ul'", ")", ";", "$", "optionlist", "->", "setAttribute", "(", "'class'", ",", "'tags'", ")", ";", "$", "optionlist", "->", "setAttribute", "(", "'data-interactive'", ",", "'data-interactive'", ")", ";", "foreach", "(", "$", "existing_options", "as", "$", "option", ")", "{", "$", "optionlist", "->", "appendChild", "(", "new", "XMLElement", "(", "'li'", ",", "$", "option", ")", ")", ";", "}", "$", "wrapper", "->", "appendChild", "(", "$", "optionlist", ")", ";", "}", "}" ]
/*------------------------------------------------------------------------- Filtering: -------------------------------------------------------------------------
[ "/", "*", "-------------------------------------------------------------------------", "Filtering", ":", "-------------------------------------------------------------------------" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/fields/field.checkbox.php#L325-L340
symphonycms/symphony-2
symphony/lib/toolkit/fields/field.checkbox.php
FieldCheckbox.getExampleFormMarkup
public function getExampleFormMarkup() { $label = Widget::Label($this->get('label')); $label->appendChild(Widget::Input('fields['.$this->get('element_name').']', 'yes', 'checkbox', ($this->get('default_state') == 'on' ? array('checked' => 'checked') : null))); return $label; }
php
public function getExampleFormMarkup() { $label = Widget::Label($this->get('label')); $label->appendChild(Widget::Input('fields['.$this->get('element_name').']', 'yes', 'checkbox', ($this->get('default_state') == 'on' ? array('checked' => 'checked') : null))); return $label; }
[ "public", "function", "getExampleFormMarkup", "(", ")", "{", "$", "label", "=", "Widget", "::", "Label", "(", "$", "this", "->", "get", "(", "'label'", ")", ")", ";", "$", "label", "->", "appendChild", "(", "Widget", "::", "Input", "(", "'fields['", ".", "$", "this", "->", "get", "(", "'element_name'", ")", ".", "']'", ",", "'yes'", ",", "'checkbox'", ",", "(", "$", "this", "->", "get", "(", "'default_state'", ")", "==", "'on'", "?", "array", "(", "'checked'", "=>", "'checked'", ")", ":", "null", ")", ")", ")", ";", "return", "$", "label", ";", "}" ]
/*------------------------------------------------------------------------- Events: -------------------------------------------------------------------------
[ "/", "*", "-------------------------------------------------------------------------", "Events", ":", "-------------------------------------------------------------------------" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/fields/field.checkbox.php#L469-L475
symphonycms/symphony-2
symphony/lib/toolkit/class.fieldmanager.php
FieldManager.__getClassPath
public static function __getClassPath($type) { if (is_file(TOOLKIT . "/fields/field.{$type}.php")) { return TOOLKIT . '/fields'; } else { $extensions = Symphony::ExtensionManager()->listInstalledHandles(); if (is_array($extensions) && !empty($extensions)) { foreach ($extensions as $e) { if (is_file(EXTENSIONS . "/{$e}/fields/field.{$type}.php")) { return EXTENSIONS . "/{$e}/fields"; } } } } return false; }
php
public static function __getClassPath($type) { if (is_file(TOOLKIT . "/fields/field.{$type}.php")) { return TOOLKIT . '/fields'; } else { $extensions = Symphony::ExtensionManager()->listInstalledHandles(); if (is_array($extensions) && !empty($extensions)) { foreach ($extensions as $e) { if (is_file(EXTENSIONS . "/{$e}/fields/field.{$type}.php")) { return EXTENSIONS . "/{$e}/fields"; } } } } return false; }
[ "public", "static", "function", "__getClassPath", "(", "$", "type", ")", "{", "if", "(", "is_file", "(", "TOOLKIT", ".", "\"/fields/field.{$type}.php\"", ")", ")", "{", "return", "TOOLKIT", ".", "'/fields'", ";", "}", "else", "{", "$", "extensions", "=", "Symphony", "::", "ExtensionManager", "(", ")", "->", "listInstalledHandles", "(", ")", ";", "if", "(", "is_array", "(", "$", "extensions", ")", "&&", "!", "empty", "(", "$", "extensions", ")", ")", "{", "foreach", "(", "$", "extensions", "as", "$", "e", ")", "{", "if", "(", "is_file", "(", "EXTENSIONS", ".", "\"/{$e}/fields/field.{$type}.php\"", ")", ")", "{", "return", "EXTENSIONS", ".", "\"/{$e}/fields\"", ";", "}", "}", "}", "}", "return", "false", ";", "}" ]
Finds a Field by type by searching the `TOOLKIT . /fields` folder and then any fields folders in the installed extensions. The function returns the path to the folder where the field class resides. @param string $type The field handle, that is, `field.{$handle}.php` @return string|boolean
[ "Finds", "a", "Field", "by", "type", "by", "searching", "the", "TOOLKIT", ".", "/", "fields", "folder", "and", "then", "any", "fields", "folders", "in", "the", "installed", "extensions", ".", "The", "function", "returns", "the", "path", "to", "the", "folder", "where", "the", "field", "class", "resides", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.fieldmanager.php#L62-L79
symphonycms/symphony-2
symphony/lib/toolkit/class.fieldmanager.php
FieldManager.saveSettings
public static function saveSettings($field_id, $settings) { // Get the type of this field: $type = self::fetchFieldTypeFromID($field_id); // Delete the original settings: Symphony::Database()->delete("tbl_fields_$type", sprintf("`field_id` = %d LIMIT 1", $field_id)); // Insert the new settings into the type table: if (!isset($settings['field_id'])) { $settings['field_id'] = $field_id; } return Symphony::Database()->insert($settings, 'tbl_fields_'.$type); }
php
public static function saveSettings($field_id, $settings) { // Get the type of this field: $type = self::fetchFieldTypeFromID($field_id); // Delete the original settings: Symphony::Database()->delete("tbl_fields_$type", sprintf("`field_id` = %d LIMIT 1", $field_id)); // Insert the new settings into the type table: if (!isset($settings['field_id'])) { $settings['field_id'] = $field_id; } return Symphony::Database()->insert($settings, 'tbl_fields_'.$type); }
[ "public", "static", "function", "saveSettings", "(", "$", "field_id", ",", "$", "settings", ")", "{", "// Get the type of this field:", "$", "type", "=", "self", "::", "fetchFieldTypeFromID", "(", "$", "field_id", ")", ";", "// Delete the original settings:", "Symphony", "::", "Database", "(", ")", "->", "delete", "(", "\"tbl_fields_$type\"", ",", "sprintf", "(", "\"`field_id` = %d LIMIT 1\"", ",", "$", "field_id", ")", ")", ";", "// Insert the new settings into the type table:", "if", "(", "!", "isset", "(", "$", "settings", "[", "'field_id'", "]", ")", ")", "{", "$", "settings", "[", "'field_id'", "]", "=", "$", "field_id", ";", "}", "return", "Symphony", "::", "Database", "(", ")", "->", "insert", "(", "$", "settings", ",", "'tbl_fields_'", ".", "$", "type", ")", ";", "}" ]
Save the settings for a Field given it's `$field_id` and an associative array of settings. @throws DatabaseException @since Symphony 2.3 @param integer $field_id The ID of the field @param array $settings An associative array of settings, where the key is the column name and the value is the value. @return boolean true on success, false on failure
[ "Save", "the", "settings", "for", "a", "Field", "given", "it", "s", "$field_id", "and", "an", "associative", "array", "of", "settings", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.fieldmanager.php#L144-L158
symphonycms/symphony-2
symphony/lib/toolkit/class.fieldmanager.php
FieldManager.edit
public static function edit($id, array $fields) { if (!Symphony::Database()->update($fields, "tbl_fields", sprintf(" `id` = %d", $id))) { return false; } return true; }
php
public static function edit($id, array $fields) { if (!Symphony::Database()->update($fields, "tbl_fields", sprintf(" `id` = %d", $id))) { return false; } return true; }
[ "public", "static", "function", "edit", "(", "$", "id", ",", "array", "$", "fields", ")", "{", "if", "(", "!", "Symphony", "::", "Database", "(", ")", "->", "update", "(", "$", "fields", ",", "\"tbl_fields\"", ",", "sprintf", "(", "\" `id` = %d\"", ",", "$", "id", ")", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Given a Field ID and associative array of fields, update an existing Field row in the `tbl_fields`table. Returns boolean for success/failure @throws DatabaseException @param integer $id The ID of the Field that should be updated @param array $fields Associative array of field names => values for the Field object This array does need to contain every value for the field object, it can just be the changed values. @return boolean
[ "Given", "a", "Field", "ID", "and", "associative", "array", "of", "fields", "update", "an", "existing", "Field", "row", "in", "the", "tbl_fields", "table", ".", "Returns", "boolean", "for", "success", "/", "failure" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.fieldmanager.php#L173-L180
symphonycms/symphony-2
symphony/lib/toolkit/class.fieldmanager.php
FieldManager.delete
public static function delete($id) { $existing = self::fetch($id); $existing->tearDown(); Symphony::Database()->delete('tbl_fields', sprintf(" `id` = %d", $id)); Symphony::Database()->delete('tbl_fields_'.$existing->handle(), sprintf(" `field_id` = %d", $id)); SectionManager::removeSectionAssociation($id); if ($existing->requiresTable()) { Symphony::Database()->query('DROP TABLE IF EXISTS `tbl_entries_data_'.$id.'`'); } return true; }
php
public static function delete($id) { $existing = self::fetch($id); $existing->tearDown(); Symphony::Database()->delete('tbl_fields', sprintf(" `id` = %d", $id)); Symphony::Database()->delete('tbl_fields_'.$existing->handle(), sprintf(" `field_id` = %d", $id)); SectionManager::removeSectionAssociation($id); if ($existing->requiresTable()) { Symphony::Database()->query('DROP TABLE IF EXISTS `tbl_entries_data_'.$id.'`'); } return true; }
[ "public", "static", "function", "delete", "(", "$", "id", ")", "{", "$", "existing", "=", "self", "::", "fetch", "(", "$", "id", ")", ";", "$", "existing", "->", "tearDown", "(", ")", ";", "Symphony", "::", "Database", "(", ")", "->", "delete", "(", "'tbl_fields'", ",", "sprintf", "(", "\" `id` = %d\"", ",", "$", "id", ")", ")", ";", "Symphony", "::", "Database", "(", ")", "->", "delete", "(", "'tbl_fields_'", ".", "$", "existing", "->", "handle", "(", ")", ",", "sprintf", "(", "\" `field_id` = %d\"", ",", "$", "id", ")", ")", ";", "SectionManager", "::", "removeSectionAssociation", "(", "$", "id", ")", ";", "if", "(", "$", "existing", "->", "requiresTable", "(", ")", ")", "{", "Symphony", "::", "Database", "(", ")", "->", "query", "(", "'DROP TABLE IF EXISTS `tbl_entries_data_'", ".", "$", "id", ".", "'`'", ")", ";", "}", "return", "true", ";", "}" ]
Given a Field ID, delete a Field from Symphony. This will remove the field from the fields table, all of the data stored in this field's `tbl_entries_data_$id` any existing section associations. This function additionally call the Field's `tearDown` method so that it can cleanup any additional settings or entry tables it may of created. @since Symphony 2.7.0 it will check to see if the field requires a data table before blindly trying to delete it. @throws DatabaseException @throws Exception @param integer $id The ID of the Field that should be deleted @return boolean
[ "Given", "a", "Field", "ID", "delete", "a", "Field", "from", "Symphony", ".", "This", "will", "remove", "the", "field", "from", "the", "fields", "table", "all", "of", "the", "data", "stored", "in", "this", "field", "s", "tbl_entries_data_$id", "any", "existing", "section", "associations", ".", "This", "function", "additionally", "call", "the", "Field", "s", "tearDown", "method", "so", "that", "it", "can", "cleanup", "any", "additional", "settings", "or", "entry", "tables", "it", "may", "of", "created", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.fieldmanager.php#L197-L211
symphonycms/symphony-2
symphony/lib/toolkit/class.fieldmanager.php
FieldManager.fetch
public static function fetch($id = null, $section_id = null, $order = 'ASC', $sortfield = 'sortorder', $type = null, $location = null, $where = null, $restrict = Field::__FIELD_ALL__) { $fields = array(); $returnSingle = false; $ids = array(); $field_contexts = array(); if (!is_null($id)) { if (is_numeric($id)) { $returnSingle = true; } if (!is_array($id)) { $field_ids = array((int)$id); } else { $field_ids = $id; } // Loop over the `$field_ids` and check to see we have // instances of the request fields foreach ($field_ids as $key => $field_id) { if ( isset(self::$_initialiased_fields[$field_id]) && self::$_initialiased_fields[$field_id] instanceof Field ) { $fields[$field_id] = self::$_initialiased_fields[$field_id]; unset($field_ids[$key]); } } } // If there is any `$field_ids` left to be resolved lets do that, otherwise // if `$id` wasn't provided in the first place, we'll also continue if (!empty($field_ids) || is_null($id)) { $sql = sprintf( "SELECT t1.* FROM tbl_fields AS `t1` WHERE 1 %s %s %s %s %s", (isset($type) ? " AND t1.`type` = '{$type}' " : null), (isset($location) ? " AND t1.`location` = '{$location}' " : null), (isset($section_id) ? " AND t1.`parent_section` = '{$section_id}' " : null), $where, isset($field_ids) ? " AND t1.`id` IN(" . implode(',', $field_ids) . ") " : " ORDER BY t1.`{$sortfield}` {$order}" ); if (!$result = Symphony::Database()->fetch($sql)) { return ($returnSingle ? null : array()); } // Loop over the resultset building an array of type, field_id foreach ($result as $f) { $ids[$f['type']][] = $f['id']; } // Loop over the `ids` array, which is grouped by field type // and get the field context. foreach ($ids as $type => $field_id) { $field_contexts[$type] = Symphony::Database()->fetch(sprintf( "SELECT * FROM `tbl_fields_%s` WHERE `field_id` IN (%s)", $type, implode(',', $field_id) ), 'field_id'); } foreach ($result as $f) { // We already have this field in our static store if ( isset(self::$_initialiased_fields[$f['id']]) && self::$_initialiased_fields[$f['id']] instanceof Field ) { $field = self::$_initialiased_fields[$f['id']]; // We don't have an instance of this field, so let's set one up } else { $field = self::create($f['type']); $field->setArray($f); // If the field has said that's going to have associations, then go find the // association setting value. In future this check will be most robust with // an interface, but for now, this is what we've got. RE: #2082 if ($field->canShowAssociationColumn()) { $field->set('show_association', SectionManager::getSectionAssociationSetting($f['id'])); } // Get the context for this field from our previous queries. $context = $field_contexts[$f['type']][$f['id']]; if (is_array($context) && !empty($context)) { try { unset($context['id']); $field->setArray($context); } catch (Exception $e) { throw new Exception(__( 'Settings for field %s could not be found in table tbl_fields_%s.', array($f['id'], $f['type']) )); } } self::$_initialiased_fields[$f['id']] = $field; } // Check to see if there was any restricts imposed on the fields if ( $restrict == Field::__FIELD_ALL__ || ($restrict == Field::__TOGGLEABLE_ONLY__ && $field->canToggle()) || ($restrict == Field::__UNTOGGLEABLE_ONLY__ && !$field->canToggle()) || ($restrict == Field::__FILTERABLE_ONLY__ && $field->canFilter()) || ($restrict == Field::__UNFILTERABLE_ONLY__ && !$field->canFilter()) ) { $fields[$f['id']] = $field; } } } return count($fields) <= 1 && $returnSingle ? current($fields) : $fields; }
php
public static function fetch($id = null, $section_id = null, $order = 'ASC', $sortfield = 'sortorder', $type = null, $location = null, $where = null, $restrict = Field::__FIELD_ALL__) { $fields = array(); $returnSingle = false; $ids = array(); $field_contexts = array(); if (!is_null($id)) { if (is_numeric($id)) { $returnSingle = true; } if (!is_array($id)) { $field_ids = array((int)$id); } else { $field_ids = $id; } // Loop over the `$field_ids` and check to see we have // instances of the request fields foreach ($field_ids as $key => $field_id) { if ( isset(self::$_initialiased_fields[$field_id]) && self::$_initialiased_fields[$field_id] instanceof Field ) { $fields[$field_id] = self::$_initialiased_fields[$field_id]; unset($field_ids[$key]); } } } // If there is any `$field_ids` left to be resolved lets do that, otherwise // if `$id` wasn't provided in the first place, we'll also continue if (!empty($field_ids) || is_null($id)) { $sql = sprintf( "SELECT t1.* FROM tbl_fields AS `t1` WHERE 1 %s %s %s %s %s", (isset($type) ? " AND t1.`type` = '{$type}' " : null), (isset($location) ? " AND t1.`location` = '{$location}' " : null), (isset($section_id) ? " AND t1.`parent_section` = '{$section_id}' " : null), $where, isset($field_ids) ? " AND t1.`id` IN(" . implode(',', $field_ids) . ") " : " ORDER BY t1.`{$sortfield}` {$order}" ); if (!$result = Symphony::Database()->fetch($sql)) { return ($returnSingle ? null : array()); } // Loop over the resultset building an array of type, field_id foreach ($result as $f) { $ids[$f['type']][] = $f['id']; } // Loop over the `ids` array, which is grouped by field type // and get the field context. foreach ($ids as $type => $field_id) { $field_contexts[$type] = Symphony::Database()->fetch(sprintf( "SELECT * FROM `tbl_fields_%s` WHERE `field_id` IN (%s)", $type, implode(',', $field_id) ), 'field_id'); } foreach ($result as $f) { // We already have this field in our static store if ( isset(self::$_initialiased_fields[$f['id']]) && self::$_initialiased_fields[$f['id']] instanceof Field ) { $field = self::$_initialiased_fields[$f['id']]; // We don't have an instance of this field, so let's set one up } else { $field = self::create($f['type']); $field->setArray($f); // If the field has said that's going to have associations, then go find the // association setting value. In future this check will be most robust with // an interface, but for now, this is what we've got. RE: #2082 if ($field->canShowAssociationColumn()) { $field->set('show_association', SectionManager::getSectionAssociationSetting($f['id'])); } // Get the context for this field from our previous queries. $context = $field_contexts[$f['type']][$f['id']]; if (is_array($context) && !empty($context)) { try { unset($context['id']); $field->setArray($context); } catch (Exception $e) { throw new Exception(__( 'Settings for field %s could not be found in table tbl_fields_%s.', array($f['id'], $f['type']) )); } } self::$_initialiased_fields[$f['id']] = $field; } // Check to see if there was any restricts imposed on the fields if ( $restrict == Field::__FIELD_ALL__ || ($restrict == Field::__TOGGLEABLE_ONLY__ && $field->canToggle()) || ($restrict == Field::__UNTOGGLEABLE_ONLY__ && !$field->canToggle()) || ($restrict == Field::__FILTERABLE_ONLY__ && $field->canFilter()) || ($restrict == Field::__UNFILTERABLE_ONLY__ && !$field->canFilter()) ) { $fields[$f['id']] = $field; } } } return count($fields) <= 1 && $returnSingle ? current($fields) : $fields; }
[ "public", "static", "function", "fetch", "(", "$", "id", "=", "null", ",", "$", "section_id", "=", "null", ",", "$", "order", "=", "'ASC'", ",", "$", "sortfield", "=", "'sortorder'", ",", "$", "type", "=", "null", ",", "$", "location", "=", "null", ",", "$", "where", "=", "null", ",", "$", "restrict", "=", "Field", "::", "__FIELD_ALL__", ")", "{", "$", "fields", "=", "array", "(", ")", ";", "$", "returnSingle", "=", "false", ";", "$", "ids", "=", "array", "(", ")", ";", "$", "field_contexts", "=", "array", "(", ")", ";", "if", "(", "!", "is_null", "(", "$", "id", ")", ")", "{", "if", "(", "is_numeric", "(", "$", "id", ")", ")", "{", "$", "returnSingle", "=", "true", ";", "}", "if", "(", "!", "is_array", "(", "$", "id", ")", ")", "{", "$", "field_ids", "=", "array", "(", "(", "int", ")", "$", "id", ")", ";", "}", "else", "{", "$", "field_ids", "=", "$", "id", ";", "}", "// Loop over the `$field_ids` and check to see we have", "// instances of the request fields", "foreach", "(", "$", "field_ids", "as", "$", "key", "=>", "$", "field_id", ")", "{", "if", "(", "isset", "(", "self", "::", "$", "_initialiased_fields", "[", "$", "field_id", "]", ")", "&&", "self", "::", "$", "_initialiased_fields", "[", "$", "field_id", "]", "instanceof", "Field", ")", "{", "$", "fields", "[", "$", "field_id", "]", "=", "self", "::", "$", "_initialiased_fields", "[", "$", "field_id", "]", ";", "unset", "(", "$", "field_ids", "[", "$", "key", "]", ")", ";", "}", "}", "}", "// If there is any `$field_ids` left to be resolved lets do that, otherwise", "// if `$id` wasn't provided in the first place, we'll also continue", "if", "(", "!", "empty", "(", "$", "field_ids", ")", "||", "is_null", "(", "$", "id", ")", ")", "{", "$", "sql", "=", "sprintf", "(", "\"SELECT t1.*\n FROM tbl_fields AS `t1`\n WHERE 1\n %s %s %s %s\n %s\"", ",", "(", "isset", "(", "$", "type", ")", "?", "\" AND t1.`type` = '{$type}' \"", ":", "null", ")", ",", "(", "isset", "(", "$", "location", ")", "?", "\" AND t1.`location` = '{$location}' \"", ":", "null", ")", ",", "(", "isset", "(", "$", "section_id", ")", "?", "\" AND t1.`parent_section` = '{$section_id}' \"", ":", "null", ")", ",", "$", "where", ",", "isset", "(", "$", "field_ids", ")", "?", "\" AND t1.`id` IN(\"", ".", "implode", "(", "','", ",", "$", "field_ids", ")", ".", "\") \"", ":", "\" ORDER BY t1.`{$sortfield}` {$order}\"", ")", ";", "if", "(", "!", "$", "result", "=", "Symphony", "::", "Database", "(", ")", "->", "fetch", "(", "$", "sql", ")", ")", "{", "return", "(", "$", "returnSingle", "?", "null", ":", "array", "(", ")", ")", ";", "}", "// Loop over the resultset building an array of type, field_id", "foreach", "(", "$", "result", "as", "$", "f", ")", "{", "$", "ids", "[", "$", "f", "[", "'type'", "]", "]", "[", "]", "=", "$", "f", "[", "'id'", "]", ";", "}", "// Loop over the `ids` array, which is grouped by field type", "// and get the field context.", "foreach", "(", "$", "ids", "as", "$", "type", "=>", "$", "field_id", ")", "{", "$", "field_contexts", "[", "$", "type", "]", "=", "Symphony", "::", "Database", "(", ")", "->", "fetch", "(", "sprintf", "(", "\"SELECT * FROM `tbl_fields_%s` WHERE `field_id` IN (%s)\"", ",", "$", "type", ",", "implode", "(", "','", ",", "$", "field_id", ")", ")", ",", "'field_id'", ")", ";", "}", "foreach", "(", "$", "result", "as", "$", "f", ")", "{", "// We already have this field in our static store", "if", "(", "isset", "(", "self", "::", "$", "_initialiased_fields", "[", "$", "f", "[", "'id'", "]", "]", ")", "&&", "self", "::", "$", "_initialiased_fields", "[", "$", "f", "[", "'id'", "]", "]", "instanceof", "Field", ")", "{", "$", "field", "=", "self", "::", "$", "_initialiased_fields", "[", "$", "f", "[", "'id'", "]", "]", ";", "// We don't have an instance of this field, so let's set one up", "}", "else", "{", "$", "field", "=", "self", "::", "create", "(", "$", "f", "[", "'type'", "]", ")", ";", "$", "field", "->", "setArray", "(", "$", "f", ")", ";", "// If the field has said that's going to have associations, then go find the", "// association setting value. In future this check will be most robust with", "// an interface, but for now, this is what we've got. RE: #2082", "if", "(", "$", "field", "->", "canShowAssociationColumn", "(", ")", ")", "{", "$", "field", "->", "set", "(", "'show_association'", ",", "SectionManager", "::", "getSectionAssociationSetting", "(", "$", "f", "[", "'id'", "]", ")", ")", ";", "}", "// Get the context for this field from our previous queries.", "$", "context", "=", "$", "field_contexts", "[", "$", "f", "[", "'type'", "]", "]", "[", "$", "f", "[", "'id'", "]", "]", ";", "if", "(", "is_array", "(", "$", "context", ")", "&&", "!", "empty", "(", "$", "context", ")", ")", "{", "try", "{", "unset", "(", "$", "context", "[", "'id'", "]", ")", ";", "$", "field", "->", "setArray", "(", "$", "context", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "throw", "new", "Exception", "(", "__", "(", "'Settings for field %s could not be found in table tbl_fields_%s.'", ",", "array", "(", "$", "f", "[", "'id'", "]", ",", "$", "f", "[", "'type'", "]", ")", ")", ")", ";", "}", "}", "self", "::", "$", "_initialiased_fields", "[", "$", "f", "[", "'id'", "]", "]", "=", "$", "field", ";", "}", "// Check to see if there was any restricts imposed on the fields", "if", "(", "$", "restrict", "==", "Field", "::", "__FIELD_ALL__", "||", "(", "$", "restrict", "==", "Field", "::", "__TOGGLEABLE_ONLY__", "&&", "$", "field", "->", "canToggle", "(", ")", ")", "||", "(", "$", "restrict", "==", "Field", "::", "__UNTOGGLEABLE_ONLY__", "&&", "!", "$", "field", "->", "canToggle", "(", ")", ")", "||", "(", "$", "restrict", "==", "Field", "::", "__FILTERABLE_ONLY__", "&&", "$", "field", "->", "canFilter", "(", ")", ")", "||", "(", "$", "restrict", "==", "Field", "::", "__UNFILTERABLE_ONLY__", "&&", "!", "$", "field", "->", "canFilter", "(", ")", ")", ")", "{", "$", "fields", "[", "$", "f", "[", "'id'", "]", "]", "=", "$", "field", ";", "}", "}", "}", "return", "count", "(", "$", "fields", ")", "<=", "1", "&&", "$", "returnSingle", "?", "current", "(", "$", "fields", ")", ":", "$", "fields", ";", "}" ]
The fetch method returns a instance of a Field from tbl_fields. The most common use of this function is to retrieve a Field by ID, but it can be used to retrieve Fields from a Section also. There are several parameters that can be used to fetch fields by their Type, Location, by a Field Constant or with a custom WHERE query. @throws DatabaseException @throws Exception @param integer|array $id The ID of the field to retrieve. Defaults to null which will return multiple field objects. Since Symphony 2.3, `$id` will accept an array of Field ID's @param integer $section_id The ID of the section to look for the fields in. Defaults to null which will allow all fields in the Symphony installation to be searched on. @param string $order Available values of ASC (Ascending) or DESC (Descending), which refer to the sort order for the query. Defaults to ASC (Ascending) @param string $sortfield The field to sort the query by. Can be any from the tbl_fields schema. Defaults to 'sortorder' @param string $type Filter fields by their type, ie. input, select. Defaults to null @param string $location Filter fields by their location in the entry form. There are two possible values, 'main' or 'sidebar'. Defaults to null @param string $where Allows a custom where query to be included. Must be valid SQL. The tbl_fields alias is t1 @param integer|string $restrict Only return fields if they match one of the Field Constants. Available values are `__TOGGLEABLE_ONLY__`, `__UNTOGGLEABLE_ONLY__`, `__FILTERABLE_ONLY__`, `__UNFILTERABLE_ONLY__` or `__FIELD_ALL__`. Defaults to `__FIELD_ALL__` @return array An array of Field objects. If no Field are found, null is returned.
[ "The", "fetch", "method", "returns", "a", "instance", "of", "a", "Field", "from", "tbl_fields", ".", "The", "most", "common", "use", "of", "this", "function", "is", "to", "retrieve", "a", "Field", "by", "ID", "but", "it", "can", "be", "used", "to", "retrieve", "Fields", "from", "a", "Section", "also", ".", "There", "are", "several", "parameters", "that", "can", "be", "used", "to", "fetch", "fields", "by", "their", "Type", "Location", "by", "a", "Field", "Constant", "or", "with", "a", "custom", "WHERE", "query", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.fieldmanager.php#L248-L365
symphonycms/symphony-2
symphony/lib/toolkit/class.fieldmanager.php
FieldManager.fetchFieldIDFromElementName
public static function fetchFieldIDFromElementName($element_name, $section_id = null) { if (is_null($element_name)) { $schema_sql = sprintf(" SELECT `id` FROM `tbl_fields` WHERE `parent_section` = %d ORDER BY `sortorder` ASC", $section_id ); } else { $element_names = !is_array($element_name) ? array($element_name) : $element_name; // allow for pseudo-fields containing colons (e.g. Textarea formatted/unformatted) foreach ($element_names as $index => $name) { $parts = explode(':', $name, 2); if (count($parts) == 1) { continue; } unset($element_names[$index]); // Prevent attempting to look up 'system', which will arise // from `system:pagination`, `system:id` etc. if ($parts[0] == 'system') { continue; } $element_names[] = Symphony::Database()->cleanValue(trim($parts[0])); } $schema_sql = empty($element_names) ? null : sprintf(" SELECT `id` FROM `tbl_fields` WHERE 1 %s AND `element_name` IN ('%s') ORDER BY `sortorder` ASC", (!is_null($section_id) ? sprintf("AND `parent_section` = %d", $section_id) : ""), implode("', '", array_map(array('MySQL', 'cleanValue'), array_unique($element_names))) ); } if (is_null($schema_sql)) { return false; } $result = Symphony::Database()->fetch($schema_sql); if (count($result) == 1) { return (int)$result[0]['id']; } elseif (empty($result)) { return false; } else { foreach ($result as &$r) { $r = (int)$r['id']; } return $result; } }
php
public static function fetchFieldIDFromElementName($element_name, $section_id = null) { if (is_null($element_name)) { $schema_sql = sprintf(" SELECT `id` FROM `tbl_fields` WHERE `parent_section` = %d ORDER BY `sortorder` ASC", $section_id ); } else { $element_names = !is_array($element_name) ? array($element_name) : $element_name; // allow for pseudo-fields containing colons (e.g. Textarea formatted/unformatted) foreach ($element_names as $index => $name) { $parts = explode(':', $name, 2); if (count($parts) == 1) { continue; } unset($element_names[$index]); // Prevent attempting to look up 'system', which will arise // from `system:pagination`, `system:id` etc. if ($parts[0] == 'system') { continue; } $element_names[] = Symphony::Database()->cleanValue(trim($parts[0])); } $schema_sql = empty($element_names) ? null : sprintf(" SELECT `id` FROM `tbl_fields` WHERE 1 %s AND `element_name` IN ('%s') ORDER BY `sortorder` ASC", (!is_null($section_id) ? sprintf("AND `parent_section` = %d", $section_id) : ""), implode("', '", array_map(array('MySQL', 'cleanValue'), array_unique($element_names))) ); } if (is_null($schema_sql)) { return false; } $result = Symphony::Database()->fetch($schema_sql); if (count($result) == 1) { return (int)$result[0]['id']; } elseif (empty($result)) { return false; } else { foreach ($result as &$r) { $r = (int)$r['id']; } return $result; } }
[ "public", "static", "function", "fetchFieldIDFromElementName", "(", "$", "element_name", ",", "$", "section_id", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "element_name", ")", ")", "{", "$", "schema_sql", "=", "sprintf", "(", "\"\n SELECT `id`\n FROM `tbl_fields`\n WHERE `parent_section` = %d\n ORDER BY `sortorder` ASC\"", ",", "$", "section_id", ")", ";", "}", "else", "{", "$", "element_names", "=", "!", "is_array", "(", "$", "element_name", ")", "?", "array", "(", "$", "element_name", ")", ":", "$", "element_name", ";", "// allow for pseudo-fields containing colons (e.g. Textarea formatted/unformatted)", "foreach", "(", "$", "element_names", "as", "$", "index", "=>", "$", "name", ")", "{", "$", "parts", "=", "explode", "(", "':'", ",", "$", "name", ",", "2", ")", ";", "if", "(", "count", "(", "$", "parts", ")", "==", "1", ")", "{", "continue", ";", "}", "unset", "(", "$", "element_names", "[", "$", "index", "]", ")", ";", "// Prevent attempting to look up 'system', which will arise", "// from `system:pagination`, `system:id` etc.", "if", "(", "$", "parts", "[", "0", "]", "==", "'system'", ")", "{", "continue", ";", "}", "$", "element_names", "[", "]", "=", "Symphony", "::", "Database", "(", ")", "->", "cleanValue", "(", "trim", "(", "$", "parts", "[", "0", "]", ")", ")", ";", "}", "$", "schema_sql", "=", "empty", "(", "$", "element_names", ")", "?", "null", ":", "sprintf", "(", "\"\n SELECT `id`\n FROM `tbl_fields`\n WHERE 1\n %s\n AND `element_name` IN ('%s')\n ORDER BY `sortorder` ASC\"", ",", "(", "!", "is_null", "(", "$", "section_id", ")", "?", "sprintf", "(", "\"AND `parent_section` = %d\"", ",", "$", "section_id", ")", ":", "\"\"", ")", ",", "implode", "(", "\"', '\"", ",", "array_map", "(", "array", "(", "'MySQL'", ",", "'cleanValue'", ")", ",", "array_unique", "(", "$", "element_names", ")", ")", ")", ")", ";", "}", "if", "(", "is_null", "(", "$", "schema_sql", ")", ")", "{", "return", "false", ";", "}", "$", "result", "=", "Symphony", "::", "Database", "(", ")", "->", "fetch", "(", "$", "schema_sql", ")", ";", "if", "(", "count", "(", "$", "result", ")", "==", "1", ")", "{", "return", "(", "int", ")", "$", "result", "[", "0", "]", "[", "'id'", "]", ";", "}", "elseif", "(", "empty", "(", "$", "result", ")", ")", "{", "return", "false", ";", "}", "else", "{", "foreach", "(", "$", "result", "as", "&", "$", "r", ")", "{", "$", "r", "=", "(", "int", ")", "$", "r", "[", "'id'", "]", ";", "}", "return", "$", "result", ";", "}", "}" ]
Given an `$element_name` and a `$section_id`, return the Field ID. Symphony enforces a uniqueness constraint on a section where every field must have a unique label (and therefore handle) so whilst it is impossible to have two fields from the same section, it would be possible to have two fields with the same name from different sections. Passing the `$section_id` lets you to specify which section should be searched. If `$element_name` is null, this function will return all the Field ID's from the given `$section_id`. @throws DatabaseException @since Symphony 2.3 This function can now accept $element_name as an array of handles. These handles can now also include the handle's mode, eg. `title: formatted` @param string|array $element_name The handle of the Field label, or an array of handles. These handles may contain a mode as well, eg. `title: formatted`. @param integer $section_id The section that this field belongs too The field ID, or an array of field ID's @return mixed
[ "Given", "an", "$element_name", "and", "a", "$section_id", "return", "the", "Field", "ID", ".", "Symphony", "enforces", "a", "uniqueness", "constraint", "on", "a", "section", "where", "every", "field", "must", "have", "a", "unique", "label", "(", "and", "therefore", "handle", ")", "so", "whilst", "it", "is", "impossible", "to", "have", "two", "fields", "from", "the", "same", "section", "it", "would", "be", "possible", "to", "have", "two", "fields", "with", "the", "same", "name", "from", "different", "sections", ".", "Passing", "the", "$section_id", "lets", "you", "to", "specify", "which", "section", "should", "be", "searched", ".", "If", "$element_name", "is", "null", "this", "function", "will", "return", "all", "the", "Field", "ID", "s", "from", "the", "given", "$section_id", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.fieldmanager.php#L415-L476
symphonycms/symphony-2
symphony/lib/toolkit/class.fieldmanager.php
FieldManager.listAll
public static function listAll() { $structure = General::listStructure(TOOLKIT . '/fields', '/field.[a-z0-9_-]+.php/i', false, 'asc', TOOLKIT . '/fields'); $extensions = Symphony::ExtensionManager()->listInstalledHandles(); $types = array(); if (is_array($extensions) && !empty($extensions)) { foreach ($extensions as $handle) { $path = EXTENSIONS . '/' . $handle . '/fields'; if (is_dir($path)) { $tmp = General::listStructure($path, '/field.[a-z0-9_-]+.php/i', false, 'asc', $path); if (is_array($tmp['filelist']) && !empty($tmp['filelist'])) { $structure['filelist'] = array_merge($structure['filelist'], $tmp['filelist']); } } } $structure['filelist'] = General::array_remove_duplicates($structure['filelist']); } foreach ($structure['filelist'] as $filename) { $types[] = self::__getHandleFromFilename($filename); } return $types; }
php
public static function listAll() { $structure = General::listStructure(TOOLKIT . '/fields', '/field.[a-z0-9_-]+.php/i', false, 'asc', TOOLKIT . '/fields'); $extensions = Symphony::ExtensionManager()->listInstalledHandles(); $types = array(); if (is_array($extensions) && !empty($extensions)) { foreach ($extensions as $handle) { $path = EXTENSIONS . '/' . $handle . '/fields'; if (is_dir($path)) { $tmp = General::listStructure($path, '/field.[a-z0-9_-]+.php/i', false, 'asc', $path); if (is_array($tmp['filelist']) && !empty($tmp['filelist'])) { $structure['filelist'] = array_merge($structure['filelist'], $tmp['filelist']); } } } $structure['filelist'] = General::array_remove_duplicates($structure['filelist']); } foreach ($structure['filelist'] as $filename) { $types[] = self::__getHandleFromFilename($filename); } return $types; }
[ "public", "static", "function", "listAll", "(", ")", "{", "$", "structure", "=", "General", "::", "listStructure", "(", "TOOLKIT", ".", "'/fields'", ",", "'/field.[a-z0-9_-]+.php/i'", ",", "false", ",", "'asc'", ",", "TOOLKIT", ".", "'/fields'", ")", ";", "$", "extensions", "=", "Symphony", "::", "ExtensionManager", "(", ")", "->", "listInstalledHandles", "(", ")", ";", "$", "types", "=", "array", "(", ")", ";", "if", "(", "is_array", "(", "$", "extensions", ")", "&&", "!", "empty", "(", "$", "extensions", ")", ")", "{", "foreach", "(", "$", "extensions", "as", "$", "handle", ")", "{", "$", "path", "=", "EXTENSIONS", ".", "'/'", ".", "$", "handle", ".", "'/fields'", ";", "if", "(", "is_dir", "(", "$", "path", ")", ")", "{", "$", "tmp", "=", "General", "::", "listStructure", "(", "$", "path", ",", "'/field.[a-z0-9_-]+.php/i'", ",", "false", ",", "'asc'", ",", "$", "path", ")", ";", "if", "(", "is_array", "(", "$", "tmp", "[", "'filelist'", "]", ")", "&&", "!", "empty", "(", "$", "tmp", "[", "'filelist'", "]", ")", ")", "{", "$", "structure", "[", "'filelist'", "]", "=", "array_merge", "(", "$", "structure", "[", "'filelist'", "]", ",", "$", "tmp", "[", "'filelist'", "]", ")", ";", "}", "}", "}", "$", "structure", "[", "'filelist'", "]", "=", "General", "::", "array_remove_duplicates", "(", "$", "structure", "[", "'filelist'", "]", ")", ";", "}", "foreach", "(", "$", "structure", "[", "'filelist'", "]", "as", "$", "filename", ")", "{", "$", "types", "[", "]", "=", "self", "::", "__getHandleFromFilename", "(", "$", "filename", ")", ";", "}", "return", "$", "types", ";", "}" ]
Returns an array of all available field handles discovered in the `TOOLKIT . /fields` or `EXTENSIONS . /extension_handle/fields`. @return array A single dimensional array of field handles.
[ "Returns", "an", "array", "of", "all", "available", "field", "handles", "discovered", "in", "the", "TOOLKIT", ".", "/", "fields", "or", "EXTENSIONS", ".", "/", "extension_handle", "/", "fields", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.fieldmanager.php#L528-L554
symphonycms/symphony-2
symphony/lib/toolkit/class.fieldmanager.php
FieldManager.create
public static function create($type) { if (!isset(self::$_pool[$type])) { $classname = self::__getClassName($type); $path = self::__getDriverPath($type); if (!file_exists($path)) { throw new Exception( __('Could not find Field %1$s at %2$s.', array('<code>' . $type . '</code>', '<code>' . $path . '</code>')) . ' ' . __('If it was provided by an Extension, ensure that it is installed, and enabled.') ); } if (!class_exists($classname)) { require_once($path); } self::$_pool[$type] = new $classname; if (self::$_pool[$type]->canShowTableColumn() && !self::$_pool[$type]->get('show_column')) { self::$_pool[$type]->set('show_column', 'yes'); } } return clone self::$_pool[$type]; }
php
public static function create($type) { if (!isset(self::$_pool[$type])) { $classname = self::__getClassName($type); $path = self::__getDriverPath($type); if (!file_exists($path)) { throw new Exception( __('Could not find Field %1$s at %2$s.', array('<code>' . $type . '</code>', '<code>' . $path . '</code>')) . ' ' . __('If it was provided by an Extension, ensure that it is installed, and enabled.') ); } if (!class_exists($classname)) { require_once($path); } self::$_pool[$type] = new $classname; if (self::$_pool[$type]->canShowTableColumn() && !self::$_pool[$type]->get('show_column')) { self::$_pool[$type]->set('show_column', 'yes'); } } return clone self::$_pool[$type]; }
[ "public", "static", "function", "create", "(", "$", "type", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "_pool", "[", "$", "type", "]", ")", ")", "{", "$", "classname", "=", "self", "::", "__getClassName", "(", "$", "type", ")", ";", "$", "path", "=", "self", "::", "__getDriverPath", "(", "$", "type", ")", ";", "if", "(", "!", "file_exists", "(", "$", "path", ")", ")", "{", "throw", "new", "Exception", "(", "__", "(", "'Could not find Field %1$s at %2$s.'", ",", "array", "(", "'<code>'", ".", "$", "type", ".", "'</code>'", ",", "'<code>'", ".", "$", "path", ".", "'</code>'", ")", ")", ".", "' '", ".", "__", "(", "'If it was provided by an Extension, ensure that it is installed, and enabled.'", ")", ")", ";", "}", "if", "(", "!", "class_exists", "(", "$", "classname", ")", ")", "{", "require_once", "(", "$", "path", ")", ";", "}", "self", "::", "$", "_pool", "[", "$", "type", "]", "=", "new", "$", "classname", ";", "if", "(", "self", "::", "$", "_pool", "[", "$", "type", "]", "->", "canShowTableColumn", "(", ")", "&&", "!", "self", "::", "$", "_pool", "[", "$", "type", "]", "->", "get", "(", "'show_column'", ")", ")", "{", "self", "::", "$", "_pool", "[", "$", "type", "]", "->", "set", "(", "'show_column'", ",", "'yes'", ")", ";", "}", "}", "return", "clone", "self", "::", "$", "_pool", "[", "$", "type", "]", ";", "}" ]
Creates an instance of a given class and returns it. Adds the instance to the `$_pool` array with the key being the handle. @throws Exception @param string $type The handle of the Field to create (which is it's handle) @return Field
[ "Creates", "an", "instance", "of", "a", "given", "class", "and", "returns", "it", ".", "Adds", "the", "instance", "to", "the", "$_pool", "array", "with", "the", "key", "being", "the", "handle", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.fieldmanager.php#L565-L590
symphonycms/symphony-2
symphony/lib/toolkit/class.fieldmanager.php
FieldManager.isTextFormatterUsed
public static function isTextFormatterUsed($text_formatter_handle) { $fields = Symphony::Database()->fetchCol('type', "SELECT DISTINCT `type` FROM `tbl_fields` WHERE `type` NOT IN ('author', 'checkbox', 'date', 'input', 'select', 'taglist', 'upload')"); if (!empty($fields)) { foreach ($fields as $field) { try { $table = Symphony::Database()->fetchVar('count', 0, sprintf( "SELECT COUNT(*) AS `count` FROM `tbl_fields_%s` WHERE `formatter` = '%s'", Symphony::Database()->cleanValue($field), $text_formatter_handle )); } catch (DatabaseException $ex) { // Table probably didn't have that column } if ($table > 0) { return true; } } } return false; }
php
public static function isTextFormatterUsed($text_formatter_handle) { $fields = Symphony::Database()->fetchCol('type', "SELECT DISTINCT `type` FROM `tbl_fields` WHERE `type` NOT IN ('author', 'checkbox', 'date', 'input', 'select', 'taglist', 'upload')"); if (!empty($fields)) { foreach ($fields as $field) { try { $table = Symphony::Database()->fetchVar('count', 0, sprintf( "SELECT COUNT(*) AS `count` FROM `tbl_fields_%s` WHERE `formatter` = '%s'", Symphony::Database()->cleanValue($field), $text_formatter_handle )); } catch (DatabaseException $ex) { // Table probably didn't have that column } if ($table > 0) { return true; } } } return false; }
[ "public", "static", "function", "isTextFormatterUsed", "(", "$", "text_formatter_handle", ")", "{", "$", "fields", "=", "Symphony", "::", "Database", "(", ")", "->", "fetchCol", "(", "'type'", ",", "\"SELECT DISTINCT `type` FROM `tbl_fields` WHERE `type` NOT IN ('author', 'checkbox', 'date', 'input', 'select', 'taglist', 'upload')\"", ")", ";", "if", "(", "!", "empty", "(", "$", "fields", ")", ")", "{", "foreach", "(", "$", "fields", "as", "$", "field", ")", "{", "try", "{", "$", "table", "=", "Symphony", "::", "Database", "(", ")", "->", "fetchVar", "(", "'count'", ",", "0", ",", "sprintf", "(", "\"SELECT COUNT(*) AS `count`\n FROM `tbl_fields_%s`\n WHERE `formatter` = '%s'\"", ",", "Symphony", "::", "Database", "(", ")", "->", "cleanValue", "(", "$", "field", ")", ",", "$", "text_formatter_handle", ")", ")", ";", "}", "catch", "(", "DatabaseException", "$", "ex", ")", "{", "// Table probably didn't have that column", "}", "if", "(", "$", "table", ">", "0", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
Check if a specific text formatter is used by a Field @since Symphony 2.3 @param string $text_formatter_handle The handle of the `TextFormatter` @return boolean true if used, false if not
[ "Check", "if", "a", "specific", "text", "formatter", "is", "used", "by", "a", "Field" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.fieldmanager.php#L617-L642
symphonycms/symphony-2
symphony/lib/toolkit/class.author.php
Author.get
public function get($field = null) { if (is_null($field)) { return $this->_fields; } if (!isset($this->_fields[$field]) || $this->_fields[$field] == '') { return null; } return $this->_fields[$field]; }
php
public function get($field = null) { if (is_null($field)) { return $this->_fields; } if (!isset($this->_fields[$field]) || $this->_fields[$field] == '') { return null; } return $this->_fields[$field]; }
[ "public", "function", "get", "(", "$", "field", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "field", ")", ")", "{", "return", "$", "this", "->", "_fields", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "_fields", "[", "$", "field", "]", ")", "||", "$", "this", "->", "_fields", "[", "$", "field", "]", "==", "''", ")", "{", "return", "null", ";", "}", "return", "$", "this", "->", "_fields", "[", "$", "field", "]", ";", "}" ]
Retrieves the value from the Author object by field from `$this->_fields` array. If field is omitted, all fields are returned. @param string $field Maps directly to a column in the `tbl_authors` table. Defaults to null @return mixed If the field is not set or is empty, returns null. If the field is not provided, returns the `$this->_fields` array Otherwise returns a string.
[ "Retrieves", "the", "value", "from", "the", "Author", "object", "by", "field", "from", "$this", "-", ">", "_fields", "array", ".", "If", "field", "is", "omitted", "all", "fields", "are", "returned", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.author.php#L49-L60
symphonycms/symphony-2
symphony/lib/toolkit/class.author.php
Author.validate
public function validate(&$errors) { $errors = array(); $current_author = null; if (is_null($this->get('first_name'))) { $errors['first_name'] = __('First name is required'); } if (is_null($this->get('last_name'))) { $errors['last_name'] = __('Last name is required'); } if ($this->get('id')) { $current_author = Symphony::Database()->fetchRow(0, sprintf( "SELECT `email`, `username` FROM `tbl_authors` WHERE `id` = %d", $this->get('id') )); } // Include validators include TOOLKIT . '/util.validators.php'; // Check that Email is provided if (is_null($this->get('email'))) { $errors['email'] = __('E-mail address is required'); // Check Email is valid } elseif (isset($validators['email']) && !General::validateString($this->get('email'), $validators['email'])) { $errors['email'] = __('E-mail address entered is invalid'); // Check Email is valid, fallback when no validator found } elseif (!isset($validators['email']) && !filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors['email'] = __('E-mail address entered is invalid'); // Check that if an existing Author changes their email address that // it is not already used by another Author } elseif ($this->get('id')) { if ( $current_author['email'] !== $this->get('email') && Symphony::Database()->fetchVar('count', 0, sprintf( "SELECT COUNT(`id`) as `count` FROM `tbl_authors` WHERE `email` = '%s'", Symphony::Database()->cleanValue($this->get('email')) )) != 0 ) { $errors['email'] = __('E-mail address is already taken'); } // Check that Email is not in use by another Author } elseif (Symphony::Database()->fetchVar('id', 0, sprintf( "SELECT `id` FROM `tbl_authors` WHERE `email` = '%s' LIMIT 1", Symphony::Database()->cleanValue($this->get('email')) ))) { $errors['email'] = __('E-mail address is already taken'); } // Check the username exists if (is_null($this->get('username'))) { $errors['username'] = __('Username is required'); // Check that if it's an existing Author that the username is not already // in use by another Author if they are trying to change it. } elseif ($this->get('id')) { if ( $current_author['username'] !== $this->get('username') && Symphony::Database()->fetchVar('count', 0, sprintf( "SELECT COUNT(`id`) as `count` FROM `tbl_authors` WHERE `username` = '%s'", Symphony::Database()->cleanValue($this->get('username')) )) != 0 ) { $errors['username'] = __('Username is already taken'); } // Check that the username is unique } elseif (Symphony::Database()->fetchVar('id', 0, sprintf( "SELECT `id` FROM `tbl_authors` WHERE `username` = '%s' LIMIT 1", Symphony::Database()->cleanValue($this->get('username')) ))) { $errors['username'] = __('Username is already taken'); } if (is_null($this->get('password'))) { $errors['password'] = __('Password is required'); } return (empty($errors) ? true : false); }
php
public function validate(&$errors) { $errors = array(); $current_author = null; if (is_null($this->get('first_name'))) { $errors['first_name'] = __('First name is required'); } if (is_null($this->get('last_name'))) { $errors['last_name'] = __('Last name is required'); } if ($this->get('id')) { $current_author = Symphony::Database()->fetchRow(0, sprintf( "SELECT `email`, `username` FROM `tbl_authors` WHERE `id` = %d", $this->get('id') )); } // Include validators include TOOLKIT . '/util.validators.php'; // Check that Email is provided if (is_null($this->get('email'))) { $errors['email'] = __('E-mail address is required'); // Check Email is valid } elseif (isset($validators['email']) && !General::validateString($this->get('email'), $validators['email'])) { $errors['email'] = __('E-mail address entered is invalid'); // Check Email is valid, fallback when no validator found } elseif (!isset($validators['email']) && !filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors['email'] = __('E-mail address entered is invalid'); // Check that if an existing Author changes their email address that // it is not already used by another Author } elseif ($this->get('id')) { if ( $current_author['email'] !== $this->get('email') && Symphony::Database()->fetchVar('count', 0, sprintf( "SELECT COUNT(`id`) as `count` FROM `tbl_authors` WHERE `email` = '%s'", Symphony::Database()->cleanValue($this->get('email')) )) != 0 ) { $errors['email'] = __('E-mail address is already taken'); } // Check that Email is not in use by another Author } elseif (Symphony::Database()->fetchVar('id', 0, sprintf( "SELECT `id` FROM `tbl_authors` WHERE `email` = '%s' LIMIT 1", Symphony::Database()->cleanValue($this->get('email')) ))) { $errors['email'] = __('E-mail address is already taken'); } // Check the username exists if (is_null($this->get('username'))) { $errors['username'] = __('Username is required'); // Check that if it's an existing Author that the username is not already // in use by another Author if they are trying to change it. } elseif ($this->get('id')) { if ( $current_author['username'] !== $this->get('username') && Symphony::Database()->fetchVar('count', 0, sprintf( "SELECT COUNT(`id`) as `count` FROM `tbl_authors` WHERE `username` = '%s'", Symphony::Database()->cleanValue($this->get('username')) )) != 0 ) { $errors['username'] = __('Username is already taken'); } // Check that the username is unique } elseif (Symphony::Database()->fetchVar('id', 0, sprintf( "SELECT `id` FROM `tbl_authors` WHERE `username` = '%s' LIMIT 1", Symphony::Database()->cleanValue($this->get('username')) ))) { $errors['username'] = __('Username is already taken'); } if (is_null($this->get('password'))) { $errors['password'] = __('Password is required'); } return (empty($errors) ? true : false); }
[ "public", "function", "validate", "(", "&", "$", "errors", ")", "{", "$", "errors", "=", "array", "(", ")", ";", "$", "current_author", "=", "null", ";", "if", "(", "is_null", "(", "$", "this", "->", "get", "(", "'first_name'", ")", ")", ")", "{", "$", "errors", "[", "'first_name'", "]", "=", "__", "(", "'First name is required'", ")", ";", "}", "if", "(", "is_null", "(", "$", "this", "->", "get", "(", "'last_name'", ")", ")", ")", "{", "$", "errors", "[", "'last_name'", "]", "=", "__", "(", "'Last name is required'", ")", ";", "}", "if", "(", "$", "this", "->", "get", "(", "'id'", ")", ")", "{", "$", "current_author", "=", "Symphony", "::", "Database", "(", ")", "->", "fetchRow", "(", "0", ",", "sprintf", "(", "\"SELECT `email`, `username`\n FROM `tbl_authors`\n WHERE `id` = %d\"", ",", "$", "this", "->", "get", "(", "'id'", ")", ")", ")", ";", "}", "// Include validators", "include", "TOOLKIT", ".", "'/util.validators.php'", ";", "// Check that Email is provided", "if", "(", "is_null", "(", "$", "this", "->", "get", "(", "'email'", ")", ")", ")", "{", "$", "errors", "[", "'email'", "]", "=", "__", "(", "'E-mail address is required'", ")", ";", "// Check Email is valid", "}", "elseif", "(", "isset", "(", "$", "validators", "[", "'email'", "]", ")", "&&", "!", "General", "::", "validateString", "(", "$", "this", "->", "get", "(", "'email'", ")", ",", "$", "validators", "[", "'email'", "]", ")", ")", "{", "$", "errors", "[", "'email'", "]", "=", "__", "(", "'E-mail address entered is invalid'", ")", ";", "// Check Email is valid, fallback when no validator found", "}", "elseif", "(", "!", "isset", "(", "$", "validators", "[", "'email'", "]", ")", "&&", "!", "filter_var", "(", "$", "email", ",", "FILTER_VALIDATE_EMAIL", ")", ")", "{", "$", "errors", "[", "'email'", "]", "=", "__", "(", "'E-mail address entered is invalid'", ")", ";", "// Check that if an existing Author changes their email address that", "// it is not already used by another Author", "}", "elseif", "(", "$", "this", "->", "get", "(", "'id'", ")", ")", "{", "if", "(", "$", "current_author", "[", "'email'", "]", "!==", "$", "this", "->", "get", "(", "'email'", ")", "&&", "Symphony", "::", "Database", "(", ")", "->", "fetchVar", "(", "'count'", ",", "0", ",", "sprintf", "(", "\"SELECT COUNT(`id`) as `count`\n FROM `tbl_authors`\n WHERE `email` = '%s'\"", ",", "Symphony", "::", "Database", "(", ")", "->", "cleanValue", "(", "$", "this", "->", "get", "(", "'email'", ")", ")", ")", ")", "!=", "0", ")", "{", "$", "errors", "[", "'email'", "]", "=", "__", "(", "'E-mail address is already taken'", ")", ";", "}", "// Check that Email is not in use by another Author", "}", "elseif", "(", "Symphony", "::", "Database", "(", ")", "->", "fetchVar", "(", "'id'", ",", "0", ",", "sprintf", "(", "\"SELECT `id`\n FROM `tbl_authors`\n WHERE `email` = '%s'\n LIMIT 1\"", ",", "Symphony", "::", "Database", "(", ")", "->", "cleanValue", "(", "$", "this", "->", "get", "(", "'email'", ")", ")", ")", ")", ")", "{", "$", "errors", "[", "'email'", "]", "=", "__", "(", "'E-mail address is already taken'", ")", ";", "}", "// Check the username exists", "if", "(", "is_null", "(", "$", "this", "->", "get", "(", "'username'", ")", ")", ")", "{", "$", "errors", "[", "'username'", "]", "=", "__", "(", "'Username is required'", ")", ";", "// Check that if it's an existing Author that the username is not already", "// in use by another Author if they are trying to change it.", "}", "elseif", "(", "$", "this", "->", "get", "(", "'id'", ")", ")", "{", "if", "(", "$", "current_author", "[", "'username'", "]", "!==", "$", "this", "->", "get", "(", "'username'", ")", "&&", "Symphony", "::", "Database", "(", ")", "->", "fetchVar", "(", "'count'", ",", "0", ",", "sprintf", "(", "\"SELECT COUNT(`id`) as `count`\n FROM `tbl_authors`\n WHERE `username` = '%s'\"", ",", "Symphony", "::", "Database", "(", ")", "->", "cleanValue", "(", "$", "this", "->", "get", "(", "'username'", ")", ")", ")", ")", "!=", "0", ")", "{", "$", "errors", "[", "'username'", "]", "=", "__", "(", "'Username is already taken'", ")", ";", "}", "// Check that the username is unique", "}", "elseif", "(", "Symphony", "::", "Database", "(", ")", "->", "fetchVar", "(", "'id'", ",", "0", ",", "sprintf", "(", "\"SELECT `id`\n FROM `tbl_authors`\n WHERE `username` = '%s'\n LIMIT 1\"", ",", "Symphony", "::", "Database", "(", ")", "->", "cleanValue", "(", "$", "this", "->", "get", "(", "'username'", ")", ")", ")", ")", ")", "{", "$", "errors", "[", "'username'", "]", "=", "__", "(", "'Username is already taken'", ")", ";", "}", "if", "(", "is_null", "(", "$", "this", "->", "get", "(", "'password'", ")", ")", ")", "{", "$", "errors", "[", "'password'", "]", "=", "__", "(", "'Password is required'", ")", ";", "}", "return", "(", "empty", "(", "$", "errors", ")", "?", "true", ":", "false", ")", ";", "}" ]
Prior to saving an Author object, the validate function ensures that the values in `$this->_fields` array are correct. As of Symphony 2.3 Authors must have unique username AND email address. This function returns boolean, with an `$errors` array provided by reference to the callee function. @param array $errors @return boolean
[ "Prior", "to", "saving", "an", "Author", "object", "the", "validate", "function", "ensures", "that", "the", "values", "in", "$this", "-", ">", "_fields", "array", "are", "correct", ".", "As", "of", "Symphony", "2", ".", "3", "Authors", "must", "have", "unique", "username", "AND", "email", "address", ".", "This", "function", "returns", "boolean", "with", "an", "$errors", "array", "provided", "by", "reference", "to", "the", "callee", "function", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.author.php#L170-L268
symphonycms/symphony-2
symphony/lib/toolkit/class.author.php
Author.commit
public function commit() { if (!is_null($this->get('id'))) { $id = $this->get('id'); $this->remove('id'); if (AuthorManager::edit($id, $this->get())) { $this->set('id', $id); return $id; } else { return false; } } else { $id = AuthorManager::add($this->get()); if ($id) { $this->set('id', $id); } return $id; } }
php
public function commit() { if (!is_null($this->get('id'))) { $id = $this->get('id'); $this->remove('id'); if (AuthorManager::edit($id, $this->get())) { $this->set('id', $id); return $id; } else { return false; } } else { $id = AuthorManager::add($this->get()); if ($id) { $this->set('id', $id); } return $id; } }
[ "public", "function", "commit", "(", ")", "{", "if", "(", "!", "is_null", "(", "$", "this", "->", "get", "(", "'id'", ")", ")", ")", "{", "$", "id", "=", "$", "this", "->", "get", "(", "'id'", ")", ";", "$", "this", "->", "remove", "(", "'id'", ")", ";", "if", "(", "AuthorManager", "::", "edit", "(", "$", "id", ",", "$", "this", "->", "get", "(", ")", ")", ")", "{", "$", "this", "->", "set", "(", "'id'", ",", "$", "id", ")", ";", "return", "$", "id", ";", "}", "else", "{", "return", "false", ";", "}", "}", "else", "{", "$", "id", "=", "AuthorManager", "::", "add", "(", "$", "this", "->", "get", "(", ")", ")", ";", "if", "(", "$", "id", ")", "{", "$", "this", "->", "set", "(", "'id'", ",", "$", "id", ")", ";", "}", "return", "$", "id", ";", "}", "}" ]
This is the insert method for the Author. This takes the current `$this->_fields` values and adds them to the database using either the `AuthorManager::edit` or `AuthorManager::add` functions. An existing user is determined by if an ID is already set. When the database is updated successfully, the id of the author is set. @see toolkit.AuthorManager#add() @see toolkit.AuthorManager#edit() @return integer|boolean When a new Author is added or updated, an integer of the Author ID will be returned, otherwise false will be returned for a failed update.
[ "This", "is", "the", "insert", "method", "for", "the", "Author", ".", "This", "takes", "the", "current", "$this", "-", ">", "_fields", "values", "and", "adds", "them", "to", "the", "database", "using", "either", "the", "AuthorManager", "::", "edit", "or", "AuthorManager", "::", "add", "functions", ".", "An", "existing", "user", "is", "determined", "by", "if", "an", "ID", "is", "already", "set", ".", "When", "the", "database", "is", "updated", "successfully", "the", "id", "of", "the", "author", "is", "set", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.author.php#L283-L302
symphonycms/symphony-2
symphony/lib/core/class.configuration.php
Configuration.set
public function set($name, $value, $group = null) { if ($this->_forceLowerCase) { $name = strtolower($name); $group = strtolower($group); } if ($group) { $this->_properties[$group][$name] = $value; } else { $this->_properties[$name] = $value; } }
php
public function set($name, $value, $group = null) { if ($this->_forceLowerCase) { $name = strtolower($name); $group = strtolower($group); } if ($group) { $this->_properties[$group][$name] = $value; } else { $this->_properties[$name] = $value; } }
[ "public", "function", "set", "(", "$", "name", ",", "$", "value", ",", "$", "group", "=", "null", ")", "{", "if", "(", "$", "this", "->", "_forceLowerCase", ")", "{", "$", "name", "=", "strtolower", "(", "$", "name", ")", ";", "$", "group", "=", "strtolower", "(", "$", "group", ")", ";", "}", "if", "(", "$", "group", ")", "{", "$", "this", "->", "_properties", "[", "$", "group", "]", "[", "$", "name", "]", "=", "$", "value", ";", "}", "else", "{", "$", "this", "->", "_properties", "[", "$", "name", "]", "=", "$", "value", ";", "}", "}" ]
Setter for the `$this->_properties`. The properties array can be grouped to be an 'array' of an 'array' of properties. For instance a 'region' key may be an array of 'properties' (that is name/value), or it may be a 'value' itself. @param string $name The name of the property to set, eg 'timezone' @param array|string|integer|float|boolean $value The value for the property to set, eg. '+10:00' @param string $group The group for this property, eg. 'region'
[ "Setter", "for", "the", "$this", "-", ">", "_properties", ".", "The", "properties", "array", "can", "be", "grouped", "to", "be", "an", "array", "of", "an", "array", "of", "properties", ".", "For", "instance", "a", "region", "key", "may", "be", "an", "array", "of", "properties", "(", "that", "is", "name", "/", "value", ")", "or", "it", "may", "be", "a", "value", "itself", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.configuration.php#L64-L76
symphonycms/symphony-2
symphony/lib/core/class.configuration.php
Configuration.setArray
public function setArray(array $array, $overwrite = false) { if ($overwrite) { $this->_properties = array_merge($this->_properties, $array); } else { foreach ($array as $set => $values) { foreach ($values as $key => $val) { self::set($key, $val, $set); } } } }
php
public function setArray(array $array, $overwrite = false) { if ($overwrite) { $this->_properties = array_merge($this->_properties, $array); } else { foreach ($array as $set => $values) { foreach ($values as $key => $val) { self::set($key, $val, $set); } } } }
[ "public", "function", "setArray", "(", "array", "$", "array", ",", "$", "overwrite", "=", "false", ")", "{", "if", "(", "$", "overwrite", ")", "{", "$", "this", "->", "_properties", "=", "array_merge", "(", "$", "this", "->", "_properties", ",", "$", "array", ")", ";", "}", "else", "{", "foreach", "(", "$", "array", "as", "$", "set", "=>", "$", "values", ")", "{", "foreach", "(", "$", "values", "as", "$", "key", "=>", "$", "val", ")", "{", "self", "::", "set", "(", "$", "key", ",", "$", "val", ",", "$", "set", ")", ";", "}", "}", "}", "}" ]
A quick way to set a large number of properties. Given an associative array or a nested associative array (where the key will be the group), this function will merge the `$array` with the existing configuration. By default the given `$array` will overwrite any existing keys unless the `$overwrite` parameter is passed as false. @since Symphony 2.3.2 The `$overwrite` parameter is available @param array $array An associative array of properties, 'property' => 'value' or 'group' => array('property' => 'value') @param boolean $overwrite An optional boolean parameter to indicate if it is safe to use array_merge or if the provided array should be integrated using the 'set()' method to avoid possible change collision. Defaults to false.
[ "A", "quick", "way", "to", "set", "a", "large", "number", "of", "properties", ".", "Given", "an", "associative", "array", "or", "a", "nested", "associative", "array", "(", "where", "the", "key", "will", "be", "the", "group", ")", "this", "function", "will", "merge", "the", "$array", "with", "the", "existing", "configuration", ".", "By", "default", "the", "given", "$array", "will", "overwrite", "any", "existing", "keys", "unless", "the", "$overwrite", "parameter", "is", "passed", "as", "false", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.configuration.php#L94-L105
symphonycms/symphony-2
symphony/lib/core/class.configuration.php
Configuration.get
public function get($name = null, $group = null) { // Return the whole array if no name or index is requested if (!$name && !$group) { return $this->_properties; } if ($this->_forceLowerCase) { $name = strtolower($name); $group = strtolower($group); } if ($group) { return (isset($this->_properties[$group][$name]) ? $this->_properties[$group][$name] : null); } return (isset($this->_properties[$name]) ? $this->_properties[$name] : null); }
php
public function get($name = null, $group = null) { // Return the whole array if no name or index is requested if (!$name && !$group) { return $this->_properties; } if ($this->_forceLowerCase) { $name = strtolower($name); $group = strtolower($group); } if ($group) { return (isset($this->_properties[$group][$name]) ? $this->_properties[$group][$name] : null); } return (isset($this->_properties[$name]) ? $this->_properties[$name] : null); }
[ "public", "function", "get", "(", "$", "name", "=", "null", ",", "$", "group", "=", "null", ")", "{", "// Return the whole array if no name or index is requested", "if", "(", "!", "$", "name", "&&", "!", "$", "group", ")", "{", "return", "$", "this", "->", "_properties", ";", "}", "if", "(", "$", "this", "->", "_forceLowerCase", ")", "{", "$", "name", "=", "strtolower", "(", "$", "name", ")", ";", "$", "group", "=", "strtolower", "(", "$", "group", ")", ";", "}", "if", "(", "$", "group", ")", "{", "return", "(", "isset", "(", "$", "this", "->", "_properties", "[", "$", "group", "]", "[", "$", "name", "]", ")", "?", "$", "this", "->", "_properties", "[", "$", "group", "]", "[", "$", "name", "]", ":", "null", ")", ";", "}", "return", "(", "isset", "(", "$", "this", "->", "_properties", "[", "$", "name", "]", ")", "?", "$", "this", "->", "_properties", "[", "$", "name", "]", ":", "null", ")", ";", "}" ]
Accessor function for the `$this->_properties`. @param string $name The name of the property to retrieve @param string $group The group that this property will be in @return array|string|integer|float|boolean If `$name` or `$group` are not provided this function will return the full `$this->_properties` array.
[ "Accessor", "function", "for", "the", "$this", "-", ">", "_properties", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.configuration.php#L119-L137
symphonycms/symphony-2
symphony/lib/core/class.configuration.php
Configuration.serializeArray
protected function serializeArray(array $arr, $indentation = 0, $tab = self::TAB) { $tabs = ''; $closeTabs = ''; for ($i = 0; $i < $indentation; $i++) { $tabs .= $tab; if ($i < $indentation - 1) { $closeTabs .= $tab; } } $string = 'array('; foreach ($arr as $key => $value) { $key = addslashes($key); $string .= (is_numeric($key) ? PHP_EOL . "$tabs $key => " : PHP_EOL . "$tabs'$key' => "); if (is_array($value)) { if (empty($value)) { $string .= 'array()'; } else { $string .= $this->serializeArray($value, $indentation + 1, $tab); } } else { $string .= (General::strlen($value) > 0 ? var_export($value, true) : 'null'); } $string .= ","; } $string .= PHP_EOL . "$closeTabs)"; return $string; }
php
protected function serializeArray(array $arr, $indentation = 0, $tab = self::TAB) { $tabs = ''; $closeTabs = ''; for ($i = 0; $i < $indentation; $i++) { $tabs .= $tab; if ($i < $indentation - 1) { $closeTabs .= $tab; } } $string = 'array('; foreach ($arr as $key => $value) { $key = addslashes($key); $string .= (is_numeric($key) ? PHP_EOL . "$tabs $key => " : PHP_EOL . "$tabs'$key' => "); if (is_array($value)) { if (empty($value)) { $string .= 'array()'; } else { $string .= $this->serializeArray($value, $indentation + 1, $tab); } } else { $string .= (General::strlen($value) > 0 ? var_export($value, true) : 'null'); } $string .= ","; } $string .= PHP_EOL . "$closeTabs)"; return $string; }
[ "protected", "function", "serializeArray", "(", "array", "$", "arr", ",", "$", "indentation", "=", "0", ",", "$", "tab", "=", "self", "::", "TAB", ")", "{", "$", "tabs", "=", "''", ";", "$", "closeTabs", "=", "''", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "indentation", ";", "$", "i", "++", ")", "{", "$", "tabs", ".=", "$", "tab", ";", "if", "(", "$", "i", "<", "$", "indentation", "-", "1", ")", "{", "$", "closeTabs", ".=", "$", "tab", ";", "}", "}", "$", "string", "=", "'array('", ";", "foreach", "(", "$", "arr", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "key", "=", "addslashes", "(", "$", "key", ")", ";", "$", "string", ".=", "(", "is_numeric", "(", "$", "key", ")", "?", "PHP_EOL", ".", "\"$tabs $key => \"", ":", "PHP_EOL", ".", "\"$tabs'$key' => \"", ")", ";", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "if", "(", "empty", "(", "$", "value", ")", ")", "{", "$", "string", ".=", "'array()'", ";", "}", "else", "{", "$", "string", ".=", "$", "this", "->", "serializeArray", "(", "$", "value", ",", "$", "indentation", "+", "1", ",", "$", "tab", ")", ";", "}", "}", "else", "{", "$", "string", ".=", "(", "General", "::", "strlen", "(", "$", "value", ")", ">", "0", "?", "var_export", "(", "$", "value", ",", "true", ")", ":", "'null'", ")", ";", "}", "$", "string", ".=", "\",\"", ";", "}", "$", "string", ".=", "PHP_EOL", ".", "\"$closeTabs)\"", ";", "return", "$", "string", ";", "}" ]
The `serializeArray` function will properly format and indent multidimensional arrays using recursivity. `__toString()` call `serializeArray` to use the recursive condition. The keys (int) in array won't have apostrophe. Array without multidimensional array will be output with normal indentation. @return string A string that contains a array representation of the '$data parameter'. @param array $arr A array of properties to serialize. @param integer $indentation The current level of indentation. @param string $tab A horizontal tab
[ "The", "serializeArray", "function", "will", "properly", "format", "and", "indent", "multidimensional", "arrays", "using", "recursivity", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.configuration.php#L218-L245
symphonycms/symphony-2
symphony/lib/core/class.configuration.php
Configuration.write
public function write($file = null, $permissions = null) { if (is_null($permissions) && isset($this->_properties['file']['write_mode'])) { $permissions = $this->_properties['file']['write_mode']; } if (is_null($file)) { $file = CONFIG; } $tab = static::TAB; $eol = PHP_EOL; $string = "<?php$eol$tab\$settings = " . (string)$this . ";$eol"; return General::writeFile($file, $string, $permissions); }
php
public function write($file = null, $permissions = null) { if (is_null($permissions) && isset($this->_properties['file']['write_mode'])) { $permissions = $this->_properties['file']['write_mode']; } if (is_null($file)) { $file = CONFIG; } $tab = static::TAB; $eol = PHP_EOL; $string = "<?php$eol$tab\$settings = " . (string)$this . ";$eol"; return General::writeFile($file, $string, $permissions); }
[ "public", "function", "write", "(", "$", "file", "=", "null", ",", "$", "permissions", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "permissions", ")", "&&", "isset", "(", "$", "this", "->", "_properties", "[", "'file'", "]", "[", "'write_mode'", "]", ")", ")", "{", "$", "permissions", "=", "$", "this", "->", "_properties", "[", "'file'", "]", "[", "'write_mode'", "]", ";", "}", "if", "(", "is_null", "(", "$", "file", ")", ")", "{", "$", "file", "=", "CONFIG", ";", "}", "$", "tab", "=", "static", "::", "TAB", ";", "$", "eol", "=", "PHP_EOL", ";", "$", "string", "=", "\"<?php$eol$tab\\$settings = \"", ".", "(", "string", ")", "$", "this", ".", "\";$eol\"", ";", "return", "General", "::", "writeFile", "(", "$", "file", ",", "$", "string", ",", "$", "permissions", ")", ";", "}" ]
Function will write the current Configuration object to a specified `$file` with the given `$permissions`. @param string $file the path of the file to write. @param integer|null $permissions (optional) the permissions as an octal number to set set on the resulting file. If this is not provided it will use the permissions defined in [`write_mode`][`file`] @return boolean
[ "Function", "will", "write", "the", "current", "Configuration", "object", "to", "a", "specified", "$file", "with", "the", "given", "$permissions", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.configuration.php#L258-L274
symphonycms/symphony-2
symphony/lib/toolkit/class.htmlpage.php
HTMLPage.generate
public function generate($page = null) { $this->__build(); parent::generate($page); return $this->Html->generate(true); }
php
public function generate($page = null) { $this->__build(); parent::generate($page); return $this->Html->generate(true); }
[ "public", "function", "generate", "(", "$", "page", "=", "null", ")", "{", "$", "this", "->", "__build", "(", ")", ";", "parent", "::", "generate", "(", "$", "page", ")", ";", "return", "$", "this", "->", "Html", "->", "generate", "(", "true", ")", ";", "}" ]
The generate function calls the `__build()` function before appending all the current page's headers and then finally calling the `$Html's` generate function which generates a HTML DOM from all the XMLElement children. @param null $page @return string
[ "The", "generate", "function", "calls", "the", "__build", "()", "function", "before", "appending", "all", "the", "current", "page", "s", "headers", "and", "then", "finally", "calling", "the", "$Html", "s", "generate", "function", "which", "generates", "a", "HTML", "DOM", "from", "all", "the", "XMLElement", "children", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.htmlpage.php#L103-L108
symphonycms/symphony-2
symphony/lib/toolkit/class.htmlpage.php
HTMLPage.__build
protected function __build() { $this->__generateHead(); $this->Html->appendChild($this->Head); $this->Html->appendChild($this->Body); }
php
protected function __build() { $this->__generateHead(); $this->Html->appendChild($this->Head); $this->Html->appendChild($this->Body); }
[ "protected", "function", "__build", "(", ")", "{", "$", "this", "->", "__generateHead", "(", ")", ";", "$", "this", "->", "Html", "->", "appendChild", "(", "$", "this", "->", "Head", ")", ";", "$", "this", "->", "Html", "->", "appendChild", "(", "$", "this", "->", "Body", ")", ";", "}" ]
Called when page is generated, this function appends the `$Head`, `$Form` and `$Body` elements to the `$Html`. @see __generateHead()
[ "Called", "when", "page", "is", "generated", "this", "function", "appends", "the", "$Head", "$Form", "and", "$Body", "elements", "to", "the", "$Html", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.htmlpage.php#L116-L121
symphonycms/symphony-2
symphony/lib/toolkit/class.htmlpage.php
HTMLPage.__generateHead
protected function __generateHead() { ksort($this->_head); foreach ($this->_head as $position => $obj) { if (is_object($obj)) { $this->Head->appendChild($obj); } } }
php
protected function __generateHead() { ksort($this->_head); foreach ($this->_head as $position => $obj) { if (is_object($obj)) { $this->Head->appendChild($obj); } } }
[ "protected", "function", "__generateHead", "(", ")", "{", "ksort", "(", "$", "this", "->", "_head", ")", ";", "foreach", "(", "$", "this", "->", "_head", "as", "$", "position", "=>", "$", "obj", ")", "{", "if", "(", "is_object", "(", "$", "obj", ")", ")", "{", "$", "this", "->", "Head", "->", "appendChild", "(", "$", "obj", ")", ";", "}", "}", "}" ]
Sorts the `$this->_head` elements by key, then appends them to the `$Head` XMLElement in order.
[ "Sorts", "the", "$this", "-", ">", "_head", "elements", "by", "key", "then", "appends", "them", "to", "the", "$Head", "XMLElement", "in", "order", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.htmlpage.php#L127-L136
symphonycms/symphony-2
symphony/lib/toolkit/class.htmlpage.php
HTMLPage.addElementToHead
public function addElementToHead(XMLElement $object, $position = null, $allowDuplicate = true) { // find the right position if (($position && isset($this->_head[$position]))) { $position = General::array_find_available_index($this->_head, $position); } elseif (is_null($position)) { if (count($this->_head) > 0) { $position = max(array_keys($this->_head))+1; } else { $position = 0; } } // check if we allow duplicate if (!$allowDuplicate && !empty($this->_head)) { $this->removeFromHead($object->getName()); } // append new element $this->_head[$position] = $object; return $position; }
php
public function addElementToHead(XMLElement $object, $position = null, $allowDuplicate = true) { // find the right position if (($position && isset($this->_head[$position]))) { $position = General::array_find_available_index($this->_head, $position); } elseif (is_null($position)) { if (count($this->_head) > 0) { $position = max(array_keys($this->_head))+1; } else { $position = 0; } } // check if we allow duplicate if (!$allowDuplicate && !empty($this->_head)) { $this->removeFromHead($object->getName()); } // append new element $this->_head[$position] = $object; return $position; }
[ "public", "function", "addElementToHead", "(", "XMLElement", "$", "object", ",", "$", "position", "=", "null", ",", "$", "allowDuplicate", "=", "true", ")", "{", "// find the right position", "if", "(", "(", "$", "position", "&&", "isset", "(", "$", "this", "->", "_head", "[", "$", "position", "]", ")", ")", ")", "{", "$", "position", "=", "General", "::", "array_find_available_index", "(", "$", "this", "->", "_head", ",", "$", "position", ")", ";", "}", "elseif", "(", "is_null", "(", "$", "position", ")", ")", "{", "if", "(", "count", "(", "$", "this", "->", "_head", ")", ">", "0", ")", "{", "$", "position", "=", "max", "(", "array_keys", "(", "$", "this", "->", "_head", ")", ")", "+", "1", ";", "}", "else", "{", "$", "position", "=", "0", ";", "}", "}", "// check if we allow duplicate", "if", "(", "!", "$", "allowDuplicate", "&&", "!", "empty", "(", "$", "this", "->", "_head", ")", ")", "{", "$", "this", "->", "removeFromHead", "(", "$", "object", "->", "getName", "(", ")", ")", ";", "}", "// append new element", "$", "this", "->", "_head", "[", "$", "position", "]", "=", "$", "object", ";", "return", "$", "position", ";", "}" ]
Adds an XMLElement to the `$this->_head` array at a desired position. If no position is given, the object will be added to the end of the `$this->_head` array. If that position is already taken, it will add the object at the next available position. @see toolkit.General#array_find_available_index() @param XMLElement $object @param integer $position Defaults to null which will put the `$object` at the end of the `$this->_head`. @param boolean $allowDuplicate If set to false, make this function check if there is already an XMLElement that as the same name in the head. Defaults to true. @since Symphony 2.3.2 @return integer Returns the position that the `$object` has been set in the `$this->_head`
[ "Adds", "an", "XMLElement", "to", "the", "$this", "-", ">", "_head", "array", "at", "a", "desired", "position", ".", "If", "no", "position", "is", "given", "the", "object", "will", "be", "added", "to", "the", "end", "of", "the", "$this", "-", ">", "_head", "array", ".", "If", "that", "position", "is", "already", "taken", "it", "will", "add", "the", "object", "at", "the", "next", "available", "position", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.htmlpage.php#L155-L177
symphonycms/symphony-2
symphony/lib/toolkit/class.htmlpage.php
HTMLPage.removeFromHead
public function removeFromHead($elementName) { foreach ($this->_head as $position => $element) { if ($element->getName() !== $elementName) { continue; } $this->removeFromHeadByPosition($position); } }
php
public function removeFromHead($elementName) { foreach ($this->_head as $position => $element) { if ($element->getName() !== $elementName) { continue; } $this->removeFromHeadByPosition($position); } }
[ "public", "function", "removeFromHead", "(", "$", "elementName", ")", "{", "foreach", "(", "$", "this", "->", "_head", "as", "$", "position", "=>", "$", "element", ")", "{", "if", "(", "$", "element", "->", "getName", "(", ")", "!==", "$", "elementName", ")", "{", "continue", ";", "}", "$", "this", "->", "removeFromHeadByPosition", "(", "$", "position", ")", ";", "}", "}" ]
Given an elementName, this function will remove the corresponding XMLElement from the `$this->_head` @param string $elementName
[ "Given", "an", "elementName", "this", "function", "will", "remove", "the", "corresponding", "XMLElement", "from", "the", "$this", "-", ">", "_head" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.htmlpage.php#L185-L194
symphonycms/symphony-2
symphony/lib/toolkit/class.htmlpage.php
HTMLPage.removeFromHeadByPosition
public function removeFromHeadByPosition($position) { if (isset($position, $this->_head[$position])) { unset($this->_head[$position]); } }
php
public function removeFromHeadByPosition($position) { if (isset($position, $this->_head[$position])) { unset($this->_head[$position]); } }
[ "public", "function", "removeFromHeadByPosition", "(", "$", "position", ")", "{", "if", "(", "isset", "(", "$", "position", ",", "$", "this", "->", "_head", "[", "$", "position", "]", ")", ")", "{", "unset", "(", "$", "this", "->", "_head", "[", "$", "position", "]", ")", ";", "}", "}" ]
Removes an item from `$this->_head` by it's index. @since Symphony 2.3.3 @param integer $position
[ "Removes", "an", "item", "from", "$this", "-", ">", "_head", "by", "it", "s", "index", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.htmlpage.php#L202-L207
symphonycms/symphony-2
symphony/lib/toolkit/class.htmlpage.php
HTMLPage.checkElementsInHead
public function checkElementsInHead($path, $attribute) { foreach ($this->_head as $element) { if (basename($element->getAttribute($attribute)) == basename($path)) { return true; } } return false; }
php
public function checkElementsInHead($path, $attribute) { foreach ($this->_head as $element) { if (basename($element->getAttribute($attribute)) == basename($path)) { return true; } } return false; }
[ "public", "function", "checkElementsInHead", "(", "$", "path", ",", "$", "attribute", ")", "{", "foreach", "(", "$", "this", "->", "_head", "as", "$", "element", ")", "{", "if", "(", "basename", "(", "$", "element", "->", "getAttribute", "(", "$", "attribute", ")", ")", "==", "basename", "(", "$", "path", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Determines if two elements are duplicates based on an attribute and value @param string $path The value of the attribute @param string $attribute The attribute to check @return boolean
[ "Determines", "if", "two", "elements", "are", "duplicates", "based", "on", "an", "attribute", "and", "value" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.htmlpage.php#L218-L227
symphonycms/symphony-2
symphony/lib/toolkit/class.htmlpage.php
HTMLPage.addScriptToHead
public function addScriptToHead($path, $position = null, $duplicate = true) { if ($duplicate === true || ($duplicate === false && $this->checkElementsInHead($path, 'src') === false)) { $script = new XMLElement('script'); $script->setSelfClosingTag(false); $script->setAttributeArray(array('type' => 'text/javascript', 'src' => $path)); return $this->addElementToHead($script, $position); } }
php
public function addScriptToHead($path, $position = null, $duplicate = true) { if ($duplicate === true || ($duplicate === false && $this->checkElementsInHead($path, 'src') === false)) { $script = new XMLElement('script'); $script->setSelfClosingTag(false); $script->setAttributeArray(array('type' => 'text/javascript', 'src' => $path)); return $this->addElementToHead($script, $position); } }
[ "public", "function", "addScriptToHead", "(", "$", "path", ",", "$", "position", "=", "null", ",", "$", "duplicate", "=", "true", ")", "{", "if", "(", "$", "duplicate", "===", "true", "||", "(", "$", "duplicate", "===", "false", "&&", "$", "this", "->", "checkElementsInHead", "(", "$", "path", ",", "'src'", ")", "===", "false", ")", ")", "{", "$", "script", "=", "new", "XMLElement", "(", "'script'", ")", ";", "$", "script", "->", "setSelfClosingTag", "(", "false", ")", ";", "$", "script", "->", "setAttributeArray", "(", "array", "(", "'type'", "=>", "'text/javascript'", ",", "'src'", "=>", "$", "path", ")", ")", ";", "return", "$", "this", "->", "addElementToHead", "(", "$", "script", ",", "$", "position", ")", ";", "}", "}" ]
Convenience function to add a `<script>` element to the `$this->_head`. By default the function will allow duplicates to be added to the `$this->_head`. A duplicate is determined by if the `$path` is unique. @param string $path The path to the script file @param integer $position The desired position that the resulting XMLElement will be placed in the `$this->_head`. Defaults to null which will append to the end. @param boolean $duplicate When set to false the function will only add the script if it doesn't already exist. Defaults to true which allows duplicates. @return integer Returns the position that the script has been set in the `$this->_head`
[ "Convenience", "function", "to", "add", "a", "<script", ">", "element", "to", "the", "$this", "-", ">", "_head", ".", "By", "default", "the", "function", "will", "allow", "duplicates", "to", "be", "added", "to", "the", "$this", "-", ">", "_head", ".", "A", "duplicate", "is", "determined", "by", "if", "the", "$path", "is", "unique", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.htmlpage.php#L245-L254
symphonycms/symphony-2
symphony/lib/toolkit/class.htmlpage.php
HTMLPage.addStylesheetToHead
public function addStylesheetToHead($path, $type = 'screen', $position = null, $duplicate = true) { if ($duplicate === true || ($duplicate === false && $this->checkElementsInHead($path, 'href') === false)) { $link = new XMLElement('link'); $link->setAttributeArray(array('rel' => 'stylesheet', 'type' => 'text/css', 'media' => $type, 'href' => $path)); return $this->addElementToHead($link, $position); } }
php
public function addStylesheetToHead($path, $type = 'screen', $position = null, $duplicate = true) { if ($duplicate === true || ($duplicate === false && $this->checkElementsInHead($path, 'href') === false)) { $link = new XMLElement('link'); $link->setAttributeArray(array('rel' => 'stylesheet', 'type' => 'text/css', 'media' => $type, 'href' => $path)); return $this->addElementToHead($link, $position); } }
[ "public", "function", "addStylesheetToHead", "(", "$", "path", ",", "$", "type", "=", "'screen'", ",", "$", "position", "=", "null", ",", "$", "duplicate", "=", "true", ")", "{", "if", "(", "$", "duplicate", "===", "true", "||", "(", "$", "duplicate", "===", "false", "&&", "$", "this", "->", "checkElementsInHead", "(", "$", "path", ",", "'href'", ")", "===", "false", ")", ")", "{", "$", "link", "=", "new", "XMLElement", "(", "'link'", ")", ";", "$", "link", "->", "setAttributeArray", "(", "array", "(", "'rel'", "=>", "'stylesheet'", ",", "'type'", "=>", "'text/css'", ",", "'media'", "=>", "$", "type", ",", "'href'", "=>", "$", "path", ")", ")", ";", "return", "$", "this", "->", "addElementToHead", "(", "$", "link", ",", "$", "position", ")", ";", "}", "}" ]
Convenience function to add a stylesheet to the `$this->_head` in a `<link>` element. By default the function will allow duplicates to be added to the `$this->_head`. A duplicate is determined by if the `$path` is unique. @param string $path The path to the stylesheet file @param string $type The media attribute for this stylesheet, defaults to 'screen' @param integer $position The desired position that the resulting XMLElement will be placed in the `$this->_head`. Defaults to null which will append to the end. @param boolean $duplicate When set to false the function will only add the script if it doesn't already exist. Defaults to true which allows duplicates. @return integer Returns the position that the stylesheet has been set in the `$this->_head`
[ "Convenience", "function", "to", "add", "a", "stylesheet", "to", "the", "$this", "-", ">", "_head", "in", "a", "<link", ">", "element", ".", "By", "default", "the", "function", "will", "allow", "duplicates", "to", "be", "added", "to", "the", "$this", "-", ">", "_head", ".", "A", "duplicate", "is", "determined", "by", "if", "the", "$path", "is", "unique", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.htmlpage.php#L274-L282
symphonycms/symphony-2
symphony/lib/toolkit/class.htmlpage.php
HTMLPage.__buildQueryString
public function __buildQueryString(array $exclude = array(), $filters = null) { $exclude[] = 'page'; if (is_null($filters)) { $filters = FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH | FILTER_SANITIZE_STRING; } // Generate the full query string and then parse it back to an array $pre_exclusion = http_build_query($_GET, null, '&'); parse_str($pre_exclusion, $query); // Remove the excluded keys from query string and then build // the query string again $post_exclusion = array_diff_key($query, array_fill_keys($exclude, true)); $query = http_build_query($post_exclusion, null, '&'); return filter_var(urldecode($query), $filters); }
php
public function __buildQueryString(array $exclude = array(), $filters = null) { $exclude[] = 'page'; if (is_null($filters)) { $filters = FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH | FILTER_SANITIZE_STRING; } // Generate the full query string and then parse it back to an array $pre_exclusion = http_build_query($_GET, null, '&'); parse_str($pre_exclusion, $query); // Remove the excluded keys from query string and then build // the query string again $post_exclusion = array_diff_key($query, array_fill_keys($exclude, true)); $query = http_build_query($post_exclusion, null, '&'); return filter_var(urldecode($query), $filters); }
[ "public", "function", "__buildQueryString", "(", "array", "$", "exclude", "=", "array", "(", ")", ",", "$", "filters", "=", "null", ")", "{", "$", "exclude", "[", "]", "=", "'page'", ";", "if", "(", "is_null", "(", "$", "filters", ")", ")", "{", "$", "filters", "=", "FILTER_FLAG_STRIP_LOW", "|", "FILTER_FLAG_STRIP_HIGH", "|", "FILTER_SANITIZE_STRING", ";", "}", "// Generate the full query string and then parse it back to an array", "$", "pre_exclusion", "=", "http_build_query", "(", "$", "_GET", ",", "null", ",", "'&'", ")", ";", "parse_str", "(", "$", "pre_exclusion", ",", "$", "query", ")", ";", "// Remove the excluded keys from query string and then build", "// the query string again", "$", "post_exclusion", "=", "array_diff_key", "(", "$", "query", ",", "array_fill_keys", "(", "$", "exclude", ",", "true", ")", ")", ";", "$", "query", "=", "http_build_query", "(", "$", "post_exclusion", ",", "null", ",", "'&'", ")", ";", "return", "filter_var", "(", "urldecode", "(", "$", "query", ")", ",", "$", "filters", ")", ";", "}" ]
This function builds a HTTP query string from `$_GET` parameters with the option to remove parameters with an `$exclude` array. Since Symphony 2.6.0 it is also possible to override the default filters on the resulting string. @link http://php.net/manual/en/filter.filters.php @param array $exclude A simple array with the keys that should be omitted in the resulting query string. @param integer $filters The resulting query string is parsed through `filter_var`. By default the options are FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH and FILTER_SANITIZE_STRING, but these can be overridden as desired. @return string
[ "This", "function", "builds", "a", "HTTP", "query", "string", "from", "$_GET", "parameters", "with", "the", "option", "to", "remove", "parameters", "with", "an", "$exclude", "array", ".", "Since", "Symphony", "2", ".", "6", ".", "0", "it", "is", "also", "possible", "to", "override", "the", "default", "filters", "on", "the", "resulting", "string", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.htmlpage.php#L299-L317
symphonycms/symphony-2
symphony/lib/toolkit/data-sources/class.datasource.section.php
SectionDatasource.canProcessSystemParameters
public function canProcessSystemParameters() { if (!is_array($this->dsParamPARAMOUTPUT)) { return false; } foreach (self::$_system_parameters as $system_parameter) { if (in_array($system_parameter, $this->dsParamPARAMOUTPUT) === true) { return true; } } return false; }
php
public function canProcessSystemParameters() { if (!is_array($this->dsParamPARAMOUTPUT)) { return false; } foreach (self::$_system_parameters as $system_parameter) { if (in_array($system_parameter, $this->dsParamPARAMOUTPUT) === true) { return true; } } return false; }
[ "public", "function", "canProcessSystemParameters", "(", ")", "{", "if", "(", "!", "is_array", "(", "$", "this", "->", "dsParamPARAMOUTPUT", ")", ")", "{", "return", "false", ";", "}", "foreach", "(", "self", "::", "$", "_system_parameters", "as", "$", "system_parameter", ")", "{", "if", "(", "in_array", "(", "$", "system_parameter", ",", "$", "this", "->", "dsParamPARAMOUTPUT", ")", "===", "true", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
If this Datasource requires System Parameters to be output, this function will return true, otherwise false. @return boolean
[ "If", "this", "Datasource", "requires", "System", "Parameters", "to", "be", "output", "this", "function", "will", "return", "true", "otherwise", "false", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/data-sources/class.datasource.section.php#L62-L75
symphonycms/symphony-2
symphony/lib/toolkit/data-sources/class.datasource.section.php
SectionDatasource.processRecordGroup
public function processRecordGroup($element, array $group) { $xGroup = new XMLElement($element, null, $group['attr']); if (is_array($group['records']) && !empty($group['records'])) { if (isset($group['records'][0])) { $data = $group['records'][0]->getData(); $pool = FieldManager::fetch(array_keys($data)); self::$_fieldPool += $pool; } foreach ($group['records'] as $entry) { $xEntry = $this->processEntry($entry); if ($xEntry instanceof XMLElement) { $xGroup->appendChild($xEntry); } } } if (is_array($group['groups']) && !empty($group['groups'])) { foreach ($group['groups'] as $element => $group) { foreach ($group as $g) { $xGroup->appendChild( $this->processRecordGroup($element, $g) ); } } } if (!$this->_param_output_only) { return $xGroup; } }
php
public function processRecordGroup($element, array $group) { $xGroup = new XMLElement($element, null, $group['attr']); if (is_array($group['records']) && !empty($group['records'])) { if (isset($group['records'][0])) { $data = $group['records'][0]->getData(); $pool = FieldManager::fetch(array_keys($data)); self::$_fieldPool += $pool; } foreach ($group['records'] as $entry) { $xEntry = $this->processEntry($entry); if ($xEntry instanceof XMLElement) { $xGroup->appendChild($xEntry); } } } if (is_array($group['groups']) && !empty($group['groups'])) { foreach ($group['groups'] as $element => $group) { foreach ($group as $g) { $xGroup->appendChild( $this->processRecordGroup($element, $g) ); } } } if (!$this->_param_output_only) { return $xGroup; } }
[ "public", "function", "processRecordGroup", "(", "$", "element", ",", "array", "$", "group", ")", "{", "$", "xGroup", "=", "new", "XMLElement", "(", "$", "element", ",", "null", ",", "$", "group", "[", "'attr'", "]", ")", ";", "if", "(", "is_array", "(", "$", "group", "[", "'records'", "]", ")", "&&", "!", "empty", "(", "$", "group", "[", "'records'", "]", ")", ")", "{", "if", "(", "isset", "(", "$", "group", "[", "'records'", "]", "[", "0", "]", ")", ")", "{", "$", "data", "=", "$", "group", "[", "'records'", "]", "[", "0", "]", "->", "getData", "(", ")", ";", "$", "pool", "=", "FieldManager", "::", "fetch", "(", "array_keys", "(", "$", "data", ")", ")", ";", "self", "::", "$", "_fieldPool", "+=", "$", "pool", ";", "}", "foreach", "(", "$", "group", "[", "'records'", "]", "as", "$", "entry", ")", "{", "$", "xEntry", "=", "$", "this", "->", "processEntry", "(", "$", "entry", ")", ";", "if", "(", "$", "xEntry", "instanceof", "XMLElement", ")", "{", "$", "xGroup", "->", "appendChild", "(", "$", "xEntry", ")", ";", "}", "}", "}", "if", "(", "is_array", "(", "$", "group", "[", "'groups'", "]", ")", "&&", "!", "empty", "(", "$", "group", "[", "'groups'", "]", ")", ")", "{", "foreach", "(", "$", "group", "[", "'groups'", "]", "as", "$", "element", "=>", "$", "group", ")", "{", "foreach", "(", "$", "group", "as", "$", "g", ")", "{", "$", "xGroup", "->", "appendChild", "(", "$", "this", "->", "processRecordGroup", "(", "$", "element", ",", "$", "g", ")", ")", ";", "}", "}", "}", "if", "(", "!", "$", "this", "->", "_param_output_only", ")", "{", "return", "$", "xGroup", ";", "}", "}" ]
Given a name for the group, and an associative array that contains three keys, `attr`, `records` and `groups`. Grouping of Entries is done by the grouping Field at a PHP level, not through the Database. @param string $element The name for the XML node for this group @param array $group An associative array of the group data, includes `attr`, `records` and `groups` keys. @throws Exception @return XMLElement
[ "Given", "a", "name", "for", "the", "group", "and", "an", "associative", "array", "that", "contains", "three", "keys", "attr", "records", "and", "groups", ".", "Grouping", "of", "Entries", "is", "done", "by", "the", "grouping", "Field", "at", "a", "PHP", "level", "not", "through", "the", "Database", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/data-sources/class.datasource.section.php#L91-L124
symphonycms/symphony-2
symphony/lib/toolkit/data-sources/class.datasource.section.php
SectionDatasource.processEntry
public function processEntry(Entry $entry) { $data = $entry->getData(); $xEntry = new XMLElement('entry'); $xEntry->setAttribute('id', $entry->get('id')); if (!empty($this->_associated_sections)) { $this->setAssociatedEntryCounts($xEntry, $entry); } if ($this->_can_process_system_parameters) { $this->processSystemParameters($entry); } foreach ($data as $field_id => $values) { if (!isset(self::$_fieldPool[$field_id]) || !is_object(self::$_fieldPool[$field_id])) { self::$_fieldPool[$field_id] = FieldManager::fetch($field_id); } $this->processOutputParameters($entry, $field_id, $values); if (!$this->_param_output_only) { foreach ($this->dsParamINCLUDEDELEMENTS as $handle) { list($handle, $mode) = preg_split('/\s*:\s*/', $handle, 2); if (self::$_fieldPool[$field_id]->get('element_name') == $handle) { self::$_fieldPool[$field_id]->appendFormattedElement($xEntry, $values, ($this->dsParamHTMLENCODE === 'yes' ? true : false), $mode, $entry->get('id')); } } } } if ($this->_param_output_only) { return true; } // This is deprecated and will be removed in Symphony 3.0.0 if (in_array('system:date', $this->dsParamINCLUDEDELEMENTS)) { if (Symphony::Log()) { Symphony::Log()->pushDeprecateWarningToLog('system:date', 'system:creation-date` or `system:modification-date', array( 'message-format' => __('The `%s` data source field is deprecated.') )); } $xDate = new XMLElement('system-date'); $xDate->appendChild( General::createXMLDateObject( DateTimeObj::get('U', $entry->get('creation_date')), 'created' ) ); $xDate->appendChild( General::createXMLDateObject( DateTimeObj::get('U', $entry->get('modification_date')), 'modified' ) ); $xEntry->appendChild($xDate); } return $xEntry; }
php
public function processEntry(Entry $entry) { $data = $entry->getData(); $xEntry = new XMLElement('entry'); $xEntry->setAttribute('id', $entry->get('id')); if (!empty($this->_associated_sections)) { $this->setAssociatedEntryCounts($xEntry, $entry); } if ($this->_can_process_system_parameters) { $this->processSystemParameters($entry); } foreach ($data as $field_id => $values) { if (!isset(self::$_fieldPool[$field_id]) || !is_object(self::$_fieldPool[$field_id])) { self::$_fieldPool[$field_id] = FieldManager::fetch($field_id); } $this->processOutputParameters($entry, $field_id, $values); if (!$this->_param_output_only) { foreach ($this->dsParamINCLUDEDELEMENTS as $handle) { list($handle, $mode) = preg_split('/\s*:\s*/', $handle, 2); if (self::$_fieldPool[$field_id]->get('element_name') == $handle) { self::$_fieldPool[$field_id]->appendFormattedElement($xEntry, $values, ($this->dsParamHTMLENCODE === 'yes' ? true : false), $mode, $entry->get('id')); } } } } if ($this->_param_output_only) { return true; } // This is deprecated and will be removed in Symphony 3.0.0 if (in_array('system:date', $this->dsParamINCLUDEDELEMENTS)) { if (Symphony::Log()) { Symphony::Log()->pushDeprecateWarningToLog('system:date', 'system:creation-date` or `system:modification-date', array( 'message-format' => __('The `%s` data source field is deprecated.') )); } $xDate = new XMLElement('system-date'); $xDate->appendChild( General::createXMLDateObject( DateTimeObj::get('U', $entry->get('creation_date')), 'created' ) ); $xDate->appendChild( General::createXMLDateObject( DateTimeObj::get('U', $entry->get('modification_date')), 'modified' ) ); $xEntry->appendChild($xDate); } return $xEntry; }
[ "public", "function", "processEntry", "(", "Entry", "$", "entry", ")", "{", "$", "data", "=", "$", "entry", "->", "getData", "(", ")", ";", "$", "xEntry", "=", "new", "XMLElement", "(", "'entry'", ")", ";", "$", "xEntry", "->", "setAttribute", "(", "'id'", ",", "$", "entry", "->", "get", "(", "'id'", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "_associated_sections", ")", ")", "{", "$", "this", "->", "setAssociatedEntryCounts", "(", "$", "xEntry", ",", "$", "entry", ")", ";", "}", "if", "(", "$", "this", "->", "_can_process_system_parameters", ")", "{", "$", "this", "->", "processSystemParameters", "(", "$", "entry", ")", ";", "}", "foreach", "(", "$", "data", "as", "$", "field_id", "=>", "$", "values", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "_fieldPool", "[", "$", "field_id", "]", ")", "||", "!", "is_object", "(", "self", "::", "$", "_fieldPool", "[", "$", "field_id", "]", ")", ")", "{", "self", "::", "$", "_fieldPool", "[", "$", "field_id", "]", "=", "FieldManager", "::", "fetch", "(", "$", "field_id", ")", ";", "}", "$", "this", "->", "processOutputParameters", "(", "$", "entry", ",", "$", "field_id", ",", "$", "values", ")", ";", "if", "(", "!", "$", "this", "->", "_param_output_only", ")", "{", "foreach", "(", "$", "this", "->", "dsParamINCLUDEDELEMENTS", "as", "$", "handle", ")", "{", "list", "(", "$", "handle", ",", "$", "mode", ")", "=", "preg_split", "(", "'/\\s*:\\s*/'", ",", "$", "handle", ",", "2", ")", ";", "if", "(", "self", "::", "$", "_fieldPool", "[", "$", "field_id", "]", "->", "get", "(", "'element_name'", ")", "==", "$", "handle", ")", "{", "self", "::", "$", "_fieldPool", "[", "$", "field_id", "]", "->", "appendFormattedElement", "(", "$", "xEntry", ",", "$", "values", ",", "(", "$", "this", "->", "dsParamHTMLENCODE", "===", "'yes'", "?", "true", ":", "false", ")", ",", "$", "mode", ",", "$", "entry", "->", "get", "(", "'id'", ")", ")", ";", "}", "}", "}", "}", "if", "(", "$", "this", "->", "_param_output_only", ")", "{", "return", "true", ";", "}", "// This is deprecated and will be removed in Symphony 3.0.0", "if", "(", "in_array", "(", "'system:date'", ",", "$", "this", "->", "dsParamINCLUDEDELEMENTS", ")", ")", "{", "if", "(", "Symphony", "::", "Log", "(", ")", ")", "{", "Symphony", "::", "Log", "(", ")", "->", "pushDeprecateWarningToLog", "(", "'system:date'", ",", "'system:creation-date` or `system:modification-date'", ",", "array", "(", "'message-format'", "=>", "__", "(", "'The `%s` data source field is deprecated.'", ")", ")", ")", ";", "}", "$", "xDate", "=", "new", "XMLElement", "(", "'system-date'", ")", ";", "$", "xDate", "->", "appendChild", "(", "General", "::", "createXMLDateObject", "(", "DateTimeObj", "::", "get", "(", "'U'", ",", "$", "entry", "->", "get", "(", "'creation_date'", ")", ")", ",", "'created'", ")", ")", ";", "$", "xDate", "->", "appendChild", "(", "General", "::", "createXMLDateObject", "(", "DateTimeObj", "::", "get", "(", "'U'", ",", "$", "entry", "->", "get", "(", "'modification_date'", ")", ")", ",", "'modified'", ")", ")", ";", "$", "xEntry", "->", "appendChild", "(", "$", "xDate", ")", ";", "}", "return", "$", "xEntry", ";", "}" ]
Given an Entry object, this function will generate an XML representation of the Entry to be returned. It will also add any parameters selected by this datasource to the parameter pool. @param Entry $entry @throws Exception @return XMLElement|boolean Returns boolean when only parameters are to be returned.
[ "Given", "an", "Entry", "object", "this", "function", "will", "generate", "an", "XML", "representation", "of", "the", "Entry", "to", "be", "returned", ".", "It", "will", "also", "add", "any", "parameters", "selected", "by", "this", "datasource", "to", "the", "parameter", "pool", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/data-sources/class.datasource.section.php#L136-L197
symphonycms/symphony-2
symphony/lib/toolkit/data-sources/class.datasource.section.php
SectionDatasource.setAssociatedEntryCounts
public function setAssociatedEntryCounts(XMLElement &$xEntry, Entry $entry) { $associated_entry_counts = $entry->fetchAllAssociatedEntryCounts($this->_associated_sections); if (!empty($associated_entry_counts)) { foreach ($associated_entry_counts as $section_id => $fields) { foreach ($this->_associated_sections as $section) { if ($section['id'] != $section_id) { continue; } // For each related field show the count (#2083) foreach ($fields as $field_id => $count) { $field_handle = FieldManager::fetchHandleFromID($field_id); $section_handle = $section['handle']; // Make sure attribute does not begin with a digit if (preg_match('/^[0-9]/', $section_handle)) { $section_handle = 'x-' . $section_handle; } if ($field_handle) { $xEntry->setAttribute($section_handle . '-' . $field_handle, (string)$count); } // Backwards compatibility (without field handle) $xEntry->setAttribute($section_handle, (string)$count); } } } } }
php
public function setAssociatedEntryCounts(XMLElement &$xEntry, Entry $entry) { $associated_entry_counts = $entry->fetchAllAssociatedEntryCounts($this->_associated_sections); if (!empty($associated_entry_counts)) { foreach ($associated_entry_counts as $section_id => $fields) { foreach ($this->_associated_sections as $section) { if ($section['id'] != $section_id) { continue; } // For each related field show the count (#2083) foreach ($fields as $field_id => $count) { $field_handle = FieldManager::fetchHandleFromID($field_id); $section_handle = $section['handle']; // Make sure attribute does not begin with a digit if (preg_match('/^[0-9]/', $section_handle)) { $section_handle = 'x-' . $section_handle; } if ($field_handle) { $xEntry->setAttribute($section_handle . '-' . $field_handle, (string)$count); } // Backwards compatibility (without field handle) $xEntry->setAttribute($section_handle, (string)$count); } } } } }
[ "public", "function", "setAssociatedEntryCounts", "(", "XMLElement", "&", "$", "xEntry", ",", "Entry", "$", "entry", ")", "{", "$", "associated_entry_counts", "=", "$", "entry", "->", "fetchAllAssociatedEntryCounts", "(", "$", "this", "->", "_associated_sections", ")", ";", "if", "(", "!", "empty", "(", "$", "associated_entry_counts", ")", ")", "{", "foreach", "(", "$", "associated_entry_counts", "as", "$", "section_id", "=>", "$", "fields", ")", "{", "foreach", "(", "$", "this", "->", "_associated_sections", "as", "$", "section", ")", "{", "if", "(", "$", "section", "[", "'id'", "]", "!=", "$", "section_id", ")", "{", "continue", ";", "}", "// For each related field show the count (#2083)", "foreach", "(", "$", "fields", "as", "$", "field_id", "=>", "$", "count", ")", "{", "$", "field_handle", "=", "FieldManager", "::", "fetchHandleFromID", "(", "$", "field_id", ")", ";", "$", "section_handle", "=", "$", "section", "[", "'handle'", "]", ";", "// Make sure attribute does not begin with a digit", "if", "(", "preg_match", "(", "'/^[0-9]/'", ",", "$", "section_handle", ")", ")", "{", "$", "section_handle", "=", "'x-'", ".", "$", "section_handle", ";", "}", "if", "(", "$", "field_handle", ")", "{", "$", "xEntry", "->", "setAttribute", "(", "$", "section_handle", ".", "'-'", ".", "$", "field_handle", ",", "(", "string", ")", "$", "count", ")", ";", "}", "// Backwards compatibility (without field handle)", "$", "xEntry", "->", "setAttribute", "(", "$", "section_handle", ",", "(", "string", ")", "$", "count", ")", ";", "}", "}", "}", "}", "}" ]
An entry may be associated to other entries from various fields through the section associations. This function will set the number of related entries as attributes to the main `<entry>` element grouped by the related entry's section. @param XMLElement $xEntry The <entry> XMLElement that the associated section counts will be set on @param Entry $entry The current entry object @throws Exception
[ "An", "entry", "may", "be", "associated", "to", "other", "entries", "from", "various", "fields", "through", "the", "section", "associations", ".", "This", "function", "will", "set", "the", "number", "of", "related", "entries", "as", "attributes", "to", "the", "main", "<entry", ">", "element", "grouped", "by", "the", "related", "entry", "s", "section", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/data-sources/class.datasource.section.php#L212-L241
symphonycms/symphony-2
symphony/lib/toolkit/data-sources/class.datasource.section.php
SectionDatasource.processSystemParameters
public function processSystemParameters(Entry $entry) { if (!isset($this->dsParamPARAMOUTPUT)) { return; } // Support the legacy parameter `ds-datasource-handle` $key = 'ds-' . $this->dsParamROOTELEMENT; $singleParam = count($this->dsParamPARAMOUTPUT) == 1; foreach ($this->dsParamPARAMOUTPUT as $param) { // The new style of paramater is `ds-datasource-handle.field-handle` $param_key = $key . '.' . str_replace(':', '-', $param); if ($param === 'system:id') { $this->_param_pool[$param_key][] = $entry->get('id'); if ($singleParam) { $this->_param_pool[$key][] = $entry->get('id'); } } elseif ($param === 'system:author') { $this->_param_pool[$param_key][] = $entry->get('author_id'); if ($singleParam) { $this->_param_pool[$key][] = $entry->get('author_id'); } } elseif ($param === 'system:creation-date' || $param === 'system:date') { if ($param === 'system:date' && Symphony::Log()) { Symphony::Log()->pushDeprecateWarningToLog('system:date', 'system:creation-date', array( 'message-format' => __('The `%s` data source output parameter is deprecated.') )); } $this->_param_pool[$param_key][] = $entry->get('creation_date'); if ($singleParam) { $this->_param_pool[$key][] = $entry->get('creation_date'); } } elseif ($param === 'system:modification-date') { $this->_param_pool[$param_key][] = $entry->get('modification_date'); if ($singleParam) { $this->_param_pool[$key][] = $entry->get('modification_date'); } } } }
php
public function processSystemParameters(Entry $entry) { if (!isset($this->dsParamPARAMOUTPUT)) { return; } // Support the legacy parameter `ds-datasource-handle` $key = 'ds-' . $this->dsParamROOTELEMENT; $singleParam = count($this->dsParamPARAMOUTPUT) == 1; foreach ($this->dsParamPARAMOUTPUT as $param) { // The new style of paramater is `ds-datasource-handle.field-handle` $param_key = $key . '.' . str_replace(':', '-', $param); if ($param === 'system:id') { $this->_param_pool[$param_key][] = $entry->get('id'); if ($singleParam) { $this->_param_pool[$key][] = $entry->get('id'); } } elseif ($param === 'system:author') { $this->_param_pool[$param_key][] = $entry->get('author_id'); if ($singleParam) { $this->_param_pool[$key][] = $entry->get('author_id'); } } elseif ($param === 'system:creation-date' || $param === 'system:date') { if ($param === 'system:date' && Symphony::Log()) { Symphony::Log()->pushDeprecateWarningToLog('system:date', 'system:creation-date', array( 'message-format' => __('The `%s` data source output parameter is deprecated.') )); } $this->_param_pool[$param_key][] = $entry->get('creation_date'); if ($singleParam) { $this->_param_pool[$key][] = $entry->get('creation_date'); } } elseif ($param === 'system:modification-date') { $this->_param_pool[$param_key][] = $entry->get('modification_date'); if ($singleParam) { $this->_param_pool[$key][] = $entry->get('modification_date'); } } } }
[ "public", "function", "processSystemParameters", "(", "Entry", "$", "entry", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "dsParamPARAMOUTPUT", ")", ")", "{", "return", ";", "}", "// Support the legacy parameter `ds-datasource-handle`", "$", "key", "=", "'ds-'", ".", "$", "this", "->", "dsParamROOTELEMENT", ";", "$", "singleParam", "=", "count", "(", "$", "this", "->", "dsParamPARAMOUTPUT", ")", "==", "1", ";", "foreach", "(", "$", "this", "->", "dsParamPARAMOUTPUT", "as", "$", "param", ")", "{", "// The new style of paramater is `ds-datasource-handle.field-handle`", "$", "param_key", "=", "$", "key", ".", "'.'", ".", "str_replace", "(", "':'", ",", "'-'", ",", "$", "param", ")", ";", "if", "(", "$", "param", "===", "'system:id'", ")", "{", "$", "this", "->", "_param_pool", "[", "$", "param_key", "]", "[", "]", "=", "$", "entry", "->", "get", "(", "'id'", ")", ";", "if", "(", "$", "singleParam", ")", "{", "$", "this", "->", "_param_pool", "[", "$", "key", "]", "[", "]", "=", "$", "entry", "->", "get", "(", "'id'", ")", ";", "}", "}", "elseif", "(", "$", "param", "===", "'system:author'", ")", "{", "$", "this", "->", "_param_pool", "[", "$", "param_key", "]", "[", "]", "=", "$", "entry", "->", "get", "(", "'author_id'", ")", ";", "if", "(", "$", "singleParam", ")", "{", "$", "this", "->", "_param_pool", "[", "$", "key", "]", "[", "]", "=", "$", "entry", "->", "get", "(", "'author_id'", ")", ";", "}", "}", "elseif", "(", "$", "param", "===", "'system:creation-date'", "||", "$", "param", "===", "'system:date'", ")", "{", "if", "(", "$", "param", "===", "'system:date'", "&&", "Symphony", "::", "Log", "(", ")", ")", "{", "Symphony", "::", "Log", "(", ")", "->", "pushDeprecateWarningToLog", "(", "'system:date'", ",", "'system:creation-date'", ",", "array", "(", "'message-format'", "=>", "__", "(", "'The `%s` data source output parameter is deprecated.'", ")", ")", ")", ";", "}", "$", "this", "->", "_param_pool", "[", "$", "param_key", "]", "[", "]", "=", "$", "entry", "->", "get", "(", "'creation_date'", ")", ";", "if", "(", "$", "singleParam", ")", "{", "$", "this", "->", "_param_pool", "[", "$", "key", "]", "[", "]", "=", "$", "entry", "->", "get", "(", "'creation_date'", ")", ";", "}", "}", "elseif", "(", "$", "param", "===", "'system:modification-date'", ")", "{", "$", "this", "->", "_param_pool", "[", "$", "param_key", "]", "[", "]", "=", "$", "entry", "->", "get", "(", "'modification_date'", ")", ";", "if", "(", "$", "singleParam", ")", "{", "$", "this", "->", "_param_pool", "[", "$", "key", "]", "[", "]", "=", "$", "entry", "->", "get", "(", "'modification_date'", ")", ";", "}", "}", "}", "}" ]
Given an Entry object, this function will iterate over the `dsParamPARAMOUTPUT` setting to see any of the Symphony system parameters need to be set. The current system parameters supported are `system:id`, `system:author`, `system:creation-date` and `system:modification-date`. If these parameters are found, the result is added to the `$param_pool` array using the key, `ds-datasource-handle.parameter-name` For the moment, this function also supports the pre Symphony 2.3 syntax, `ds-datasource-handle` which did not support multiple parameters. @param Entry $entry The Entry object that contains the values that may need to be added into the parameter pool.
[ "Given", "an", "Entry", "object", "this", "function", "will", "iterate", "over", "the", "dsParamPARAMOUTPUT", "setting", "to", "see", "any", "of", "the", "Symphony", "system", "parameters", "need", "to", "be", "set", ".", "The", "current", "system", "parameters", "supported", "are", "system", ":", "id", "system", ":", "author", "system", ":", "creation", "-", "date", "and", "system", ":", "modification", "-", "date", ".", "If", "these", "parameters", "are", "found", "the", "result", "is", "added", "to", "the", "$param_pool", "array", "using", "the", "key", "ds", "-", "datasource", "-", "handle", ".", "parameter", "-", "name", "For", "the", "moment", "this", "function", "also", "supports", "the", "pre", "Symphony", "2", ".", "3", "syntax", "ds", "-", "datasource", "-", "handle", "which", "did", "not", "support", "multiple", "parameters", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/data-sources/class.datasource.section.php#L257-L302
symphonycms/symphony-2
symphony/lib/toolkit/data-sources/class.datasource.section.php
SectionDatasource.processOutputParameters
public function processOutputParameters(Entry $entry, $field_id, array $data) { if (!isset($this->dsParamPARAMOUTPUT)) { return; } // Support the legacy parameter `ds-datasource-handle` $key = 'ds-' . $this->dsParamROOTELEMENT; $singleParam = count($this->dsParamPARAMOUTPUT) == 1; if ($singleParam && (!isset($this->_param_pool[$key]) || !is_array($this->_param_pool[$key]))) { $this->_param_pool[$key] = array(); } foreach ($this->dsParamPARAMOUTPUT as $param) { if (self::$_fieldPool[$field_id]->get('element_name') !== $param) { continue; } // The new style of paramater is `ds-datasource-handle.field-handle` $param_key = $key . '.' . str_replace(':', '-', $param); if (!isset($this->_param_pool[$param_key]) || !is_array($this->_param_pool[$param_key])) { $this->_param_pool[$param_key] = array(); } $param_pool_values = self::$_fieldPool[$field_id]->getParameterPoolValue($data, $entry->get('id')); if (is_array($param_pool_values)) { $this->_param_pool[$param_key] = array_merge($param_pool_values, $this->_param_pool[$param_key]); if ($singleParam) { $this->_param_pool[$key] = array_merge($param_pool_values, $this->_param_pool[$key]); } } elseif (!is_null($param_pool_values)) { $this->_param_pool[$param_key][] = $param_pool_values; if ($singleParam) { $this->_param_pool[$key][] = $param_pool_values; } } } }
php
public function processOutputParameters(Entry $entry, $field_id, array $data) { if (!isset($this->dsParamPARAMOUTPUT)) { return; } // Support the legacy parameter `ds-datasource-handle` $key = 'ds-' . $this->dsParamROOTELEMENT; $singleParam = count($this->dsParamPARAMOUTPUT) == 1; if ($singleParam && (!isset($this->_param_pool[$key]) || !is_array($this->_param_pool[$key]))) { $this->_param_pool[$key] = array(); } foreach ($this->dsParamPARAMOUTPUT as $param) { if (self::$_fieldPool[$field_id]->get('element_name') !== $param) { continue; } // The new style of paramater is `ds-datasource-handle.field-handle` $param_key = $key . '.' . str_replace(':', '-', $param); if (!isset($this->_param_pool[$param_key]) || !is_array($this->_param_pool[$param_key])) { $this->_param_pool[$param_key] = array(); } $param_pool_values = self::$_fieldPool[$field_id]->getParameterPoolValue($data, $entry->get('id')); if (is_array($param_pool_values)) { $this->_param_pool[$param_key] = array_merge($param_pool_values, $this->_param_pool[$param_key]); if ($singleParam) { $this->_param_pool[$key] = array_merge($param_pool_values, $this->_param_pool[$key]); } } elseif (!is_null($param_pool_values)) { $this->_param_pool[$param_key][] = $param_pool_values; if ($singleParam) { $this->_param_pool[$key][] = $param_pool_values; } } } }
[ "public", "function", "processOutputParameters", "(", "Entry", "$", "entry", ",", "$", "field_id", ",", "array", "$", "data", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "dsParamPARAMOUTPUT", ")", ")", "{", "return", ";", "}", "// Support the legacy parameter `ds-datasource-handle`", "$", "key", "=", "'ds-'", ".", "$", "this", "->", "dsParamROOTELEMENT", ";", "$", "singleParam", "=", "count", "(", "$", "this", "->", "dsParamPARAMOUTPUT", ")", "==", "1", ";", "if", "(", "$", "singleParam", "&&", "(", "!", "isset", "(", "$", "this", "->", "_param_pool", "[", "$", "key", "]", ")", "||", "!", "is_array", "(", "$", "this", "->", "_param_pool", "[", "$", "key", "]", ")", ")", ")", "{", "$", "this", "->", "_param_pool", "[", "$", "key", "]", "=", "array", "(", ")", ";", "}", "foreach", "(", "$", "this", "->", "dsParamPARAMOUTPUT", "as", "$", "param", ")", "{", "if", "(", "self", "::", "$", "_fieldPool", "[", "$", "field_id", "]", "->", "get", "(", "'element_name'", ")", "!==", "$", "param", ")", "{", "continue", ";", "}", "// The new style of paramater is `ds-datasource-handle.field-handle`", "$", "param_key", "=", "$", "key", ".", "'.'", ".", "str_replace", "(", "':'", ",", "'-'", ",", "$", "param", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "_param_pool", "[", "$", "param_key", "]", ")", "||", "!", "is_array", "(", "$", "this", "->", "_param_pool", "[", "$", "param_key", "]", ")", ")", "{", "$", "this", "->", "_param_pool", "[", "$", "param_key", "]", "=", "array", "(", ")", ";", "}", "$", "param_pool_values", "=", "self", "::", "$", "_fieldPool", "[", "$", "field_id", "]", "->", "getParameterPoolValue", "(", "$", "data", ",", "$", "entry", "->", "get", "(", "'id'", ")", ")", ";", "if", "(", "is_array", "(", "$", "param_pool_values", ")", ")", "{", "$", "this", "->", "_param_pool", "[", "$", "param_key", "]", "=", "array_merge", "(", "$", "param_pool_values", ",", "$", "this", "->", "_param_pool", "[", "$", "param_key", "]", ")", ";", "if", "(", "$", "singleParam", ")", "{", "$", "this", "->", "_param_pool", "[", "$", "key", "]", "=", "array_merge", "(", "$", "param_pool_values", ",", "$", "this", "->", "_param_pool", "[", "$", "key", "]", ")", ";", "}", "}", "elseif", "(", "!", "is_null", "(", "$", "param_pool_values", ")", ")", "{", "$", "this", "->", "_param_pool", "[", "$", "param_key", "]", "[", "]", "=", "$", "param_pool_values", ";", "if", "(", "$", "singleParam", ")", "{", "$", "this", "->", "_param_pool", "[", "$", "key", "]", "[", "]", "=", "$", "param_pool_values", ";", "}", "}", "}", "}" ]
Given an Entry object, a `$field_id` and an array of `$data`, this function iterates over the `dsParamPARAMOUTPUT` and will call the field's (identified by `$field_id`) `getParameterPoolValue` function to add parameters to the `$this->_param_pool`. @param Entry $entry @param integer $field_id @param array $data
[ "Given", "an", "Entry", "object", "a", "$field_id", "and", "an", "array", "of", "$data", "this", "function", "iterates", "over", "the", "dsParamPARAMOUTPUT", "and", "will", "call", "the", "field", "s", "(", "identified", "by", "$field_id", ")", "getParameterPoolValue", "function", "to", "add", "parameters", "to", "the", "$this", "-", ">", "_param_pool", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/data-sources/class.datasource.section.php#L314-L356
symphonycms/symphony-2
symphony/lib/toolkit/data-sources/class.datasource.section.php
SectionDatasource.processFilters
public function processFilters(&$where, &$joins, &$group) { if (!is_array($this->dsParamFILTERS) || empty($this->dsParamFILTERS)) { return; } $pool = FieldManager::fetch(array_filter(array_keys($this->dsParamFILTERS), 'is_int')); self::$_fieldPool += $pool; if (!is_string($where)) { $where = ''; } foreach ($this->dsParamFILTERS as $field_id => $filter) { if ((is_array($filter) && empty($filter)) || trim($filter) == '') { continue; } if (!is_array($filter)) { $filter_type = Datasource::determineFilterType($filter); $value = Datasource::splitFilter($filter_type, $filter); } else { $filter_type = Datasource::FILTER_OR; $value = $filter; } if (!in_array($field_id, self::$_system_parameters) && $field_id != 'id' && !(self::$_fieldPool[$field_id] instanceof Field)) { throw new Exception( __( 'Error creating field object with id %1$d, for filtering in data source %2$s. Check this field exists.', array($field_id, '<code>' . $this->dsParamROOTELEMENT . '</code>') ) ); } // Support system:id as well as the old 'id'. #1691 if ($field_id === 'system:id' || $field_id === 'id') { if ($filter_type == Datasource::FILTER_AND) { $value = array_map(function ($val) { return explode(',', $val); }, $value); } else { $value = array($value); } foreach ($value as $v) { $c = 'IN'; if (stripos($v[0], 'not:') === 0) { $v[0] = preg_replace('/^not:\s*/', null, $v[0]); $c = 'NOT IN'; } // Cast all ID's to integers. (RE: #2191) $v = array_map(function ($val) { $val = General::intval($val); // General::intval can return -1, so reset that to 0 // so there are no side effects for the following // array_sum and array_filter calls. RE: #2475 if ($val === -1) { $val = 0; } return $val; }, $v); $count = array_sum($v); $v = array_filter($v); // If the ID was cast to 0, then we need to filter on 'id' = 0, // which will of course return no results, but without it the // Datasource will return ALL results, which is not the // desired behaviour. RE: #1619 if ($count === 0) { $v[] = 0; } // If there are no ID's, no need to filter. RE: #1567 if (!empty($v)) { $where .= " AND `e`.id " . $c . " (".implode(", ", $v).") "; } } } elseif ($field_id === 'system:creation-date' || $field_id === 'system:modification-date' || $field_id === 'system:date') { if ($field_id === 'system:date' && Symphony::Log()) { Symphony::Log()->pushDeprecateWarningToLog('system:date', 'system:creation-date` or `system:modification-date', array( 'message-format' => __('The `%s` data source filter is deprecated.') )); } $date_joins = ''; $date_where = ''; $date = new FieldDate(); $date->buildDSRetrievalSQL($value, $date_joins, $date_where, ($filter_type == Datasource::FILTER_AND ? true : false)); // Replace the date field where with the `creation_date` or `modification_date`. $date_where = preg_replace('/`t\d+`.date/', ($field_id !== 'system:modification-date') ? '`e`.creation_date_gmt' : '`e`.modification_date_gmt', $date_where); $where .= $date_where; } else { if (!self::$_fieldPool[$field_id]->buildDSRetrievalSQL($value, $joins, $where, ($filter_type == Datasource::FILTER_AND ? true : false))) { $this->_force_empty_result = true; return; } if (!$group) { $group = self::$_fieldPool[$field_id]->requiresSQLGrouping(); } } } }
php
public function processFilters(&$where, &$joins, &$group) { if (!is_array($this->dsParamFILTERS) || empty($this->dsParamFILTERS)) { return; } $pool = FieldManager::fetch(array_filter(array_keys($this->dsParamFILTERS), 'is_int')); self::$_fieldPool += $pool; if (!is_string($where)) { $where = ''; } foreach ($this->dsParamFILTERS as $field_id => $filter) { if ((is_array($filter) && empty($filter)) || trim($filter) == '') { continue; } if (!is_array($filter)) { $filter_type = Datasource::determineFilterType($filter); $value = Datasource::splitFilter($filter_type, $filter); } else { $filter_type = Datasource::FILTER_OR; $value = $filter; } if (!in_array($field_id, self::$_system_parameters) && $field_id != 'id' && !(self::$_fieldPool[$field_id] instanceof Field)) { throw new Exception( __( 'Error creating field object with id %1$d, for filtering in data source %2$s. Check this field exists.', array($field_id, '<code>' . $this->dsParamROOTELEMENT . '</code>') ) ); } // Support system:id as well as the old 'id'. #1691 if ($field_id === 'system:id' || $field_id === 'id') { if ($filter_type == Datasource::FILTER_AND) { $value = array_map(function ($val) { return explode(',', $val); }, $value); } else { $value = array($value); } foreach ($value as $v) { $c = 'IN'; if (stripos($v[0], 'not:') === 0) { $v[0] = preg_replace('/^not:\s*/', null, $v[0]); $c = 'NOT IN'; } // Cast all ID's to integers. (RE: #2191) $v = array_map(function ($val) { $val = General::intval($val); // General::intval can return -1, so reset that to 0 // so there are no side effects for the following // array_sum and array_filter calls. RE: #2475 if ($val === -1) { $val = 0; } return $val; }, $v); $count = array_sum($v); $v = array_filter($v); // If the ID was cast to 0, then we need to filter on 'id' = 0, // which will of course return no results, but without it the // Datasource will return ALL results, which is not the // desired behaviour. RE: #1619 if ($count === 0) { $v[] = 0; } // If there are no ID's, no need to filter. RE: #1567 if (!empty($v)) { $where .= " AND `e`.id " . $c . " (".implode(", ", $v).") "; } } } elseif ($field_id === 'system:creation-date' || $field_id === 'system:modification-date' || $field_id === 'system:date') { if ($field_id === 'system:date' && Symphony::Log()) { Symphony::Log()->pushDeprecateWarningToLog('system:date', 'system:creation-date` or `system:modification-date', array( 'message-format' => __('The `%s` data source filter is deprecated.') )); } $date_joins = ''; $date_where = ''; $date = new FieldDate(); $date->buildDSRetrievalSQL($value, $date_joins, $date_where, ($filter_type == Datasource::FILTER_AND ? true : false)); // Replace the date field where with the `creation_date` or `modification_date`. $date_where = preg_replace('/`t\d+`.date/', ($field_id !== 'system:modification-date') ? '`e`.creation_date_gmt' : '`e`.modification_date_gmt', $date_where); $where .= $date_where; } else { if (!self::$_fieldPool[$field_id]->buildDSRetrievalSQL($value, $joins, $where, ($filter_type == Datasource::FILTER_AND ? true : false))) { $this->_force_empty_result = true; return; } if (!$group) { $group = self::$_fieldPool[$field_id]->requiresSQLGrouping(); } } } }
[ "public", "function", "processFilters", "(", "&", "$", "where", ",", "&", "$", "joins", ",", "&", "$", "group", ")", "{", "if", "(", "!", "is_array", "(", "$", "this", "->", "dsParamFILTERS", ")", "||", "empty", "(", "$", "this", "->", "dsParamFILTERS", ")", ")", "{", "return", ";", "}", "$", "pool", "=", "FieldManager", "::", "fetch", "(", "array_filter", "(", "array_keys", "(", "$", "this", "->", "dsParamFILTERS", ")", ",", "'is_int'", ")", ")", ";", "self", "::", "$", "_fieldPool", "+=", "$", "pool", ";", "if", "(", "!", "is_string", "(", "$", "where", ")", ")", "{", "$", "where", "=", "''", ";", "}", "foreach", "(", "$", "this", "->", "dsParamFILTERS", "as", "$", "field_id", "=>", "$", "filter", ")", "{", "if", "(", "(", "is_array", "(", "$", "filter", ")", "&&", "empty", "(", "$", "filter", ")", ")", "||", "trim", "(", "$", "filter", ")", "==", "''", ")", "{", "continue", ";", "}", "if", "(", "!", "is_array", "(", "$", "filter", ")", ")", "{", "$", "filter_type", "=", "Datasource", "::", "determineFilterType", "(", "$", "filter", ")", ";", "$", "value", "=", "Datasource", "::", "splitFilter", "(", "$", "filter_type", ",", "$", "filter", ")", ";", "}", "else", "{", "$", "filter_type", "=", "Datasource", "::", "FILTER_OR", ";", "$", "value", "=", "$", "filter", ";", "}", "if", "(", "!", "in_array", "(", "$", "field_id", ",", "self", "::", "$", "_system_parameters", ")", "&&", "$", "field_id", "!=", "'id'", "&&", "!", "(", "self", "::", "$", "_fieldPool", "[", "$", "field_id", "]", "instanceof", "Field", ")", ")", "{", "throw", "new", "Exception", "(", "__", "(", "'Error creating field object with id %1$d, for filtering in data source %2$s. Check this field exists.'", ",", "array", "(", "$", "field_id", ",", "'<code>'", ".", "$", "this", "->", "dsParamROOTELEMENT", ".", "'</code>'", ")", ")", ")", ";", "}", "// Support system:id as well as the old 'id'. #1691", "if", "(", "$", "field_id", "===", "'system:id'", "||", "$", "field_id", "===", "'id'", ")", "{", "if", "(", "$", "filter_type", "==", "Datasource", "::", "FILTER_AND", ")", "{", "$", "value", "=", "array_map", "(", "function", "(", "$", "val", ")", "{", "return", "explode", "(", "','", ",", "$", "val", ")", ";", "}", ",", "$", "value", ")", ";", "}", "else", "{", "$", "value", "=", "array", "(", "$", "value", ")", ";", "}", "foreach", "(", "$", "value", "as", "$", "v", ")", "{", "$", "c", "=", "'IN'", ";", "if", "(", "stripos", "(", "$", "v", "[", "0", "]", ",", "'not:'", ")", "===", "0", ")", "{", "$", "v", "[", "0", "]", "=", "preg_replace", "(", "'/^not:\\s*/'", ",", "null", ",", "$", "v", "[", "0", "]", ")", ";", "$", "c", "=", "'NOT IN'", ";", "}", "// Cast all ID's to integers. (RE: #2191)", "$", "v", "=", "array_map", "(", "function", "(", "$", "val", ")", "{", "$", "val", "=", "General", "::", "intval", "(", "$", "val", ")", ";", "// General::intval can return -1, so reset that to 0", "// so there are no side effects for the following", "// array_sum and array_filter calls. RE: #2475", "if", "(", "$", "val", "===", "-", "1", ")", "{", "$", "val", "=", "0", ";", "}", "return", "$", "val", ";", "}", ",", "$", "v", ")", ";", "$", "count", "=", "array_sum", "(", "$", "v", ")", ";", "$", "v", "=", "array_filter", "(", "$", "v", ")", ";", "// If the ID was cast to 0, then we need to filter on 'id' = 0,", "// which will of course return no results, but without it the", "// Datasource will return ALL results, which is not the", "// desired behaviour. RE: #1619", "if", "(", "$", "count", "===", "0", ")", "{", "$", "v", "[", "]", "=", "0", ";", "}", "// If there are no ID's, no need to filter. RE: #1567", "if", "(", "!", "empty", "(", "$", "v", ")", ")", "{", "$", "where", ".=", "\" AND `e`.id \"", ".", "$", "c", ".", "\" (\"", ".", "implode", "(", "\", \"", ",", "$", "v", ")", ".", "\") \"", ";", "}", "}", "}", "elseif", "(", "$", "field_id", "===", "'system:creation-date'", "||", "$", "field_id", "===", "'system:modification-date'", "||", "$", "field_id", "===", "'system:date'", ")", "{", "if", "(", "$", "field_id", "===", "'system:date'", "&&", "Symphony", "::", "Log", "(", ")", ")", "{", "Symphony", "::", "Log", "(", ")", "->", "pushDeprecateWarningToLog", "(", "'system:date'", ",", "'system:creation-date` or `system:modification-date'", ",", "array", "(", "'message-format'", "=>", "__", "(", "'The `%s` data source filter is deprecated.'", ")", ")", ")", ";", "}", "$", "date_joins", "=", "''", ";", "$", "date_where", "=", "''", ";", "$", "date", "=", "new", "FieldDate", "(", ")", ";", "$", "date", "->", "buildDSRetrievalSQL", "(", "$", "value", ",", "$", "date_joins", ",", "$", "date_where", ",", "(", "$", "filter_type", "==", "Datasource", "::", "FILTER_AND", "?", "true", ":", "false", ")", ")", ";", "// Replace the date field where with the `creation_date` or `modification_date`.", "$", "date_where", "=", "preg_replace", "(", "'/`t\\d+`.date/'", ",", "(", "$", "field_id", "!==", "'system:modification-date'", ")", "?", "'`e`.creation_date_gmt'", ":", "'`e`.modification_date_gmt'", ",", "$", "date_where", ")", ";", "$", "where", ".=", "$", "date_where", ";", "}", "else", "{", "if", "(", "!", "self", "::", "$", "_fieldPool", "[", "$", "field_id", "]", "->", "buildDSRetrievalSQL", "(", "$", "value", ",", "$", "joins", ",", "$", "where", ",", "(", "$", "filter_type", "==", "Datasource", "::", "FILTER_AND", "?", "true", ":", "false", ")", ")", ")", "{", "$", "this", "->", "_force_empty_result", "=", "true", ";", "return", ";", "}", "if", "(", "!", "$", "group", ")", "{", "$", "group", "=", "self", "::", "$", "_fieldPool", "[", "$", "field_id", "]", "->", "requiresSQLGrouping", "(", ")", ";", "}", "}", "}", "}" ]
This function iterates over `dsParamFILTERS` and builds the relevant `$where` and `$joins` parameters with SQL. This SQL is generated from `Field->buildDSRetrievalSQL`. A third parameter, `$group` is populated with boolean from `Field->requiresSQLGrouping()` @param string $where @param string $joins @param boolean $group @throws Exception
[ "This", "function", "iterates", "over", "dsParamFILTERS", "and", "builds", "the", "relevant", "$where", "and", "$joins", "parameters", "with", "SQL", ".", "This", "SQL", "is", "generated", "from", "Field", "-", ">", "buildDSRetrievalSQL", ".", "A", "third", "parameter", "$group", "is", "populated", "with", "boolean", "from", "Field", "-", ">", "requiresSQLGrouping", "()" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/data-sources/class.datasource.section.php#L369-L475
symphonycms/symphony-2
symphony/lib/toolkit/fields/field.upload.php
FieldUpload.entryDataCleanup
public function entryDataCleanup($entry_id, $data = null) { $file_location = $this->getFilePath($data['file']); if (is_file($file_location)) { General::deleteFile($file_location); } parent::entryDataCleanup($entry_id); return true; }
php
public function entryDataCleanup($entry_id, $data = null) { $file_location = $this->getFilePath($data['file']); if (is_file($file_location)) { General::deleteFile($file_location); } parent::entryDataCleanup($entry_id); return true; }
[ "public", "function", "entryDataCleanup", "(", "$", "entry_id", ",", "$", "data", "=", "null", ")", "{", "$", "file_location", "=", "$", "this", "->", "getFilePath", "(", "$", "data", "[", "'file'", "]", ")", ";", "if", "(", "is_file", "(", "$", "file_location", ")", ")", "{", "General", "::", "deleteFile", "(", "$", "file_location", ")", ";", "}", "parent", "::", "entryDataCleanup", "(", "$", "entry_id", ")", ";", "return", "true", ";", "}" ]
/*------------------------------------------------------------------------- Utilities: -------------------------------------------------------------------------
[ "/", "*", "-------------------------------------------------------------------------", "Utilities", ":", "-------------------------------------------------------------------------" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/fields/field.upload.php#L122-L133
symphonycms/symphony-2
symphony/lib/toolkit/fields/field.upload.php
FieldUpload.displaySettingsPanel
public function displaySettingsPanel(XMLElement &$wrapper, $errors = null) { parent::displaySettingsPanel($wrapper, $errors); // Destination Folder $ignore = array( '/workspace/events', '/workspace/data-sources', '/workspace/text-formatters', '/workspace/pages', '/workspace/utilities' ); $directories = General::listDirStructure(WORKSPACE, null, true, DOCROOT, $ignore); $label = Widget::Label(__('Destination Directory')); $options = array(); $options[] = array('/workspace', false, '/workspace'); if (!empty($directories) && is_array($directories)) { foreach ($directories as $d) { $d = '/' . trim($d, '/'); if (!in_array($d, $ignore)) { $options[] = array($d, ($this->get('destination') == $d), $d); } } } $label->appendChild(Widget::Select('fields['.$this->get('sortorder').'][destination]', $options)); if (isset($errors['destination'])) { $wrapper->appendChild(Widget::Error($label, $errors['destination'])); } else { $wrapper->appendChild($label); } // Validation rule $this->buildValidationSelect($wrapper, $this->get('validator'), 'fields['.$this->get('sortorder').'][validator]', 'upload', $errors); // Requirements and table display $this->appendStatusFooter($wrapper); }
php
public function displaySettingsPanel(XMLElement &$wrapper, $errors = null) { parent::displaySettingsPanel($wrapper, $errors); // Destination Folder $ignore = array( '/workspace/events', '/workspace/data-sources', '/workspace/text-formatters', '/workspace/pages', '/workspace/utilities' ); $directories = General::listDirStructure(WORKSPACE, null, true, DOCROOT, $ignore); $label = Widget::Label(__('Destination Directory')); $options = array(); $options[] = array('/workspace', false, '/workspace'); if (!empty($directories) && is_array($directories)) { foreach ($directories as $d) { $d = '/' . trim($d, '/'); if (!in_array($d, $ignore)) { $options[] = array($d, ($this->get('destination') == $d), $d); } } } $label->appendChild(Widget::Select('fields['.$this->get('sortorder').'][destination]', $options)); if (isset($errors['destination'])) { $wrapper->appendChild(Widget::Error($label, $errors['destination'])); } else { $wrapper->appendChild($label); } // Validation rule $this->buildValidationSelect($wrapper, $this->get('validator'), 'fields['.$this->get('sortorder').'][validator]', 'upload', $errors); // Requirements and table display $this->appendStatusFooter($wrapper); }
[ "public", "function", "displaySettingsPanel", "(", "XMLElement", "&", "$", "wrapper", ",", "$", "errors", "=", "null", ")", "{", "parent", "::", "displaySettingsPanel", "(", "$", "wrapper", ",", "$", "errors", ")", ";", "// Destination Folder", "$", "ignore", "=", "array", "(", "'/workspace/events'", ",", "'/workspace/data-sources'", ",", "'/workspace/text-formatters'", ",", "'/workspace/pages'", ",", "'/workspace/utilities'", ")", ";", "$", "directories", "=", "General", "::", "listDirStructure", "(", "WORKSPACE", ",", "null", ",", "true", ",", "DOCROOT", ",", "$", "ignore", ")", ";", "$", "label", "=", "Widget", "::", "Label", "(", "__", "(", "'Destination Directory'", ")", ")", ";", "$", "options", "=", "array", "(", ")", ";", "$", "options", "[", "]", "=", "array", "(", "'/workspace'", ",", "false", ",", "'/workspace'", ")", ";", "if", "(", "!", "empty", "(", "$", "directories", ")", "&&", "is_array", "(", "$", "directories", ")", ")", "{", "foreach", "(", "$", "directories", "as", "$", "d", ")", "{", "$", "d", "=", "'/'", ".", "trim", "(", "$", "d", ",", "'/'", ")", ";", "if", "(", "!", "in_array", "(", "$", "d", ",", "$", "ignore", ")", ")", "{", "$", "options", "[", "]", "=", "array", "(", "$", "d", ",", "(", "$", "this", "->", "get", "(", "'destination'", ")", "==", "$", "d", ")", ",", "$", "d", ")", ";", "}", "}", "}", "$", "label", "->", "appendChild", "(", "Widget", "::", "Select", "(", "'fields['", ".", "$", "this", "->", "get", "(", "'sortorder'", ")", ".", "'][destination]'", ",", "$", "options", ")", ")", ";", "if", "(", "isset", "(", "$", "errors", "[", "'destination'", "]", ")", ")", "{", "$", "wrapper", "->", "appendChild", "(", "Widget", "::", "Error", "(", "$", "label", ",", "$", "errors", "[", "'destination'", "]", ")", ")", ";", "}", "else", "{", "$", "wrapper", "->", "appendChild", "(", "$", "label", ")", ";", "}", "// Validation rule", "$", "this", "->", "buildValidationSelect", "(", "$", "wrapper", ",", "$", "this", "->", "get", "(", "'validator'", ")", ",", "'fields['", ".", "$", "this", "->", "get", "(", "'sortorder'", ")", ".", "'][validator]'", ",", "'upload'", ",", "$", "errors", ")", ";", "// Requirements and table display", "$", "this", "->", "appendStatusFooter", "(", "$", "wrapper", ")", ";", "}" ]
/*------------------------------------------------------------------------- Settings: -------------------------------------------------------------------------
[ "/", "*", "-------------------------------------------------------------------------", "Settings", ":", "-------------------------------------------------------------------------" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/fields/field.upload.php#L168-L210
symphonycms/symphony-2
symphony/lib/toolkit/fields/field.upload.php
FieldUpload.displayPublishPanel
public function displayPublishPanel(XMLElement &$wrapper, $data = null, $flagWithError = null, $fieldnamePrefix = null, $fieldnamePostfix = null, $entry_id = null) { if (is_dir(DOCROOT . $this->get('destination') . '/') === false) { $flagWithError = __('The destination directory, %s, does not exist.', array( '<code>' . $this->get('destination') . '</code>' )); } elseif ($flagWithError && is_writable(DOCROOT . $this->get('destination') . '/') === false) { $flagWithError = __('Destination folder is not writable.') . ' ' . __('Please check permissions on %s.', array( '<code>' . $this->get('destination') . '</code>' )); } $label = Widget::Label($this->get('label')); $label->setAttribute('class', 'file'); if ($this->get('required') !== 'yes') { $label->appendChild(new XMLElement('i', __('Optional'))); } $span = new XMLElement('span', null, array('class' => 'frame')); if (isset($data['file'])) { $filename = $this->get('destination') . '/' . basename($data['file']); $file = $this->getFilePath($data['file']); if (file_exists($file) === false || !is_readable($file)) { $flagWithError = __('The file uploaded is no longer available. Please check that it exists, and is readable.'); } $span->appendChild(new XMLElement('span', Widget::Anchor(preg_replace("![^a-z0-9]+!i", "$0&#8203;", $filename), URL . $filename))); } else { $filename = null; } $span->appendChild(Widget::Input('fields'.$fieldnamePrefix.'['.$this->get('element_name').']'.$fieldnamePostfix, $filename, ($filename ? 'hidden' : 'file'))); $label->appendChild($span); if ($flagWithError != null) { $wrapper->appendChild(Widget::Error($label, $flagWithError)); } else { $wrapper->appendChild($label); } }
php
public function displayPublishPanel(XMLElement &$wrapper, $data = null, $flagWithError = null, $fieldnamePrefix = null, $fieldnamePostfix = null, $entry_id = null) { if (is_dir(DOCROOT . $this->get('destination') . '/') === false) { $flagWithError = __('The destination directory, %s, does not exist.', array( '<code>' . $this->get('destination') . '</code>' )); } elseif ($flagWithError && is_writable(DOCROOT . $this->get('destination') . '/') === false) { $flagWithError = __('Destination folder is not writable.') . ' ' . __('Please check permissions on %s.', array( '<code>' . $this->get('destination') . '</code>' )); } $label = Widget::Label($this->get('label')); $label->setAttribute('class', 'file'); if ($this->get('required') !== 'yes') { $label->appendChild(new XMLElement('i', __('Optional'))); } $span = new XMLElement('span', null, array('class' => 'frame')); if (isset($data['file'])) { $filename = $this->get('destination') . '/' . basename($data['file']); $file = $this->getFilePath($data['file']); if (file_exists($file) === false || !is_readable($file)) { $flagWithError = __('The file uploaded is no longer available. Please check that it exists, and is readable.'); } $span->appendChild(new XMLElement('span', Widget::Anchor(preg_replace("![^a-z0-9]+!i", "$0&#8203;", $filename), URL . $filename))); } else { $filename = null; } $span->appendChild(Widget::Input('fields'.$fieldnamePrefix.'['.$this->get('element_name').']'.$fieldnamePostfix, $filename, ($filename ? 'hidden' : 'file'))); $label->appendChild($span); if ($flagWithError != null) { $wrapper->appendChild(Widget::Error($label, $flagWithError)); } else { $wrapper->appendChild($label); } }
[ "public", "function", "displayPublishPanel", "(", "XMLElement", "&", "$", "wrapper", ",", "$", "data", "=", "null", ",", "$", "flagWithError", "=", "null", ",", "$", "fieldnamePrefix", "=", "null", ",", "$", "fieldnamePostfix", "=", "null", ",", "$", "entry_id", "=", "null", ")", "{", "if", "(", "is_dir", "(", "DOCROOT", ".", "$", "this", "->", "get", "(", "'destination'", ")", ".", "'/'", ")", "===", "false", ")", "{", "$", "flagWithError", "=", "__", "(", "'The destination directory, %s, does not exist.'", ",", "array", "(", "'<code>'", ".", "$", "this", "->", "get", "(", "'destination'", ")", ".", "'</code>'", ")", ")", ";", "}", "elseif", "(", "$", "flagWithError", "&&", "is_writable", "(", "DOCROOT", ".", "$", "this", "->", "get", "(", "'destination'", ")", ".", "'/'", ")", "===", "false", ")", "{", "$", "flagWithError", "=", "__", "(", "'Destination folder is not writable.'", ")", ".", "' '", ".", "__", "(", "'Please check permissions on %s.'", ",", "array", "(", "'<code>'", ".", "$", "this", "->", "get", "(", "'destination'", ")", ".", "'</code>'", ")", ")", ";", "}", "$", "label", "=", "Widget", "::", "Label", "(", "$", "this", "->", "get", "(", "'label'", ")", ")", ";", "$", "label", "->", "setAttribute", "(", "'class'", ",", "'file'", ")", ";", "if", "(", "$", "this", "->", "get", "(", "'required'", ")", "!==", "'yes'", ")", "{", "$", "label", "->", "appendChild", "(", "new", "XMLElement", "(", "'i'", ",", "__", "(", "'Optional'", ")", ")", ")", ";", "}", "$", "span", "=", "new", "XMLElement", "(", "'span'", ",", "null", ",", "array", "(", "'class'", "=>", "'frame'", ")", ")", ";", "if", "(", "isset", "(", "$", "data", "[", "'file'", "]", ")", ")", "{", "$", "filename", "=", "$", "this", "->", "get", "(", "'destination'", ")", ".", "'/'", ".", "basename", "(", "$", "data", "[", "'file'", "]", ")", ";", "$", "file", "=", "$", "this", "->", "getFilePath", "(", "$", "data", "[", "'file'", "]", ")", ";", "if", "(", "file_exists", "(", "$", "file", ")", "===", "false", "||", "!", "is_readable", "(", "$", "file", ")", ")", "{", "$", "flagWithError", "=", "__", "(", "'The file uploaded is no longer available. Please check that it exists, and is readable.'", ")", ";", "}", "$", "span", "->", "appendChild", "(", "new", "XMLElement", "(", "'span'", ",", "Widget", "::", "Anchor", "(", "preg_replace", "(", "\"![^a-z0-9]+!i\"", ",", "\"$0&#8203;\"", ",", "$", "filename", ")", ",", "URL", ".", "$", "filename", ")", ")", ")", ";", "}", "else", "{", "$", "filename", "=", "null", ";", "}", "$", "span", "->", "appendChild", "(", "Widget", "::", "Input", "(", "'fields'", ".", "$", "fieldnamePrefix", ".", "'['", ".", "$", "this", "->", "get", "(", "'element_name'", ")", ".", "']'", ".", "$", "fieldnamePostfix", ",", "$", "filename", ",", "(", "$", "filename", "?", "'hidden'", ":", "'file'", ")", ")", ")", ";", "$", "label", "->", "appendChild", "(", "$", "span", ")", ";", "if", "(", "$", "flagWithError", "!=", "null", ")", "{", "$", "wrapper", "->", "appendChild", "(", "Widget", "::", "Error", "(", "$", "label", ",", "$", "flagWithError", ")", ")", ";", "}", "else", "{", "$", "wrapper", "->", "appendChild", "(", "$", "label", ")", ";", "}", "}" ]
/*------------------------------------------------------------------------- Publish: -------------------------------------------------------------------------
[ "/", "*", "-------------------------------------------------------------------------", "Publish", ":", "-------------------------------------------------------------------------" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/fields/field.upload.php#L253-L297
symphonycms/symphony-2
symphony/lib/toolkit/fields/field.upload.php
FieldUpload.appendFormattedElement
public function appendFormattedElement(XMLElement &$wrapper, $data, $encode = false, $mode = null, $entry_id = null) { // It is possible an array of null data will be passed in. Check for this. if (!is_array($data) || !isset($data['file']) || is_null($data['file'])) { return; } $file = $this->getFilePath($data['file']); $filesize = (file_exists($file) && is_readable($file)) ? filesize($file) : null; $item = new XMLElement($this->get('element_name')); $item->setAttributeArray(array( 'size' => !is_null($filesize) ? General::formatFilesize($filesize) : 'unknown', 'bytes' => !is_null($filesize) ? $filesize : 'unknown', 'path' => General::sanitize( str_replace(WORKSPACE, null, dirname($file)) ), 'type' => $data['mimetype'] )); $item->appendChild(new XMLElement('filename', General::sanitize(basename($file)))); $m = unserialize($data['meta']); if (is_array($m) && !empty($m)) { $item->appendChild(new XMLElement('meta', null, $m)); } $wrapper->appendChild($item); }
php
public function appendFormattedElement(XMLElement &$wrapper, $data, $encode = false, $mode = null, $entry_id = null) { // It is possible an array of null data will be passed in. Check for this. if (!is_array($data) || !isset($data['file']) || is_null($data['file'])) { return; } $file = $this->getFilePath($data['file']); $filesize = (file_exists($file) && is_readable($file)) ? filesize($file) : null; $item = new XMLElement($this->get('element_name')); $item->setAttributeArray(array( 'size' => !is_null($filesize) ? General::formatFilesize($filesize) : 'unknown', 'bytes' => !is_null($filesize) ? $filesize : 'unknown', 'path' => General::sanitize( str_replace(WORKSPACE, null, dirname($file)) ), 'type' => $data['mimetype'] )); $item->appendChild(new XMLElement('filename', General::sanitize(basename($file)))); $m = unserialize($data['meta']); if (is_array($m) && !empty($m)) { $item->appendChild(new XMLElement('meta', null, $m)); } $wrapper->appendChild($item); }
[ "public", "function", "appendFormattedElement", "(", "XMLElement", "&", "$", "wrapper", ",", "$", "data", ",", "$", "encode", "=", "false", ",", "$", "mode", "=", "null", ",", "$", "entry_id", "=", "null", ")", "{", "// It is possible an array of null data will be passed in. Check for this.", "if", "(", "!", "is_array", "(", "$", "data", ")", "||", "!", "isset", "(", "$", "data", "[", "'file'", "]", ")", "||", "is_null", "(", "$", "data", "[", "'file'", "]", ")", ")", "{", "return", ";", "}", "$", "file", "=", "$", "this", "->", "getFilePath", "(", "$", "data", "[", "'file'", "]", ")", ";", "$", "filesize", "=", "(", "file_exists", "(", "$", "file", ")", "&&", "is_readable", "(", "$", "file", ")", ")", "?", "filesize", "(", "$", "file", ")", ":", "null", ";", "$", "item", "=", "new", "XMLElement", "(", "$", "this", "->", "get", "(", "'element_name'", ")", ")", ";", "$", "item", "->", "setAttributeArray", "(", "array", "(", "'size'", "=>", "!", "is_null", "(", "$", "filesize", ")", "?", "General", "::", "formatFilesize", "(", "$", "filesize", ")", ":", "'unknown'", ",", "'bytes'", "=>", "!", "is_null", "(", "$", "filesize", ")", "?", "$", "filesize", ":", "'unknown'", ",", "'path'", "=>", "General", "::", "sanitize", "(", "str_replace", "(", "WORKSPACE", ",", "null", ",", "dirname", "(", "$", "file", ")", ")", ")", ",", "'type'", "=>", "$", "data", "[", "'mimetype'", "]", ")", ")", ";", "$", "item", "->", "appendChild", "(", "new", "XMLElement", "(", "'filename'", ",", "General", "::", "sanitize", "(", "basename", "(", "$", "file", ")", ")", ")", ")", ";", "$", "m", "=", "unserialize", "(", "$", "data", "[", "'meta'", "]", ")", ";", "if", "(", "is_array", "(", "$", "m", ")", "&&", "!", "empty", "(", "$", "m", ")", ")", "{", "$", "item", "->", "appendChild", "(", "new", "XMLElement", "(", "'meta'", ",", "null", ",", "$", "m", ")", ")", ";", "}", "$", "wrapper", "->", "appendChild", "(", "$", "item", ")", ";", "}" ]
/*------------------------------------------------------------------------- Output: -------------------------------------------------------------------------
[ "/", "*", "-------------------------------------------------------------------------", "Output", ":", "-------------------------------------------------------------------------" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/fields/field.upload.php#L580-L608
symphonycms/symphony-2
symphony/lib/toolkit/fields/field.upload.php
FieldUpload.prepareExportValue
public function prepareExportValue($data, $mode, $entry_id = null) { $modes = (object)$this->getExportModes(); $filepath = $this->getFilePath($data['file']); // No file, or the file that the entry is meant to have no // longer exists. if (!isset($data['file']) || !is_file($filepath)) { return null; } if ($mode === $modes->getFilename) { return $data['file']; } if ($mode === $modes->getObject) { $object = (object)$data; if (isset($object->meta)) { $object->meta = unserialize($object->meta); } return $object; } if ($mode === $modes->getPostdata) { return $data['file']; } }
php
public function prepareExportValue($data, $mode, $entry_id = null) { $modes = (object)$this->getExportModes(); $filepath = $this->getFilePath($data['file']); // No file, or the file that the entry is meant to have no // longer exists. if (!isset($data['file']) || !is_file($filepath)) { return null; } if ($mode === $modes->getFilename) { return $data['file']; } if ($mode === $modes->getObject) { $object = (object)$data; if (isset($object->meta)) { $object->meta = unserialize($object->meta); } return $object; } if ($mode === $modes->getPostdata) { return $data['file']; } }
[ "public", "function", "prepareExportValue", "(", "$", "data", ",", "$", "mode", ",", "$", "entry_id", "=", "null", ")", "{", "$", "modes", "=", "(", "object", ")", "$", "this", "->", "getExportModes", "(", ")", ";", "$", "filepath", "=", "$", "this", "->", "getFilePath", "(", "$", "data", "[", "'file'", "]", ")", ";", "// No file, or the file that the entry is meant to have no", "// longer exists.", "if", "(", "!", "isset", "(", "$", "data", "[", "'file'", "]", ")", "||", "!", "is_file", "(", "$", "filepath", ")", ")", "{", "return", "null", ";", "}", "if", "(", "$", "mode", "===", "$", "modes", "->", "getFilename", ")", "{", "return", "$", "data", "[", "'file'", "]", ";", "}", "if", "(", "$", "mode", "===", "$", "modes", "->", "getObject", ")", "{", "$", "object", "=", "(", "object", ")", "$", "data", ";", "if", "(", "isset", "(", "$", "object", "->", "meta", ")", ")", "{", "$", "object", "->", "meta", "=", "unserialize", "(", "$", "object", "->", "meta", ")", ";", "}", "return", "$", "object", ";", "}", "if", "(", "$", "mode", "===", "$", "modes", "->", "getPostdata", ")", "{", "return", "$", "data", "[", "'file'", "]", ";", "}", "}" ]
Give the field some data and ask it to return a value using one of many possible modes. @param mixed $data @param integer $mode @param integer $entry_id @return array|string|null
[ "Give", "the", "field", "some", "data", "and", "ask", "it", "to", "return", "a", "value", "using", "one", "of", "many", "possible", "modes", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/fields/field.upload.php#L699-L728
symphonycms/symphony-2
symphony/lib/toolkit/fields/field.upload.php
FieldUpload.buildDSRetrievalSQL
public function buildDSRetrievalSQL($data, &$joins, &$where, $andOperation = false) { $field_id = $this->get('id'); if (preg_match('/^mimetype:/', $data[0])) { $data[0] = str_replace('mimetype:', '', $data[0]); $column = 'mimetype'; } elseif (preg_match('/^size:/', $data[0])) { $data[0] = str_replace('size:', '', $data[0]); $column = 'size'; } else { $column = 'file'; } if (self::isFilterRegex($data[0])) { $this->buildRegexSQL($data[0], array($column), $joins, $where); } elseif (self::isFilterSQL($data[0])) { $this->buildFilterSQL($data[0], array($column), $joins, $where); } elseif ($andOperation) { foreach ($data as $value) { $this->_key++; $value = $this->cleanValue($value); $joins .= " LEFT JOIN `tbl_entries_data_{$field_id}` AS t{$field_id}_{$this->_key} ON (e.id = t{$field_id}_{$this->_key}.entry_id) "; $where .= " AND t{$field_id}_{$this->_key}.{$column} = '{$value}' "; } } else { if (!is_array($data)) { $data = array($data); } foreach ($data as &$value) { $value = $this->cleanValue($value); } $this->_key++; $data = implode("', '", $data); $joins .= " LEFT JOIN `tbl_entries_data_{$field_id}` AS t{$field_id}_{$this->_key} ON (e.id = t{$field_id}_{$this->_key}.entry_id) "; $where .= " AND t{$field_id}_{$this->_key}.{$column} IN ('{$data}') "; } return true; }
php
public function buildDSRetrievalSQL($data, &$joins, &$where, $andOperation = false) { $field_id = $this->get('id'); if (preg_match('/^mimetype:/', $data[0])) { $data[0] = str_replace('mimetype:', '', $data[0]); $column = 'mimetype'; } elseif (preg_match('/^size:/', $data[0])) { $data[0] = str_replace('size:', '', $data[0]); $column = 'size'; } else { $column = 'file'; } if (self::isFilterRegex($data[0])) { $this->buildRegexSQL($data[0], array($column), $joins, $where); } elseif (self::isFilterSQL($data[0])) { $this->buildFilterSQL($data[0], array($column), $joins, $where); } elseif ($andOperation) { foreach ($data as $value) { $this->_key++; $value = $this->cleanValue($value); $joins .= " LEFT JOIN `tbl_entries_data_{$field_id}` AS t{$field_id}_{$this->_key} ON (e.id = t{$field_id}_{$this->_key}.entry_id) "; $where .= " AND t{$field_id}_{$this->_key}.{$column} = '{$value}' "; } } else { if (!is_array($data)) { $data = array($data); } foreach ($data as &$value) { $value = $this->cleanValue($value); } $this->_key++; $data = implode("', '", $data); $joins .= " LEFT JOIN `tbl_entries_data_{$field_id}` AS t{$field_id}_{$this->_key} ON (e.id = t{$field_id}_{$this->_key}.entry_id) "; $where .= " AND t{$field_id}_{$this->_key}.{$column} IN ('{$data}') "; } return true; }
[ "public", "function", "buildDSRetrievalSQL", "(", "$", "data", ",", "&", "$", "joins", ",", "&", "$", "where", ",", "$", "andOperation", "=", "false", ")", "{", "$", "field_id", "=", "$", "this", "->", "get", "(", "'id'", ")", ";", "if", "(", "preg_match", "(", "'/^mimetype:/'", ",", "$", "data", "[", "0", "]", ")", ")", "{", "$", "data", "[", "0", "]", "=", "str_replace", "(", "'mimetype:'", ",", "''", ",", "$", "data", "[", "0", "]", ")", ";", "$", "column", "=", "'mimetype'", ";", "}", "elseif", "(", "preg_match", "(", "'/^size:/'", ",", "$", "data", "[", "0", "]", ")", ")", "{", "$", "data", "[", "0", "]", "=", "str_replace", "(", "'size:'", ",", "''", ",", "$", "data", "[", "0", "]", ")", ";", "$", "column", "=", "'size'", ";", "}", "else", "{", "$", "column", "=", "'file'", ";", "}", "if", "(", "self", "::", "isFilterRegex", "(", "$", "data", "[", "0", "]", ")", ")", "{", "$", "this", "->", "buildRegexSQL", "(", "$", "data", "[", "0", "]", ",", "array", "(", "$", "column", ")", ",", "$", "joins", ",", "$", "where", ")", ";", "}", "elseif", "(", "self", "::", "isFilterSQL", "(", "$", "data", "[", "0", "]", ")", ")", "{", "$", "this", "->", "buildFilterSQL", "(", "$", "data", "[", "0", "]", ",", "array", "(", "$", "column", ")", ",", "$", "joins", ",", "$", "where", ")", ";", "}", "elseif", "(", "$", "andOperation", ")", "{", "foreach", "(", "$", "data", "as", "$", "value", ")", "{", "$", "this", "->", "_key", "++", ";", "$", "value", "=", "$", "this", "->", "cleanValue", "(", "$", "value", ")", ";", "$", "joins", ".=", "\"\n LEFT JOIN\n `tbl_entries_data_{$field_id}` AS t{$field_id}_{$this->_key}\n ON (e.id = t{$field_id}_{$this->_key}.entry_id)\n \"", ";", "$", "where", ".=", "\"\n AND t{$field_id}_{$this->_key}.{$column} = '{$value}'\n \"", ";", "}", "}", "else", "{", "if", "(", "!", "is_array", "(", "$", "data", ")", ")", "{", "$", "data", "=", "array", "(", "$", "data", ")", ";", "}", "foreach", "(", "$", "data", "as", "&", "$", "value", ")", "{", "$", "value", "=", "$", "this", "->", "cleanValue", "(", "$", "value", ")", ";", "}", "$", "this", "->", "_key", "++", ";", "$", "data", "=", "implode", "(", "\"', '\"", ",", "$", "data", ")", ";", "$", "joins", ".=", "\"\n LEFT JOIN\n `tbl_entries_data_{$field_id}` AS t{$field_id}_{$this->_key}\n ON (e.id = t{$field_id}_{$this->_key}.entry_id)\n \"", ";", "$", "where", ".=", "\"\n AND t{$field_id}_{$this->_key}.{$column} IN ('{$data}')\n \"", ";", "}", "return", "true", ";", "}" ]
/*------------------------------------------------------------------------- Filtering: -------------------------------------------------------------------------
[ "/", "*", "-------------------------------------------------------------------------", "Filtering", ":", "-------------------------------------------------------------------------" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/fields/field.upload.php#L734-L787
symphonycms/symphony-2
symphony/lib/toolkit/email-gateways/email.sendmail.php
SendmailGateway.send
public function send() { $this->validate(); try { // 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 message from the attachments, the html-text and the 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, 'MIME-Version' => '1.0', ) ); // Format header fields $header_fields = array(); foreach ($this->_header_fields as $name => $body) { $header_fields[] = sprintf('%s: %s', $name, $body); } /** * Make things nice for mail(). * - Replace CRLF in the message body by LF as required by mail(). * - Implode the header fields as required by mail(). */ $this->_body = str_replace("\r\n", "\n", $this->_body); $header_fields = implode("\r\n", $header_fields); // Send the email mail($recipient_list, $subject, $this->_body, $header_fields, "-f{$this->_sender_email_address}"); } catch (Exception $e) { throw new EmailGatewayException($e->getMessage()); } return true; }
php
public function send() { $this->validate(); try { // 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 message from the attachments, the html-text and the 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, 'MIME-Version' => '1.0', ) ); // Format header fields $header_fields = array(); foreach ($this->_header_fields as $name => $body) { $header_fields[] = sprintf('%s: %s', $name, $body); } /** * Make things nice for mail(). * - Replace CRLF in the message body by LF as required by mail(). * - Implode the header fields as required by mail(). */ $this->_body = str_replace("\r\n", "\n", $this->_body); $header_fields = implode("\r\n", $header_fields); // Send the email mail($recipient_list, $subject, $this->_body, $header_fields, "-f{$this->_sender_email_address}"); } catch (Exception $e) { throw new EmailGatewayException($e->getMessage()); } return true; }
[ "public", "function", "send", "(", ")", "{", "$", "this", "->", "validate", "(", ")", ";", "try", "{", "// 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 message from the attachments, the html-text and the 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", ",", "'MIME-Version'", "=>", "'1.0'", ",", ")", ")", ";", "// Format header fields", "$", "header_fields", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "_header_fields", "as", "$", "name", "=>", "$", "body", ")", "{", "$", "header_fields", "[", "]", "=", "sprintf", "(", "'%s: %s'", ",", "$", "name", ",", "$", "body", ")", ";", "}", "/**\n * Make things nice for mail().\n * - Replace CRLF in the message body by LF as required by mail().\n * - Implode the header fields as required by mail().\n */", "$", "this", "->", "_body", "=", "str_replace", "(", "\"\\r\\n\"", ",", "\"\\n\"", ",", "$", "this", "->", "_body", ")", ";", "$", "header_fields", "=", "implode", "(", "\"\\r\\n\"", ",", "$", "header_fields", ")", ";", "// Send the email", "mail", "(", "$", "recipient_list", ",", "$", "subject", ",", "$", "this", "->", "_body", ",", "$", "header_fields", ",", "\"-f{$this->_sender_email_address}\"", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "throw", "new", "EmailGatewayException", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "return", "true", ";", "}" ]
Send an email using the PHP mail() function Please note that 'encoded-words' should be used according to RFC2047. Basically this means that the subject should be encoded if necessary, as well as (real) names in 'From', 'To' or 'Reply-To' header field bodies. For details see RFC2047. The parts of a message body should be encoded (quoted-printable or base64) to make non-US-ASCII text work with the widest range of email transports and clients. @throws EmailGatewayException @throws EmailValidationException @return bool
[ "Send", "an", "email", "using", "the", "PHP", "mail", "()", "function" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/email-gateways/email.sendmail.php#L52-L132
symphonycms/symphony-2
symphony/lib/toolkit/email-gateways/email.sendmail.php
SendmailGateway.getPreferencesPane
public function getPreferencesPane() { parent::getPreferencesPane(); $group = new XMLElement('fieldset'); $group->setAttribute('class', 'settings condensed pickable'); $group->setAttribute('id', 'sendmail'); $group->appendChild(new XMLElement('legend', __('Email: Sendmail'))); $div = new XMLElement('div'); $div->setAttribute('class', 'two columns'); $readonly = array('readonly' => 'readonly'); $label = Widget::Label(__('From Name')); $label->setAttribute('class', 'column'); $label->appendChild(Widget::Input('settings[email_sendmail][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_sendmail][from_address]', General::sanitize($this->_sender_email_address), 'text', $readonly)); $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', 'sendmail'); $group->appendChild(new XMLElement('legend', __('Email: Sendmail'))); $div = new XMLElement('div'); $div->setAttribute('class', 'two columns'); $readonly = array('readonly' => 'readonly'); $label = Widget::Label(__('From Name')); $label->setAttribute('class', 'column'); $label->appendChild(Widget::Input('settings[email_sendmail][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_sendmail][from_address]', General::sanitize($this->_sender_email_address), 'text', $readonly)); $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'", ",", "'sendmail'", ")", ";", "$", "group", "->", "appendChild", "(", "new", "XMLElement", "(", "'legend'", ",", "__", "(", "'Email: Sendmail'", ")", ")", ")", ";", "$", "div", "=", "new", "XMLElement", "(", "'div'", ")", ";", "$", "div", "->", "setAttribute", "(", "'class'", ",", "'two columns'", ")", ";", "$", "readonly", "=", "array", "(", "'readonly'", "=>", "'readonly'", ")", ";", "$", "label", "=", "Widget", "::", "Label", "(", "__", "(", "'From Name'", ")", ")", ";", "$", "label", "->", "setAttribute", "(", "'class'", ",", "'column'", ")", ";", "$", "label", "->", "appendChild", "(", "Widget", "::", "Input", "(", "'settings[email_sendmail][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_sendmail][from_address]'", ",", "General", "::", "sanitize", "(", "$", "this", "->", "_sender_email_address", ")", ",", "'text'", ",", "$", "readonly", ")", ")", ";", "$", "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.sendmail.php#L154-L180
symphonycms/symphony-2
install/lib/class.migration.php
Migration.run
public static function run($function, $existing_version = null) { static::$existing_version = $existing_version; try { $canProceed = static::$function(); return ($canProceed === false) ? false : true; } catch (DatabaseException $e) { Symphony::Log()->pushToLog('Could not complete upgrading. MySQL returned: ' . $e->getDatabaseErrorCode() . ': ' . $e->getMessage(), E_ERROR, true); return false; } catch (Exception $e) { Symphony::Log()->pushToLog('Could not complete upgrading because of the following error: ' . $e->getMessage(), E_ERROR, true); return false; } }
php
public static function run($function, $existing_version = null) { static::$existing_version = $existing_version; try { $canProceed = static::$function(); return ($canProceed === false) ? false : true; } catch (DatabaseException $e) { Symphony::Log()->pushToLog('Could not complete upgrading. MySQL returned: ' . $e->getDatabaseErrorCode() . ': ' . $e->getMessage(), E_ERROR, true); return false; } catch (Exception $e) { Symphony::Log()->pushToLog('Could not complete upgrading because of the following error: ' . $e->getMessage(), E_ERROR, true); return false; } }
[ "public", "static", "function", "run", "(", "$", "function", ",", "$", "existing_version", "=", "null", ")", "{", "static", "::", "$", "existing_version", "=", "$", "existing_version", ";", "try", "{", "$", "canProceed", "=", "static", "::", "$", "function", "(", ")", ";", "return", "(", "$", "canProceed", "===", "false", ")", "?", "false", ":", "true", ";", "}", "catch", "(", "DatabaseException", "$", "e", ")", "{", "Symphony", "::", "Log", "(", ")", "->", "pushToLog", "(", "'Could not complete upgrading. MySQL returned: '", ".", "$", "e", "->", "getDatabaseErrorCode", "(", ")", ".", "': '", ".", "$", "e", "->", "getMessage", "(", ")", ",", "E_ERROR", ",", "true", ")", ";", "return", "false", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "Symphony", "::", "Log", "(", ")", "->", "pushToLog", "(", "'Could not complete upgrading because of the following error: '", ".", "$", "e", "->", "getMessage", "(", ")", ",", "E_ERROR", ",", "true", ")", ";", "return", "false", ";", "}", "}" ]
While we are supporting PHP5.2, we can't do this neatly as 5.2 lacks late static binding. `self` will always refer to `Migration`, not the calling class, ie. `Migration_202`. In Symphony 2.4, we will support PHP5.3 only, and we can have this efficiency! @return boolean true if successful, false otherwise
[ "While", "we", "are", "supporting", "PHP5", ".", "2", "we", "can", "t", "do", "this", "neatly", "as", "5", ".", "2", "lacks", "late", "static", "binding", ".", "self", "will", "always", "refer", "to", "Migration", "not", "the", "calling", "class", "ie", ".", "Migration_202", ".", "In", "Symphony", "2", ".", "4", "we", "will", "support", "PHP5", ".", "3", "only", "and", "we", "can", "have", "this", "efficiency!" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/install/lib/class.migration.php#L31-L48
symphonycms/symphony-2
install/lib/class.migration.php
Migration.upgrade
public static function upgrade() { Symphony::Configuration()->set('version', static::getVersion(), 'symphony'); Symphony::Configuration()->set('useragent', 'Symphony/' . static::getVersion(), 'general'); if (Symphony::Configuration()->write() === false) { throw new Exception('Failed to write configuration file, please check the file permissions.'); } else { return true; } }
php
public static function upgrade() { Symphony::Configuration()->set('version', static::getVersion(), 'symphony'); Symphony::Configuration()->set('useragent', 'Symphony/' . static::getVersion(), 'general'); if (Symphony::Configuration()->write() === false) { throw new Exception('Failed to write configuration file, please check the file permissions.'); } else { return true; } }
[ "public", "static", "function", "upgrade", "(", ")", "{", "Symphony", "::", "Configuration", "(", ")", "->", "set", "(", "'version'", ",", "static", "::", "getVersion", "(", ")", ",", "'symphony'", ")", ";", "Symphony", "::", "Configuration", "(", ")", "->", "set", "(", "'useragent'", ",", "'Symphony/'", ".", "static", "::", "getVersion", "(", ")", ",", "'general'", ")", ";", "if", "(", "Symphony", "::", "Configuration", "(", ")", "->", "write", "(", ")", "===", "false", ")", "{", "throw", "new", "Exception", "(", "'Failed to write configuration file, please check the file permissions.'", ")", ";", "}", "else", "{", "return", "true", ";", "}", "}" ]
This function will upgrade Symphony from the `self::$existing_version` to `getVersion()`. @return boolean
[ "This", "function", "will", "upgrade", "Symphony", "from", "the", "self", "::", "$existing_version", "to", "getVersion", "()", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/install/lib/class.migration.php#L80-L90
symphonycms/symphony-2
symphony/lib/toolkit/fields/field.author.php
FieldAuthor.set
public function set($field, $value) { if ($field === 'author_types' && !is_array($value)) { $value = explode(',', $value); } $this->_settings[$field] = $value; }
php
public function set($field, $value) { if ($field === 'author_types' && !is_array($value)) { $value = explode(',', $value); } $this->_settings[$field] = $value; }
[ "public", "function", "set", "(", "$", "field", ",", "$", "value", ")", "{", "if", "(", "$", "field", "===", "'author_types'", "&&", "!", "is_array", "(", "$", "value", ")", ")", "{", "$", "value", "=", "explode", "(", "','", ",", "$", "value", ")", ";", "}", "$", "this", "->", "_settings", "[", "$", "field", "]", "=", "$", "value", ";", "}" ]
/*------------------------------------------------------------------------- Utilities: -------------------------------------------------------------------------
[ "/", "*", "-------------------------------------------------------------------------", "Utilities", ":", "-------------------------------------------------------------------------" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/fields/field.author.php#L101-L108
symphonycms/symphony-2
symphony/lib/toolkit/fields/field.author.php
FieldAuthor.displayPublishPanel
public function displayPublishPanel(XMLElement &$wrapper, $data = null, $flagWithError = null, $fieldnamePrefix = null, $fieldnamePostfix = null, $entry_id = null) { $value = isset($data['author_id']) ? $data['author_id'] : null; if ($this->get('default_to_current_user') === 'yes' && empty($data) && empty($_POST)) { $value = array(Symphony::Author()->get('id')); } if (!is_array($value)) { $value = array($value); } $options = array(); if ($this->get('required') !== 'yes') { $options[] = array(null, false, null); } // Custom where to only show Authors based off the Author Types setting $types = $this->get('author_types'); if (!empty($types)) { $types = implode('","', $this->get('author_types')); $where = 'user_type IN ("' . $types . '")'; } $authors = AuthorManager::fetch('id', 'ASC', null, null, $where); $found = false; foreach ($authors as $a) { if (in_array($a->get('id'), $value)) { $found = true; } $options[] = array($a->get('id'), in_array($a->get('id'), $value), $a->getFullName()); } // Ensure the selected Author is included in the options (incase // the settings change after the original entry was created) if (!$found && !is_null($value)) { $authors = AuthorManager::fetchByID($value); foreach ($authors as $a) { $options[] = array($a->get('id'), in_array($a->get('id'), $value), $a->getFullName()); } } $fieldname = 'fields'.$fieldnamePrefix.'['.$this->get('element_name').']'.$fieldnamePostfix; if ($this->get('allow_multiple_selection') === 'yes') { $fieldname .= '[]'; } $label = Widget::Label($this->get('label')); if ($this->get('required') !== 'yes') { $label->appendChild(new XMLElement('i', __('Optional'))); } $label->appendChild(Widget::Select($fieldname, $options, ($this->get('allow_multiple_selection') === 'yes' ? array('multiple' => 'multiple') : null))); if ($flagWithError != null) { $wrapper->appendChild(Widget::Error($label, $flagWithError)); } else { $wrapper->appendChild($label); } }
php
public function displayPublishPanel(XMLElement &$wrapper, $data = null, $flagWithError = null, $fieldnamePrefix = null, $fieldnamePostfix = null, $entry_id = null) { $value = isset($data['author_id']) ? $data['author_id'] : null; if ($this->get('default_to_current_user') === 'yes' && empty($data) && empty($_POST)) { $value = array(Symphony::Author()->get('id')); } if (!is_array($value)) { $value = array($value); } $options = array(); if ($this->get('required') !== 'yes') { $options[] = array(null, false, null); } // Custom where to only show Authors based off the Author Types setting $types = $this->get('author_types'); if (!empty($types)) { $types = implode('","', $this->get('author_types')); $where = 'user_type IN ("' . $types . '")'; } $authors = AuthorManager::fetch('id', 'ASC', null, null, $where); $found = false; foreach ($authors as $a) { if (in_array($a->get('id'), $value)) { $found = true; } $options[] = array($a->get('id'), in_array($a->get('id'), $value), $a->getFullName()); } // Ensure the selected Author is included in the options (incase // the settings change after the original entry was created) if (!$found && !is_null($value)) { $authors = AuthorManager::fetchByID($value); foreach ($authors as $a) { $options[] = array($a->get('id'), in_array($a->get('id'), $value), $a->getFullName()); } } $fieldname = 'fields'.$fieldnamePrefix.'['.$this->get('element_name').']'.$fieldnamePostfix; if ($this->get('allow_multiple_selection') === 'yes') { $fieldname .= '[]'; } $label = Widget::Label($this->get('label')); if ($this->get('required') !== 'yes') { $label->appendChild(new XMLElement('i', __('Optional'))); } $label->appendChild(Widget::Select($fieldname, $options, ($this->get('allow_multiple_selection') === 'yes' ? array('multiple' => 'multiple') : null))); if ($flagWithError != null) { $wrapper->appendChild(Widget::Error($label, $flagWithError)); } else { $wrapper->appendChild($label); } }
[ "public", "function", "displayPublishPanel", "(", "XMLElement", "&", "$", "wrapper", ",", "$", "data", "=", "null", ",", "$", "flagWithError", "=", "null", ",", "$", "fieldnamePrefix", "=", "null", ",", "$", "fieldnamePostfix", "=", "null", ",", "$", "entry_id", "=", "null", ")", "{", "$", "value", "=", "isset", "(", "$", "data", "[", "'author_id'", "]", ")", "?", "$", "data", "[", "'author_id'", "]", ":", "null", ";", "if", "(", "$", "this", "->", "get", "(", "'default_to_current_user'", ")", "===", "'yes'", "&&", "empty", "(", "$", "data", ")", "&&", "empty", "(", "$", "_POST", ")", ")", "{", "$", "value", "=", "array", "(", "Symphony", "::", "Author", "(", ")", "->", "get", "(", "'id'", ")", ")", ";", "}", "if", "(", "!", "is_array", "(", "$", "value", ")", ")", "{", "$", "value", "=", "array", "(", "$", "value", ")", ";", "}", "$", "options", "=", "array", "(", ")", ";", "if", "(", "$", "this", "->", "get", "(", "'required'", ")", "!==", "'yes'", ")", "{", "$", "options", "[", "]", "=", "array", "(", "null", ",", "false", ",", "null", ")", ";", "}", "// Custom where to only show Authors based off the Author Types setting", "$", "types", "=", "$", "this", "->", "get", "(", "'author_types'", ")", ";", "if", "(", "!", "empty", "(", "$", "types", ")", ")", "{", "$", "types", "=", "implode", "(", "'\",\"'", ",", "$", "this", "->", "get", "(", "'author_types'", ")", ")", ";", "$", "where", "=", "'user_type IN (\"'", ".", "$", "types", ".", "'\")'", ";", "}", "$", "authors", "=", "AuthorManager", "::", "fetch", "(", "'id'", ",", "'ASC'", ",", "null", ",", "null", ",", "$", "where", ")", ";", "$", "found", "=", "false", ";", "foreach", "(", "$", "authors", "as", "$", "a", ")", "{", "if", "(", "in_array", "(", "$", "a", "->", "get", "(", "'id'", ")", ",", "$", "value", ")", ")", "{", "$", "found", "=", "true", ";", "}", "$", "options", "[", "]", "=", "array", "(", "$", "a", "->", "get", "(", "'id'", ")", ",", "in_array", "(", "$", "a", "->", "get", "(", "'id'", ")", ",", "$", "value", ")", ",", "$", "a", "->", "getFullName", "(", ")", ")", ";", "}", "// Ensure the selected Author is included in the options (incase", "// the settings change after the original entry was created)", "if", "(", "!", "$", "found", "&&", "!", "is_null", "(", "$", "value", ")", ")", "{", "$", "authors", "=", "AuthorManager", "::", "fetchByID", "(", "$", "value", ")", ";", "foreach", "(", "$", "authors", "as", "$", "a", ")", "{", "$", "options", "[", "]", "=", "array", "(", "$", "a", "->", "get", "(", "'id'", ")", ",", "in_array", "(", "$", "a", "->", "get", "(", "'id'", ")", ",", "$", "value", ")", ",", "$", "a", "->", "getFullName", "(", ")", ")", ";", "}", "}", "$", "fieldname", "=", "'fields'", ".", "$", "fieldnamePrefix", ".", "'['", ".", "$", "this", "->", "get", "(", "'element_name'", ")", ".", "']'", ".", "$", "fieldnamePostfix", ";", "if", "(", "$", "this", "->", "get", "(", "'allow_multiple_selection'", ")", "===", "'yes'", ")", "{", "$", "fieldname", ".=", "'[]'", ";", "}", "$", "label", "=", "Widget", "::", "Label", "(", "$", "this", "->", "get", "(", "'label'", ")", ")", ";", "if", "(", "$", "this", "->", "get", "(", "'required'", ")", "!==", "'yes'", ")", "{", "$", "label", "->", "appendChild", "(", "new", "XMLElement", "(", "'i'", ",", "__", "(", "'Optional'", ")", ")", ")", ";", "}", "$", "label", "->", "appendChild", "(", "Widget", "::", "Select", "(", "$", "fieldname", ",", "$", "options", ",", "(", "$", "this", "->", "get", "(", "'allow_multiple_selection'", ")", "===", "'yes'", "?", "array", "(", "'multiple'", "=>", "'multiple'", ")", ":", "null", ")", ")", ")", ";", "if", "(", "$", "flagWithError", "!=", "null", ")", "{", "$", "wrapper", "->", "appendChild", "(", "Widget", "::", "Error", "(", "$", "label", ",", "$", "flagWithError", ")", ")", ";", "}", "else", "{", "$", "wrapper", "->", "appendChild", "(", "$", "label", ")", ";", "}", "}" ]
/*------------------------------------------------------------------------- Publish: -------------------------------------------------------------------------
[ "/", "*", "-------------------------------------------------------------------------", "Publish", ":", "-------------------------------------------------------------------------" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/fields/field.author.php#L218-L284
symphonycms/symphony-2
symphony/lib/toolkit/fields/field.author.php
FieldAuthor.appendFormattedElement
public function appendFormattedElement(XMLElement &$wrapper, $data, $encode = false, $mode = null, $entry_id = null) { if (!is_array($data['author_id'])) { $data['author_id'] = array($data['author_id']); } $list = new XMLElement($this->get('element_name')); $authors = AuthorManager::fetchByID($data['author_id']); foreach ($authors as $author) { if (is_null($author)) { continue; } $list->appendChild(new XMLElement( 'item', $author->getFullName(), array( 'id' => (string)$author->get('id'), 'handle' => Lang::createHandle($author->getFullName()), 'username' => General::sanitize($author->get('username')) ) )); } $wrapper->appendChild($list); }
php
public function appendFormattedElement(XMLElement &$wrapper, $data, $encode = false, $mode = null, $entry_id = null) { if (!is_array($data['author_id'])) { $data['author_id'] = array($data['author_id']); } $list = new XMLElement($this->get('element_name')); $authors = AuthorManager::fetchByID($data['author_id']); foreach ($authors as $author) { if (is_null($author)) { continue; } $list->appendChild(new XMLElement( 'item', $author->getFullName(), array( 'id' => (string)$author->get('id'), 'handle' => Lang::createHandle($author->getFullName()), 'username' => General::sanitize($author->get('username')) ) )); } $wrapper->appendChild($list); }
[ "public", "function", "appendFormattedElement", "(", "XMLElement", "&", "$", "wrapper", ",", "$", "data", ",", "$", "encode", "=", "false", ",", "$", "mode", "=", "null", ",", "$", "entry_id", "=", "null", ")", "{", "if", "(", "!", "is_array", "(", "$", "data", "[", "'author_id'", "]", ")", ")", "{", "$", "data", "[", "'author_id'", "]", "=", "array", "(", "$", "data", "[", "'author_id'", "]", ")", ";", "}", "$", "list", "=", "new", "XMLElement", "(", "$", "this", "->", "get", "(", "'element_name'", ")", ")", ";", "$", "authors", "=", "AuthorManager", "::", "fetchByID", "(", "$", "data", "[", "'author_id'", "]", ")", ";", "foreach", "(", "$", "authors", "as", "$", "author", ")", "{", "if", "(", "is_null", "(", "$", "author", ")", ")", "{", "continue", ";", "}", "$", "list", "->", "appendChild", "(", "new", "XMLElement", "(", "'item'", ",", "$", "author", "->", "getFullName", "(", ")", ",", "array", "(", "'id'", "=>", "(", "string", ")", "$", "author", "->", "get", "(", "'id'", ")", ",", "'handle'", "=>", "Lang", "::", "createHandle", "(", "$", "author", "->", "getFullName", "(", ")", ")", ",", "'username'", "=>", "General", "::", "sanitize", "(", "$", "author", "->", "get", "(", "'username'", ")", ")", ")", ")", ")", ";", "}", "$", "wrapper", "->", "appendChild", "(", "$", "list", ")", ";", "}" ]
/*------------------------------------------------------------------------- Output: -------------------------------------------------------------------------
[ "/", "*", "-------------------------------------------------------------------------", "Output", ":", "-------------------------------------------------------------------------" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/fields/field.author.php#L311-L337
symphonycms/symphony-2
symphony/lib/toolkit/fields/field.author.php
FieldAuthor.getExportModes
public function getExportModes() { return array( 'listAuthor' => ExportableField::LIST_OF + ExportableField::AUTHOR, 'listAuthorObject' => ExportableField::LIST_OF + ExportableField::AUTHOR + ExportableField::OBJECT, 'listAuthorToValue' => ExportableField::LIST_OF + ExportableField::AUTHOR + ExportableField::VALUE, 'listValue' => ExportableField::LIST_OF + ExportableField::VALUE, 'getPostdata' => ExportableField::POSTDATA ); }
php
public function getExportModes() { return array( 'listAuthor' => ExportableField::LIST_OF + ExportableField::AUTHOR, 'listAuthorObject' => ExportableField::LIST_OF + ExportableField::AUTHOR + ExportableField::OBJECT, 'listAuthorToValue' => ExportableField::LIST_OF + ExportableField::AUTHOR + ExportableField::VALUE, 'listValue' => ExportableField::LIST_OF + ExportableField::VALUE, 'getPostdata' => ExportableField::POSTDATA ); }
[ "public", "function", "getExportModes", "(", ")", "{", "return", "array", "(", "'listAuthor'", "=>", "ExportableField", "::", "LIST_OF", "+", "ExportableField", "::", "AUTHOR", ",", "'listAuthorObject'", "=>", "ExportableField", "::", "LIST_OF", "+", "ExportableField", "::", "AUTHOR", "+", "ExportableField", "::", "OBJECT", ",", "'listAuthorToValue'", "=>", "ExportableField", "::", "LIST_OF", "+", "ExportableField", "::", "AUTHOR", "+", "ExportableField", "::", "VALUE", ",", "'listValue'", "=>", "ExportableField", "::", "LIST_OF", "+", "ExportableField", "::", "VALUE", ",", "'getPostdata'", "=>", "ExportableField", "::", "POSTDATA", ")", ";", "}" ]
Return a list of supported export modes for use with `prepareExportValue`. @return array
[ "Return", "a", "list", "of", "supported", "export", "modes", "for", "use", "with", "prepareExportValue", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/fields/field.author.php#L359-L374
symphonycms/symphony-2
symphony/lib/toolkit/fields/field.author.php
FieldAuthor.prepareExportValue
public function prepareExportValue($data, $mode, $entry_id = null) { $modes = (object)$this->getExportModes(); // Make sure we have an array to work with: if (isset($data['author_id']) && is_array($data['author_id']) === false) { $data['author_id'] = array( $data['author_id'] ); } // Return the author IDs: if ($mode === $modes->listAuthor || $mode === $modes->getPostdata) { return isset($data['author_id']) ? $data['author_id'] : array(); } // All other modes require full data: $authors = isset($data['author_id']) ? AuthorManager::fetchByID($data['author_id']) : array(); $items = array(); foreach ($authors as $author) { if (is_null($author)) { continue; } if ($mode === $modes->listAuthorObject) { $items[] = $author; } elseif ($mode === $modes->listValue) { $items[] = $author->getFullName(); } elseif ($mode === $modes->listAuthorToValue) { $items[$data['author_id']] = $author->getFullName(); } } return $items; }
php
public function prepareExportValue($data, $mode, $entry_id = null) { $modes = (object)$this->getExportModes(); // Make sure we have an array to work with: if (isset($data['author_id']) && is_array($data['author_id']) === false) { $data['author_id'] = array( $data['author_id'] ); } // Return the author IDs: if ($mode === $modes->listAuthor || $mode === $modes->getPostdata) { return isset($data['author_id']) ? $data['author_id'] : array(); } // All other modes require full data: $authors = isset($data['author_id']) ? AuthorManager::fetchByID($data['author_id']) : array(); $items = array(); foreach ($authors as $author) { if (is_null($author)) { continue; } if ($mode === $modes->listAuthorObject) { $items[] = $author; } elseif ($mode === $modes->listValue) { $items[] = $author->getFullName(); } elseif ($mode === $modes->listAuthorToValue) { $items[$data['author_id']] = $author->getFullName(); } } return $items; }
[ "public", "function", "prepareExportValue", "(", "$", "data", ",", "$", "mode", ",", "$", "entry_id", "=", "null", ")", "{", "$", "modes", "=", "(", "object", ")", "$", "this", "->", "getExportModes", "(", ")", ";", "// Make sure we have an array to work with:", "if", "(", "isset", "(", "$", "data", "[", "'author_id'", "]", ")", "&&", "is_array", "(", "$", "data", "[", "'author_id'", "]", ")", "===", "false", ")", "{", "$", "data", "[", "'author_id'", "]", "=", "array", "(", "$", "data", "[", "'author_id'", "]", ")", ";", "}", "// Return the author IDs:", "if", "(", "$", "mode", "===", "$", "modes", "->", "listAuthor", "||", "$", "mode", "===", "$", "modes", "->", "getPostdata", ")", "{", "return", "isset", "(", "$", "data", "[", "'author_id'", "]", ")", "?", "$", "data", "[", "'author_id'", "]", ":", "array", "(", ")", ";", "}", "// All other modes require full data:", "$", "authors", "=", "isset", "(", "$", "data", "[", "'author_id'", "]", ")", "?", "AuthorManager", "::", "fetchByID", "(", "$", "data", "[", "'author_id'", "]", ")", ":", "array", "(", ")", ";", "$", "items", "=", "array", "(", ")", ";", "foreach", "(", "$", "authors", "as", "$", "author", ")", "{", "if", "(", "is_null", "(", "$", "author", ")", ")", "{", "continue", ";", "}", "if", "(", "$", "mode", "===", "$", "modes", "->", "listAuthorObject", ")", "{", "$", "items", "[", "]", "=", "$", "author", ";", "}", "elseif", "(", "$", "mode", "===", "$", "modes", "->", "listValue", ")", "{", "$", "items", "[", "]", "=", "$", "author", "->", "getFullName", "(", ")", ";", "}", "elseif", "(", "$", "mode", "===", "$", "modes", "->", "listAuthorToValue", ")", "{", "$", "items", "[", "$", "data", "[", "'author_id'", "]", "]", "=", "$", "author", "->", "getFullName", "(", ")", ";", "}", "}", "return", "$", "items", ";", "}" ]
Give the field some data and ask it to return a value using one of many possible modes. @param mixed $data @param integer $mode @param integer $entry_id @return array|null
[ "Give", "the", "field", "some", "data", "and", "ask", "it", "to", "return", "a", "value", "using", "one", "of", "many", "possible", "modes", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/fields/field.author.php#L385-L424
symphonycms/symphony-2
symphony/lib/toolkit/fields/field.author.php
FieldAuthor.buildDSRetrievalSQL
public function buildDSRetrievalSQL($data, &$joins, &$where, $andOperation = false) { $field_id = $this->get('id'); if (self::isFilterRegex($data[0])) { $this->_key++; if (preg_match('/^regexp:/i', $data[0])) { $pattern = preg_replace('/^regexp:\s*/i', null, $this->cleanValue($data[0])); $regex = 'REGEXP'; } else { $pattern = preg_replace('/^not-?regexp:\s*/i', null, $this->cleanValue($data[0])); $regex = 'NOT REGEXP'; } if (strlen($pattern) == 0) { return; } $joins .= " LEFT JOIN `tbl_entries_data_{$field_id}` AS t{$field_id}_{$this->_key} ON (e.id = t{$field_id}_{$this->_key}.entry_id) JOIN `tbl_authors` AS t{$field_id}_{$this->_key}_authors ON (t{$field_id}_{$this->_key}.author_id = t{$field_id}_{$this->_key}_authors.id) "; $where .= " AND ( t{$field_id}_{$this->_key}.author_id {$regex} '{$pattern}' OR t{$field_id}_{$this->_key}_authors.username {$regex} '{$pattern}' OR CONCAT_WS(' ', t{$field_id}_{$this->_key}_authors.first_name, t{$field_id}_{$this->_key}_authors.last_name ) {$regex} '{$pattern}' ) "; } elseif (self::isFilterSQL($data[0])) { $this->buildFilterSQL($data[0], array('username', 'first_name', 'last_name'), $joins, $where); } elseif ($andOperation) { foreach ($data as $value) { $this->_key++; $value = $this->cleanValue($value); if (self::__parseFilter($value) == "author_id") { $where .= " AND t{$field_id}_{$this->_key}.author_id = '{$value}' "; $joins .= " LEFT JOIN `tbl_entries_data_{$field_id}` AS t{$field_id}_{$this->_key} ON (e.id = t{$field_id}_{$this->_key}.entry_id) "; } else { $joins .= " LEFT JOIN `tbl_entries_data_{$field_id}` AS t{$field_id}_{$this->_key} ON (e.id = t{$field_id}_{$this->_key}.entry_id) JOIN `tbl_authors` AS t{$field_id}_{$this->_key}_authors ON (t{$field_id}_{$this->_key}.author_id = t{$field_id}_{$this->_key}_authors.id) "; $where .= " AND ( t{$field_id}_{$this->_key}_authors.username = '{$value}' OR CONCAT_WS(' ', t{$field_id}_{$this->_key}_authors.first_name, t{$field_id}_{$this->_key}_authors.last_name ) = '{$value}' ) "; } } } else { if (!is_array($data)) { $data = array($data); } foreach ($data as &$value) { $value = $this->cleanValue($value); } $this->_key++; $data = implode("', '", $data); $joins .= " LEFT JOIN `tbl_entries_data_{$field_id}` AS t{$field_id}_{$this->_key} ON (e.id = t{$field_id}_{$this->_key}.entry_id) JOIN `tbl_authors` AS t{$field_id}_{$this->_key}_authors ON (t{$field_id}_{$this->_key}.author_id = t{$field_id}_{$this->_key}_authors.id) "; $where .= " AND ( t{$field_id}_{$this->_key}.author_id IN ('{$data}') OR t{$field_id}_{$this->_key}_authors.username IN ('{$data}') OR CONCAT_WS(' ', t{$field_id}_{$this->_key}_authors.first_name, t{$field_id}_{$this->_key}_authors.last_name ) IN ('{$data}') ) "; } return true; }
php
public function buildDSRetrievalSQL($data, &$joins, &$where, $andOperation = false) { $field_id = $this->get('id'); if (self::isFilterRegex($data[0])) { $this->_key++; if (preg_match('/^regexp:/i', $data[0])) { $pattern = preg_replace('/^regexp:\s*/i', null, $this->cleanValue($data[0])); $regex = 'REGEXP'; } else { $pattern = preg_replace('/^not-?regexp:\s*/i', null, $this->cleanValue($data[0])); $regex = 'NOT REGEXP'; } if (strlen($pattern) == 0) { return; } $joins .= " LEFT JOIN `tbl_entries_data_{$field_id}` AS t{$field_id}_{$this->_key} ON (e.id = t{$field_id}_{$this->_key}.entry_id) JOIN `tbl_authors` AS t{$field_id}_{$this->_key}_authors ON (t{$field_id}_{$this->_key}.author_id = t{$field_id}_{$this->_key}_authors.id) "; $where .= " AND ( t{$field_id}_{$this->_key}.author_id {$regex} '{$pattern}' OR t{$field_id}_{$this->_key}_authors.username {$regex} '{$pattern}' OR CONCAT_WS(' ', t{$field_id}_{$this->_key}_authors.first_name, t{$field_id}_{$this->_key}_authors.last_name ) {$regex} '{$pattern}' ) "; } elseif (self::isFilterSQL($data[0])) { $this->buildFilterSQL($data[0], array('username', 'first_name', 'last_name'), $joins, $where); } elseif ($andOperation) { foreach ($data as $value) { $this->_key++; $value = $this->cleanValue($value); if (self::__parseFilter($value) == "author_id") { $where .= " AND t{$field_id}_{$this->_key}.author_id = '{$value}' "; $joins .= " LEFT JOIN `tbl_entries_data_{$field_id}` AS t{$field_id}_{$this->_key} ON (e.id = t{$field_id}_{$this->_key}.entry_id) "; } else { $joins .= " LEFT JOIN `tbl_entries_data_{$field_id}` AS t{$field_id}_{$this->_key} ON (e.id = t{$field_id}_{$this->_key}.entry_id) JOIN `tbl_authors` AS t{$field_id}_{$this->_key}_authors ON (t{$field_id}_{$this->_key}.author_id = t{$field_id}_{$this->_key}_authors.id) "; $where .= " AND ( t{$field_id}_{$this->_key}_authors.username = '{$value}' OR CONCAT_WS(' ', t{$field_id}_{$this->_key}_authors.first_name, t{$field_id}_{$this->_key}_authors.last_name ) = '{$value}' ) "; } } } else { if (!is_array($data)) { $data = array($data); } foreach ($data as &$value) { $value = $this->cleanValue($value); } $this->_key++; $data = implode("', '", $data); $joins .= " LEFT JOIN `tbl_entries_data_{$field_id}` AS t{$field_id}_{$this->_key} ON (e.id = t{$field_id}_{$this->_key}.entry_id) JOIN `tbl_authors` AS t{$field_id}_{$this->_key}_authors ON (t{$field_id}_{$this->_key}.author_id = t{$field_id}_{$this->_key}_authors.id) "; $where .= " AND ( t{$field_id}_{$this->_key}.author_id IN ('{$data}') OR t{$field_id}_{$this->_key}_authors.username IN ('{$data}') OR CONCAT_WS(' ', t{$field_id}_{$this->_key}_authors.first_name, t{$field_id}_{$this->_key}_authors.last_name ) IN ('{$data}') ) "; } return true; }
[ "public", "function", "buildDSRetrievalSQL", "(", "$", "data", ",", "&", "$", "joins", ",", "&", "$", "where", ",", "$", "andOperation", "=", "false", ")", "{", "$", "field_id", "=", "$", "this", "->", "get", "(", "'id'", ")", ";", "if", "(", "self", "::", "isFilterRegex", "(", "$", "data", "[", "0", "]", ")", ")", "{", "$", "this", "->", "_key", "++", ";", "if", "(", "preg_match", "(", "'/^regexp:/i'", ",", "$", "data", "[", "0", "]", ")", ")", "{", "$", "pattern", "=", "preg_replace", "(", "'/^regexp:\\s*/i'", ",", "null", ",", "$", "this", "->", "cleanValue", "(", "$", "data", "[", "0", "]", ")", ")", ";", "$", "regex", "=", "'REGEXP'", ";", "}", "else", "{", "$", "pattern", "=", "preg_replace", "(", "'/^not-?regexp:\\s*/i'", ",", "null", ",", "$", "this", "->", "cleanValue", "(", "$", "data", "[", "0", "]", ")", ")", ";", "$", "regex", "=", "'NOT REGEXP'", ";", "}", "if", "(", "strlen", "(", "$", "pattern", ")", "==", "0", ")", "{", "return", ";", "}", "$", "joins", ".=", "\"\n LEFT JOIN\n `tbl_entries_data_{$field_id}` AS t{$field_id}_{$this->_key}\n ON (e.id = t{$field_id}_{$this->_key}.entry_id)\n JOIN\n `tbl_authors` AS t{$field_id}_{$this->_key}_authors\n ON (t{$field_id}_{$this->_key}.author_id = t{$field_id}_{$this->_key}_authors.id)\n \"", ";", "$", "where", ".=", "\"\n AND (\n t{$field_id}_{$this->_key}.author_id {$regex} '{$pattern}'\n OR t{$field_id}_{$this->_key}_authors.username {$regex} '{$pattern}'\n OR CONCAT_WS(' ',\n t{$field_id}_{$this->_key}_authors.first_name,\n t{$field_id}_{$this->_key}_authors.last_name\n ) {$regex} '{$pattern}'\n )\n \"", ";", "}", "elseif", "(", "self", "::", "isFilterSQL", "(", "$", "data", "[", "0", "]", ")", ")", "{", "$", "this", "->", "buildFilterSQL", "(", "$", "data", "[", "0", "]", ",", "array", "(", "'username'", ",", "'first_name'", ",", "'last_name'", ")", ",", "$", "joins", ",", "$", "where", ")", ";", "}", "elseif", "(", "$", "andOperation", ")", "{", "foreach", "(", "$", "data", "as", "$", "value", ")", "{", "$", "this", "->", "_key", "++", ";", "$", "value", "=", "$", "this", "->", "cleanValue", "(", "$", "value", ")", ";", "if", "(", "self", "::", "__parseFilter", "(", "$", "value", ")", "==", "\"author_id\"", ")", "{", "$", "where", ".=", "\"\n AND t{$field_id}_{$this->_key}.author_id = '{$value}'\n \"", ";", "$", "joins", ".=", "\"\n LEFT JOIN\n `tbl_entries_data_{$field_id}` AS t{$field_id}_{$this->_key}\n ON (e.id = t{$field_id}_{$this->_key}.entry_id)\n \"", ";", "}", "else", "{", "$", "joins", ".=", "\"\n LEFT JOIN\n `tbl_entries_data_{$field_id}` AS t{$field_id}_{$this->_key}\n ON (e.id = t{$field_id}_{$this->_key}.entry_id)\n JOIN\n `tbl_authors` AS t{$field_id}_{$this->_key}_authors\n ON (t{$field_id}_{$this->_key}.author_id = t{$field_id}_{$this->_key}_authors.id)\n \"", ";", "$", "where", ".=", "\"\n AND (\n t{$field_id}_{$this->_key}_authors.username = '{$value}'\n OR CONCAT_WS(' ',\n t{$field_id}_{$this->_key}_authors.first_name,\n t{$field_id}_{$this->_key}_authors.last_name\n ) = '{$value}'\n )\n \"", ";", "}", "}", "}", "else", "{", "if", "(", "!", "is_array", "(", "$", "data", ")", ")", "{", "$", "data", "=", "array", "(", "$", "data", ")", ";", "}", "foreach", "(", "$", "data", "as", "&", "$", "value", ")", "{", "$", "value", "=", "$", "this", "->", "cleanValue", "(", "$", "value", ")", ";", "}", "$", "this", "->", "_key", "++", ";", "$", "data", "=", "implode", "(", "\"', '\"", ",", "$", "data", ")", ";", "$", "joins", ".=", "\"\n LEFT JOIN\n `tbl_entries_data_{$field_id}` AS t{$field_id}_{$this->_key}\n ON (e.id = t{$field_id}_{$this->_key}.entry_id)\n JOIN\n `tbl_authors` AS t{$field_id}_{$this->_key}_authors\n ON (t{$field_id}_{$this->_key}.author_id = t{$field_id}_{$this->_key}_authors.id)\n \"", ";", "$", "where", ".=", "\"\n AND (\n t{$field_id}_{$this->_key}.author_id IN ('{$data}')\n OR\n t{$field_id}_{$this->_key}_authors.username IN ('{$data}')\n OR CONCAT_WS(' ',\n t{$field_id}_{$this->_key}_authors.first_name,\n t{$field_id}_{$this->_key}_authors.last_name\n ) IN ('{$data}')\n )\n \"", ";", "}", "return", "true", ";", "}" ]
/*------------------------------------------------------------------------- Filtering: -------------------------------------------------------------------------
[ "/", "*", "-------------------------------------------------------------------------", "Filtering", ":", "-------------------------------------------------------------------------" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/fields/field.author.php#L430-L536
symphonycms/symphony-2
symphony/lib/toolkit/fields/field.author.php
FieldAuthor.getExampleFormMarkup
public function getExampleFormMarkup() { $authors = AuthorManager::fetch(); $options = array(); foreach ($authors as $a) { $options[] = array($a->get('id'), null, $a->getFullName()); } $fieldname = 'fields['.$this->get('element_name').']'; if ($this->get('allow_multiple_selection') === 'yes') { $fieldname .= '[]'; } $attr = array(); if ($this->get('allow_multiple_selection') === 'yes') { $attr['multiple'] = 'multiple'; } $label = Widget::Label($this->get('label')); $label->appendChild(Widget::Select($fieldname, $options, $attr)); return $label; }
php
public function getExampleFormMarkup() { $authors = AuthorManager::fetch(); $options = array(); foreach ($authors as $a) { $options[] = array($a->get('id'), null, $a->getFullName()); } $fieldname = 'fields['.$this->get('element_name').']'; if ($this->get('allow_multiple_selection') === 'yes') { $fieldname .= '[]'; } $attr = array(); if ($this->get('allow_multiple_selection') === 'yes') { $attr['multiple'] = 'multiple'; } $label = Widget::Label($this->get('label')); $label->appendChild(Widget::Select($fieldname, $options, $attr)); return $label; }
[ "public", "function", "getExampleFormMarkup", "(", ")", "{", "$", "authors", "=", "AuthorManager", "::", "fetch", "(", ")", ";", "$", "options", "=", "array", "(", ")", ";", "foreach", "(", "$", "authors", "as", "$", "a", ")", "{", "$", "options", "[", "]", "=", "array", "(", "$", "a", "->", "get", "(", "'id'", ")", ",", "null", ",", "$", "a", "->", "getFullName", "(", ")", ")", ";", "}", "$", "fieldname", "=", "'fields['", ".", "$", "this", "->", "get", "(", "'element_name'", ")", ".", "']'", ";", "if", "(", "$", "this", "->", "get", "(", "'allow_multiple_selection'", ")", "===", "'yes'", ")", "{", "$", "fieldname", ".=", "'[]'", ";", "}", "$", "attr", "=", "array", "(", ")", ";", "if", "(", "$", "this", "->", "get", "(", "'allow_multiple_selection'", ")", "===", "'yes'", ")", "{", "$", "attr", "[", "'multiple'", "]", "=", "'multiple'", ";", "}", "$", "label", "=", "Widget", "::", "Label", "(", "$", "this", "->", "get", "(", "'label'", ")", ")", ";", "$", "label", "->", "appendChild", "(", "Widget", "::", "Select", "(", "$", "fieldname", ",", "$", "options", ",", "$", "attr", ")", ")", ";", "return", "$", "label", ";", "}" ]
/*------------------------------------------------------------------------- Events: -------------------------------------------------------------------------
[ "/", "*", "-------------------------------------------------------------------------", "Events", ":", "-------------------------------------------------------------------------" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/fields/field.author.php#L567-L592
symphonycms/symphony-2
symphony/lib/toolkit/fields/field.author.php
FieldAuthor.groupRecords
public function groupRecords($records) { if (!is_array($records) || empty($records)) { return; } $groups = array($this->get('element_name') => array()); foreach ($records as $r) { $data = $r->getData($this->get('id')); $author_id = !isset($data['author_id']) ? 0 : $data['author_id']; if (!isset($groups[$this->get('element_name')][$author_id])) { $author = AuthorManager::fetchByID($author_id); // If there is an author, use those values, otherwise just blank it. if ($author instanceof Author) { $username = $author->get('username'); $full_name = $author->getFullName(); } else { $username = ''; $full_name = ''; } $groups[$this->get('element_name')][$author_id] = array( 'attr' => array('author-id' => $author_id, 'username' => $username, 'full-name' => $full_name), 'records' => array(), 'groups' => array() ); } $groups[$this->get('element_name')][$author_id]['records'][] = $r; } return $groups; }
php
public function groupRecords($records) { if (!is_array($records) || empty($records)) { return; } $groups = array($this->get('element_name') => array()); foreach ($records as $r) { $data = $r->getData($this->get('id')); $author_id = !isset($data['author_id']) ? 0 : $data['author_id']; if (!isset($groups[$this->get('element_name')][$author_id])) { $author = AuthorManager::fetchByID($author_id); // If there is an author, use those values, otherwise just blank it. if ($author instanceof Author) { $username = $author->get('username'); $full_name = $author->getFullName(); } else { $username = ''; $full_name = ''; } $groups[$this->get('element_name')][$author_id] = array( 'attr' => array('author-id' => $author_id, 'username' => $username, 'full-name' => $full_name), 'records' => array(), 'groups' => array() ); } $groups[$this->get('element_name')][$author_id]['records'][] = $r; } return $groups; }
[ "public", "function", "groupRecords", "(", "$", "records", ")", "{", "if", "(", "!", "is_array", "(", "$", "records", ")", "||", "empty", "(", "$", "records", ")", ")", "{", "return", ";", "}", "$", "groups", "=", "array", "(", "$", "this", "->", "get", "(", "'element_name'", ")", "=>", "array", "(", ")", ")", ";", "foreach", "(", "$", "records", "as", "$", "r", ")", "{", "$", "data", "=", "$", "r", "->", "getData", "(", "$", "this", "->", "get", "(", "'id'", ")", ")", ";", "$", "author_id", "=", "!", "isset", "(", "$", "data", "[", "'author_id'", "]", ")", "?", "0", ":", "$", "data", "[", "'author_id'", "]", ";", "if", "(", "!", "isset", "(", "$", "groups", "[", "$", "this", "->", "get", "(", "'element_name'", ")", "]", "[", "$", "author_id", "]", ")", ")", "{", "$", "author", "=", "AuthorManager", "::", "fetchByID", "(", "$", "author_id", ")", ";", "// If there is an author, use those values, otherwise just blank it.", "if", "(", "$", "author", "instanceof", "Author", ")", "{", "$", "username", "=", "$", "author", "->", "get", "(", "'username'", ")", ";", "$", "full_name", "=", "$", "author", "->", "getFullName", "(", ")", ";", "}", "else", "{", "$", "username", "=", "''", ";", "$", "full_name", "=", "''", ";", "}", "$", "groups", "[", "$", "this", "->", "get", "(", "'element_name'", ")", "]", "[", "$", "author_id", "]", "=", "array", "(", "'attr'", "=>", "array", "(", "'author-id'", "=>", "$", "author_id", ",", "'username'", "=>", "$", "username", ",", "'full-name'", "=>", "$", "full_name", ")", ",", "'records'", "=>", "array", "(", ")", ",", "'groups'", "=>", "array", "(", ")", ")", ";", "}", "$", "groups", "[", "$", "this", "->", "get", "(", "'element_name'", ")", "]", "[", "$", "author_id", "]", "[", "'records'", "]", "[", "]", "=", "$", "r", ";", "}", "return", "$", "groups", ";", "}" ]
/*------------------------------------------------------------------------- Grouping: -------------------------------------------------------------------------
[ "/", "*", "-------------------------------------------------------------------------", "Grouping", ":", "-------------------------------------------------------------------------" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/fields/field.author.php#L598-L632
symphonycms/symphony-2
symphony/lib/toolkit/class.textformattermanager.php
TextformatterManager.create
public static function create($handle) { if (!isset(self::$_pool[$handle])) { $classname = self::__getClassName($handle); $path = self::__getDriverPath($handle); if (!is_file($path)) { throw new Exception( __('Could not find Text Formatter %s.', array('<code>' . $classname . '</code>')) . ' ' . __('If it was provided by an Extension, ensure that it is installed, and enabled.') ); } if (!class_exists($classname)) { require_once $path; } self::$_pool[$handle] = new $classname; } return self::$_pool[$handle]; }
php
public static function create($handle) { if (!isset(self::$_pool[$handle])) { $classname = self::__getClassName($handle); $path = self::__getDriverPath($handle); if (!is_file($path)) { throw new Exception( __('Could not find Text Formatter %s.', array('<code>' . $classname . '</code>')) . ' ' . __('If it was provided by an Extension, ensure that it is installed, and enabled.') ); } if (!class_exists($classname)) { require_once $path; } self::$_pool[$handle] = new $classname; } return self::$_pool[$handle]; }
[ "public", "static", "function", "create", "(", "$", "handle", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "_pool", "[", "$", "handle", "]", ")", ")", "{", "$", "classname", "=", "self", "::", "__getClassName", "(", "$", "handle", ")", ";", "$", "path", "=", "self", "::", "__getDriverPath", "(", "$", "handle", ")", ";", "if", "(", "!", "is_file", "(", "$", "path", ")", ")", "{", "throw", "new", "Exception", "(", "__", "(", "'Could not find Text Formatter %s.'", ",", "array", "(", "'<code>'", ".", "$", "classname", ".", "'</code>'", ")", ")", ".", "' '", ".", "__", "(", "'If it was provided by an Extension, ensure that it is installed, and enabled.'", ")", ")", ";", "}", "if", "(", "!", "class_exists", "(", "$", "classname", ")", ")", "{", "require_once", "$", "path", ";", "}", "self", "::", "$", "_pool", "[", "$", "handle", "]", "=", "new", "$", "classname", ";", "}", "return", "self", "::", "$", "_pool", "[", "$", "handle", "]", ";", "}" ]
Creates an instance of a given class and returns it. Adds the instance to the `$_pool` array with the key being the handle. @param string $handle The handle of the Text Formatter to create @throws Exception @return TextFormatter
[ "Creates", "an", "instance", "of", "a", "given", "class", "and", "returns", "it", ".", "Adds", "the", "instance", "to", "the", "$_pool", "array", "with", "the", "key", "being", "the", "handle", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.textformattermanager.php#L168-L189
symphonycms/symphony-2
symphony/lib/toolkit/class.cryptography.php
Cryptography.compare
public static function compare($input, $hash, $isHash = false) { $version = substr($hash, 0, 8); if ($isHash === true) { return $input == $hash; } elseif ($version == 'PBKDF2v1') { // salted PBKDF2 return PBKDF2::compare($input, $hash); } elseif (strlen($hash) == 40) { // legacy, unsalted SHA1 return SHA1::compare($input, $hash); } elseif (strlen($hash) == 32) { // legacy, unsalted MD5 return MD5::compare($input, $hash); } else { // the hash provided doesn't make any sense return false; } }
php
public static function compare($input, $hash, $isHash = false) { $version = substr($hash, 0, 8); if ($isHash === true) { return $input == $hash; } elseif ($version == 'PBKDF2v1') { // salted PBKDF2 return PBKDF2::compare($input, $hash); } elseif (strlen($hash) == 40) { // legacy, unsalted SHA1 return SHA1::compare($input, $hash); } elseif (strlen($hash) == 32) { // legacy, unsalted MD5 return MD5::compare($input, $hash); } else { // the hash provided doesn't make any sense return false; } }
[ "public", "static", "function", "compare", "(", "$", "input", ",", "$", "hash", ",", "$", "isHash", "=", "false", ")", "{", "$", "version", "=", "substr", "(", "$", "hash", ",", "0", ",", "8", ")", ";", "if", "(", "$", "isHash", "===", "true", ")", "{", "return", "$", "input", "==", "$", "hash", ";", "}", "elseif", "(", "$", "version", "==", "'PBKDF2v1'", ")", "{", "// salted PBKDF2", "return", "PBKDF2", "::", "compare", "(", "$", "input", ",", "$", "hash", ")", ";", "}", "elseif", "(", "strlen", "(", "$", "hash", ")", "==", "40", ")", "{", "// legacy, unsalted SHA1", "return", "SHA1", "::", "compare", "(", "$", "input", ",", "$", "hash", ")", ";", "}", "elseif", "(", "strlen", "(", "$", "hash", ")", "==", "32", ")", "{", "// legacy, unsalted MD5", "return", "MD5", "::", "compare", "(", "$", "input", ",", "$", "hash", ")", ";", "}", "else", "{", "// the hash provided doesn't make any sense", "return", "false", ";", "}", "}" ]
Compares a given hash with a clean text password by figuring out the algorithm that has been used and then calling the appropriate sub-class @see cryptography.MD5#compare() @see cryptography.SHA1#compare() @see cryptography.PBKDF2#compare() @param string $input the cleartext password @param string $hash the hash the password should be checked against @param boolean $isHash @return boolean the result of the comparison
[ "Compares", "a", "given", "hash", "with", "a", "clean", "text", "password", "by", "figuring", "out", "the", "algorithm", "that", "has", "been", "used", "and", "then", "calling", "the", "appropriate", "sub", "-", "class" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.cryptography.php#L53-L68
symphonycms/symphony-2
symphony/lib/toolkit/class.cryptography.php
Cryptography.requiresMigration
public static function requiresMigration($hash) { $version = substr($hash, 0, 8); if ($version == PBKDF2::PREFIX) { // salted PBKDF2, let the responsible class decide return PBKDF2::requiresMigration($hash); } else { // everything else return true; } }
php
public static function requiresMigration($hash) { $version = substr($hash, 0, 8); if ($version == PBKDF2::PREFIX) { // salted PBKDF2, let the responsible class decide return PBKDF2::requiresMigration($hash); } else { // everything else return true; } }
[ "public", "static", "function", "requiresMigration", "(", "$", "hash", ")", "{", "$", "version", "=", "substr", "(", "$", "hash", ",", "0", ",", "8", ")", ";", "if", "(", "$", "version", "==", "PBKDF2", "::", "PREFIX", ")", "{", "// salted PBKDF2, let the responsible class decide", "return", "PBKDF2", "::", "requiresMigration", "(", "$", "hash", ")", ";", "}", "else", "{", "// everything else", "return", "true", ";", "}", "}" ]
Checks if provided hash has been computed by most recent algorithm returns true if otherwise @param string $hash the hash to be checked @return boolean whether the hash should be re-computed
[ "Checks", "if", "provided", "hash", "has", "been", "computed", "by", "most", "recent", "algorithm", "returns", "true", "if", "otherwise" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.cryptography.php#L79-L88
symphonycms/symphony-2
symphony/lib/toolkit/class.cryptography.php
Cryptography.generateSalt
public static function generateSalt($length) { mt_srand(intval(microtime(true)*100000 + memory_get_usage(true))); return substr(sha1(uniqid(mt_rand(), true)), 0, $length); }
php
public static function generateSalt($length) { mt_srand(intval(microtime(true)*100000 + memory_get_usage(true))); return substr(sha1(uniqid(mt_rand(), true)), 0, $length); }
[ "public", "static", "function", "generateSalt", "(", "$", "length", ")", "{", "mt_srand", "(", "intval", "(", "microtime", "(", "true", ")", "*", "100000", "+", "memory_get_usage", "(", "true", ")", ")", ")", ";", "return", "substr", "(", "sha1", "(", "uniqid", "(", "mt_rand", "(", ")", ",", "true", ")", ")", ",", "0", ",", "$", "length", ")", ";", "}" ]
Generates a salt to be used in message digestation. @param integer $length the length of the salt @return string a hexadecimal string
[ "Generates", "a", "salt", "to", "be", "used", "in", "message", "digestation", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.cryptography.php#L98-L102
symphonycms/symphony-2
symphony/lib/core/class.administration.php
Administration.isLoggedIn
public static function isLoggedIn() { if (isset($_REQUEST['auth-token']) && $_REQUEST['auth-token'] && in_array(strlen($_REQUEST['auth-token']), array(6, 8, 16))) { return self::loginFromToken($_REQUEST['auth-token']); } return parent::isLoggedIn(); }
php
public static function isLoggedIn() { if (isset($_REQUEST['auth-token']) && $_REQUEST['auth-token'] && in_array(strlen($_REQUEST['auth-token']), array(6, 8, 16))) { return self::loginFromToken($_REQUEST['auth-token']); } return parent::isLoggedIn(); }
[ "public", "static", "function", "isLoggedIn", "(", ")", "{", "if", "(", "isset", "(", "$", "_REQUEST", "[", "'auth-token'", "]", ")", "&&", "$", "_REQUEST", "[", "'auth-token'", "]", "&&", "in_array", "(", "strlen", "(", "$", "_REQUEST", "[", "'auth-token'", "]", ")", ",", "array", "(", "6", ",", "8", ",", "16", ")", ")", ")", "{", "return", "self", "::", "loginFromToken", "(", "$", "_REQUEST", "[", "'auth-token'", "]", ")", ";", "}", "return", "parent", "::", "isLoggedIn", "(", ")", ";", "}" ]
Overrides the Symphony isLoggedIn function to allow Authors to become logged into the backend when `$_REQUEST['auth-token']` is present. This logs an Author in using the loginFromToken function. A token may be 6 or 8 characters in length in the backend. A 6 or 16 character token is used for forget password requests, whereas the 8 character token is used to login an Author into the page @see core.Symphony#loginFromToken() @return boolean
[ "Overrides", "the", "Symphony", "isLoggedIn", "function", "to", "allow", "Authors", "to", "become", "logged", "into", "the", "backend", "when", "$_REQUEST", "[", "auth", "-", "token", "]", "is", "present", ".", "This", "logs", "an", "Author", "in", "using", "the", "loginFromToken", "function", ".", "A", "token", "may", "be", "6", "or", "8", "characters", "in", "length", "in", "the", "backend", ".", "A", "6", "or", "16", "character", "token", "is", "used", "for", "forget", "password", "requests", "whereas", "the", "8", "character", "token", "is", "used", "to", "login", "an", "Author", "into", "the", "page" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.administration.php#L94-L101
symphonycms/symphony-2
symphony/lib/core/class.administration.php
Administration.__buildPage
private function __buildPage($page) { $is_logged_in = self::isLoggedIn(); if (empty($page) || is_null($page)) { if (!$is_logged_in) { $page = "/login"; } else { // Will redirect an Author to their default area of the Backend // Integers are indicative of section's, text is treated as the path // to the page after `SYMPHONY_URL` $default_area = null; if (is_numeric(Symphony::Author()->get('default_area'))) { $default_section = SectionManager::fetch(Symphony::Author()->get('default_area')); if ($default_section instanceof Section) { $section_handle = $default_section->get('handle'); } if (!$section_handle) { $all_sections = SectionManager::fetch(); if (!empty($all_sections)) { $section_handle = $all_sections[0]->get('handle'); } else { $section_handle = null; } } if (!is_null($section_handle)) { $default_area = "/publish/{$section_handle}/"; } } elseif (!is_null(Symphony::Author()->get('default_area'))) { $default_area = preg_replace('/^' . preg_quote(SYMPHONY_URL, '/') . '/i', '', Symphony::Author()->get('default_area')); } // Fallback: No default area found if (is_null($default_area)) { if (Symphony::Author()->isDeveloper()) { // Redirect to the section index if author is a developer redirect(SYMPHONY_URL . '/blueprints/sections/'); } else { // Redirect to the author page if author is not a developer redirect(SYMPHONY_URL . "/system/authors/edit/".Symphony::Author()->get('id')."/"); } } else { redirect(SYMPHONY_URL . $default_area); } } } if (!$this->_callback = $this->getPageCallback($page)) { if ($page === '/publish/') { $sections = SectionManager::fetch(null, 'ASC', 'sortorder'); $section = current($sections); redirect(SYMPHONY_URL . '/publish/' . $section->get('handle')); } else { $this->errorPageNotFound(); } } include_once($this->_callback['driver_location']); $this->Page = new $this->_callback['classname']; if (!$is_logged_in && $this->_callback['driver'] !== 'login') { if (is_callable(array($this->Page, 'handleFailedAuthorisation'))) { $this->Page->handleFailedAuthorisation(); } else { $this->Page = new contentLogin; // Include the query string for the login, RE: #2324 if ($queryString = $this->Page->__buildQueryString(array('symphony-page', 'mode'), FILTER_SANITIZE_STRING)) { $page .= '?' . $queryString; } $this->Page->build(array('redirect' => $page)); } } else { if (!is_array($this->_callback['context'])) { $this->_callback['context'] = array(); } if ($this->__canAccessAlerts()) { // Can the core be updated? $this->checkCoreForUpdates(); // Do any extensions need updating? $this->checkExtensionsForUpdates(); } $this->Page->build($this->_callback['context']); } return $this->Page; }
php
private function __buildPage($page) { $is_logged_in = self::isLoggedIn(); if (empty($page) || is_null($page)) { if (!$is_logged_in) { $page = "/login"; } else { // Will redirect an Author to their default area of the Backend // Integers are indicative of section's, text is treated as the path // to the page after `SYMPHONY_URL` $default_area = null; if (is_numeric(Symphony::Author()->get('default_area'))) { $default_section = SectionManager::fetch(Symphony::Author()->get('default_area')); if ($default_section instanceof Section) { $section_handle = $default_section->get('handle'); } if (!$section_handle) { $all_sections = SectionManager::fetch(); if (!empty($all_sections)) { $section_handle = $all_sections[0]->get('handle'); } else { $section_handle = null; } } if (!is_null($section_handle)) { $default_area = "/publish/{$section_handle}/"; } } elseif (!is_null(Symphony::Author()->get('default_area'))) { $default_area = preg_replace('/^' . preg_quote(SYMPHONY_URL, '/') . '/i', '', Symphony::Author()->get('default_area')); } // Fallback: No default area found if (is_null($default_area)) { if (Symphony::Author()->isDeveloper()) { // Redirect to the section index if author is a developer redirect(SYMPHONY_URL . '/blueprints/sections/'); } else { // Redirect to the author page if author is not a developer redirect(SYMPHONY_URL . "/system/authors/edit/".Symphony::Author()->get('id')."/"); } } else { redirect(SYMPHONY_URL . $default_area); } } } if (!$this->_callback = $this->getPageCallback($page)) { if ($page === '/publish/') { $sections = SectionManager::fetch(null, 'ASC', 'sortorder'); $section = current($sections); redirect(SYMPHONY_URL . '/publish/' . $section->get('handle')); } else { $this->errorPageNotFound(); } } include_once($this->_callback['driver_location']); $this->Page = new $this->_callback['classname']; if (!$is_logged_in && $this->_callback['driver'] !== 'login') { if (is_callable(array($this->Page, 'handleFailedAuthorisation'))) { $this->Page->handleFailedAuthorisation(); } else { $this->Page = new contentLogin; // Include the query string for the login, RE: #2324 if ($queryString = $this->Page->__buildQueryString(array('symphony-page', 'mode'), FILTER_SANITIZE_STRING)) { $page .= '?' . $queryString; } $this->Page->build(array('redirect' => $page)); } } else { if (!is_array($this->_callback['context'])) { $this->_callback['context'] = array(); } if ($this->__canAccessAlerts()) { // Can the core be updated? $this->checkCoreForUpdates(); // Do any extensions need updating? $this->checkExtensionsForUpdates(); } $this->Page->build($this->_callback['context']); } return $this->Page; }
[ "private", "function", "__buildPage", "(", "$", "page", ")", "{", "$", "is_logged_in", "=", "self", "::", "isLoggedIn", "(", ")", ";", "if", "(", "empty", "(", "$", "page", ")", "||", "is_null", "(", "$", "page", ")", ")", "{", "if", "(", "!", "$", "is_logged_in", ")", "{", "$", "page", "=", "\"/login\"", ";", "}", "else", "{", "// Will redirect an Author to their default area of the Backend", "// Integers are indicative of section's, text is treated as the path", "// to the page after `SYMPHONY_URL`", "$", "default_area", "=", "null", ";", "if", "(", "is_numeric", "(", "Symphony", "::", "Author", "(", ")", "->", "get", "(", "'default_area'", ")", ")", ")", "{", "$", "default_section", "=", "SectionManager", "::", "fetch", "(", "Symphony", "::", "Author", "(", ")", "->", "get", "(", "'default_area'", ")", ")", ";", "if", "(", "$", "default_section", "instanceof", "Section", ")", "{", "$", "section_handle", "=", "$", "default_section", "->", "get", "(", "'handle'", ")", ";", "}", "if", "(", "!", "$", "section_handle", ")", "{", "$", "all_sections", "=", "SectionManager", "::", "fetch", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "all_sections", ")", ")", "{", "$", "section_handle", "=", "$", "all_sections", "[", "0", "]", "->", "get", "(", "'handle'", ")", ";", "}", "else", "{", "$", "section_handle", "=", "null", ";", "}", "}", "if", "(", "!", "is_null", "(", "$", "section_handle", ")", ")", "{", "$", "default_area", "=", "\"/publish/{$section_handle}/\"", ";", "}", "}", "elseif", "(", "!", "is_null", "(", "Symphony", "::", "Author", "(", ")", "->", "get", "(", "'default_area'", ")", ")", ")", "{", "$", "default_area", "=", "preg_replace", "(", "'/^'", ".", "preg_quote", "(", "SYMPHONY_URL", ",", "'/'", ")", ".", "'/i'", ",", "''", ",", "Symphony", "::", "Author", "(", ")", "->", "get", "(", "'default_area'", ")", ")", ";", "}", "// Fallback: No default area found", "if", "(", "is_null", "(", "$", "default_area", ")", ")", "{", "if", "(", "Symphony", "::", "Author", "(", ")", "->", "isDeveloper", "(", ")", ")", "{", "// Redirect to the section index if author is a developer", "redirect", "(", "SYMPHONY_URL", ".", "'/blueprints/sections/'", ")", ";", "}", "else", "{", "// Redirect to the author page if author is not a developer", "redirect", "(", "SYMPHONY_URL", ".", "\"/system/authors/edit/\"", ".", "Symphony", "::", "Author", "(", ")", "->", "get", "(", "'id'", ")", ".", "\"/\"", ")", ";", "}", "}", "else", "{", "redirect", "(", "SYMPHONY_URL", ".", "$", "default_area", ")", ";", "}", "}", "}", "if", "(", "!", "$", "this", "->", "_callback", "=", "$", "this", "->", "getPageCallback", "(", "$", "page", ")", ")", "{", "if", "(", "$", "page", "===", "'/publish/'", ")", "{", "$", "sections", "=", "SectionManager", "::", "fetch", "(", "null", ",", "'ASC'", ",", "'sortorder'", ")", ";", "$", "section", "=", "current", "(", "$", "sections", ")", ";", "redirect", "(", "SYMPHONY_URL", ".", "'/publish/'", ".", "$", "section", "->", "get", "(", "'handle'", ")", ")", ";", "}", "else", "{", "$", "this", "->", "errorPageNotFound", "(", ")", ";", "}", "}", "include_once", "(", "$", "this", "->", "_callback", "[", "'driver_location'", "]", ")", ";", "$", "this", "->", "Page", "=", "new", "$", "this", "->", "_callback", "[", "'classname'", "]", ";", "if", "(", "!", "$", "is_logged_in", "&&", "$", "this", "->", "_callback", "[", "'driver'", "]", "!==", "'login'", ")", "{", "if", "(", "is_callable", "(", "array", "(", "$", "this", "->", "Page", ",", "'handleFailedAuthorisation'", ")", ")", ")", "{", "$", "this", "->", "Page", "->", "handleFailedAuthorisation", "(", ")", ";", "}", "else", "{", "$", "this", "->", "Page", "=", "new", "contentLogin", ";", "// Include the query string for the login, RE: #2324", "if", "(", "$", "queryString", "=", "$", "this", "->", "Page", "->", "__buildQueryString", "(", "array", "(", "'symphony-page'", ",", "'mode'", ")", ",", "FILTER_SANITIZE_STRING", ")", ")", "{", "$", "page", ".=", "'?'", ".", "$", "queryString", ";", "}", "$", "this", "->", "Page", "->", "build", "(", "array", "(", "'redirect'", "=>", "$", "page", ")", ")", ";", "}", "}", "else", "{", "if", "(", "!", "is_array", "(", "$", "this", "->", "_callback", "[", "'context'", "]", ")", ")", "{", "$", "this", "->", "_callback", "[", "'context'", "]", "=", "array", "(", ")", ";", "}", "if", "(", "$", "this", "->", "__canAccessAlerts", "(", ")", ")", "{", "// Can the core be updated?", "$", "this", "->", "checkCoreForUpdates", "(", ")", ";", "// Do any extensions need updating?", "$", "this", "->", "checkExtensionsForUpdates", "(", ")", ";", "}", "$", "this", "->", "Page", "->", "build", "(", "$", "this", "->", "_callback", "[", "'context'", "]", ")", ";", "}", "return", "$", "this", "->", "Page", ";", "}" ]
Given the URL path of a Symphony backend page, this function will attempt to resolve the URL to a Symphony content page in the backend or a page provided by an extension. This function checks to ensure a user is logged in, otherwise it will direct them to the login page @param string $page The URL path after the root of the Symphony installation, including a starting slash, such as '/login/' @throws SymphonyErrorPage @throws Exception @return HTMLPage
[ "Given", "the", "URL", "path", "of", "a", "Symphony", "backend", "page", "this", "function", "will", "attempt", "to", "resolve", "the", "URL", "to", "a", "Symphony", "content", "page", "in", "the", "backend", "or", "a", "page", "provided", "by", "an", "extension", ".", "This", "function", "checks", "to", "ensure", "a", "user", "is", "logged", "in", "otherwise", "it", "will", "direct", "them", "to", "the", "login", "page" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.administration.php#L116-L209
symphonycms/symphony-2
symphony/lib/core/class.administration.php
Administration.checkCoreForUpdates
public function checkCoreForUpdates() { // Is there even an install directory to check? if ($this->isInstallerAvailable() === false) { return false; } try { // The updater contains a version higher than the current Symphony version. if ($this->isUpgradeAvailable()) { $message = __('An update has been found in your installation to upgrade Symphony to %s.', array($this->getMigrationVersion())) . ' <a href="' . URL . '/install/">' . __('View update.') . '</a>'; // The updater contains a version lower than the current Symphony version. // The updater is the same version as the current Symphony install. } else { $message = __('Your Symphony installation is up to date, but the installer was still detected. For security reasons, it should be removed.') . ' <a href="' . URL . '/install/?action=remove">' . __('Remove installer?') . '</a>'; } // Can't detect update Symphony version } catch (Exception $e) { $message = __('An update script has been found in your installation.') . ' <a href="' . URL . '/install/">' . __('View update.') . '</a>'; } $this->Page->pageAlert($message, Alert::NOTICE); return true; }
php
public function checkCoreForUpdates() { // Is there even an install directory to check? if ($this->isInstallerAvailable() === false) { return false; } try { // The updater contains a version higher than the current Symphony version. if ($this->isUpgradeAvailable()) { $message = __('An update has been found in your installation to upgrade Symphony to %s.', array($this->getMigrationVersion())) . ' <a href="' . URL . '/install/">' . __('View update.') . '</a>'; // The updater contains a version lower than the current Symphony version. // The updater is the same version as the current Symphony install. } else { $message = __('Your Symphony installation is up to date, but the installer was still detected. For security reasons, it should be removed.') . ' <a href="' . URL . '/install/?action=remove">' . __('Remove installer?') . '</a>'; } // Can't detect update Symphony version } catch (Exception $e) { $message = __('An update script has been found in your installation.') . ' <a href="' . URL . '/install/">' . __('View update.') . '</a>'; } $this->Page->pageAlert($message, Alert::NOTICE); return true; }
[ "public", "function", "checkCoreForUpdates", "(", ")", "{", "// Is there even an install directory to check?", "if", "(", "$", "this", "->", "isInstallerAvailable", "(", ")", "===", "false", ")", "{", "return", "false", ";", "}", "try", "{", "// The updater contains a version higher than the current Symphony version.", "if", "(", "$", "this", "->", "isUpgradeAvailable", "(", ")", ")", "{", "$", "message", "=", "__", "(", "'An update has been found in your installation to upgrade Symphony to %s.'", ",", "array", "(", "$", "this", "->", "getMigrationVersion", "(", ")", ")", ")", ".", "' <a href=\"'", ".", "URL", ".", "'/install/\">'", ".", "__", "(", "'View update.'", ")", ".", "'</a>'", ";", "// The updater contains a version lower than the current Symphony version.", "// The updater is the same version as the current Symphony install.", "}", "else", "{", "$", "message", "=", "__", "(", "'Your Symphony installation is up to date, but the installer was still detected. For security reasons, it should be removed.'", ")", ".", "' <a href=\"'", ".", "URL", ".", "'/install/?action=remove\">'", ".", "__", "(", "'Remove installer?'", ")", ".", "'</a>'", ";", "}", "// Can't detect update Symphony version", "}", "catch", "(", "Exception", "$", "e", ")", "{", "$", "message", "=", "__", "(", "'An update script has been found in your installation.'", ")", ".", "' <a href=\"'", ".", "URL", ".", "'/install/\">'", ".", "__", "(", "'View update.'", ")", ".", "'</a>'", ";", "}", "$", "this", "->", "Page", "->", "pageAlert", "(", "$", "message", ",", "Alert", "::", "NOTICE", ")", ";", "return", "true", ";", "}" ]
Scan the install directory to look for new migrations that can be applied to update this version of Symphony. If one if found, a new Alert is added to the page. @since Symphony 2.5.2 @return boolean Returns true if there is an update available, false otherwise.
[ "Scan", "the", "install", "directory", "to", "look", "for", "new", "migrations", "that", "can", "be", "applied", "to", "update", "this", "version", "of", "Symphony", ".", "If", "one", "if", "found", "a", "new", "Alert", "is", "added", "to", "the", "page", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.administration.php#L220-L246
symphonycms/symphony-2
symphony/lib/core/class.administration.php
Administration.checkExtensionsForUpdates
public function checkExtensionsForUpdates() { $extensions = Symphony::ExtensionManager()->listInstalledHandles(); if (is_array($extensions) && !empty($extensions)) { foreach ($extensions as $name) { $about = Symphony::ExtensionManager()->about($name); if (array_key_exists('status', $about) && in_array(EXTENSION_REQUIRES_UPDATE, $about['status'])) { $this->Page->pageAlert( __('An extension requires updating.') . ' <a href="' . SYMPHONY_URL . '/system/extensions/">' . __('View extensions') . '</a>' ); break; } } } }
php
public function checkExtensionsForUpdates() { $extensions = Symphony::ExtensionManager()->listInstalledHandles(); if (is_array($extensions) && !empty($extensions)) { foreach ($extensions as $name) { $about = Symphony::ExtensionManager()->about($name); if (array_key_exists('status', $about) && in_array(EXTENSION_REQUIRES_UPDATE, $about['status'])) { $this->Page->pageAlert( __('An extension requires updating.') . ' <a href="' . SYMPHONY_URL . '/system/extensions/">' . __('View extensions') . '</a>' ); break; } } } }
[ "public", "function", "checkExtensionsForUpdates", "(", ")", "{", "$", "extensions", "=", "Symphony", "::", "ExtensionManager", "(", ")", "->", "listInstalledHandles", "(", ")", ";", "if", "(", "is_array", "(", "$", "extensions", ")", "&&", "!", "empty", "(", "$", "extensions", ")", ")", "{", "foreach", "(", "$", "extensions", "as", "$", "name", ")", "{", "$", "about", "=", "Symphony", "::", "ExtensionManager", "(", ")", "->", "about", "(", "$", "name", ")", ";", "if", "(", "array_key_exists", "(", "'status'", ",", "$", "about", ")", "&&", "in_array", "(", "EXTENSION_REQUIRES_UPDATE", ",", "$", "about", "[", "'status'", "]", ")", ")", "{", "$", "this", "->", "Page", "->", "pageAlert", "(", "__", "(", "'An extension requires updating.'", ")", ".", "' <a href=\"'", ".", "SYMPHONY_URL", ".", "'/system/extensions/\">'", ".", "__", "(", "'View extensions'", ")", ".", "'</a>'", ")", ";", "break", ";", "}", "}", "}", "}" ]
Checks all installed extensions to see any have an outstanding update. If any do an Alert will be added to the current page directing the Author to the Extension page @since Symphony 2.5.2
[ "Checks", "all", "installed", "extensions", "to", "see", "any", "have", "an", "outstanding", "update", ".", "If", "any", "do", "an", "Alert", "will", "be", "added", "to", "the", "current", "page", "directing", "the", "Author", "to", "the", "Extension", "page" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.administration.php#L254-L270
symphonycms/symphony-2
symphony/lib/core/class.administration.php
Administration.__canAccessAlerts
private function __canAccessAlerts() { if ($this->Page instanceof AdministrationPage && self::isLoggedIn() && Symphony::Author()->isDeveloper()) { return true; } return false; }
php
private function __canAccessAlerts() { if ($this->Page instanceof AdministrationPage && self::isLoggedIn() && Symphony::Author()->isDeveloper()) { return true; } return false; }
[ "private", "function", "__canAccessAlerts", "(", ")", "{", "if", "(", "$", "this", "->", "Page", "instanceof", "AdministrationPage", "&&", "self", "::", "isLoggedIn", "(", ")", "&&", "Symphony", "::", "Author", "(", ")", "->", "isDeveloper", "(", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
This function determines whether an administrative alert can be displayed on the current page. It ensures that the page exists, and the user is logged in and a developer @since Symphony 2.2 @return boolean
[ "This", "function", "determines", "whether", "an", "administrative", "alert", "can", "be", "displayed", "on", "the", "current", "page", ".", "It", "ensures", "that", "the", "page", "exists", "and", "the", "user", "is", "logged", "in", "and", "a", "developer" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.administration.php#L280-L287
symphonycms/symphony-2
symphony/lib/core/class.administration.php
Administration.getPageCallback
public function getPageCallback($page = null) { if (!$page && $this->_callback) { return $this->_callback; } elseif (!$page && !$this->_callback) { trigger_error(__('Cannot request a page callback without first specifying the page.')); } $this->_currentPage = SYMPHONY_URL . preg_replace('/\/{2,}/', '/', $page); $bits = preg_split('/\//', trim($page, '/'), 3, PREG_SPLIT_NO_EMPTY); $callback = array( 'driver' => null, 'driver_location' => null, 'context' => null, 'classname' => null, 'pageroot' => null ); // Login page, /symphony/login/ if ($bits[0] == 'login') { if (isset($bits[1], $bits[2])) { $context = preg_split('/\//', $bits[1] . '/' . $bits[2], -1, PREG_SPLIT_NO_EMPTY); } elseif (isset($bits[1])) { $context = preg_split('/\//', $bits[1], -1, PREG_SPLIT_NO_EMPTY); } else { $context = array(); } $callback = array( 'driver' => 'login', 'driver_location' => CONTENT . '/content.login.php', 'context' => $context, 'classname' => 'contentLogin', 'pageroot' => '/login/' ); // Extension page, /symphony/extension/{extension_name}/ } elseif ($bits[0] == 'extension' && isset($bits[1])) { $extension_name = $bits[1]; $bits = preg_split('/\//', trim($bits[2], '/'), 2, PREG_SPLIT_NO_EMPTY); $callback['driver'] = 'index'; $callback['classname'] = 'contentExtension' . ucfirst($extension_name) . 'Index'; $callback['pageroot'] = '/extension/' . $extension_name. '/'; if (isset($bits[0])) { $callback['driver'] = $bits[0]; $callback['classname'] = 'contentExtension' . ucfirst($extension_name) . ucfirst($bits[0]); $callback['pageroot'] .= $bits[0] . '/'; } if (isset($bits[1])) { $callback['context'] = preg_split('/\//', $bits[1], -1, PREG_SPLIT_NO_EMPTY); } $callback['driver_location'] = EXTENSIONS . '/' . $extension_name . '/content/content.' . $callback['driver'] . '.php'; // Publish page, /symphony/publish/{section_handle}/ } elseif ($bits[0] == 'publish') { if (!isset($bits[1])) { return false; } $callback = array( 'driver' => 'publish', 'driver_location' => $callback['driver_location'] = CONTENT . '/content.publish.php', 'context' => array( 'section_handle' => $bits[1], 'page' => null, 'entry_id' => null, 'flag' => null ), 'pageroot' => '/' . $bits[0] . '/' . $bits[1] . '/', 'classname' => 'contentPublish' ); if (isset($bits[2])) { $extras = preg_split('/\//', $bits[2], -1, PREG_SPLIT_NO_EMPTY); $callback['context']['page'] = $extras[0]; if (isset($extras[1])) { $callback['context']['entry_id'] = intval($extras[1]); } if (isset($extras[2])) { $callback['context']['flag'] = $extras[2]; } } else { $callback['context']['page'] = 'index'; } // Everything else } else { $callback['driver'] = ucfirst($bits[0]); $callback['pageroot'] = '/' . $bits[0] . '/'; if (isset($bits[1])) { $callback['driver'] = $callback['driver'] . ucfirst($bits[1]); $callback['pageroot'] .= $bits[1] . '/'; } if (isset($bits[2])) { $callback['context'] = preg_split('/\//', $bits[2], -1, PREG_SPLIT_NO_EMPTY); } $callback['classname'] = 'content' . $callback['driver']; $callback['driver'] = strtolower($callback['driver']); $callback['driver_location'] = CONTENT . '/content.' . $callback['driver'] . '.php'; } /** * Immediately after determining which class will resolve the current page, this * delegate allows extension to modify the routing or provide additional information. * * @since Symphony 2.3.1 * @delegate AdminPagePostCallback * @param string $context * '/backend/' * @param string $page * The current URL string, after the SYMPHONY_URL constant (which is `/symphony/` * at the moment. * @param array $parts * An array representation of `$page` * @param array $callback * An associative array that contains `driver`, `pageroot`, `classname` and * `context` keys. The `driver_location` is the path to the class to render this * page, `driver` should be the view to render, the `classname` the name of the * class, `pageroot` the rootpage, before any extra URL params and `context` can * provide additional information about the page */ Symphony::ExtensionManager()->notifyMembers('AdminPagePostCallback', '/backend/', array( 'page' => $this->_currentPage, 'parts' => $bits, 'callback' => &$callback )); if (isset($callback['driver_location']) && !is_file($callback['driver_location'])) { return false; } return $callback; }
php
public function getPageCallback($page = null) { if (!$page && $this->_callback) { return $this->_callback; } elseif (!$page && !$this->_callback) { trigger_error(__('Cannot request a page callback without first specifying the page.')); } $this->_currentPage = SYMPHONY_URL . preg_replace('/\/{2,}/', '/', $page); $bits = preg_split('/\//', trim($page, '/'), 3, PREG_SPLIT_NO_EMPTY); $callback = array( 'driver' => null, 'driver_location' => null, 'context' => null, 'classname' => null, 'pageroot' => null ); // Login page, /symphony/login/ if ($bits[0] == 'login') { if (isset($bits[1], $bits[2])) { $context = preg_split('/\//', $bits[1] . '/' . $bits[2], -1, PREG_SPLIT_NO_EMPTY); } elseif (isset($bits[1])) { $context = preg_split('/\//', $bits[1], -1, PREG_SPLIT_NO_EMPTY); } else { $context = array(); } $callback = array( 'driver' => 'login', 'driver_location' => CONTENT . '/content.login.php', 'context' => $context, 'classname' => 'contentLogin', 'pageroot' => '/login/' ); // Extension page, /symphony/extension/{extension_name}/ } elseif ($bits[0] == 'extension' && isset($bits[1])) { $extension_name = $bits[1]; $bits = preg_split('/\//', trim($bits[2], '/'), 2, PREG_SPLIT_NO_EMPTY); $callback['driver'] = 'index'; $callback['classname'] = 'contentExtension' . ucfirst($extension_name) . 'Index'; $callback['pageroot'] = '/extension/' . $extension_name. '/'; if (isset($bits[0])) { $callback['driver'] = $bits[0]; $callback['classname'] = 'contentExtension' . ucfirst($extension_name) . ucfirst($bits[0]); $callback['pageroot'] .= $bits[0] . '/'; } if (isset($bits[1])) { $callback['context'] = preg_split('/\//', $bits[1], -1, PREG_SPLIT_NO_EMPTY); } $callback['driver_location'] = EXTENSIONS . '/' . $extension_name . '/content/content.' . $callback['driver'] . '.php'; // Publish page, /symphony/publish/{section_handle}/ } elseif ($bits[0] == 'publish') { if (!isset($bits[1])) { return false; } $callback = array( 'driver' => 'publish', 'driver_location' => $callback['driver_location'] = CONTENT . '/content.publish.php', 'context' => array( 'section_handle' => $bits[1], 'page' => null, 'entry_id' => null, 'flag' => null ), 'pageroot' => '/' . $bits[0] . '/' . $bits[1] . '/', 'classname' => 'contentPublish' ); if (isset($bits[2])) { $extras = preg_split('/\//', $bits[2], -1, PREG_SPLIT_NO_EMPTY); $callback['context']['page'] = $extras[0]; if (isset($extras[1])) { $callback['context']['entry_id'] = intval($extras[1]); } if (isset($extras[2])) { $callback['context']['flag'] = $extras[2]; } } else { $callback['context']['page'] = 'index'; } // Everything else } else { $callback['driver'] = ucfirst($bits[0]); $callback['pageroot'] = '/' . $bits[0] . '/'; if (isset($bits[1])) { $callback['driver'] = $callback['driver'] . ucfirst($bits[1]); $callback['pageroot'] .= $bits[1] . '/'; } if (isset($bits[2])) { $callback['context'] = preg_split('/\//', $bits[2], -1, PREG_SPLIT_NO_EMPTY); } $callback['classname'] = 'content' . $callback['driver']; $callback['driver'] = strtolower($callback['driver']); $callback['driver_location'] = CONTENT . '/content.' . $callback['driver'] . '.php'; } /** * Immediately after determining which class will resolve the current page, this * delegate allows extension to modify the routing or provide additional information. * * @since Symphony 2.3.1 * @delegate AdminPagePostCallback * @param string $context * '/backend/' * @param string $page * The current URL string, after the SYMPHONY_URL constant (which is `/symphony/` * at the moment. * @param array $parts * An array representation of `$page` * @param array $callback * An associative array that contains `driver`, `pageroot`, `classname` and * `context` keys. The `driver_location` is the path to the class to render this * page, `driver` should be the view to render, the `classname` the name of the * class, `pageroot` the rootpage, before any extra URL params and `context` can * provide additional information about the page */ Symphony::ExtensionManager()->notifyMembers('AdminPagePostCallback', '/backend/', array( 'page' => $this->_currentPage, 'parts' => $bits, 'callback' => &$callback )); if (isset($callback['driver_location']) && !is_file($callback['driver_location'])) { return false; } return $callback; }
[ "public", "function", "getPageCallback", "(", "$", "page", "=", "null", ")", "{", "if", "(", "!", "$", "page", "&&", "$", "this", "->", "_callback", ")", "{", "return", "$", "this", "->", "_callback", ";", "}", "elseif", "(", "!", "$", "page", "&&", "!", "$", "this", "->", "_callback", ")", "{", "trigger_error", "(", "__", "(", "'Cannot request a page callback without first specifying the page.'", ")", ")", ";", "}", "$", "this", "->", "_currentPage", "=", "SYMPHONY_URL", ".", "preg_replace", "(", "'/\\/{2,}/'", ",", "'/'", ",", "$", "page", ")", ";", "$", "bits", "=", "preg_split", "(", "'/\\//'", ",", "trim", "(", "$", "page", ",", "'/'", ")", ",", "3", ",", "PREG_SPLIT_NO_EMPTY", ")", ";", "$", "callback", "=", "array", "(", "'driver'", "=>", "null", ",", "'driver_location'", "=>", "null", ",", "'context'", "=>", "null", ",", "'classname'", "=>", "null", ",", "'pageroot'", "=>", "null", ")", ";", "// Login page, /symphony/login/", "if", "(", "$", "bits", "[", "0", "]", "==", "'login'", ")", "{", "if", "(", "isset", "(", "$", "bits", "[", "1", "]", ",", "$", "bits", "[", "2", "]", ")", ")", "{", "$", "context", "=", "preg_split", "(", "'/\\//'", ",", "$", "bits", "[", "1", "]", ".", "'/'", ".", "$", "bits", "[", "2", "]", ",", "-", "1", ",", "PREG_SPLIT_NO_EMPTY", ")", ";", "}", "elseif", "(", "isset", "(", "$", "bits", "[", "1", "]", ")", ")", "{", "$", "context", "=", "preg_split", "(", "'/\\//'", ",", "$", "bits", "[", "1", "]", ",", "-", "1", ",", "PREG_SPLIT_NO_EMPTY", ")", ";", "}", "else", "{", "$", "context", "=", "array", "(", ")", ";", "}", "$", "callback", "=", "array", "(", "'driver'", "=>", "'login'", ",", "'driver_location'", "=>", "CONTENT", ".", "'/content.login.php'", ",", "'context'", "=>", "$", "context", ",", "'classname'", "=>", "'contentLogin'", ",", "'pageroot'", "=>", "'/login/'", ")", ";", "// Extension page, /symphony/extension/{extension_name}/", "}", "elseif", "(", "$", "bits", "[", "0", "]", "==", "'extension'", "&&", "isset", "(", "$", "bits", "[", "1", "]", ")", ")", "{", "$", "extension_name", "=", "$", "bits", "[", "1", "]", ";", "$", "bits", "=", "preg_split", "(", "'/\\//'", ",", "trim", "(", "$", "bits", "[", "2", "]", ",", "'/'", ")", ",", "2", ",", "PREG_SPLIT_NO_EMPTY", ")", ";", "$", "callback", "[", "'driver'", "]", "=", "'index'", ";", "$", "callback", "[", "'classname'", "]", "=", "'contentExtension'", ".", "ucfirst", "(", "$", "extension_name", ")", ".", "'Index'", ";", "$", "callback", "[", "'pageroot'", "]", "=", "'/extension/'", ".", "$", "extension_name", ".", "'/'", ";", "if", "(", "isset", "(", "$", "bits", "[", "0", "]", ")", ")", "{", "$", "callback", "[", "'driver'", "]", "=", "$", "bits", "[", "0", "]", ";", "$", "callback", "[", "'classname'", "]", "=", "'contentExtension'", ".", "ucfirst", "(", "$", "extension_name", ")", ".", "ucfirst", "(", "$", "bits", "[", "0", "]", ")", ";", "$", "callback", "[", "'pageroot'", "]", ".=", "$", "bits", "[", "0", "]", ".", "'/'", ";", "}", "if", "(", "isset", "(", "$", "bits", "[", "1", "]", ")", ")", "{", "$", "callback", "[", "'context'", "]", "=", "preg_split", "(", "'/\\//'", ",", "$", "bits", "[", "1", "]", ",", "-", "1", ",", "PREG_SPLIT_NO_EMPTY", ")", ";", "}", "$", "callback", "[", "'driver_location'", "]", "=", "EXTENSIONS", ".", "'/'", ".", "$", "extension_name", ".", "'/content/content.'", ".", "$", "callback", "[", "'driver'", "]", ".", "'.php'", ";", "// Publish page, /symphony/publish/{section_handle}/", "}", "elseif", "(", "$", "bits", "[", "0", "]", "==", "'publish'", ")", "{", "if", "(", "!", "isset", "(", "$", "bits", "[", "1", "]", ")", ")", "{", "return", "false", ";", "}", "$", "callback", "=", "array", "(", "'driver'", "=>", "'publish'", ",", "'driver_location'", "=>", "$", "callback", "[", "'driver_location'", "]", "=", "CONTENT", ".", "'/content.publish.php'", ",", "'context'", "=>", "array", "(", "'section_handle'", "=>", "$", "bits", "[", "1", "]", ",", "'page'", "=>", "null", ",", "'entry_id'", "=>", "null", ",", "'flag'", "=>", "null", ")", ",", "'pageroot'", "=>", "'/'", ".", "$", "bits", "[", "0", "]", ".", "'/'", ".", "$", "bits", "[", "1", "]", ".", "'/'", ",", "'classname'", "=>", "'contentPublish'", ")", ";", "if", "(", "isset", "(", "$", "bits", "[", "2", "]", ")", ")", "{", "$", "extras", "=", "preg_split", "(", "'/\\//'", ",", "$", "bits", "[", "2", "]", ",", "-", "1", ",", "PREG_SPLIT_NO_EMPTY", ")", ";", "$", "callback", "[", "'context'", "]", "[", "'page'", "]", "=", "$", "extras", "[", "0", "]", ";", "if", "(", "isset", "(", "$", "extras", "[", "1", "]", ")", ")", "{", "$", "callback", "[", "'context'", "]", "[", "'entry_id'", "]", "=", "intval", "(", "$", "extras", "[", "1", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "extras", "[", "2", "]", ")", ")", "{", "$", "callback", "[", "'context'", "]", "[", "'flag'", "]", "=", "$", "extras", "[", "2", "]", ";", "}", "}", "else", "{", "$", "callback", "[", "'context'", "]", "[", "'page'", "]", "=", "'index'", ";", "}", "// Everything else", "}", "else", "{", "$", "callback", "[", "'driver'", "]", "=", "ucfirst", "(", "$", "bits", "[", "0", "]", ")", ";", "$", "callback", "[", "'pageroot'", "]", "=", "'/'", ".", "$", "bits", "[", "0", "]", ".", "'/'", ";", "if", "(", "isset", "(", "$", "bits", "[", "1", "]", ")", ")", "{", "$", "callback", "[", "'driver'", "]", "=", "$", "callback", "[", "'driver'", "]", ".", "ucfirst", "(", "$", "bits", "[", "1", "]", ")", ";", "$", "callback", "[", "'pageroot'", "]", ".=", "$", "bits", "[", "1", "]", ".", "'/'", ";", "}", "if", "(", "isset", "(", "$", "bits", "[", "2", "]", ")", ")", "{", "$", "callback", "[", "'context'", "]", "=", "preg_split", "(", "'/\\//'", ",", "$", "bits", "[", "2", "]", ",", "-", "1", ",", "PREG_SPLIT_NO_EMPTY", ")", ";", "}", "$", "callback", "[", "'classname'", "]", "=", "'content'", ".", "$", "callback", "[", "'driver'", "]", ";", "$", "callback", "[", "'driver'", "]", "=", "strtolower", "(", "$", "callback", "[", "'driver'", "]", ")", ";", "$", "callback", "[", "'driver_location'", "]", "=", "CONTENT", ".", "'/content.'", ".", "$", "callback", "[", "'driver'", "]", ".", "'.php'", ";", "}", "/**\n * Immediately after determining which class will resolve the current page, this\n * delegate allows extension to modify the routing or provide additional information.\n *\n * @since Symphony 2.3.1\n * @delegate AdminPagePostCallback\n * @param string $context\n * '/backend/'\n * @param string $page\n * The current URL string, after the SYMPHONY_URL constant (which is `/symphony/`\n * at the moment.\n * @param array $parts\n * An array representation of `$page`\n * @param array $callback\n * An associative array that contains `driver`, `pageroot`, `classname` and\n * `context` keys. The `driver_location` is the path to the class to render this\n * page, `driver` should be the view to render, the `classname` the name of the\n * class, `pageroot` the rootpage, before any extra URL params and `context` can\n * provide additional information about the page\n */", "Symphony", "::", "ExtensionManager", "(", ")", "->", "notifyMembers", "(", "'AdminPagePostCallback'", ",", "'/backend/'", ",", "array", "(", "'page'", "=>", "$", "this", "->", "_currentPage", ",", "'parts'", "=>", "$", "bits", ",", "'callback'", "=>", "&", "$", "callback", ")", ")", ";", "if", "(", "isset", "(", "$", "callback", "[", "'driver_location'", "]", ")", "&&", "!", "is_file", "(", "$", "callback", "[", "'driver_location'", "]", ")", ")", "{", "return", "false", ";", "}", "return", "$", "callback", ";", "}" ]
This function resolves the string of the page to the relevant backend page class. The path to the backend page is split on the slashes and the resulting pieces used to determine if the page is provided by an extension, is a section (index or entry creation) or finally a standard Symphony content page. If no page driver can be found, this function will return false. @uses AdminPagePostCallback @param string $page The full path (including the domain) of the Symphony backend page @return array|boolean If successful, this function will return an associative array that at the very least will return the page's classname, pageroot, driver, driver_location and context, otherwise this will return false.
[ "This", "function", "resolves", "the", "string", "of", "the", "page", "to", "the", "relevant", "backend", "page", "class", ".", "The", "path", "to", "the", "backend", "page", "is", "split", "on", "the", "slashes", "and", "the", "resulting", "pieces", "used", "to", "determine", "if", "the", "page", "is", "provided", "by", "an", "extension", "is", "a", "section", "(", "index", "or", "entry", "creation", ")", "or", "finally", "a", "standard", "Symphony", "content", "page", ".", "If", "no", "page", "driver", "can", "be", "found", "this", "function", "will", "return", "false", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.administration.php#L305-L446
symphonycms/symphony-2
symphony/lib/core/class.administration.php
Administration.display
public function display($page) { Symphony::Profiler()->sample('Page build process started'); /** * Immediately before building the admin page. Provided with the page parameter * @delegate AdminPagePreBuild * @since Symphony 2.6.0 * @param string $context * '/backend/' * @param string $page * The result of getCurrentPage, which returns the $_GET['symphony-page'] * variable. */ Symphony::ExtensionManager()->notifyMembers('AdminPagePreBuild', '/backend/', array('page' => $page)); $this->__buildPage($page); // Add XSRF token to form's in the backend if (self::isXSRFEnabled() && isset($this->Page->Form)) { $this->Page->Form->prependChild(XSRF::formToken()); } /** * Immediately before generating the admin page. Provided with the page object * @delegate AdminPagePreGenerate * @param string $context * '/backend/' * @param HTMLPage $oPage * An instance of the current page to be rendered, this will usually be a class that * extends HTMLPage. The Symphony backend uses a convention of contentPageName * as the class that extends the HTMLPage */ Symphony::ExtensionManager()->notifyMembers('AdminPagePreGenerate', '/backend/', array('oPage' => &$this->Page)); $output = $this->Page->generate(); /** * Immediately after generating the admin page. Provided with string containing page source * @delegate AdminPagePostGenerate * @param string $context * '/backend/' * @param string $output * The resulting backend page HTML as a string, passed by reference */ Symphony::ExtensionManager()->notifyMembers('AdminPagePostGenerate', '/backend/', array('output' => &$output)); Symphony::Profiler()->sample('Page built'); return $output; }
php
public function display($page) { Symphony::Profiler()->sample('Page build process started'); /** * Immediately before building the admin page. Provided with the page parameter * @delegate AdminPagePreBuild * @since Symphony 2.6.0 * @param string $context * '/backend/' * @param string $page * The result of getCurrentPage, which returns the $_GET['symphony-page'] * variable. */ Symphony::ExtensionManager()->notifyMembers('AdminPagePreBuild', '/backend/', array('page' => $page)); $this->__buildPage($page); // Add XSRF token to form's in the backend if (self::isXSRFEnabled() && isset($this->Page->Form)) { $this->Page->Form->prependChild(XSRF::formToken()); } /** * Immediately before generating the admin page. Provided with the page object * @delegate AdminPagePreGenerate * @param string $context * '/backend/' * @param HTMLPage $oPage * An instance of the current page to be rendered, this will usually be a class that * extends HTMLPage. The Symphony backend uses a convention of contentPageName * as the class that extends the HTMLPage */ Symphony::ExtensionManager()->notifyMembers('AdminPagePreGenerate', '/backend/', array('oPage' => &$this->Page)); $output = $this->Page->generate(); /** * Immediately after generating the admin page. Provided with string containing page source * @delegate AdminPagePostGenerate * @param string $context * '/backend/' * @param string $output * The resulting backend page HTML as a string, passed by reference */ Symphony::ExtensionManager()->notifyMembers('AdminPagePostGenerate', '/backend/', array('output' => &$output)); Symphony::Profiler()->sample('Page built'); return $output; }
[ "public", "function", "display", "(", "$", "page", ")", "{", "Symphony", "::", "Profiler", "(", ")", "->", "sample", "(", "'Page build process started'", ")", ";", "/**\n * Immediately before building the admin page. Provided with the page parameter\n * @delegate AdminPagePreBuild\n * @since Symphony 2.6.0\n * @param string $context\n * '/backend/'\n * @param string $page\n * The result of getCurrentPage, which returns the $_GET['symphony-page']\n * variable.\n */", "Symphony", "::", "ExtensionManager", "(", ")", "->", "notifyMembers", "(", "'AdminPagePreBuild'", ",", "'/backend/'", ",", "array", "(", "'page'", "=>", "$", "page", ")", ")", ";", "$", "this", "->", "__buildPage", "(", "$", "page", ")", ";", "// Add XSRF token to form's in the backend", "if", "(", "self", "::", "isXSRFEnabled", "(", ")", "&&", "isset", "(", "$", "this", "->", "Page", "->", "Form", ")", ")", "{", "$", "this", "->", "Page", "->", "Form", "->", "prependChild", "(", "XSRF", "::", "formToken", "(", ")", ")", ";", "}", "/**\n * Immediately before generating the admin page. Provided with the page object\n * @delegate AdminPagePreGenerate\n * @param string $context\n * '/backend/'\n * @param HTMLPage $oPage\n * An instance of the current page to be rendered, this will usually be a class that\n * extends HTMLPage. The Symphony backend uses a convention of contentPageName\n * as the class that extends the HTMLPage\n */", "Symphony", "::", "ExtensionManager", "(", ")", "->", "notifyMembers", "(", "'AdminPagePreGenerate'", ",", "'/backend/'", ",", "array", "(", "'oPage'", "=>", "&", "$", "this", "->", "Page", ")", ")", ";", "$", "output", "=", "$", "this", "->", "Page", "->", "generate", "(", ")", ";", "/**\n * Immediately after generating the admin page. Provided with string containing page source\n * @delegate AdminPagePostGenerate\n * @param string $context\n * '/backend/'\n * @param string $output\n * The resulting backend page HTML as a string, passed by reference\n */", "Symphony", "::", "ExtensionManager", "(", ")", "->", "notifyMembers", "(", "'AdminPagePostGenerate'", ",", "'/backend/'", ",", "array", "(", "'output'", "=>", "&", "$", "output", ")", ")", ";", "Symphony", "::", "Profiler", "(", ")", "->", "sample", "(", "'Page built'", ")", ";", "return", "$", "output", ";", "}" ]
Called by index.php, this function is responsible for rendering the current page on the Frontend. Two delegates are fired, AdminPagePreGenerate and AdminPagePostGenerate. This function runs the Profiler for the page build process. @uses AdminPagePreBuild @uses AdminPagePreGenerate @uses AdminPagePostGenerate @see core.Symphony#__buildPage() @see boot.getCurrentPage() @param string $page The result of getCurrentPage, which returns the $_GET['symphony-page'] variable. @throws Exception @throws SymphonyErrorPage @return string The HTML of the page to return
[ "Called", "by", "index", ".", "php", "this", "function", "is", "responsible", "for", "rendering", "the", "current", "page", "on", "the", "Frontend", ".", "Two", "delegates", "are", "fired", "AdminPagePreGenerate", "and", "AdminPagePostGenerate", ".", "This", "function", "runs", "the", "Profiler", "for", "the", "page", "build", "process", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.administration.php#L467-L517
symphonycms/symphony-2
symphony/lib/toolkit/class.gateway.php
Gateway.setopt
public function setopt($opt, $value) { switch ($opt) { case 'URL': $this->_url = $value; $url_parsed = parse_url($value); $this->_host = $url_parsed['host']; if (isset($url_parsed['scheme']) && strlen(trim($url_parsed['scheme'])) > 0) { $this->_scheme = $url_parsed['scheme']; } if (isset($url_parsed['port'])) { $this->_port = $url_parsed['port']; } if (isset($url_parsed['path'])) { $this->_path = $url_parsed['path']; } if (isset($url_parsed['query'])) { $this->_path .= '?' . $url_parsed['query']; } // Allow basic HTTP authentiction if (isset($url_parsed['user']) && isset($url_parsed['pass'])) { $this->setopt(CURLOPT_USERPWD, sprintf('%s:%s', $url_parsed['user'], $url_parsed['pass'])); $this->setopt(CURLOPT_HTTPAUTH, CURLAUTH_ANY); } // Better support for HTTPS requests if ($url_parsed['scheme'] == 'https') { $this->setopt(CURLOPT_SSL_VERIFYPEER, false); } break; case 'POST': case 'GET': case 'PUT': case 'DELETE': $this->_method = ($value == 1 ? $opt : 'GET'); break; case 'POSTFIELDS': if (is_array($value) && !empty($value)) { $this->_postfields = http_build_query($value); } else { $this->_postfields = $value; } break; case 'USERAGENT': $this->_agent = $value; break; case 'HTTPHEADER': // merge the values, so multiple calls won't erase other values if (is_array($value)) { $this->_headers = array_merge($this->_headers, $value); } else { $this->_headers[] = $value; } break; case 'RETURNHEADERS': $this->_returnHeaders = (intval($value) == 1 ? true : false); break; case 'CONTENTTYPE': $this->_content_type = $value; break; case 'TIMEOUT': $this->_timeout = max(1, intval($value)); break; default: $this->_custom_opt[$opt] = $value; break; } }
php
public function setopt($opt, $value) { switch ($opt) { case 'URL': $this->_url = $value; $url_parsed = parse_url($value); $this->_host = $url_parsed['host']; if (isset($url_parsed['scheme']) && strlen(trim($url_parsed['scheme'])) > 0) { $this->_scheme = $url_parsed['scheme']; } if (isset($url_parsed['port'])) { $this->_port = $url_parsed['port']; } if (isset($url_parsed['path'])) { $this->_path = $url_parsed['path']; } if (isset($url_parsed['query'])) { $this->_path .= '?' . $url_parsed['query']; } // Allow basic HTTP authentiction if (isset($url_parsed['user']) && isset($url_parsed['pass'])) { $this->setopt(CURLOPT_USERPWD, sprintf('%s:%s', $url_parsed['user'], $url_parsed['pass'])); $this->setopt(CURLOPT_HTTPAUTH, CURLAUTH_ANY); } // Better support for HTTPS requests if ($url_parsed['scheme'] == 'https') { $this->setopt(CURLOPT_SSL_VERIFYPEER, false); } break; case 'POST': case 'GET': case 'PUT': case 'DELETE': $this->_method = ($value == 1 ? $opt : 'GET'); break; case 'POSTFIELDS': if (is_array($value) && !empty($value)) { $this->_postfields = http_build_query($value); } else { $this->_postfields = $value; } break; case 'USERAGENT': $this->_agent = $value; break; case 'HTTPHEADER': // merge the values, so multiple calls won't erase other values if (is_array($value)) { $this->_headers = array_merge($this->_headers, $value); } else { $this->_headers[] = $value; } break; case 'RETURNHEADERS': $this->_returnHeaders = (intval($value) == 1 ? true : false); break; case 'CONTENTTYPE': $this->_content_type = $value; break; case 'TIMEOUT': $this->_timeout = max(1, intval($value)); break; default: $this->_custom_opt[$opt] = $value; break; } }
[ "public", "function", "setopt", "(", "$", "opt", ",", "$", "value", ")", "{", "switch", "(", "$", "opt", ")", "{", "case", "'URL'", ":", "$", "this", "->", "_url", "=", "$", "value", ";", "$", "url_parsed", "=", "parse_url", "(", "$", "value", ")", ";", "$", "this", "->", "_host", "=", "$", "url_parsed", "[", "'host'", "]", ";", "if", "(", "isset", "(", "$", "url_parsed", "[", "'scheme'", "]", ")", "&&", "strlen", "(", "trim", "(", "$", "url_parsed", "[", "'scheme'", "]", ")", ")", ">", "0", ")", "{", "$", "this", "->", "_scheme", "=", "$", "url_parsed", "[", "'scheme'", "]", ";", "}", "if", "(", "isset", "(", "$", "url_parsed", "[", "'port'", "]", ")", ")", "{", "$", "this", "->", "_port", "=", "$", "url_parsed", "[", "'port'", "]", ";", "}", "if", "(", "isset", "(", "$", "url_parsed", "[", "'path'", "]", ")", ")", "{", "$", "this", "->", "_path", "=", "$", "url_parsed", "[", "'path'", "]", ";", "}", "if", "(", "isset", "(", "$", "url_parsed", "[", "'query'", "]", ")", ")", "{", "$", "this", "->", "_path", ".=", "'?'", ".", "$", "url_parsed", "[", "'query'", "]", ";", "}", "// Allow basic HTTP authentiction", "if", "(", "isset", "(", "$", "url_parsed", "[", "'user'", "]", ")", "&&", "isset", "(", "$", "url_parsed", "[", "'pass'", "]", ")", ")", "{", "$", "this", "->", "setopt", "(", "CURLOPT_USERPWD", ",", "sprintf", "(", "'%s:%s'", ",", "$", "url_parsed", "[", "'user'", "]", ",", "$", "url_parsed", "[", "'pass'", "]", ")", ")", ";", "$", "this", "->", "setopt", "(", "CURLOPT_HTTPAUTH", ",", "CURLAUTH_ANY", ")", ";", "}", "// Better support for HTTPS requests", "if", "(", "$", "url_parsed", "[", "'scheme'", "]", "==", "'https'", ")", "{", "$", "this", "->", "setopt", "(", "CURLOPT_SSL_VERIFYPEER", ",", "false", ")", ";", "}", "break", ";", "case", "'POST'", ":", "case", "'GET'", ":", "case", "'PUT'", ":", "case", "'DELETE'", ":", "$", "this", "->", "_method", "=", "(", "$", "value", "==", "1", "?", "$", "opt", ":", "'GET'", ")", ";", "break", ";", "case", "'POSTFIELDS'", ":", "if", "(", "is_array", "(", "$", "value", ")", "&&", "!", "empty", "(", "$", "value", ")", ")", "{", "$", "this", "->", "_postfields", "=", "http_build_query", "(", "$", "value", ")", ";", "}", "else", "{", "$", "this", "->", "_postfields", "=", "$", "value", ";", "}", "break", ";", "case", "'USERAGENT'", ":", "$", "this", "->", "_agent", "=", "$", "value", ";", "break", ";", "case", "'HTTPHEADER'", ":", "// merge the values, so multiple calls won't erase other values", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "this", "->", "_headers", "=", "array_merge", "(", "$", "this", "->", "_headers", ",", "$", "value", ")", ";", "}", "else", "{", "$", "this", "->", "_headers", "[", "]", "=", "$", "value", ";", "}", "break", ";", "case", "'RETURNHEADERS'", ":", "$", "this", "->", "_returnHeaders", "=", "(", "intval", "(", "$", "value", ")", "==", "1", "?", "true", ":", "false", ")", ";", "break", ";", "case", "'CONTENTTYPE'", ":", "$", "this", "->", "_content_type", "=", "$", "value", ";", "break", ";", "case", "'TIMEOUT'", ":", "$", "this", "->", "_timeout", "=", "max", "(", "1", ",", "intval", "(", "$", "value", ")", ")", ";", "break", ";", "default", ":", "$", "this", "->", "_custom_opt", "[", "$", "opt", "]", "=", "$", "value", ";", "break", ";", "}", "}" ]
A basic wrapper that simulates the curl_setopt function. Any options that are not recognised by Symphony will fallback to being added to the `$custom_opt` array. Any options in `$custom_opt` will be applied on executed using curl_setopt. Custom options are not available for Socket requests. The benefit of using this function is for convienience as it performs some basic preprocessing for some options such as 'URL', which will take a full formatted URL string and set any authentication or SSL curl options automatically @link http://php.net/manual/en/function.curl-setopt.php @param string $opt A string representing a CURL constant. Symphony will intercept the following, URL, POST, POSTFIELDS, USERAGENT, HTTPHEADER, RETURNHEADERS, CONTENTTYPE and TIMEOUT. Any other values will be saved in the `$custom_opt` array. @param mixed $value The value of the option, usually boolean or a string. Consult the setopt documentation for more information.
[ "A", "basic", "wrapper", "that", "simulates", "the", "curl_setopt", "function", ".", "Any", "options", "that", "are", "not", "recognised", "by", "Symphony", "will", "fallback", "to", "being", "added", "to", "the", "$custom_opt", "array", ".", "Any", "options", "in", "$custom_opt", "will", "be", "applied", "on", "executed", "using", "curl_setopt", ".", "Custom", "options", "are", "not", "available", "for", "Socket", "requests", ".", "The", "benefit", "of", "using", "this", "function", "is", "for", "convienience", "as", "it", "performs", "some", "basic", "preprocessing", "for", "some", "options", "such", "as", "URL", "which", "will", "take", "a", "full", "formatted", "URL", "string", "and", "set", "any", "authentication", "or", "SSL", "curl", "options", "automatically" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.gateway.php#L197-L269
symphonycms/symphony-2
symphony/lib/toolkit/class.gateway.php
Gateway.exec
public function exec($force_connection_method = null) { if ($force_connection_method !== self::FORCE_SOCKET && self::isCurlAvailable()) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, sprintf( "%s://%s%s%s", $this->_scheme, $this->_host, (!is_null($this->_port) ? ':' . $this->_port : null), $this->_path )); curl_setopt($ch, CURLOPT_HEADER, $this->_returnHeaders); curl_setopt($ch, CURLOPT_USERAGENT, $this->_agent); curl_setopt($ch, CURLOPT_PORT, $this->_port); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, $this->_timeout); if (ini_get('safe_mode') == 0 && ini_get('open_basedir') == '') { curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); } switch ($this->_method) { case 'POST': curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $this->_postfields); break; case 'PUT': curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_POSTFIELDS, $this->_postfields); $this->setopt('HTTPHEADER', array('Content-Length:' => strlen($this->_postfields))); break; case 'DELETE': curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); curl_setopt($ch, CURLOPT_POSTFIELDS, $this->_postfields); break; } if (is_array($this->_headers) && !empty($this->_headers)) { curl_setopt($ch, CURLOPT_HTTPHEADER, $this->_headers); } if (is_array($this->_custom_opt) && !empty($this->_custom_opt)) { foreach ($this->_custom_opt as $opt => $value) { curl_setopt($ch, $opt, $value); } } // Grab the result $result = curl_exec($ch); $this->_info_last = curl_getinfo($ch); $this->_info_last['curl_error'] = curl_errno($ch); // Close the connection curl_close($ch); return $result; } $start = precision_timer(); if (is_null($this->_port)) { $this->_port = (!is_null($this->_scheme) ? self::$ports[$this->_scheme] : 80); } // No CURL is available, use attempt to use normal sockets $handle = @fsockopen($this->_host, $this->_port, $errno, $errstr, $this->_timeout); if ($handle === false) { return false; } $query = $this->_method . ' ' . $this->_path . ' HTTP/1.1' . PHP_EOL; $query .= 'Host: '.$this->_host . PHP_EOL; $query .= 'Content-type: '.$this->_content_type . PHP_EOL; $query .= 'User-Agent: '.$this->_agent . PHP_EOL; $query .= @implode(PHP_EOL, $this->_headers); $query .= 'Content-length: ' . strlen($this->_postfields) . PHP_EOL; $query .= 'Connection: close' . PHP_EOL . PHP_EOL; if (in_array($this->_method, array('PUT', 'POST', 'DELETE'))) { $query .= $this->_postfields; } // send request if (!@fwrite($handle, $query)) { return false; } stream_set_blocking($handle, false); stream_set_timeout($handle, $this->_timeout); $status = stream_get_meta_data($handle); $response = $dechunked = ''; // get header while (!preg_match('/\\r\\n\\r\\n$/', $header) && !$status['timed_out']) { $header .= @fread($handle, 1); $status = stream_get_meta_data($handle); } $status = socket_get_status($handle); // Get rest of the page data while (!feof($handle) && !$status['timed_out']) { $response .= fread($handle, 4096); $status = stream_get_meta_data($handle); } @fclose($handle); $end = precision_timer('stop', $start); if (preg_match('/Transfer\\-Encoding:\\s+chunked\\r\\n/', $header)) { $fp = 0; do { $byte = ''; $chunk_size = ''; do { $chunk_size .= $byte; $byte = substr($response, $fp, 1); $fp++; } while ($byte !== "\r" && $byte !== "\\r"); $chunk_size = hexdec($chunk_size); // convert to real number if ($chunk_size == 0) { break(1); } $fp++; $dechunked .= substr($response, $fp, $chunk_size); $fp += $chunk_size; $fp += 2; } while (true); $response = $dechunked; } // Following code emulates part of the function curl_getinfo() preg_match('/Content-Type:\s*([^\r\n]+)/i', $header, $match); $content_type = $match[1]; preg_match('/HTTP\/\d+.\d+\s+(\d+)/i', $header, $match); $status = $match[1]; $this->_info_last = array( 'url' => $this->_url, 'content_type' => $content_type, 'http_code' => (int)$status, 'total_time' => $end ); return ($this->_returnHeaders ? $header : null) . $response; }
php
public function exec($force_connection_method = null) { if ($force_connection_method !== self::FORCE_SOCKET && self::isCurlAvailable()) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, sprintf( "%s://%s%s%s", $this->_scheme, $this->_host, (!is_null($this->_port) ? ':' . $this->_port : null), $this->_path )); curl_setopt($ch, CURLOPT_HEADER, $this->_returnHeaders); curl_setopt($ch, CURLOPT_USERAGENT, $this->_agent); curl_setopt($ch, CURLOPT_PORT, $this->_port); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, $this->_timeout); if (ini_get('safe_mode') == 0 && ini_get('open_basedir') == '') { curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); } switch ($this->_method) { case 'POST': curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $this->_postfields); break; case 'PUT': curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_POSTFIELDS, $this->_postfields); $this->setopt('HTTPHEADER', array('Content-Length:' => strlen($this->_postfields))); break; case 'DELETE': curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); curl_setopt($ch, CURLOPT_POSTFIELDS, $this->_postfields); break; } if (is_array($this->_headers) && !empty($this->_headers)) { curl_setopt($ch, CURLOPT_HTTPHEADER, $this->_headers); } if (is_array($this->_custom_opt) && !empty($this->_custom_opt)) { foreach ($this->_custom_opt as $opt => $value) { curl_setopt($ch, $opt, $value); } } // Grab the result $result = curl_exec($ch); $this->_info_last = curl_getinfo($ch); $this->_info_last['curl_error'] = curl_errno($ch); // Close the connection curl_close($ch); return $result; } $start = precision_timer(); if (is_null($this->_port)) { $this->_port = (!is_null($this->_scheme) ? self::$ports[$this->_scheme] : 80); } // No CURL is available, use attempt to use normal sockets $handle = @fsockopen($this->_host, $this->_port, $errno, $errstr, $this->_timeout); if ($handle === false) { return false; } $query = $this->_method . ' ' . $this->_path . ' HTTP/1.1' . PHP_EOL; $query .= 'Host: '.$this->_host . PHP_EOL; $query .= 'Content-type: '.$this->_content_type . PHP_EOL; $query .= 'User-Agent: '.$this->_agent . PHP_EOL; $query .= @implode(PHP_EOL, $this->_headers); $query .= 'Content-length: ' . strlen($this->_postfields) . PHP_EOL; $query .= 'Connection: close' . PHP_EOL . PHP_EOL; if (in_array($this->_method, array('PUT', 'POST', 'DELETE'))) { $query .= $this->_postfields; } // send request if (!@fwrite($handle, $query)) { return false; } stream_set_blocking($handle, false); stream_set_timeout($handle, $this->_timeout); $status = stream_get_meta_data($handle); $response = $dechunked = ''; // get header while (!preg_match('/\\r\\n\\r\\n$/', $header) && !$status['timed_out']) { $header .= @fread($handle, 1); $status = stream_get_meta_data($handle); } $status = socket_get_status($handle); // Get rest of the page data while (!feof($handle) && !$status['timed_out']) { $response .= fread($handle, 4096); $status = stream_get_meta_data($handle); } @fclose($handle); $end = precision_timer('stop', $start); if (preg_match('/Transfer\\-Encoding:\\s+chunked\\r\\n/', $header)) { $fp = 0; do { $byte = ''; $chunk_size = ''; do { $chunk_size .= $byte; $byte = substr($response, $fp, 1); $fp++; } while ($byte !== "\r" && $byte !== "\\r"); $chunk_size = hexdec($chunk_size); // convert to real number if ($chunk_size == 0) { break(1); } $fp++; $dechunked .= substr($response, $fp, $chunk_size); $fp += $chunk_size; $fp += 2; } while (true); $response = $dechunked; } // Following code emulates part of the function curl_getinfo() preg_match('/Content-Type:\s*([^\r\n]+)/i', $header, $match); $content_type = $match[1]; preg_match('/HTTP\/\d+.\d+\s+(\d+)/i', $header, $match); $status = $match[1]; $this->_info_last = array( 'url' => $this->_url, 'content_type' => $content_type, 'http_code' => (int)$status, 'total_time' => $end ); return ($this->_returnHeaders ? $header : null) . $response; }
[ "public", "function", "exec", "(", "$", "force_connection_method", "=", "null", ")", "{", "if", "(", "$", "force_connection_method", "!==", "self", "::", "FORCE_SOCKET", "&&", "self", "::", "isCurlAvailable", "(", ")", ")", "{", "$", "ch", "=", "curl_init", "(", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_URL", ",", "sprintf", "(", "\"%s://%s%s%s\"", ",", "$", "this", "->", "_scheme", ",", "$", "this", "->", "_host", ",", "(", "!", "is_null", "(", "$", "this", "->", "_port", ")", "?", "':'", ".", "$", "this", "->", "_port", ":", "null", ")", ",", "$", "this", "->", "_path", ")", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HEADER", ",", "$", "this", "->", "_returnHeaders", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_USERAGENT", ",", "$", "this", "->", "_agent", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_PORT", ",", "$", "this", "->", "_port", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_RETURNTRANSFER", ",", "1", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_TIMEOUT", ",", "$", "this", "->", "_timeout", ")", ";", "if", "(", "ini_get", "(", "'safe_mode'", ")", "==", "0", "&&", "ini_get", "(", "'open_basedir'", ")", "==", "''", ")", "{", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_FOLLOWLOCATION", ",", "1", ")", ";", "}", "switch", "(", "$", "this", "->", "_method", ")", "{", "case", "'POST'", ":", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POST", ",", "1", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POSTFIELDS", ",", "$", "this", "->", "_postfields", ")", ";", "break", ";", "case", "'PUT'", ":", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_CUSTOMREQUEST", ",", "'PUT'", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POSTFIELDS", ",", "$", "this", "->", "_postfields", ")", ";", "$", "this", "->", "setopt", "(", "'HTTPHEADER'", ",", "array", "(", "'Content-Length:'", "=>", "strlen", "(", "$", "this", "->", "_postfields", ")", ")", ")", ";", "break", ";", "case", "'DELETE'", ":", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_CUSTOMREQUEST", ",", "'DELETE'", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POSTFIELDS", ",", "$", "this", "->", "_postfields", ")", ";", "break", ";", "}", "if", "(", "is_array", "(", "$", "this", "->", "_headers", ")", "&&", "!", "empty", "(", "$", "this", "->", "_headers", ")", ")", "{", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HTTPHEADER", ",", "$", "this", "->", "_headers", ")", ";", "}", "if", "(", "is_array", "(", "$", "this", "->", "_custom_opt", ")", "&&", "!", "empty", "(", "$", "this", "->", "_custom_opt", ")", ")", "{", "foreach", "(", "$", "this", "->", "_custom_opt", "as", "$", "opt", "=>", "$", "value", ")", "{", "curl_setopt", "(", "$", "ch", ",", "$", "opt", ",", "$", "value", ")", ";", "}", "}", "// Grab the result", "$", "result", "=", "curl_exec", "(", "$", "ch", ")", ";", "$", "this", "->", "_info_last", "=", "curl_getinfo", "(", "$", "ch", ")", ";", "$", "this", "->", "_info_last", "[", "'curl_error'", "]", "=", "curl_errno", "(", "$", "ch", ")", ";", "// Close the connection", "curl_close", "(", "$", "ch", ")", ";", "return", "$", "result", ";", "}", "$", "start", "=", "precision_timer", "(", ")", ";", "if", "(", "is_null", "(", "$", "this", "->", "_port", ")", ")", "{", "$", "this", "->", "_port", "=", "(", "!", "is_null", "(", "$", "this", "->", "_scheme", ")", "?", "self", "::", "$", "ports", "[", "$", "this", "->", "_scheme", "]", ":", "80", ")", ";", "}", "// No CURL is available, use attempt to use normal sockets", "$", "handle", "=", "@", "fsockopen", "(", "$", "this", "->", "_host", ",", "$", "this", "->", "_port", ",", "$", "errno", ",", "$", "errstr", ",", "$", "this", "->", "_timeout", ")", ";", "if", "(", "$", "handle", "===", "false", ")", "{", "return", "false", ";", "}", "$", "query", "=", "$", "this", "->", "_method", ".", "' '", ".", "$", "this", "->", "_path", ".", "' HTTP/1.1'", ".", "PHP_EOL", ";", "$", "query", ".=", "'Host: '", ".", "$", "this", "->", "_host", ".", "PHP_EOL", ";", "$", "query", ".=", "'Content-type: '", ".", "$", "this", "->", "_content_type", ".", "PHP_EOL", ";", "$", "query", ".=", "'User-Agent: '", ".", "$", "this", "->", "_agent", ".", "PHP_EOL", ";", "$", "query", ".=", "@", "implode", "(", "PHP_EOL", ",", "$", "this", "->", "_headers", ")", ";", "$", "query", ".=", "'Content-length: '", ".", "strlen", "(", "$", "this", "->", "_postfields", ")", ".", "PHP_EOL", ";", "$", "query", ".=", "'Connection: close'", ".", "PHP_EOL", ".", "PHP_EOL", ";", "if", "(", "in_array", "(", "$", "this", "->", "_method", ",", "array", "(", "'PUT'", ",", "'POST'", ",", "'DELETE'", ")", ")", ")", "{", "$", "query", ".=", "$", "this", "->", "_postfields", ";", "}", "// send request", "if", "(", "!", "@", "fwrite", "(", "$", "handle", ",", "$", "query", ")", ")", "{", "return", "false", ";", "}", "stream_set_blocking", "(", "$", "handle", ",", "false", ")", ";", "stream_set_timeout", "(", "$", "handle", ",", "$", "this", "->", "_timeout", ")", ";", "$", "status", "=", "stream_get_meta_data", "(", "$", "handle", ")", ";", "$", "response", "=", "$", "dechunked", "=", "''", ";", "// get header", "while", "(", "!", "preg_match", "(", "'/\\\\r\\\\n\\\\r\\\\n$/'", ",", "$", "header", ")", "&&", "!", "$", "status", "[", "'timed_out'", "]", ")", "{", "$", "header", ".=", "@", "fread", "(", "$", "handle", ",", "1", ")", ";", "$", "status", "=", "stream_get_meta_data", "(", "$", "handle", ")", ";", "}", "$", "status", "=", "socket_get_status", "(", "$", "handle", ")", ";", "// Get rest of the page data", "while", "(", "!", "feof", "(", "$", "handle", ")", "&&", "!", "$", "status", "[", "'timed_out'", "]", ")", "{", "$", "response", ".=", "fread", "(", "$", "handle", ",", "4096", ")", ";", "$", "status", "=", "stream_get_meta_data", "(", "$", "handle", ")", ";", "}", "@", "fclose", "(", "$", "handle", ")", ";", "$", "end", "=", "precision_timer", "(", "'stop'", ",", "$", "start", ")", ";", "if", "(", "preg_match", "(", "'/Transfer\\\\-Encoding:\\\\s+chunked\\\\r\\\\n/'", ",", "$", "header", ")", ")", "{", "$", "fp", "=", "0", ";", "do", "{", "$", "byte", "=", "''", ";", "$", "chunk_size", "=", "''", ";", "do", "{", "$", "chunk_size", ".=", "$", "byte", ";", "$", "byte", "=", "substr", "(", "$", "response", ",", "$", "fp", ",", "1", ")", ";", "$", "fp", "++", ";", "}", "while", "(", "$", "byte", "!==", "\"\\r\"", "&&", "$", "byte", "!==", "\"\\\\r\"", ")", ";", "$", "chunk_size", "=", "hexdec", "(", "$", "chunk_size", ")", ";", "// convert to real number", "if", "(", "$", "chunk_size", "==", "0", ")", "{", "break", "(", "1", ")", ";", "}", "$", "fp", "++", ";", "$", "dechunked", ".=", "substr", "(", "$", "response", ",", "$", "fp", ",", "$", "chunk_size", ")", ";", "$", "fp", "+=", "$", "chunk_size", ";", "$", "fp", "+=", "2", ";", "}", "while", "(", "true", ")", ";", "$", "response", "=", "$", "dechunked", ";", "}", "// Following code emulates part of the function curl_getinfo()", "preg_match", "(", "'/Content-Type:\\s*([^\\r\\n]+)/i'", ",", "$", "header", ",", "$", "match", ")", ";", "$", "content_type", "=", "$", "match", "[", "1", "]", ";", "preg_match", "(", "'/HTTP\\/\\d+.\\d+\\s+(\\d+)/i'", ",", "$", "header", ",", "$", "match", ")", ";", "$", "status", "=", "$", "match", "[", "1", "]", ";", "$", "this", "->", "_info_last", "=", "array", "(", "'url'", "=>", "$", "this", "->", "_url", ",", "'content_type'", "=>", "$", "content_type", ",", "'http_code'", "=>", "(", "int", ")", "$", "status", ",", "'total_time'", "=>", "$", "end", ")", ";", "return", "(", "$", "this", "->", "_returnHeaders", "?", "$", "header", ":", "null", ")", ".", "$", "response", ";", "}" ]
Executes the request using Curl unless it is not available or this function has explicitly been told not by providing the `Gateway::FORCE_SOCKET` constant as a parameter. The function will apply all the options set using `curl_setopt` before executing the request. Information about the transfer is available using the `getInfoLast()` function. Should Curl not be available, this function will fallback to using Sockets with `fsockopen` @see toolkit.Gateway#getInfoLast() @param string $force_connection_method Only one valid parameter, `Gateway::FORCE_SOCKET` @return string|boolean The result of the transfer as a string. If any errors occur during a socket request, false will be returned.
[ "Executes", "the", "request", "using", "Curl", "unless", "it", "is", "not", "available", "or", "this", "function", "has", "explicitly", "been", "told", "not", "by", "providing", "the", "Gateway", "::", "FORCE_SOCKET", "constant", "as", "a", "parameter", ".", "The", "function", "will", "apply", "all", "the", "options", "set", "using", "curl_setopt", "before", "executing", "the", "request", ".", "Information", "about", "the", "transfer", "is", "available", "using", "the", "getInfoLast", "()", "function", ".", "Should", "Curl", "not", "be", "available", "this", "function", "will", "fallback", "to", "using", "Sockets", "with", "fsockopen" ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/toolkit/class.gateway.php#L287-L446
symphonycms/symphony-2
symphony/lib/core/class.session.php
Session.start
public static function start($lifetime = 0, $path = '/', $domain = null, $httpOnly = true, $secure = false) { if (!self::$_initialized) { if (!is_object(Symphony::Database()) || !Symphony::Database()->isConnected()) { return false; } if (session_id() == '') { ini_set('session.use_trans_sid', '0'); ini_set('session.use_strict_mode', '1'); ini_set('session.use_only_cookies', '1'); ini_set('session.gc_maxlifetime', $lifetime); ini_set('session.gc_probability', '1'); ini_set('session.gc_divisor', Symphony::Configuration()->get('session_gc_divisor', 'symphony')); } session_set_save_handler( array('Session', 'open'), array('Session', 'close'), array('Session', 'read'), array('Session', 'write'), array('Session', 'destroy'), array('Session', 'gc') ); session_set_cookie_params( $lifetime, static::createCookieSafePath($path), ($domain ? $domain : self::getDomain()), $secure, $httpOnly ); session_cache_limiter(''); if (session_id() == '') { if (headers_sent()) { throw new Exception('Headers already sent. Cannot start session.'); } register_shutdown_function('session_write_close'); session_start(); } self::$_initialized = true; } return session_id(); }
php
public static function start($lifetime = 0, $path = '/', $domain = null, $httpOnly = true, $secure = false) { if (!self::$_initialized) { if (!is_object(Symphony::Database()) || !Symphony::Database()->isConnected()) { return false; } if (session_id() == '') { ini_set('session.use_trans_sid', '0'); ini_set('session.use_strict_mode', '1'); ini_set('session.use_only_cookies', '1'); ini_set('session.gc_maxlifetime', $lifetime); ini_set('session.gc_probability', '1'); ini_set('session.gc_divisor', Symphony::Configuration()->get('session_gc_divisor', 'symphony')); } session_set_save_handler( array('Session', 'open'), array('Session', 'close'), array('Session', 'read'), array('Session', 'write'), array('Session', 'destroy'), array('Session', 'gc') ); session_set_cookie_params( $lifetime, static::createCookieSafePath($path), ($domain ? $domain : self::getDomain()), $secure, $httpOnly ); session_cache_limiter(''); if (session_id() == '') { if (headers_sent()) { throw new Exception('Headers already sent. Cannot start session.'); } register_shutdown_function('session_write_close'); session_start(); } self::$_initialized = true; } return session_id(); }
[ "public", "static", "function", "start", "(", "$", "lifetime", "=", "0", ",", "$", "path", "=", "'/'", ",", "$", "domain", "=", "null", ",", "$", "httpOnly", "=", "true", ",", "$", "secure", "=", "false", ")", "{", "if", "(", "!", "self", "::", "$", "_initialized", ")", "{", "if", "(", "!", "is_object", "(", "Symphony", "::", "Database", "(", ")", ")", "||", "!", "Symphony", "::", "Database", "(", ")", "->", "isConnected", "(", ")", ")", "{", "return", "false", ";", "}", "if", "(", "session_id", "(", ")", "==", "''", ")", "{", "ini_set", "(", "'session.use_trans_sid'", ",", "'0'", ")", ";", "ini_set", "(", "'session.use_strict_mode'", ",", "'1'", ")", ";", "ini_set", "(", "'session.use_only_cookies'", ",", "'1'", ")", ";", "ini_set", "(", "'session.gc_maxlifetime'", ",", "$", "lifetime", ")", ";", "ini_set", "(", "'session.gc_probability'", ",", "'1'", ")", ";", "ini_set", "(", "'session.gc_divisor'", ",", "Symphony", "::", "Configuration", "(", ")", "->", "get", "(", "'session_gc_divisor'", ",", "'symphony'", ")", ")", ";", "}", "session_set_save_handler", "(", "array", "(", "'Session'", ",", "'open'", ")", ",", "array", "(", "'Session'", ",", "'close'", ")", ",", "array", "(", "'Session'", ",", "'read'", ")", ",", "array", "(", "'Session'", ",", "'write'", ")", ",", "array", "(", "'Session'", ",", "'destroy'", ")", ",", "array", "(", "'Session'", ",", "'gc'", ")", ")", ";", "session_set_cookie_params", "(", "$", "lifetime", ",", "static", "::", "createCookieSafePath", "(", "$", "path", ")", ",", "(", "$", "domain", "?", "$", "domain", ":", "self", "::", "getDomain", "(", ")", ")", ",", "$", "secure", ",", "$", "httpOnly", ")", ";", "session_cache_limiter", "(", "''", ")", ";", "if", "(", "session_id", "(", ")", "==", "''", ")", "{", "if", "(", "headers_sent", "(", ")", ")", "{", "throw", "new", "Exception", "(", "'Headers already sent. Cannot start session.'", ")", ";", "}", "register_shutdown_function", "(", "'session_write_close'", ")", ";", "session_start", "(", ")", ";", "}", "self", "::", "$", "_initialized", "=", "true", ";", "}", "return", "session_id", "(", ")", ";", "}" ]
Starts a Session object, only if one doesn't already exist. This function maps the Session Handler functions to this classes methods by reading the default information from the PHP ini file. @link http://php.net/manual/en/function.session-set-save-handler.php @link http://php.net/manual/en/function.session-set-cookie-params.php @param integer $lifetime How long a Session is valid for, by default this is 0, which means it never expires @param string $path The path the cookie is valid for on the domain @param string $domain The domain this cookie is valid for @param boolean $httpOnly Whether this cookie can be read by Javascript. By default the cookie cannot be read by Javascript @param boolean $secure Whether this cookie should only be sent on secure servers. By default this is false, which means the cookie can be sent over HTTP and HTTPS @throws Exception @return string|boolean Returns the Session ID on success, or false on error.
[ "Starts", "a", "Session", "object", "only", "if", "one", "doesn", "t", "already", "exist", ".", "This", "function", "maps", "the", "Session", "Handler", "functions", "to", "this", "classes", "methods", "by", "reading", "the", "default", "information", "from", "the", "PHP", "ini", "file", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.session.php#L52-L99
symphonycms/symphony-2
symphony/lib/core/class.session.php
Session.createCookieSafePath
protected static function createCookieSafePath($path) { $path = array_filter(explode('/', $path)); if (empty($path)) { return '/'; } $path = array_map('rawurlencode', $path); return '/' . implode('/', $path); }
php
protected static function createCookieSafePath($path) { $path = array_filter(explode('/', $path)); if (empty($path)) { return '/'; } $path = array_map('rawurlencode', $path); return '/' . implode('/', $path); }
[ "protected", "static", "function", "createCookieSafePath", "(", "$", "path", ")", "{", "$", "path", "=", "array_filter", "(", "explode", "(", "'/'", ",", "$", "path", ")", ")", ";", "if", "(", "empty", "(", "$", "path", ")", ")", "{", "return", "'/'", ";", "}", "$", "path", "=", "array_map", "(", "'rawurlencode'", ",", "$", "path", ")", ";", "return", "'/'", ".", "implode", "(", "'/'", ",", "$", "path", ")", ";", "}" ]
Returns a properly formatted ascii string for the cookie path. Browsers are notoriously bad at parsing the cookie path. They do not respect the content-encoding header. So we must be careful when dealing with setups with special characters in their paths. @since Symphony 2.7.0
[ "Returns", "a", "properly", "formatted", "ascii", "string", "for", "the", "cookie", "path", ".", "Browsers", "are", "notoriously", "bad", "at", "parsing", "the", "cookie", "path", ".", "They", "do", "not", "respect", "the", "content", "-", "encoding", "header", ".", "So", "we", "must", "be", "careful", "when", "dealing", "with", "setups", "with", "special", "characters", "in", "their", "paths", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.session.php#L109-L117
symphonycms/symphony-2
symphony/lib/core/class.session.php
Session.getDomain
public static function getDomain() { if (HTTP_HOST != null) { if (preg_match('/(localhost|127\.0\.0\.1)/', HTTP_HOST)) { return null; // prevent problems on local setups } return preg_replace('/(^www\.|:\d+$)/i', null, HTTP_HOST); } return null; }
php
public static function getDomain() { if (HTTP_HOST != null) { if (preg_match('/(localhost|127\.0\.0\.1)/', HTTP_HOST)) { return null; // prevent problems on local setups } return preg_replace('/(^www\.|:\d+$)/i', null, HTTP_HOST); } return null; }
[ "public", "static", "function", "getDomain", "(", ")", "{", "if", "(", "HTTP_HOST", "!=", "null", ")", "{", "if", "(", "preg_match", "(", "'/(localhost|127\\.0\\.0\\.1)/'", ",", "HTTP_HOST", ")", ")", "{", "return", "null", ";", "// prevent problems on local setups", "}", "return", "preg_replace", "(", "'/(^www\\.|:\\d+$)/i'", ",", "null", ",", "HTTP_HOST", ")", ";", "}", "return", "null", ";", "}" ]
Returns the current domain for the Session to be saved to, if the installation is on localhost, this returns null and just allows PHP to take care of setting the valid domain for the Session, otherwise it will return the non-www version of the domain host. @return string|null Null if on localhost, or HTTP_HOST is not set, a string of the domain name sans www otherwise
[ "Returns", "the", "current", "domain", "for", "the", "Session", "to", "be", "saved", "to", "if", "the", "installation", "is", "on", "localhost", "this", "returns", "null", "and", "just", "allows", "PHP", "to", "take", "care", "of", "setting", "the", "valid", "domain", "for", "the", "Session", "otherwise", "it", "will", "return", "the", "non", "-", "www", "version", "of", "the", "domain", "host", "." ]
train
https://github.com/symphonycms/symphony-2/blob/68f44f0c36ad3345068676bfb8a61c2e6a2e51f4/symphony/lib/core/class.session.php#L129-L140