repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
silverstripe/silverstripe-framework
src/Security/Member.php
Member.member_from_tempid
public static function member_from_tempid($tempid) { $members = static::get() ->filter('TempIDHash', $tempid); // Exclude expired if (static::config()->get('temp_id_lifetime')) { /** @var DataList|Member[] $members */ $members = $members->filter('TempIDExpired:GreaterThan', DBDatetime::now()->getValue()); } return $members->first(); }
php
public static function member_from_tempid($tempid) { $members = static::get() ->filter('TempIDHash', $tempid); // Exclude expired if (static::config()->get('temp_id_lifetime')) { /** @var DataList|Member[] $members */ $members = $members->filter('TempIDExpired:GreaterThan', DBDatetime::now()->getValue()); } return $members->first(); }
[ "public", "static", "function", "member_from_tempid", "(", "$", "tempid", ")", "{", "$", "members", "=", "static", "::", "get", "(", ")", "->", "filter", "(", "'TempIDHash'", ",", "$", "tempid", ")", ";", "// Exclude expired", "if", "(", "static", "::", "config", "(", ")", "->", "get", "(", "'temp_id_lifetime'", ")", ")", "{", "/** @var DataList|Member[] $members */", "$", "members", "=", "$", "members", "->", "filter", "(", "'TempIDExpired:GreaterThan'", ",", "DBDatetime", "::", "now", "(", ")", "->", "getValue", "(", ")", ")", ";", "}", "return", "$", "members", "->", "first", "(", ")", ";", "}" ]
Find a member record with the given TempIDHash value @param string $tempid @return Member
[ "Find", "a", "member", "record", "with", "the", "given", "TempIDHash", "value" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member.php#L674-L686
train
silverstripe/silverstripe-framework
src/Security/Member.php
Member.create_new_password
public static function create_new_password() { $words = Security::config()->uninherited('word_list'); if ($words && file_exists($words)) { $words = file($words); list($usec, $sec) = explode(' ', microtime()); mt_srand($sec + ((float)$usec * 100000)); $word = trim($words[random_int(0, count($words) - 1)]); $number = random_int(10, 999); return $word . $number; } else { $random = mt_rand(); $string = md5($random); $output = substr($string, 0, 8); return $output; } }
php
public static function create_new_password() { $words = Security::config()->uninherited('word_list'); if ($words && file_exists($words)) { $words = file($words); list($usec, $sec) = explode(' ', microtime()); mt_srand($sec + ((float)$usec * 100000)); $word = trim($words[random_int(0, count($words) - 1)]); $number = random_int(10, 999); return $word . $number; } else { $random = mt_rand(); $string = md5($random); $output = substr($string, 0, 8); return $output; } }
[ "public", "static", "function", "create_new_password", "(", ")", "{", "$", "words", "=", "Security", "::", "config", "(", ")", "->", "uninherited", "(", "'word_list'", ")", ";", "if", "(", "$", "words", "&&", "file_exists", "(", "$", "words", ")", ")", "{", "$", "words", "=", "file", "(", "$", "words", ")", ";", "list", "(", "$", "usec", ",", "$", "sec", ")", "=", "explode", "(", "' '", ",", "microtime", "(", ")", ")", ";", "mt_srand", "(", "$", "sec", "+", "(", "(", "float", ")", "$", "usec", "*", "100000", ")", ")", ";", "$", "word", "=", "trim", "(", "$", "words", "[", "random_int", "(", "0", ",", "count", "(", "$", "words", ")", "-", "1", ")", "]", ")", ";", "$", "number", "=", "random_int", "(", "10", ",", "999", ")", ";", "return", "$", "word", ".", "$", "number", ";", "}", "else", "{", "$", "random", "=", "mt_rand", "(", ")", ";", "$", "string", "=", "md5", "(", "$", "random", ")", ";", "$", "output", "=", "substr", "(", "$", "string", ",", "0", ",", "8", ")", ";", "return", "$", "output", ";", "}", "}" ]
Generate a random password, with randomiser to kick in if there's no words file on the filesystem. @return string Returns a random password.
[ "Generate", "a", "random", "password", "with", "randomiser", "to", "kick", "in", "if", "there", "s", "no", "words", "file", "on", "the", "filesystem", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member.php#L847-L868
train
silverstripe/silverstripe-framework
src/Security/Member.php
Member.deletePasswordLogs
protected function deletePasswordLogs() { foreach ($this->LoggedPasswords() as $password) { $password->delete(); $password->destroy(); } return $this; }
php
protected function deletePasswordLogs() { foreach ($this->LoggedPasswords() as $password) { $password->delete(); $password->destroy(); } return $this; }
[ "protected", "function", "deletePasswordLogs", "(", ")", "{", "foreach", "(", "$", "this", "->", "LoggedPasswords", "(", ")", "as", "$", "password", ")", "{", "$", "password", "->", "delete", "(", ")", ";", "$", "password", "->", "destroy", "(", ")", ";", "}", "return", "$", "this", ";", "}" ]
Delete the MemberPassword objects that are associated to this user @return $this
[ "Delete", "the", "MemberPassword", "objects", "that", "are", "associated", "to", "this", "user" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member.php#L964-L972
train
silverstripe/silverstripe-framework
src/Security/Member.php
Member.inGroups
public function inGroups($groups, $strict = false) { if ($groups) { foreach ($groups as $group) { if ($this->inGroup($group, $strict)) { return true; } } } return false; }
php
public function inGroups($groups, $strict = false) { if ($groups) { foreach ($groups as $group) { if ($this->inGroup($group, $strict)) { return true; } } } return false; }
[ "public", "function", "inGroups", "(", "$", "groups", ",", "$", "strict", "=", "false", ")", "{", "if", "(", "$", "groups", ")", "{", "foreach", "(", "$", "groups", "as", "$", "group", ")", "{", "if", "(", "$", "this", "->", "inGroup", "(", "$", "group", ",", "$", "strict", ")", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
Check if the member is in one of the given groups. @param array|SS_List $groups Collection of {@link Group} DataObjects to check @param boolean $strict Only determine direct group membership if set to true (Default: false) @return bool Returns TRUE if the member is in one of the given groups, otherwise FALSE.
[ "Check", "if", "the", "member", "is", "in", "one", "of", "the", "given", "groups", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member.php#L1012-L1023
train
silverstripe/silverstripe-framework
src/Security/Member.php
Member.inGroup
public function inGroup($group, $strict = false) { if (is_numeric($group)) { $groupCheckObj = DataObject::get_by_id(Group::class, $group); } elseif (is_string($group)) { $groupCheckObj = DataObject::get_one(Group::class, array( '"Group"."Code"' => $group )); } elseif ($group instanceof Group) { $groupCheckObj = $group; } else { throw new InvalidArgumentException('Member::inGroup(): Wrong format for $group parameter'); } if (!$groupCheckObj) { return false; } $groupCandidateObjs = ($strict) ? $this->getManyManyComponents("Groups") : $this->Groups(); if ($groupCandidateObjs) { foreach ($groupCandidateObjs as $groupCandidateObj) { if ($groupCandidateObj->ID == $groupCheckObj->ID) { return true; } } } return false; }
php
public function inGroup($group, $strict = false) { if (is_numeric($group)) { $groupCheckObj = DataObject::get_by_id(Group::class, $group); } elseif (is_string($group)) { $groupCheckObj = DataObject::get_one(Group::class, array( '"Group"."Code"' => $group )); } elseif ($group instanceof Group) { $groupCheckObj = $group; } else { throw new InvalidArgumentException('Member::inGroup(): Wrong format for $group parameter'); } if (!$groupCheckObj) { return false; } $groupCandidateObjs = ($strict) ? $this->getManyManyComponents("Groups") : $this->Groups(); if ($groupCandidateObjs) { foreach ($groupCandidateObjs as $groupCandidateObj) { if ($groupCandidateObj->ID == $groupCheckObj->ID) { return true; } } } return false; }
[ "public", "function", "inGroup", "(", "$", "group", ",", "$", "strict", "=", "false", ")", "{", "if", "(", "is_numeric", "(", "$", "group", ")", ")", "{", "$", "groupCheckObj", "=", "DataObject", "::", "get_by_id", "(", "Group", "::", "class", ",", "$", "group", ")", ";", "}", "elseif", "(", "is_string", "(", "$", "group", ")", ")", "{", "$", "groupCheckObj", "=", "DataObject", "::", "get_one", "(", "Group", "::", "class", ",", "array", "(", "'\"Group\".\"Code\"'", "=>", "$", "group", ")", ")", ";", "}", "elseif", "(", "$", "group", "instanceof", "Group", ")", "{", "$", "groupCheckObj", "=", "$", "group", ";", "}", "else", "{", "throw", "new", "InvalidArgumentException", "(", "'Member::inGroup(): Wrong format for $group parameter'", ")", ";", "}", "if", "(", "!", "$", "groupCheckObj", ")", "{", "return", "false", ";", "}", "$", "groupCandidateObjs", "=", "(", "$", "strict", ")", "?", "$", "this", "->", "getManyManyComponents", "(", "\"Groups\"", ")", ":", "$", "this", "->", "Groups", "(", ")", ";", "if", "(", "$", "groupCandidateObjs", ")", "{", "foreach", "(", "$", "groupCandidateObjs", "as", "$", "groupCandidateObj", ")", "{", "if", "(", "$", "groupCandidateObj", "->", "ID", "==", "$", "groupCheckObj", "->", "ID", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
Check if the member is in the given group or any parent groups. @param int|Group|string $group Group instance, Group Code or ID @param boolean $strict Only determine direct group membership if set to TRUE (Default: FALSE) @return bool Returns TRUE if the member is in the given group, otherwise FALSE.
[ "Check", "if", "the", "member", "is", "in", "the", "given", "group", "or", "any", "parent", "groups", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member.php#L1033-L1061
train
silverstripe/silverstripe-framework
src/Security/Member.php
Member.addToGroupByCode
public function addToGroupByCode($groupcode, $title = "") { $group = DataObject::get_one(Group::class, array( '"Group"."Code"' => $groupcode )); if ($group) { $this->Groups()->add($group); } else { if (!$title) { $title = $groupcode; } $group = new Group(); $group->Code = $groupcode; $group->Title = $title; $group->write(); $this->Groups()->add($group); } }
php
public function addToGroupByCode($groupcode, $title = "") { $group = DataObject::get_one(Group::class, array( '"Group"."Code"' => $groupcode )); if ($group) { $this->Groups()->add($group); } else { if (!$title) { $title = $groupcode; } $group = new Group(); $group->Code = $groupcode; $group->Title = $title; $group->write(); $this->Groups()->add($group); } }
[ "public", "function", "addToGroupByCode", "(", "$", "groupcode", ",", "$", "title", "=", "\"\"", ")", "{", "$", "group", "=", "DataObject", "::", "get_one", "(", "Group", "::", "class", ",", "array", "(", "'\"Group\".\"Code\"'", "=>", "$", "groupcode", ")", ")", ";", "if", "(", "$", "group", ")", "{", "$", "this", "->", "Groups", "(", ")", "->", "add", "(", "$", "group", ")", ";", "}", "else", "{", "if", "(", "!", "$", "title", ")", "{", "$", "title", "=", "$", "groupcode", ";", "}", "$", "group", "=", "new", "Group", "(", ")", ";", "$", "group", "->", "Code", "=", "$", "groupcode", ";", "$", "group", "->", "Title", "=", "$", "title", ";", "$", "group", "->", "write", "(", ")", ";", "$", "this", "->", "Groups", "(", ")", "->", "add", "(", "$", "group", ")", ";", "}", "}" ]
Adds the member to a group. This will create the group if the given group code does not return a valid group object. @param string $groupcode @param string $title Title of the group
[ "Adds", "the", "member", "to", "a", "group", ".", "This", "will", "create", "the", "group", "if", "the", "given", "group", "code", "does", "not", "return", "a", "valid", "group", "object", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member.php#L1070-L1090
train
silverstripe/silverstripe-framework
src/Security/Member.php
Member.removeFromGroupByCode
public function removeFromGroupByCode($groupcode) { $group = Group::get()->filter(array('Code' => $groupcode))->first(); if ($group) { $this->Groups()->remove($group); } }
php
public function removeFromGroupByCode($groupcode) { $group = Group::get()->filter(array('Code' => $groupcode))->first(); if ($group) { $this->Groups()->remove($group); } }
[ "public", "function", "removeFromGroupByCode", "(", "$", "groupcode", ")", "{", "$", "group", "=", "Group", "::", "get", "(", ")", "->", "filter", "(", "array", "(", "'Code'", "=>", "$", "groupcode", ")", ")", "->", "first", "(", ")", ";", "if", "(", "$", "group", ")", "{", "$", "this", "->", "Groups", "(", ")", "->", "remove", "(", "$", "group", ")", ";", "}", "}" ]
Removes a member from a group. @param string $groupcode
[ "Removes", "a", "member", "from", "a", "group", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member.php#L1097-L1104
train
silverstripe/silverstripe-framework
src/Security/Member.php
Member.setName
public function setName($name) { $nameParts = explode(' ', $name); $this->Surname = array_pop($nameParts); $this->FirstName = join(' ', $nameParts); }
php
public function setName($name) { $nameParts = explode(' ', $name); $this->Surname = array_pop($nameParts); $this->FirstName = join(' ', $nameParts); }
[ "public", "function", "setName", "(", "$", "name", ")", "{", "$", "nameParts", "=", "explode", "(", "' '", ",", "$", "name", ")", ";", "$", "this", "->", "Surname", "=", "array_pop", "(", "$", "nameParts", ")", ";", "$", "this", "->", "FirstName", "=", "join", "(", "' '", ",", "$", "nameParts", ")", ";", "}" ]
Set first- and surname This method assumes that the last part of the name is the surname, e.g. <i>A B C</i> will result in firstname <i>A B</i> and surname <i>C</i> @param string $name The name
[ "Set", "first", "-", "and", "surname" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member.php#L1211-L1216
train
silverstripe/silverstripe-framework
src/Security/Member.php
Member.map_in_groups
public static function map_in_groups($groups = null) { $groupIDList = array(); if ($groups instanceof SS_List) { foreach ($groups as $group) { $groupIDList[] = $group->ID; } } elseif (is_array($groups)) { $groupIDList = $groups; } elseif ($groups) { $groupIDList[] = $groups; } // No groups, return all Members if (!$groupIDList) { return static::get()->sort(array('Surname' => 'ASC', 'FirstName' => 'ASC'))->map(); } $membersList = new ArrayList(); // This is a bit ineffective, but follow the ORM style /** @var Group $group */ foreach (Group::get()->byIDs($groupIDList) as $group) { $membersList->merge($group->Members()); } $membersList->removeDuplicates('ID'); return $membersList->map(); }
php
public static function map_in_groups($groups = null) { $groupIDList = array(); if ($groups instanceof SS_List) { foreach ($groups as $group) { $groupIDList[] = $group->ID; } } elseif (is_array($groups)) { $groupIDList = $groups; } elseif ($groups) { $groupIDList[] = $groups; } // No groups, return all Members if (!$groupIDList) { return static::get()->sort(array('Surname' => 'ASC', 'FirstName' => 'ASC'))->map(); } $membersList = new ArrayList(); // This is a bit ineffective, but follow the ORM style /** @var Group $group */ foreach (Group::get()->byIDs($groupIDList) as $group) { $membersList->merge($group->Members()); } $membersList->removeDuplicates('ID'); return $membersList->map(); }
[ "public", "static", "function", "map_in_groups", "(", "$", "groups", "=", "null", ")", "{", "$", "groupIDList", "=", "array", "(", ")", ";", "if", "(", "$", "groups", "instanceof", "SS_List", ")", "{", "foreach", "(", "$", "groups", "as", "$", "group", ")", "{", "$", "groupIDList", "[", "]", "=", "$", "group", "->", "ID", ";", "}", "}", "elseif", "(", "is_array", "(", "$", "groups", ")", ")", "{", "$", "groupIDList", "=", "$", "groups", ";", "}", "elseif", "(", "$", "groups", ")", "{", "$", "groupIDList", "[", "]", "=", "$", "groups", ";", "}", "// No groups, return all Members", "if", "(", "!", "$", "groupIDList", ")", "{", "return", "static", "::", "get", "(", ")", "->", "sort", "(", "array", "(", "'Surname'", "=>", "'ASC'", ",", "'FirstName'", "=>", "'ASC'", ")", ")", "->", "map", "(", ")", ";", "}", "$", "membersList", "=", "new", "ArrayList", "(", ")", ";", "// This is a bit ineffective, but follow the ORM style", "/** @var Group $group */", "foreach", "(", "Group", "::", "get", "(", ")", "->", "byIDs", "(", "$", "groupIDList", ")", "as", "$", "group", ")", "{", "$", "membersList", "->", "merge", "(", "$", "group", "->", "Members", "(", ")", ")", ";", "}", "$", "membersList", "->", "removeDuplicates", "(", "'ID'", ")", ";", "return", "$", "membersList", "->", "map", "(", ")", ";", "}" ]
Get a member SQLMap of members in specific groups If no $groups is passed, all members will be returned @param mixed $groups - takes a SS_List, an array or a single Group.ID @return Map Returns an Map that returns all Member data.
[ "Get", "a", "member", "SQLMap", "of", "members", "in", "specific", "groups" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member.php#L1320-L1349
train
silverstripe/silverstripe-framework
src/Security/Member.php
Member.mapInCMSGroups
public static function mapInCMSGroups($groups = null) { // non-countable $groups will issue a warning when using count() in PHP 7.2+ if (!$groups) { $groups = []; } // Check CMS module exists if (!class_exists(LeftAndMain::class)) { return ArrayList::create()->map(); } if (count($groups) == 0) { $perms = array('ADMIN', 'CMS_ACCESS_AssetAdmin'); if (class_exists(CMSMain::class)) { $cmsPerms = CMSMain::singleton()->providePermissions(); } else { $cmsPerms = LeftAndMain::singleton()->providePermissions(); } if (!empty($cmsPerms)) { $perms = array_unique(array_merge($perms, array_keys($cmsPerms))); } $permsClause = DB::placeholders($perms); /** @skipUpgrade */ $groups = Group::get() ->innerJoin("Permission", '"Permission"."GroupID" = "Group"."ID"') ->where(array( "\"Permission\".\"Code\" IN ($permsClause)" => $perms )); } $groupIDList = array(); if ($groups instanceof SS_List) { foreach ($groups as $group) { $groupIDList[] = $group->ID; } } elseif (is_array($groups)) { $groupIDList = $groups; } /** @skipUpgrade */ $members = static::get() ->innerJoin("Group_Members", '"Group_Members"."MemberID" = "Member"."ID"') ->innerJoin("Group", '"Group"."ID" = "Group_Members"."GroupID"'); if ($groupIDList) { $groupClause = DB::placeholders($groupIDList); $members = $members->where(array( "\"Group\".\"ID\" IN ($groupClause)" => $groupIDList )); } return $members->sort('"Member"."Surname", "Member"."FirstName"')->map(); }
php
public static function mapInCMSGroups($groups = null) { // non-countable $groups will issue a warning when using count() in PHP 7.2+ if (!$groups) { $groups = []; } // Check CMS module exists if (!class_exists(LeftAndMain::class)) { return ArrayList::create()->map(); } if (count($groups) == 0) { $perms = array('ADMIN', 'CMS_ACCESS_AssetAdmin'); if (class_exists(CMSMain::class)) { $cmsPerms = CMSMain::singleton()->providePermissions(); } else { $cmsPerms = LeftAndMain::singleton()->providePermissions(); } if (!empty($cmsPerms)) { $perms = array_unique(array_merge($perms, array_keys($cmsPerms))); } $permsClause = DB::placeholders($perms); /** @skipUpgrade */ $groups = Group::get() ->innerJoin("Permission", '"Permission"."GroupID" = "Group"."ID"') ->where(array( "\"Permission\".\"Code\" IN ($permsClause)" => $perms )); } $groupIDList = array(); if ($groups instanceof SS_List) { foreach ($groups as $group) { $groupIDList[] = $group->ID; } } elseif (is_array($groups)) { $groupIDList = $groups; } /** @skipUpgrade */ $members = static::get() ->innerJoin("Group_Members", '"Group_Members"."MemberID" = "Member"."ID"') ->innerJoin("Group", '"Group"."ID" = "Group_Members"."GroupID"'); if ($groupIDList) { $groupClause = DB::placeholders($groupIDList); $members = $members->where(array( "\"Group\".\"ID\" IN ($groupClause)" => $groupIDList )); } return $members->sort('"Member"."Surname", "Member"."FirstName"')->map(); }
[ "public", "static", "function", "mapInCMSGroups", "(", "$", "groups", "=", "null", ")", "{", "// non-countable $groups will issue a warning when using count() in PHP 7.2+", "if", "(", "!", "$", "groups", ")", "{", "$", "groups", "=", "[", "]", ";", "}", "// Check CMS module exists", "if", "(", "!", "class_exists", "(", "LeftAndMain", "::", "class", ")", ")", "{", "return", "ArrayList", "::", "create", "(", ")", "->", "map", "(", ")", ";", "}", "if", "(", "count", "(", "$", "groups", ")", "==", "0", ")", "{", "$", "perms", "=", "array", "(", "'ADMIN'", ",", "'CMS_ACCESS_AssetAdmin'", ")", ";", "if", "(", "class_exists", "(", "CMSMain", "::", "class", ")", ")", "{", "$", "cmsPerms", "=", "CMSMain", "::", "singleton", "(", ")", "->", "providePermissions", "(", ")", ";", "}", "else", "{", "$", "cmsPerms", "=", "LeftAndMain", "::", "singleton", "(", ")", "->", "providePermissions", "(", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "cmsPerms", ")", ")", "{", "$", "perms", "=", "array_unique", "(", "array_merge", "(", "$", "perms", ",", "array_keys", "(", "$", "cmsPerms", ")", ")", ")", ";", "}", "$", "permsClause", "=", "DB", "::", "placeholders", "(", "$", "perms", ")", ";", "/** @skipUpgrade */", "$", "groups", "=", "Group", "::", "get", "(", ")", "->", "innerJoin", "(", "\"Permission\"", ",", "'\"Permission\".\"GroupID\" = \"Group\".\"ID\"'", ")", "->", "where", "(", "array", "(", "\"\\\"Permission\\\".\\\"Code\\\" IN ($permsClause)\"", "=>", "$", "perms", ")", ")", ";", "}", "$", "groupIDList", "=", "array", "(", ")", ";", "if", "(", "$", "groups", "instanceof", "SS_List", ")", "{", "foreach", "(", "$", "groups", "as", "$", "group", ")", "{", "$", "groupIDList", "[", "]", "=", "$", "group", "->", "ID", ";", "}", "}", "elseif", "(", "is_array", "(", "$", "groups", ")", ")", "{", "$", "groupIDList", "=", "$", "groups", ";", "}", "/** @skipUpgrade */", "$", "members", "=", "static", "::", "get", "(", ")", "->", "innerJoin", "(", "\"Group_Members\"", ",", "'\"Group_Members\".\"MemberID\" = \"Member\".\"ID\"'", ")", "->", "innerJoin", "(", "\"Group\"", ",", "'\"Group\".\"ID\" = \"Group_Members\".\"GroupID\"'", ")", ";", "if", "(", "$", "groupIDList", ")", "{", "$", "groupClause", "=", "DB", "::", "placeholders", "(", "$", "groupIDList", ")", ";", "$", "members", "=", "$", "members", "->", "where", "(", "array", "(", "\"\\\"Group\\\".\\\"ID\\\" IN ($groupClause)\"", "=>", "$", "groupIDList", ")", ")", ";", "}", "return", "$", "members", "->", "sort", "(", "'\"Member\".\"Surname\", \"Member\".\"FirstName\"'", ")", "->", "map", "(", ")", ";", "}" ]
Get a map of all members in the groups given that have CMS permissions If no groups are passed, all groups with CMS permissions will be used. @param array $groups Groups to consider or NULL to use all groups with CMS permissions. @return Map Returns a map of all members in the groups given that have CMS permissions.
[ "Get", "a", "map", "of", "all", "members", "in", "the", "groups", "given", "that", "have", "CMS", "permissions" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member.php#L1362-L1418
train
silverstripe/silverstripe-framework
src/Security/Member.php
Member.memberNotInGroups
public function memberNotInGroups($groupList, $memberGroups = null) { if (!$memberGroups) { $memberGroups = $this->Groups(); } foreach ($memberGroups as $group) { if (in_array($group->Code, $groupList)) { $index = array_search($group->Code, $groupList); unset($groupList[$index]); } } return $groupList; }
php
public function memberNotInGroups($groupList, $memberGroups = null) { if (!$memberGroups) { $memberGroups = $this->Groups(); } foreach ($memberGroups as $group) { if (in_array($group->Code, $groupList)) { $index = array_search($group->Code, $groupList); unset($groupList[$index]); } } return $groupList; }
[ "public", "function", "memberNotInGroups", "(", "$", "groupList", ",", "$", "memberGroups", "=", "null", ")", "{", "if", "(", "!", "$", "memberGroups", ")", "{", "$", "memberGroups", "=", "$", "this", "->", "Groups", "(", ")", ";", "}", "foreach", "(", "$", "memberGroups", "as", "$", "group", ")", "{", "if", "(", "in_array", "(", "$", "group", "->", "Code", ",", "$", "groupList", ")", ")", "{", "$", "index", "=", "array_search", "(", "$", "group", "->", "Code", ",", "$", "groupList", ")", ";", "unset", "(", "$", "groupList", "[", "$", "index", "]", ")", ";", "}", "}", "return", "$", "groupList", ";", "}" ]
Get the groups in which the member is NOT in When passed an array of groups, and a component set of groups, this function will return the array of groups the member is NOT in. @param array $groupList An array of group code names. @param array $memberGroups A component set of groups (if set to NULL, $this->groups() will be used) @return array Groups in which the member is NOT in.
[ "Get", "the", "groups", "in", "which", "the", "member", "is", "NOT", "in" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member.php#L1432-L1446
train
silverstripe/silverstripe-framework
src/Security/Member.php
Member.canView
public function canView($member = null) { //get member if (!$member) { $member = Security::getCurrentUser(); } //check for extensions, we do this first as they can overrule everything $extended = $this->extendedCan(__FUNCTION__, $member); if ($extended !== null) { return $extended; } //need to be logged in and/or most checks below rely on $member being a Member if (!$member) { return false; } // members can usually view their own record if ($this->ID == $member->ID) { return true; } //standard check return Permission::checkMember($member, 'CMS_ACCESS_SecurityAdmin'); }
php
public function canView($member = null) { //get member if (!$member) { $member = Security::getCurrentUser(); } //check for extensions, we do this first as they can overrule everything $extended = $this->extendedCan(__FUNCTION__, $member); if ($extended !== null) { return $extended; } //need to be logged in and/or most checks below rely on $member being a Member if (!$member) { return false; } // members can usually view their own record if ($this->ID == $member->ID) { return true; } //standard check return Permission::checkMember($member, 'CMS_ACCESS_SecurityAdmin'); }
[ "public", "function", "canView", "(", "$", "member", "=", "null", ")", "{", "//get member", "if", "(", "!", "$", "member", ")", "{", "$", "member", "=", "Security", "::", "getCurrentUser", "(", ")", ";", "}", "//check for extensions, we do this first as they can overrule everything", "$", "extended", "=", "$", "this", "->", "extendedCan", "(", "__FUNCTION__", ",", "$", "member", ")", ";", "if", "(", "$", "extended", "!==", "null", ")", "{", "return", "$", "extended", ";", "}", "//need to be logged in and/or most checks below rely on $member being a Member", "if", "(", "!", "$", "member", ")", "{", "return", "false", ";", "}", "// members can usually view their own record", "if", "(", "$", "this", "->", "ID", "==", "$", "member", "->", "ID", ")", "{", "return", "true", ";", "}", "//standard check", "return", "Permission", "::", "checkMember", "(", "$", "member", ",", "'CMS_ACCESS_SecurityAdmin'", ")", ";", "}" ]
Users can view their own record. Otherwise they'll need ADMIN or CMS_ACCESS_SecurityAdmin permissions. This is likely to be customized for social sites etc. with a looser permission model. @param Member $member @return bool
[ "Users", "can", "view", "their", "own", "record", ".", "Otherwise", "they", "ll", "need", "ADMIN", "or", "CMS_ACCESS_SecurityAdmin", "permissions", ".", "This", "is", "likely", "to", "be", "customized", "for", "social", "sites", "etc", ".", "with", "a", "looser", "permission", "model", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member.php#L1579-L1602
train
silverstripe/silverstripe-framework
src/Security/Member.php
Member.validate
public function validate() { // If validation is disabled, skip this step if (!DataObject::config()->uninherited('validation_enabled')) { return ValidationResult::create(); } $valid = parent::validate(); $validator = static::password_validator(); if (!$this->ID || $this->isChanged('Password')) { if ($this->Password && $validator) { $userValid = $validator->validate($this->Password, $this); $valid->combineAnd($userValid); } } return $valid; }
php
public function validate() { // If validation is disabled, skip this step if (!DataObject::config()->uninherited('validation_enabled')) { return ValidationResult::create(); } $valid = parent::validate(); $validator = static::password_validator(); if (!$this->ID || $this->isChanged('Password')) { if ($this->Password && $validator) { $userValid = $validator->validate($this->Password, $this); $valid->combineAnd($userValid); } } return $valid; }
[ "public", "function", "validate", "(", ")", "{", "// If validation is disabled, skip this step", "if", "(", "!", "DataObject", "::", "config", "(", ")", "->", "uninherited", "(", "'validation_enabled'", ")", ")", "{", "return", "ValidationResult", "::", "create", "(", ")", ";", "}", "$", "valid", "=", "parent", "::", "validate", "(", ")", ";", "$", "validator", "=", "static", "::", "password_validator", "(", ")", ";", "if", "(", "!", "$", "this", "->", "ID", "||", "$", "this", "->", "isChanged", "(", "'Password'", ")", ")", "{", "if", "(", "$", "this", "->", "Password", "&&", "$", "validator", ")", "{", "$", "userValid", "=", "$", "validator", "->", "validate", "(", "$", "this", "->", "Password", ",", "$", "this", ")", ";", "$", "valid", "->", "combineAnd", "(", "$", "userValid", ")", ";", "}", "}", "return", "$", "valid", ";", "}" ]
Validate this member object.
[ "Validate", "this", "member", "object", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member.php#L1685-L1703
train
silverstripe/silverstripe-framework
src/Security/Member.php
Member.changePassword
public function changePassword($password, $write = true) { $this->Password = $password; $valid = $this->validate(); $this->extend('onBeforeChangePassword', $password, $valid); if ($valid->isValid()) { $this->AutoLoginHash = null; $this->encryptPassword(); if ($write) { $this->passwordChangesToWrite = true; $this->write(); } } $this->extend('onAfterChangePassword', $password, $valid); return $valid; }
php
public function changePassword($password, $write = true) { $this->Password = $password; $valid = $this->validate(); $this->extend('onBeforeChangePassword', $password, $valid); if ($valid->isValid()) { $this->AutoLoginHash = null; $this->encryptPassword(); if ($write) { $this->passwordChangesToWrite = true; $this->write(); } } $this->extend('onAfterChangePassword', $password, $valid); return $valid; }
[ "public", "function", "changePassword", "(", "$", "password", ",", "$", "write", "=", "true", ")", "{", "$", "this", "->", "Password", "=", "$", "password", ";", "$", "valid", "=", "$", "this", "->", "validate", "(", ")", ";", "$", "this", "->", "extend", "(", "'onBeforeChangePassword'", ",", "$", "password", ",", "$", "valid", ")", ";", "if", "(", "$", "valid", "->", "isValid", "(", ")", ")", "{", "$", "this", "->", "AutoLoginHash", "=", "null", ";", "$", "this", "->", "encryptPassword", "(", ")", ";", "if", "(", "$", "write", ")", "{", "$", "this", "->", "passwordChangesToWrite", "=", "true", ";", "$", "this", "->", "write", "(", ")", ";", "}", "}", "$", "this", "->", "extend", "(", "'onAfterChangePassword'", ",", "$", "password", ",", "$", "valid", ")", ";", "return", "$", "valid", ";", "}" ]
Change password. This will cause rehashing according to the `PasswordEncryption` property. This method will allow extensions to perform actions and augment the validation result if required before the password is written and can check it after the write also. This method will encrypt the password prior to writing. @param string $password Cleartext password @param bool $write Whether to write the member afterwards @return ValidationResult
[ "Change", "password", ".", "This", "will", "cause", "rehashing", "according", "to", "the", "PasswordEncryption", "property", ".", "This", "method", "will", "allow", "extensions", "to", "perform", "actions", "and", "augment", "the", "validation", "result", "if", "required", "before", "the", "password", "is", "written", "and", "can", "check", "it", "after", "the", "write", "also", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member.php#L1716-L1737
train
silverstripe/silverstripe-framework
src/Security/Member.php
Member.registerFailedLogin
public function registerFailedLogin() { $lockOutAfterCount = self::config()->get('lock_out_after_incorrect_logins'); if ($lockOutAfterCount) { // Keep a tally of the number of failed log-ins so that we can lock people out ++$this->FailedLoginCount; if ($this->FailedLoginCount >= $lockOutAfterCount) { $lockoutMins = self::config()->get('lock_out_delay_mins'); $this->LockedOutUntil = date('Y-m-d H:i:s', DBDatetime::now()->getTimestamp() + $lockoutMins * 60); $this->FailedLoginCount = 0; } } $this->extend('registerFailedLogin'); $this->write(); }
php
public function registerFailedLogin() { $lockOutAfterCount = self::config()->get('lock_out_after_incorrect_logins'); if ($lockOutAfterCount) { // Keep a tally of the number of failed log-ins so that we can lock people out ++$this->FailedLoginCount; if ($this->FailedLoginCount >= $lockOutAfterCount) { $lockoutMins = self::config()->get('lock_out_delay_mins'); $this->LockedOutUntil = date('Y-m-d H:i:s', DBDatetime::now()->getTimestamp() + $lockoutMins * 60); $this->FailedLoginCount = 0; } } $this->extend('registerFailedLogin'); $this->write(); }
[ "public", "function", "registerFailedLogin", "(", ")", "{", "$", "lockOutAfterCount", "=", "self", "::", "config", "(", ")", "->", "get", "(", "'lock_out_after_incorrect_logins'", ")", ";", "if", "(", "$", "lockOutAfterCount", ")", "{", "// Keep a tally of the number of failed log-ins so that we can lock people out", "++", "$", "this", "->", "FailedLoginCount", ";", "if", "(", "$", "this", "->", "FailedLoginCount", ">=", "$", "lockOutAfterCount", ")", "{", "$", "lockoutMins", "=", "self", "::", "config", "(", ")", "->", "get", "(", "'lock_out_delay_mins'", ")", ";", "$", "this", "->", "LockedOutUntil", "=", "date", "(", "'Y-m-d H:i:s'", ",", "DBDatetime", "::", "now", "(", ")", "->", "getTimestamp", "(", ")", "+", "$", "lockoutMins", "*", "60", ")", ";", "$", "this", "->", "FailedLoginCount", "=", "0", ";", "}", "}", "$", "this", "->", "extend", "(", "'registerFailedLogin'", ")", ";", "$", "this", "->", "write", "(", ")", ";", "}" ]
Tell this member that someone made a failed attempt at logging in as them. This can be used to lock the user out temporarily if too many failed attempts are made.
[ "Tell", "this", "member", "that", "someone", "made", "a", "failed", "attempt", "at", "logging", "in", "as", "them", ".", "This", "can", "be", "used", "to", "lock", "the", "user", "out", "temporarily", "if", "too", "many", "failed", "attempts", "are", "made", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member.php#L1780-L1795
train
silverstripe/silverstripe-framework
src/Security/Member.php
Member.registerSuccessfulLogin
public function registerSuccessfulLogin() { if (self::config()->get('lock_out_after_incorrect_logins')) { // Forgive all past login failures $this->FailedLoginCount = 0; $this->LockedOutUntil = null; $this->write(); } }
php
public function registerSuccessfulLogin() { if (self::config()->get('lock_out_after_incorrect_logins')) { // Forgive all past login failures $this->FailedLoginCount = 0; $this->LockedOutUntil = null; $this->write(); } }
[ "public", "function", "registerSuccessfulLogin", "(", ")", "{", "if", "(", "self", "::", "config", "(", ")", "->", "get", "(", "'lock_out_after_incorrect_logins'", ")", ")", "{", "// Forgive all past login failures", "$", "this", "->", "FailedLoginCount", "=", "0", ";", "$", "this", "->", "LockedOutUntil", "=", "null", ";", "$", "this", "->", "write", "(", ")", ";", "}", "}" ]
Tell this member that a successful login has been made
[ "Tell", "this", "member", "that", "a", "successful", "login", "has", "been", "made" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member.php#L1800-L1808
train
silverstripe/silverstripe-framework
src/Security/Member.php
Member.getHtmlEditorConfigForCMS
public function getHtmlEditorConfigForCMS() { $currentName = ''; $currentPriority = 0; foreach ($this->Groups() as $group) { $configName = $group->HtmlEditorConfig; if ($configName) { $config = HTMLEditorConfig::get($group->HtmlEditorConfig); if ($config && $config->getOption('priority') > $currentPriority) { $currentName = $configName; $currentPriority = $config->getOption('priority'); } } } // If can't find a suitable editor, just default to cms return $currentName ? $currentName : 'cms'; }
php
public function getHtmlEditorConfigForCMS() { $currentName = ''; $currentPriority = 0; foreach ($this->Groups() as $group) { $configName = $group->HtmlEditorConfig; if ($configName) { $config = HTMLEditorConfig::get($group->HtmlEditorConfig); if ($config && $config->getOption('priority') > $currentPriority) { $currentName = $configName; $currentPriority = $config->getOption('priority'); } } } // If can't find a suitable editor, just default to cms return $currentName ? $currentName : 'cms'; }
[ "public", "function", "getHtmlEditorConfigForCMS", "(", ")", "{", "$", "currentName", "=", "''", ";", "$", "currentPriority", "=", "0", ";", "foreach", "(", "$", "this", "->", "Groups", "(", ")", "as", "$", "group", ")", "{", "$", "configName", "=", "$", "group", "->", "HtmlEditorConfig", ";", "if", "(", "$", "configName", ")", "{", "$", "config", "=", "HTMLEditorConfig", "::", "get", "(", "$", "group", "->", "HtmlEditorConfig", ")", ";", "if", "(", "$", "config", "&&", "$", "config", "->", "getOption", "(", "'priority'", ")", ">", "$", "currentPriority", ")", "{", "$", "currentName", "=", "$", "configName", ";", "$", "currentPriority", "=", "$", "config", "->", "getOption", "(", "'priority'", ")", ";", "}", "}", "}", "// If can't find a suitable editor, just default to cms", "return", "$", "currentName", "?", "$", "currentName", ":", "'cms'", ";", "}" ]
Get the HtmlEditorConfig for this user to be used in the CMS. This is set by the group. If multiple configurations are set, the one with the highest priority wins. @return string
[ "Get", "the", "HtmlEditorConfig", "for", "this", "user", "to", "be", "used", "in", "the", "CMS", ".", "This", "is", "set", "by", "the", "group", ".", "If", "multiple", "configurations", "are", "set", "the", "one", "with", "the", "highest", "priority", "wins", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member.php#L1817-L1835
train
silverstripe/silverstripe-framework
src/Core/CustomMethods.php
CustomMethods.registerExtraMethodCallback
protected function registerExtraMethodCallback($name, $callback) { if (!isset($this->extra_method_registers[$name])) { $this->extra_method_registers[$name] = $callback; } }
php
protected function registerExtraMethodCallback($name, $callback) { if (!isset($this->extra_method_registers[$name])) { $this->extra_method_registers[$name] = $callback; } }
[ "protected", "function", "registerExtraMethodCallback", "(", "$", "name", ",", "$", "callback", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "extra_method_registers", "[", "$", "name", "]", ")", ")", "{", "$", "this", "->", "extra_method_registers", "[", "$", "name", "]", "=", "$", "callback", ";", "}", "}" ]
Register an callback to invoke that defines extra methods @param string $name @param callable $callback
[ "Register", "an", "callback", "to", "invoke", "that", "defines", "extra", "methods" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/CustomMethods.php#L128-L133
train
silverstripe/silverstripe-framework
src/Core/CustomMethods.php
CustomMethods.getExtraMethodConfig
protected function getExtraMethodConfig($method) { // Lazy define methods if (!isset(self::$extra_methods[static::class])) { $this->defineMethods(); } if (isset(self::$extra_methods[static::class][strtolower($method)])) { return self::$extra_methods[static::class][strtolower($method)]; } return null; }
php
protected function getExtraMethodConfig($method) { // Lazy define methods if (!isset(self::$extra_methods[static::class])) { $this->defineMethods(); } if (isset(self::$extra_methods[static::class][strtolower($method)])) { return self::$extra_methods[static::class][strtolower($method)]; } return null; }
[ "protected", "function", "getExtraMethodConfig", "(", "$", "method", ")", "{", "// Lazy define methods", "if", "(", "!", "isset", "(", "self", "::", "$", "extra_methods", "[", "static", "::", "class", "]", ")", ")", "{", "$", "this", "->", "defineMethods", "(", ")", ";", "}", "if", "(", "isset", "(", "self", "::", "$", "extra_methods", "[", "static", "::", "class", "]", "[", "strtolower", "(", "$", "method", ")", "]", ")", ")", "{", "return", "self", "::", "$", "extra_methods", "[", "static", "::", "class", "]", "[", "strtolower", "(", "$", "method", ")", "]", ";", "}", "return", "null", ";", "}" ]
Get meta-data details on a named method @param string $method @return array List of custom method details, if defined for this method
[ "Get", "meta", "-", "data", "details", "on", "a", "named", "method" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/CustomMethods.php#L157-L168
train
silverstripe/silverstripe-framework
src/Core/CustomMethods.php
CustomMethods.allMethodNames
public function allMethodNames($custom = false) { $class = static::class; if (!isset(self::$built_in_methods[$class])) { self::$built_in_methods[$class] = array_map('strtolower', get_class_methods($this)); } if ($custom && isset(self::$extra_methods[$class])) { return array_merge(self::$built_in_methods[$class], array_keys(self::$extra_methods[$class])); } else { return self::$built_in_methods[$class]; } }
php
public function allMethodNames($custom = false) { $class = static::class; if (!isset(self::$built_in_methods[$class])) { self::$built_in_methods[$class] = array_map('strtolower', get_class_methods($this)); } if ($custom && isset(self::$extra_methods[$class])) { return array_merge(self::$built_in_methods[$class], array_keys(self::$extra_methods[$class])); } else { return self::$built_in_methods[$class]; } }
[ "public", "function", "allMethodNames", "(", "$", "custom", "=", "false", ")", "{", "$", "class", "=", "static", "::", "class", ";", "if", "(", "!", "isset", "(", "self", "::", "$", "built_in_methods", "[", "$", "class", "]", ")", ")", "{", "self", "::", "$", "built_in_methods", "[", "$", "class", "]", "=", "array_map", "(", "'strtolower'", ",", "get_class_methods", "(", "$", "this", ")", ")", ";", "}", "if", "(", "$", "custom", "&&", "isset", "(", "self", "::", "$", "extra_methods", "[", "$", "class", "]", ")", ")", "{", "return", "array_merge", "(", "self", "::", "$", "built_in_methods", "[", "$", "class", "]", ",", "array_keys", "(", "self", "::", "$", "extra_methods", "[", "$", "class", "]", ")", ")", ";", "}", "else", "{", "return", "self", "::", "$", "built_in_methods", "[", "$", "class", "]", ";", "}", "}" ]
Return the names of all the methods available on this object @param bool $custom include methods added dynamically at runtime @return array
[ "Return", "the", "names", "of", "all", "the", "methods", "available", "on", "this", "object" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/CustomMethods.php#L176-L188
train
silverstripe/silverstripe-framework
src/Forms/TextareaField.php
TextareaField.getSchemaDataDefaults
public function getSchemaDataDefaults() { $data = parent::getSchemaDataDefaults(); $data['data']['rows'] = $this->getRows(); $data['data']['columns'] = $this->getColumns(); $data['data']['maxlength'] = $this->getMaxLength(); return $data; }
php
public function getSchemaDataDefaults() { $data = parent::getSchemaDataDefaults(); $data['data']['rows'] = $this->getRows(); $data['data']['columns'] = $this->getColumns(); $data['data']['maxlength'] = $this->getMaxLength(); return $data; }
[ "public", "function", "getSchemaDataDefaults", "(", ")", "{", "$", "data", "=", "parent", "::", "getSchemaDataDefaults", "(", ")", ";", "$", "data", "[", "'data'", "]", "[", "'rows'", "]", "=", "$", "this", "->", "getRows", "(", ")", ";", "$", "data", "[", "'data'", "]", "[", "'columns'", "]", "=", "$", "this", "->", "getColumns", "(", ")", ";", "$", "data", "[", "'data'", "]", "[", "'maxlength'", "]", "=", "$", "this", "->", "getMaxLength", "(", ")", ";", "return", "$", "data", ";", "}" ]
Set textarea specific schema data
[ "Set", "textarea", "specific", "schema", "data" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/TextareaField.php#L56-L63
train
silverstripe/silverstripe-framework
src/Control/Cookie.php
Cookie.set
public static function set( $name, $value, $expiry = 90, $path = null, $domain = null, $secure = false, $httpOnly = true ) { return self::get_inst()->set($name, $value, $expiry, $path, $domain, $secure, $httpOnly); }
php
public static function set( $name, $value, $expiry = 90, $path = null, $domain = null, $secure = false, $httpOnly = true ) { return self::get_inst()->set($name, $value, $expiry, $path, $domain, $secure, $httpOnly); }
[ "public", "static", "function", "set", "(", "$", "name", ",", "$", "value", ",", "$", "expiry", "=", "90", ",", "$", "path", "=", "null", ",", "$", "domain", "=", "null", ",", "$", "secure", "=", "false", ",", "$", "httpOnly", "=", "true", ")", "{", "return", "self", "::", "get_inst", "(", ")", "->", "set", "(", "$", "name", ",", "$", "value", ",", "$", "expiry", ",", "$", "path", ",", "$", "domain", ",", "$", "secure", ",", "$", "httpOnly", ")", ";", "}" ]
Set a cookie variable. Expiry time is set in days, and defaults to 90. @param string $name @param mixed $value @param int $expiry @param string $path @param string $domain @param bool $secure @param bool $httpOnly See http://php.net/set_session
[ "Set", "a", "cookie", "variable", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Cookie.php#L47-L57
train
silverstripe/silverstripe-framework
src/i18n/TextCollection/Parser.php
Parser.getTranslatables
public static function getTranslatables($template, $warnIfEmpty = true) { // Run the parser and throw away the result $parser = new Parser($template, $warnIfEmpty); if (substr($template, 0, 3) == pack("CCC", 0xef, 0xbb, 0xbf)) { $parser->pos = 3; } $parser->match_TopTemplate(); return $parser->getEntities(); }
php
public static function getTranslatables($template, $warnIfEmpty = true) { // Run the parser and throw away the result $parser = new Parser($template, $warnIfEmpty); if (substr($template, 0, 3) == pack("CCC", 0xef, 0xbb, 0xbf)) { $parser->pos = 3; } $parser->match_TopTemplate(); return $parser->getEntities(); }
[ "public", "static", "function", "getTranslatables", "(", "$", "template", ",", "$", "warnIfEmpty", "=", "true", ")", "{", "// Run the parser and throw away the result", "$", "parser", "=", "new", "Parser", "(", "$", "template", ",", "$", "warnIfEmpty", ")", ";", "if", "(", "substr", "(", "$", "template", ",", "0", ",", "3", ")", "==", "pack", "(", "\"CCC\"", ",", "0xef", ",", "0xbb", ",", "0xbf", ")", ")", "{", "$", "parser", "->", "pos", "=", "3", ";", "}", "$", "parser", "->", "match_TopTemplate", "(", ")", ";", "return", "$", "parser", "->", "getEntities", "(", ")", ";", "}" ]
Parses a template and returns any translatable entities @param string $template String to parse for translations @param bool $warnIfEmpty Show warnings if default omitted @return array Map of keys -> values
[ "Parses", "a", "template", "and", "returns", "any", "translatable", "entities" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/i18n/TextCollection/Parser.php#L110-L119
train
silverstripe/silverstripe-framework
src/Control/RSS/RSSFeed.php
RSSFeed.linkToFeed
public static function linkToFeed($url, $title = null) { $title = Convert::raw2xml($title); Requirements::insertHeadTags( '<link rel="alternate" type="application/rss+xml" title="' . $title . '" href="' . $url . '" />' ); }
php
public static function linkToFeed($url, $title = null) { $title = Convert::raw2xml($title); Requirements::insertHeadTags( '<link rel="alternate" type="application/rss+xml" title="' . $title . '" href="' . $url . '" />' ); }
[ "public", "static", "function", "linkToFeed", "(", "$", "url", ",", "$", "title", "=", "null", ")", "{", "$", "title", "=", "Convert", "::", "raw2xml", "(", "$", "title", ")", ";", "Requirements", "::", "insertHeadTags", "(", "'<link rel=\"alternate\" type=\"application/rss+xml\" title=\"'", ".", "$", "title", ".", "'\" href=\"'", ".", "$", "url", ".", "'\" />'", ")", ";", "}" ]
Include an link to the feed @param string $url URL of the feed @param string $title Title to show
[ "Include", "an", "link", "to", "the", "feed" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/RSS/RSSFeed.php#L157-L163
train
silverstripe/silverstripe-framework
src/Control/RSS/RSSFeed.php
RSSFeed.Entries
public function Entries() { $output = new ArrayList(); if (isset($this->entries)) { foreach ($this->entries as $entry) { $output->push( RSSFeed_Entry::create($entry, $this->titleField, $this->descriptionField, $this->authorField) ); } } return $output; }
php
public function Entries() { $output = new ArrayList(); if (isset($this->entries)) { foreach ($this->entries as $entry) { $output->push( RSSFeed_Entry::create($entry, $this->titleField, $this->descriptionField, $this->authorField) ); } } return $output; }
[ "public", "function", "Entries", "(", ")", "{", "$", "output", "=", "new", "ArrayList", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "entries", ")", ")", "{", "foreach", "(", "$", "this", "->", "entries", "as", "$", "entry", ")", "{", "$", "output", "->", "push", "(", "RSSFeed_Entry", "::", "create", "(", "$", "entry", ",", "$", "this", "->", "titleField", ",", "$", "this", "->", "descriptionField", ",", "$", "this", "->", "authorField", ")", ")", ";", "}", "}", "return", "$", "output", ";", "}" ]
Get the RSS feed entries @return SS_List Returns the {@link RSSFeed_Entry} objects.
[ "Get", "the", "RSS", "feed", "entries" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/RSS/RSSFeed.php#L170-L182
train
silverstripe/silverstripe-framework
src/Control/RSS/RSSFeed.php
RSSFeed.Link
public function Link($action = null) { return Controller::join_links(Director::absoluteURL($this->link), $action); }
php
public function Link($action = null) { return Controller::join_links(Director::absoluteURL($this->link), $action); }
[ "public", "function", "Link", "(", "$", "action", "=", "null", ")", "{", "return", "Controller", "::", "join_links", "(", "Director", "::", "absoluteURL", "(", "$", "this", "->", "link", ")", ",", "$", "action", ")", ";", "}" ]
Get the URL of this feed @param string $action @return string Returns the URL of the feed.
[ "Get", "the", "URL", "of", "this", "feed" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/RSS/RSSFeed.php#L200-L203
train
silverstripe/silverstripe-framework
src/Control/RSS/RSSFeed.php
RSSFeed.outputToBrowser
public function outputToBrowser() { $prevState = SSViewer::config()->uninherited('source_file_comments'); SSViewer::config()->update('source_file_comments', false); $response = Controller::curr()->getResponse(); if (is_int($this->lastModified)) { HTTPCacheControlMiddleware::singleton()->registerModificationDate($this->lastModified); $response->addHeader("Last-Modified", gmdate("D, d M Y H:i:s", $this->lastModified) . ' GMT'); } if (!empty($this->etag)) { $response->addHeader('ETag', "\"{$this->etag}\""); } $response->addHeader("Content-Type", "application/rss+xml; charset=utf-8"); SSViewer::config()->update('source_file_comments', $prevState); return $this->renderWith($this->getTemplates()); }
php
public function outputToBrowser() { $prevState = SSViewer::config()->uninherited('source_file_comments'); SSViewer::config()->update('source_file_comments', false); $response = Controller::curr()->getResponse(); if (is_int($this->lastModified)) { HTTPCacheControlMiddleware::singleton()->registerModificationDate($this->lastModified); $response->addHeader("Last-Modified", gmdate("D, d M Y H:i:s", $this->lastModified) . ' GMT'); } if (!empty($this->etag)) { $response->addHeader('ETag', "\"{$this->etag}\""); } $response->addHeader("Content-Type", "application/rss+xml; charset=utf-8"); SSViewer::config()->update('source_file_comments', $prevState); return $this->renderWith($this->getTemplates()); }
[ "public", "function", "outputToBrowser", "(", ")", "{", "$", "prevState", "=", "SSViewer", "::", "config", "(", ")", "->", "uninherited", "(", "'source_file_comments'", ")", ";", "SSViewer", "::", "config", "(", ")", "->", "update", "(", "'source_file_comments'", ",", "false", ")", ";", "$", "response", "=", "Controller", "::", "curr", "(", ")", "->", "getResponse", "(", ")", ";", "if", "(", "is_int", "(", "$", "this", "->", "lastModified", ")", ")", "{", "HTTPCacheControlMiddleware", "::", "singleton", "(", ")", "->", "registerModificationDate", "(", "$", "this", "->", "lastModified", ")", ";", "$", "response", "->", "addHeader", "(", "\"Last-Modified\"", ",", "gmdate", "(", "\"D, d M Y H:i:s\"", ",", "$", "this", "->", "lastModified", ")", ".", "' GMT'", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "this", "->", "etag", ")", ")", "{", "$", "response", "->", "addHeader", "(", "'ETag'", ",", "\"\\\"{$this->etag}\\\"\"", ")", ";", "}", "$", "response", "->", "addHeader", "(", "\"Content-Type\"", ",", "\"application/rss+xml; charset=utf-8\"", ")", ";", "SSViewer", "::", "config", "(", ")", "->", "update", "(", "'source_file_comments'", ",", "$", "prevState", ")", ";", "return", "$", "this", "->", "renderWith", "(", "$", "this", "->", "getTemplates", "(", ")", ")", ";", "}" ]
Output the feed to the browser. TODO: Pass $response object to ->outputToBrowser() to loosen dependence on global state for easier testing/prototyping so dev can inject custom HTTPResponse instance. @return DBHTMLText
[ "Output", "the", "feed", "to", "the", "browser", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/RSS/RSSFeed.php#L222-L241
train
silverstripe/silverstripe-framework
src/Core/Startup/ParameterConfirmationToken.php
ParameterConfirmationToken.backURLToken
protected function backURLToken(HTTPRequest $request) { $backURL = $request->getVar('BackURL'); if (!strstr($backURL, '?')) { return null; } // Filter backURL if it contains the given request parameter list(,$query) = explode('?', $backURL); parse_str($query, $queryArgs); $name = $this->getName(); if (isset($queryArgs[$name])) { return $queryArgs[$name]; } return null; }
php
protected function backURLToken(HTTPRequest $request) { $backURL = $request->getVar('BackURL'); if (!strstr($backURL, '?')) { return null; } // Filter backURL if it contains the given request parameter list(,$query) = explode('?', $backURL); parse_str($query, $queryArgs); $name = $this->getName(); if (isset($queryArgs[$name])) { return $queryArgs[$name]; } return null; }
[ "protected", "function", "backURLToken", "(", "HTTPRequest", "$", "request", ")", "{", "$", "backURL", "=", "$", "request", "->", "getVar", "(", "'BackURL'", ")", ";", "if", "(", "!", "strstr", "(", "$", "backURL", ",", "'?'", ")", ")", "{", "return", "null", ";", "}", "// Filter backURL if it contains the given request parameter", "list", "(", ",", "$", "query", ")", "=", "explode", "(", "'?'", ",", "$", "backURL", ")", ";", "parse_str", "(", "$", "query", ",", "$", "queryArgs", ")", ";", "$", "name", "=", "$", "this", "->", "getName", "(", ")", ";", "if", "(", "isset", "(", "$", "queryArgs", "[", "$", "name", "]", ")", ")", "{", "return", "$", "queryArgs", "[", "$", "name", "]", ";", "}", "return", "null", ";", "}" ]
Check if this token exists in the BackURL @param HTTPRequest $request @return string Value of token in backurl, or null if not in backurl
[ "Check", "if", "this", "token", "exists", "in", "the", "BackURL" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Startup/ParameterConfirmationToken.php#L69-L84
train
silverstripe/silverstripe-framework
src/Dev/BulkLoader_Result.php
BulkLoader_Result.merge
public function merge(BulkLoader_Result $other) { $this->created = array_merge($this->created, $other->created); $this->updated = array_merge($this->updated, $other->updated); $this->deleted = array_merge($this->deleted, $other->deleted); }
php
public function merge(BulkLoader_Result $other) { $this->created = array_merge($this->created, $other->created); $this->updated = array_merge($this->updated, $other->updated); $this->deleted = array_merge($this->deleted, $other->deleted); }
[ "public", "function", "merge", "(", "BulkLoader_Result", "$", "other", ")", "{", "$", "this", "->", "created", "=", "array_merge", "(", "$", "this", "->", "created", ",", "$", "other", "->", "created", ")", ";", "$", "this", "->", "updated", "=", "array_merge", "(", "$", "this", "->", "updated", ",", "$", "other", "->", "updated", ")", ";", "$", "this", "->", "deleted", "=", "array_merge", "(", "$", "this", "->", "deleted", ",", "$", "other", "->", "deleted", ")", ";", "}" ]
Merges another BulkLoader_Result into this one. @param BulkLoader_Result $other
[ "Merges", "another", "BulkLoader_Result", "into", "this", "one", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/BulkLoader_Result.php#L198-L203
train
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/HTMLEditorField.php
HTMLEditorField.getEditorConfig
public function getEditorConfig() { // Instance override if ($this->editorConfig instanceof HTMLEditorConfig) { return $this->editorConfig; } // Get named / active config return HTMLEditorConfig::get($this->editorConfig); }
php
public function getEditorConfig() { // Instance override if ($this->editorConfig instanceof HTMLEditorConfig) { return $this->editorConfig; } // Get named / active config return HTMLEditorConfig::get($this->editorConfig); }
[ "public", "function", "getEditorConfig", "(", ")", "{", "// Instance override", "if", "(", "$", "this", "->", "editorConfig", "instanceof", "HTMLEditorConfig", ")", "{", "return", "$", "this", "->", "editorConfig", ";", "}", "// Get named / active config", "return", "HTMLEditorConfig", "::", "get", "(", "$", "this", "->", "editorConfig", ")", ";", "}" ]
Gets the HTMLEditorConfig instance @return HTMLEditorConfig
[ "Gets", "the", "HTMLEditorConfig", "instance" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/HTMLEditor/HTMLEditorField.php#L80-L89
train
silverstripe/silverstripe-framework
src/ORM/Connect/PDOConnector.php
PDOConnector.getOrPrepareStatement
public function getOrPrepareStatement($sql) { // Return cached statements if (isset($this->cachedStatements[$sql])) { return $this->cachedStatements[$sql]; } // Generate new statement $statement = $this->pdoConnection->prepare( $sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY) ); // Wrap in a PDOStatementHandle, to cache column metadata $statementHandle = ($statement === false) ? false : new PDOStatementHandle($statement); // Only cache select statements if (preg_match('/^(\s*)select\b/i', $sql)) { $this->cachedStatements[$sql] = $statementHandle; } return $statementHandle; }
php
public function getOrPrepareStatement($sql) { // Return cached statements if (isset($this->cachedStatements[$sql])) { return $this->cachedStatements[$sql]; } // Generate new statement $statement = $this->pdoConnection->prepare( $sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY) ); // Wrap in a PDOStatementHandle, to cache column metadata $statementHandle = ($statement === false) ? false : new PDOStatementHandle($statement); // Only cache select statements if (preg_match('/^(\s*)select\b/i', $sql)) { $this->cachedStatements[$sql] = $statementHandle; } return $statementHandle; }
[ "public", "function", "getOrPrepareStatement", "(", "$", "sql", ")", "{", "// Return cached statements", "if", "(", "isset", "(", "$", "this", "->", "cachedStatements", "[", "$", "sql", "]", ")", ")", "{", "return", "$", "this", "->", "cachedStatements", "[", "$", "sql", "]", ";", "}", "// Generate new statement", "$", "statement", "=", "$", "this", "->", "pdoConnection", "->", "prepare", "(", "$", "sql", ",", "array", "(", "PDO", "::", "ATTR_CURSOR", "=>", "PDO", "::", "CURSOR_FWDONLY", ")", ")", ";", "// Wrap in a PDOStatementHandle, to cache column metadata", "$", "statementHandle", "=", "(", "$", "statement", "===", "false", ")", "?", "false", ":", "new", "PDOStatementHandle", "(", "$", "statement", ")", ";", "// Only cache select statements", "if", "(", "preg_match", "(", "'/^(\\s*)select\\b/i'", ",", "$", "sql", ")", ")", "{", "$", "this", "->", "cachedStatements", "[", "$", "sql", "]", "=", "$", "statementHandle", ";", "}", "return", "$", "statementHandle", ";", "}" ]
Retrieve a prepared statement for a given SQL string, or return an already prepared version if one exists for the given query @param string $sql @return PDOStatementHandle|false
[ "Retrieve", "a", "prepared", "statement", "for", "a", "given", "SQL", "string", "or", "return", "an", "already", "prepared", "version", "if", "one", "exists", "for", "the", "given", "query" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/PDOConnector.php#L103-L124
train
silverstripe/silverstripe-framework
src/ORM/Connect/PDOConnector.php
PDOConnector.beforeQuery
protected function beforeQuery($sql) { // Reset state $this->rowCount = 0; $this->lastStatementError = null; // Flush if necessary if ($this->isQueryDDL($sql)) { $this->flushStatements(); } }
php
protected function beforeQuery($sql) { // Reset state $this->rowCount = 0; $this->lastStatementError = null; // Flush if necessary if ($this->isQueryDDL($sql)) { $this->flushStatements(); } }
[ "protected", "function", "beforeQuery", "(", "$", "sql", ")", "{", "// Reset state", "$", "this", "->", "rowCount", "=", "0", ";", "$", "this", "->", "lastStatementError", "=", "null", ";", "// Flush if necessary", "if", "(", "$", "this", "->", "isQueryDDL", "(", "$", "sql", ")", ")", "{", "$", "this", "->", "flushStatements", "(", ")", ";", "}", "}" ]
Invoked before any query is executed @param string $sql
[ "Invoked", "before", "any", "query", "is", "executed" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/PDOConnector.php#L293-L303
train
silverstripe/silverstripe-framework
src/ORM/Connect/PDOConnector.php
PDOConnector.exec
public function exec($sql, $errorLevel = E_USER_ERROR) { $this->beforeQuery($sql); // Directly exec this query $result = $this->pdoConnection->exec($sql); // Check for errors if ($result !== false) { return $this->rowCount = $result; } $this->databaseError($this->getLastError(), $errorLevel, $sql); return null; }
php
public function exec($sql, $errorLevel = E_USER_ERROR) { $this->beforeQuery($sql); // Directly exec this query $result = $this->pdoConnection->exec($sql); // Check for errors if ($result !== false) { return $this->rowCount = $result; } $this->databaseError($this->getLastError(), $errorLevel, $sql); return null; }
[ "public", "function", "exec", "(", "$", "sql", ",", "$", "errorLevel", "=", "E_USER_ERROR", ")", "{", "$", "this", "->", "beforeQuery", "(", "$", "sql", ")", ";", "// Directly exec this query", "$", "result", "=", "$", "this", "->", "pdoConnection", "->", "exec", "(", "$", "sql", ")", ";", "// Check for errors", "if", "(", "$", "result", "!==", "false", ")", "{", "return", "$", "this", "->", "rowCount", "=", "$", "result", ";", "}", "$", "this", "->", "databaseError", "(", "$", "this", "->", "getLastError", "(", ")", ",", "$", "errorLevel", ",", "$", "sql", ")", ";", "return", "null", ";", "}" ]
Executes a query that doesn't return a resultset @param string $sql The SQL query to execute @param integer $errorLevel For errors to this query, raise PHP errors using this error level. @return int
[ "Executes", "a", "query", "that", "doesn", "t", "return", "a", "resultset" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/PDOConnector.php#L313-L327
train
silverstripe/silverstripe-framework
src/ORM/Connect/PDOConnector.php
PDOConnector.bindParameters
public function bindParameters(PDOStatement $statement, $parameters) { // Bind all parameters $parameterCount = count($parameters); for ($index = 0; $index < $parameterCount; $index++) { $value = $parameters[$index]; $phpType = gettype($value); // Allow overriding of parameter type using an associative array if ($phpType === 'array') { $phpType = $value['type']; $value = $value['value']; } // Check type of parameter $type = $this->getPDOParamType($phpType); if ($type === PDO::PARAM_STR) { $value = (string) $value; } // Bind this value $statement->bindValue($index+1, $value, $type); } }
php
public function bindParameters(PDOStatement $statement, $parameters) { // Bind all parameters $parameterCount = count($parameters); for ($index = 0; $index < $parameterCount; $index++) { $value = $parameters[$index]; $phpType = gettype($value); // Allow overriding of parameter type using an associative array if ($phpType === 'array') { $phpType = $value['type']; $value = $value['value']; } // Check type of parameter $type = $this->getPDOParamType($phpType); if ($type === PDO::PARAM_STR) { $value = (string) $value; } // Bind this value $statement->bindValue($index+1, $value, $type); } }
[ "public", "function", "bindParameters", "(", "PDOStatement", "$", "statement", ",", "$", "parameters", ")", "{", "// Bind all parameters", "$", "parameterCount", "=", "count", "(", "$", "parameters", ")", ";", "for", "(", "$", "index", "=", "0", ";", "$", "index", "<", "$", "parameterCount", ";", "$", "index", "++", ")", "{", "$", "value", "=", "$", "parameters", "[", "$", "index", "]", ";", "$", "phpType", "=", "gettype", "(", "$", "value", ")", ";", "// Allow overriding of parameter type using an associative array", "if", "(", "$", "phpType", "===", "'array'", ")", "{", "$", "phpType", "=", "$", "value", "[", "'type'", "]", ";", "$", "value", "=", "$", "value", "[", "'value'", "]", ";", "}", "// Check type of parameter", "$", "type", "=", "$", "this", "->", "getPDOParamType", "(", "$", "phpType", ")", ";", "if", "(", "$", "type", "===", "PDO", "::", "PARAM_STR", ")", "{", "$", "value", "=", "(", "string", ")", "$", "value", ";", "}", "// Bind this value", "$", "statement", "->", "bindValue", "(", "$", "index", "+", "1", ",", "$", "value", ",", "$", "type", ")", ";", "}", "}" ]
Bind all parameters to a PDOStatement @param PDOStatement $statement @param array $parameters
[ "Bind", "all", "parameters", "to", "a", "PDOStatement" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/PDOConnector.php#L379-L402
train
silverstripe/silverstripe-framework
src/ORM/Connect/PDOConnector.php
PDOConnector.prepareResults
protected function prepareResults(PDOStatementHandle $statement, $errorLevel, $sql, $parameters = array()) { // Catch error if ($this->hasError($statement)) { $this->lastStatementError = $statement->errorInfo(); $statement->closeCursor(); $this->databaseError($this->getLastError(), $errorLevel, $sql, $this->parameterValues($parameters)); return null; } // Count and return results $this->rowCount = $statement->rowCount(); return new PDOQuery($statement); }
php
protected function prepareResults(PDOStatementHandle $statement, $errorLevel, $sql, $parameters = array()) { // Catch error if ($this->hasError($statement)) { $this->lastStatementError = $statement->errorInfo(); $statement->closeCursor(); $this->databaseError($this->getLastError(), $errorLevel, $sql, $this->parameterValues($parameters)); return null; } // Count and return results $this->rowCount = $statement->rowCount(); return new PDOQuery($statement); }
[ "protected", "function", "prepareResults", "(", "PDOStatementHandle", "$", "statement", ",", "$", "errorLevel", ",", "$", "sql", ",", "$", "parameters", "=", "array", "(", ")", ")", "{", "// Catch error", "if", "(", "$", "this", "->", "hasError", "(", "$", "statement", ")", ")", "{", "$", "this", "->", "lastStatementError", "=", "$", "statement", "->", "errorInfo", "(", ")", ";", "$", "statement", "->", "closeCursor", "(", ")", ";", "$", "this", "->", "databaseError", "(", "$", "this", "->", "getLastError", "(", ")", ",", "$", "errorLevel", ",", "$", "sql", ",", "$", "this", "->", "parameterValues", "(", "$", "parameters", ")", ")", ";", "return", "null", ";", "}", "// Count and return results", "$", "this", "->", "rowCount", "=", "$", "statement", "->", "rowCount", "(", ")", ";", "return", "new", "PDOQuery", "(", "$", "statement", ")", ";", "}" ]
Given a PDOStatement that has just been executed, generate results and report any errors @param PDOStatementHandle $statement @param int $errorLevel @param string $sql @param array $parameters @return PDOQuery
[ "Given", "a", "PDOStatement", "that", "has", "just", "been", "executed", "generate", "results", "and", "report", "any", "errors" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/PDOConnector.php#L435-L451
train
silverstripe/silverstripe-framework
src/ORM/Connect/PDOConnector.php
PDOConnector.hasError
protected function hasError($resource) { // No error if no resource if (empty($resource)) { return false; } // If the error code is empty the statement / connection has not been run yet $code = $resource->errorCode(); if (empty($code)) { return false; } // Skip 'ok' and undefined 'warning' types. // @see http://docstore.mik.ua/orelly/java-ent/jenut/ch08_06.htm return $code !== '00000' && $code !== '01000'; }
php
protected function hasError($resource) { // No error if no resource if (empty($resource)) { return false; } // If the error code is empty the statement / connection has not been run yet $code = $resource->errorCode(); if (empty($code)) { return false; } // Skip 'ok' and undefined 'warning' types. // @see http://docstore.mik.ua/orelly/java-ent/jenut/ch08_06.htm return $code !== '00000' && $code !== '01000'; }
[ "protected", "function", "hasError", "(", "$", "resource", ")", "{", "// No error if no resource", "if", "(", "empty", "(", "$", "resource", ")", ")", "{", "return", "false", ";", "}", "// If the error code is empty the statement / connection has not been run yet", "$", "code", "=", "$", "resource", "->", "errorCode", "(", ")", ";", "if", "(", "empty", "(", "$", "code", ")", ")", "{", "return", "false", ";", "}", "// Skip 'ok' and undefined 'warning' types.", "// @see http://docstore.mik.ua/orelly/java-ent/jenut/ch08_06.htm", "return", "$", "code", "!==", "'00000'", "&&", "$", "code", "!==", "'01000'", ";", "}" ]
Determine if a resource has an attached error @param PDOStatement|PDO $resource the resource to check @return boolean Flag indicating true if the resource has an error
[ "Determine", "if", "a", "resource", "has", "an", "attached", "error" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/PDOConnector.php#L459-L475
train
silverstripe/silverstripe-framework
src/Control/HTTPResponse.php
HTTPResponse.output
public function output() { // Attach appropriate X-Include-JavaScript and X-Include-CSS headers if (Director::is_ajax()) { Requirements::include_in_response($this); } if ($this->isRedirect() && headers_sent()) { $this->htmlRedirect(); } else { $this->outputHeaders(); $this->outputBody(); } }
php
public function output() { // Attach appropriate X-Include-JavaScript and X-Include-CSS headers if (Director::is_ajax()) { Requirements::include_in_response($this); } if ($this->isRedirect() && headers_sent()) { $this->htmlRedirect(); } else { $this->outputHeaders(); $this->outputBody(); } }
[ "public", "function", "output", "(", ")", "{", "// Attach appropriate X-Include-JavaScript and X-Include-CSS headers", "if", "(", "Director", "::", "is_ajax", "(", ")", ")", "{", "Requirements", "::", "include_in_response", "(", "$", "this", ")", ";", "}", "if", "(", "$", "this", "->", "isRedirect", "(", ")", "&&", "headers_sent", "(", ")", ")", "{", "$", "this", "->", "htmlRedirect", "(", ")", ";", "}", "else", "{", "$", "this", "->", "outputHeaders", "(", ")", ";", "$", "this", "->", "outputBody", "(", ")", ";", "}", "}" ]
Send this HTTPResponse to the browser
[ "Send", "this", "HTTPResponse", "to", "the", "browser" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/HTTPResponse.php#L333-L346
train
silverstripe/silverstripe-framework
src/Control/HTTPResponse.php
HTTPResponse.htmlRedirect
protected function htmlRedirect() { $headersSent = headers_sent($file, $line); $location = $this->getHeader('location'); $url = Director::absoluteURL($location); $urlATT = Convert::raw2htmlatt($url); $urlJS = Convert::raw2js($url); $title = (Director::isDev() && $headersSent) ? "{$urlATT}... (output started on {$file}, line {$line})" : "{$urlATT}..."; echo <<<EOT <p>Redirecting to <a href="{$urlATT}" title="Click this link if your browser does not redirect you">{$title}</a></p> <meta http-equiv="refresh" content="1; url={$urlATT}" /> <script type="application/javascript">setTimeout(function(){ window.location.href = "{$urlJS}"; }, 50);</script> EOT ; }
php
protected function htmlRedirect() { $headersSent = headers_sent($file, $line); $location = $this->getHeader('location'); $url = Director::absoluteURL($location); $urlATT = Convert::raw2htmlatt($url); $urlJS = Convert::raw2js($url); $title = (Director::isDev() && $headersSent) ? "{$urlATT}... (output started on {$file}, line {$line})" : "{$urlATT}..."; echo <<<EOT <p>Redirecting to <a href="{$urlATT}" title="Click this link if your browser does not redirect you">{$title}</a></p> <meta http-equiv="refresh" content="1; url={$urlATT}" /> <script type="application/javascript">setTimeout(function(){ window.location.href = "{$urlJS}"; }, 50);</script> EOT ; }
[ "protected", "function", "htmlRedirect", "(", ")", "{", "$", "headersSent", "=", "headers_sent", "(", "$", "file", ",", "$", "line", ")", ";", "$", "location", "=", "$", "this", "->", "getHeader", "(", "'location'", ")", ";", "$", "url", "=", "Director", "::", "absoluteURL", "(", "$", "location", ")", ";", "$", "urlATT", "=", "Convert", "::", "raw2htmlatt", "(", "$", "url", ")", ";", "$", "urlJS", "=", "Convert", "::", "raw2js", "(", "$", "url", ")", ";", "$", "title", "=", "(", "Director", "::", "isDev", "(", ")", "&&", "$", "headersSent", ")", "?", "\"{$urlATT}... (output started on {$file}, line {$line})\"", ":", "\"{$urlATT}...\"", ";", "echo", " <<<EOT\n<p>Redirecting to <a href=\"{$urlATT}\" title=\"Click this link if your browser does not redirect you\">{$title}</a></p>\n<meta http-equiv=\"refresh\" content=\"1; url={$urlATT}\" />\n<script type=\"application/javascript\">setTimeout(function(){\n\twindow.location.href = \"{$urlJS}\";\n}, 50);</script>\nEOT", ";", "}" ]
Generate a browser redirect without setting headers
[ "Generate", "a", "browser", "redirect", "without", "setting", "headers" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/HTTPResponse.php#L351-L369
train
silverstripe/silverstripe-framework
src/Control/HTTPResponse.php
HTTPResponse.outputHeaders
protected function outputHeaders() { $headersSent = headers_sent($file, $line); if (!$headersSent) { $method = sprintf( "%s %d %s", $_SERVER['SERVER_PROTOCOL'], $this->getStatusCode(), $this->getStatusDescription() ); header($method); foreach ($this->getHeaders() as $header => $value) { header("{$header}: {$value}", true, $this->getStatusCode()); } } elseif ($this->getStatusCode() >= 300) { // It's critical that these status codes are sent; we need to report a failure if not. user_error( sprintf( "Couldn't set response type to %d because of output on line %s of %s", $this->getStatusCode(), $line, $file ), E_USER_WARNING ); } }
php
protected function outputHeaders() { $headersSent = headers_sent($file, $line); if (!$headersSent) { $method = sprintf( "%s %d %s", $_SERVER['SERVER_PROTOCOL'], $this->getStatusCode(), $this->getStatusDescription() ); header($method); foreach ($this->getHeaders() as $header => $value) { header("{$header}: {$value}", true, $this->getStatusCode()); } } elseif ($this->getStatusCode() >= 300) { // It's critical that these status codes are sent; we need to report a failure if not. user_error( sprintf( "Couldn't set response type to %d because of output on line %s of %s", $this->getStatusCode(), $line, $file ), E_USER_WARNING ); } }
[ "protected", "function", "outputHeaders", "(", ")", "{", "$", "headersSent", "=", "headers_sent", "(", "$", "file", ",", "$", "line", ")", ";", "if", "(", "!", "$", "headersSent", ")", "{", "$", "method", "=", "sprintf", "(", "\"%s %d %s\"", ",", "$", "_SERVER", "[", "'SERVER_PROTOCOL'", "]", ",", "$", "this", "->", "getStatusCode", "(", ")", ",", "$", "this", "->", "getStatusDescription", "(", ")", ")", ";", "header", "(", "$", "method", ")", ";", "foreach", "(", "$", "this", "->", "getHeaders", "(", ")", "as", "$", "header", "=>", "$", "value", ")", "{", "header", "(", "\"{$header}: {$value}\"", ",", "true", ",", "$", "this", "->", "getStatusCode", "(", ")", ")", ";", "}", "}", "elseif", "(", "$", "this", "->", "getStatusCode", "(", ")", ">=", "300", ")", "{", "// It's critical that these status codes are sent; we need to report a failure if not.", "user_error", "(", "sprintf", "(", "\"Couldn't set response type to %d because of output on line %s of %s\"", ",", "$", "this", "->", "getStatusCode", "(", ")", ",", "$", "line", ",", "$", "file", ")", ",", "E_USER_WARNING", ")", ";", "}", "}" ]
Output HTTP headers to the browser
[ "Output", "HTTP", "headers", "to", "the", "browser" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/HTTPResponse.php#L374-L400
train
silverstripe/silverstripe-framework
src/Core/Manifest/ManifestFileFinder.php
ManifestFileFinder.isInsideVendor
public function isInsideVendor($basename, $pathname, $depth) { $base = basename($this->upLevels($pathname, $depth - 1)); return $base === self::VENDOR_DIR; }
php
public function isInsideVendor($basename, $pathname, $depth) { $base = basename($this->upLevels($pathname, $depth - 1)); return $base === self::VENDOR_DIR; }
[ "public", "function", "isInsideVendor", "(", "$", "basename", ",", "$", "pathname", ",", "$", "depth", ")", "{", "$", "base", "=", "basename", "(", "$", "this", "->", "upLevels", "(", "$", "pathname", ",", "$", "depth", "-", "1", ")", ")", ";", "return", "$", "base", "===", "self", "::", "VENDOR_DIR", ";", "}" ]
Check if the given dir is, or is inside the vendor folder @param string $basename @param string $pathname @param int $depth @return bool
[ "Check", "if", "the", "given", "dir", "is", "or", "is", "inside", "the", "vendor", "folder" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/ManifestFileFinder.php#L87-L91
train
silverstripe/silverstripe-framework
src/Core/Manifest/ManifestFileFinder.php
ManifestFileFinder.isInsideThemes
public function isInsideThemes($basename, $pathname, $depth) { $base = basename($this->upLevels($pathname, $depth - 1)); return $base === THEMES_DIR; }
php
public function isInsideThemes($basename, $pathname, $depth) { $base = basename($this->upLevels($pathname, $depth - 1)); return $base === THEMES_DIR; }
[ "public", "function", "isInsideThemes", "(", "$", "basename", ",", "$", "pathname", ",", "$", "depth", ")", "{", "$", "base", "=", "basename", "(", "$", "this", "->", "upLevels", "(", "$", "pathname", ",", "$", "depth", "-", "1", ")", ")", ";", "return", "$", "base", "===", "THEMES_DIR", ";", "}" ]
Check if the given dir is, or is inside the themes folder @param string $basename @param string $pathname @param int $depth @return bool
[ "Check", "if", "the", "given", "dir", "is", "or", "is", "inside", "the", "themes", "folder" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/ManifestFileFinder.php#L101-L105
train
silverstripe/silverstripe-framework
src/Core/Manifest/ManifestFileFinder.php
ManifestFileFinder.isInsideIgnored
public function isInsideIgnored($basename, $pathname, $depth) { return $this->anyParents($basename, $pathname, $depth, function ($basename, $pathname, $depth) { return $this->isDirectoryIgnored($basename, $pathname, $depth); }); }
php
public function isInsideIgnored($basename, $pathname, $depth) { return $this->anyParents($basename, $pathname, $depth, function ($basename, $pathname, $depth) { return $this->isDirectoryIgnored($basename, $pathname, $depth); }); }
[ "public", "function", "isInsideIgnored", "(", "$", "basename", ",", "$", "pathname", ",", "$", "depth", ")", "{", "return", "$", "this", "->", "anyParents", "(", "$", "basename", ",", "$", "pathname", ",", "$", "depth", ",", "function", "(", "$", "basename", ",", "$", "pathname", ",", "$", "depth", ")", "{", "return", "$", "this", "->", "isDirectoryIgnored", "(", "$", "basename", ",", "$", "pathname", ",", "$", "depth", ")", ";", "}", ")", ";", "}" ]
Check if this folder or any parent is ignored @param string $basename @param string $pathname @param int $depth @return bool
[ "Check", "if", "this", "folder", "or", "any", "parent", "is", "ignored" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/ManifestFileFinder.php#L115-L120
train
silverstripe/silverstripe-framework
src/Core/Manifest/ManifestFileFinder.php
ManifestFileFinder.isInsideModule
public function isInsideModule($basename, $pathname, $depth) { return $this->anyParents($basename, $pathname, $depth, function ($basename, $pathname, $depth) { return $this->isDirectoryModule($basename, $pathname, $depth); }); }
php
public function isInsideModule($basename, $pathname, $depth) { return $this->anyParents($basename, $pathname, $depth, function ($basename, $pathname, $depth) { return $this->isDirectoryModule($basename, $pathname, $depth); }); }
[ "public", "function", "isInsideModule", "(", "$", "basename", ",", "$", "pathname", ",", "$", "depth", ")", "{", "return", "$", "this", "->", "anyParents", "(", "$", "basename", ",", "$", "pathname", ",", "$", "depth", ",", "function", "(", "$", "basename", ",", "$", "pathname", ",", "$", "depth", ")", "{", "return", "$", "this", "->", "isDirectoryModule", "(", "$", "basename", ",", "$", "pathname", ",", "$", "depth", ")", ";", "}", ")", ";", "}" ]
Check if this folder is inside any module @param string $basename @param string $pathname @param int $depth @return bool
[ "Check", "if", "this", "folder", "is", "inside", "any", "module" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/ManifestFileFinder.php#L130-L135
train
silverstripe/silverstripe-framework
src/Core/Manifest/ManifestFileFinder.php
ManifestFileFinder.anyParents
protected function anyParents($basename, $pathname, $depth, $callback) { // Check all ignored dir up the path while ($depth >= 0) { $ignored = $callback($basename, $pathname, $depth); if ($ignored) { return true; } $pathname = dirname($pathname); $basename = basename($pathname); $depth--; } return false; }
php
protected function anyParents($basename, $pathname, $depth, $callback) { // Check all ignored dir up the path while ($depth >= 0) { $ignored = $callback($basename, $pathname, $depth); if ($ignored) { return true; } $pathname = dirname($pathname); $basename = basename($pathname); $depth--; } return false; }
[ "protected", "function", "anyParents", "(", "$", "basename", ",", "$", "pathname", ",", "$", "depth", ",", "$", "callback", ")", "{", "// Check all ignored dir up the path", "while", "(", "$", "depth", ">=", "0", ")", "{", "$", "ignored", "=", "$", "callback", "(", "$", "basename", ",", "$", "pathname", ",", "$", "depth", ")", ";", "if", "(", "$", "ignored", ")", "{", "return", "true", ";", "}", "$", "pathname", "=", "dirname", "(", "$", "pathname", ")", ";", "$", "basename", "=", "basename", "(", "$", "pathname", ")", ";", "$", "depth", "--", ";", "}", "return", "false", ";", "}" ]
Check if any parents match the given callback @param string $basename @param string $pathname @param int $depth @param callable $callback @return bool
[ "Check", "if", "any", "parents", "match", "the", "given", "callback" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/ManifestFileFinder.php#L146-L159
train
silverstripe/silverstripe-framework
src/Core/Manifest/ManifestFileFinder.php
ManifestFileFinder.upLevels
protected function upLevels($pathname, $depth) { if ($depth < 0) { return null; } while ($depth--) { $pathname = dirname($pathname); } return $pathname; }
php
protected function upLevels($pathname, $depth) { if ($depth < 0) { return null; } while ($depth--) { $pathname = dirname($pathname); } return $pathname; }
[ "protected", "function", "upLevels", "(", "$", "pathname", ",", "$", "depth", ")", "{", "if", "(", "$", "depth", "<", "0", ")", "{", "return", "null", ";", "}", "while", "(", "$", "depth", "--", ")", "{", "$", "pathname", "=", "dirname", "(", "$", "pathname", ")", ";", "}", "return", "$", "pathname", ";", "}" ]
Get a parent path the given levels above @param string $pathname @param int $depth Number of parents to rise @return string
[ "Get", "a", "parent", "path", "the", "given", "levels", "above" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/ManifestFileFinder.php#L197-L206
train
silverstripe/silverstripe-framework
src/Core/Manifest/ManifestFileFinder.php
ManifestFileFinder.getIgnoredDirs
protected function getIgnoredDirs() { $ignored = [self::LANG_DIR, 'node_modules']; if ($this->getOption('ignore_tests')) { $ignored[] = self::TESTS_DIR; } return $ignored; }
php
protected function getIgnoredDirs() { $ignored = [self::LANG_DIR, 'node_modules']; if ($this->getOption('ignore_tests')) { $ignored[] = self::TESTS_DIR; } return $ignored; }
[ "protected", "function", "getIgnoredDirs", "(", ")", "{", "$", "ignored", "=", "[", "self", "::", "LANG_DIR", ",", "'node_modules'", "]", ";", "if", "(", "$", "this", "->", "getOption", "(", "'ignore_tests'", ")", ")", "{", "$", "ignored", "[", "]", "=", "self", "::", "TESTS_DIR", ";", "}", "return", "$", "ignored", ";", "}" ]
Get all ignored directories @return array
[ "Get", "all", "ignored", "directories" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/ManifestFileFinder.php#L213-L220
train
silverstripe/silverstripe-framework
src/Core/Manifest/ManifestFileFinder.php
ManifestFileFinder.isDirectoryIgnored
public function isDirectoryIgnored($basename, $pathname, $depth) { // Don't ignore root if ($depth === 0) { return false; } // Check if manifest-ignored is present if (file_exists($pathname . '/' . self::EXCLUDE_FILE)) { return true; } // Check if directory name is ignored $ignored = $this->getIgnoredDirs(); if (in_array($basename, $ignored)) { return true; } // Ignore these dirs in the root only if ($depth === 1 && in_array($basename, [ASSETS_DIR, RESOURCES_DIR])) { return true; } return false; }
php
public function isDirectoryIgnored($basename, $pathname, $depth) { // Don't ignore root if ($depth === 0) { return false; } // Check if manifest-ignored is present if (file_exists($pathname . '/' . self::EXCLUDE_FILE)) { return true; } // Check if directory name is ignored $ignored = $this->getIgnoredDirs(); if (in_array($basename, $ignored)) { return true; } // Ignore these dirs in the root only if ($depth === 1 && in_array($basename, [ASSETS_DIR, RESOURCES_DIR])) { return true; } return false; }
[ "public", "function", "isDirectoryIgnored", "(", "$", "basename", ",", "$", "pathname", ",", "$", "depth", ")", "{", "// Don't ignore root", "if", "(", "$", "depth", "===", "0", ")", "{", "return", "false", ";", "}", "// Check if manifest-ignored is present", "if", "(", "file_exists", "(", "$", "pathname", ".", "'/'", ".", "self", "::", "EXCLUDE_FILE", ")", ")", "{", "return", "true", ";", "}", "// Check if directory name is ignored", "$", "ignored", "=", "$", "this", "->", "getIgnoredDirs", "(", ")", ";", "if", "(", "in_array", "(", "$", "basename", ",", "$", "ignored", ")", ")", "{", "return", "true", ";", "}", "// Ignore these dirs in the root only", "if", "(", "$", "depth", "===", "1", "&&", "in_array", "(", "$", "basename", ",", "[", "ASSETS_DIR", ",", "RESOURCES_DIR", "]", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Check if the given directory is ignored @param string $basename @param string $pathname @param string $depth @return bool
[ "Check", "if", "the", "given", "directory", "is", "ignored" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/ManifestFileFinder.php#L229-L253
train
silverstripe/silverstripe-framework
src/ORM/FieldType/DBDatetime.php
DBDatetime.Date
public function Date() { $formatter = $this->getFormatter(IntlDateFormatter::MEDIUM, IntlDateFormatter::NONE); return $formatter->format($this->getTimestamp()); }
php
public function Date() { $formatter = $this->getFormatter(IntlDateFormatter::MEDIUM, IntlDateFormatter::NONE); return $formatter->format($this->getTimestamp()); }
[ "public", "function", "Date", "(", ")", "{", "$", "formatter", "=", "$", "this", "->", "getFormatter", "(", "IntlDateFormatter", "::", "MEDIUM", ",", "IntlDateFormatter", "::", "NONE", ")", ";", "return", "$", "formatter", "->", "format", "(", "$", "this", "->", "getTimestamp", "(", ")", ")", ";", "}" ]
Returns the standard localised date @return string Formatted date.
[ "Returns", "the", "standard", "localised", "date" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBDatetime.php#L55-L59
train
silverstripe/silverstripe-framework
src/ORM/FieldType/DBDatetime.php
DBDatetime.FormatFromSettings
public function FormatFromSettings($member = null) { if (!$member) { $member = Security::getCurrentUser(); } // Fall back to nice if (!$member) { return $this->Nice(); } $dateFormat = $member->getDateFormat(); $timeFormat = $member->getTimeFormat(); // Get user format return $this->Format($dateFormat . ' ' . $timeFormat, $member->getLocale()); }
php
public function FormatFromSettings($member = null) { if (!$member) { $member = Security::getCurrentUser(); } // Fall back to nice if (!$member) { return $this->Nice(); } $dateFormat = $member->getDateFormat(); $timeFormat = $member->getTimeFormat(); // Get user format return $this->Format($dateFormat . ' ' . $timeFormat, $member->getLocale()); }
[ "public", "function", "FormatFromSettings", "(", "$", "member", "=", "null", ")", "{", "if", "(", "!", "$", "member", ")", "{", "$", "member", "=", "Security", "::", "getCurrentUser", "(", ")", ";", "}", "// Fall back to nice", "if", "(", "!", "$", "member", ")", "{", "return", "$", "this", "->", "Nice", "(", ")", ";", "}", "$", "dateFormat", "=", "$", "member", "->", "getDateFormat", "(", ")", ";", "$", "timeFormat", "=", "$", "member", "->", "getTimeFormat", "(", ")", ";", "// Get user format", "return", "$", "this", "->", "Format", "(", "$", "dateFormat", ".", "' '", ".", "$", "timeFormat", ",", "$", "member", "->", "getLocale", "(", ")", ")", ";", "}" ]
Return a date and time formatted as per a CMS user's settings. @param Member $member @return boolean | string A time and date pair formatted as per user-defined settings.
[ "Return", "a", "date", "and", "time", "formatted", "as", "per", "a", "CMS", "user", "s", "settings", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBDatetime.php#L98-L114
train
silverstripe/silverstripe-framework
src/View/ViewableData.php
ViewableData.setFailover
public function setFailover(ViewableData $failover) { // Ensure cached methods from previous failover are removed if ($this->failover) { $this->removeMethodsFrom('failover'); } $this->failover = $failover; $this->defineMethods(); }
php
public function setFailover(ViewableData $failover) { // Ensure cached methods from previous failover are removed if ($this->failover) { $this->removeMethodsFrom('failover'); } $this->failover = $failover; $this->defineMethods(); }
[ "public", "function", "setFailover", "(", "ViewableData", "$", "failover", ")", "{", "// Ensure cached methods from previous failover are removed", "if", "(", "$", "this", "->", "failover", ")", "{", "$", "this", "->", "removeMethodsFrom", "(", "'failover'", ")", ";", "}", "$", "this", "->", "failover", "=", "$", "failover", ";", "$", "this", "->", "defineMethods", "(", ")", ";", "}" ]
Set a failover object to attempt to get data from if it is not present on this object. @param ViewableData $failover
[ "Set", "a", "failover", "object", "to", "attempt", "to", "get", "data", "from", "if", "it", "is", "not", "present", "on", "this", "object", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/ViewableData.php#L167-L176
train
silverstripe/silverstripe-framework
src/View/ViewableData.php
ViewableData.escapeTypeForField
public function escapeTypeForField($field) { $class = $this->castingClass($field) ?: $this->config()->get('default_cast'); // TODO: It would be quicker not to instantiate the object, but to merely // get its class from the Injector /** @var DBField $type */ $type = Injector::inst()->get($class, true); return $type->config()->get('escape_type'); }
php
public function escapeTypeForField($field) { $class = $this->castingClass($field) ?: $this->config()->get('default_cast'); // TODO: It would be quicker not to instantiate the object, but to merely // get its class from the Injector /** @var DBField $type */ $type = Injector::inst()->get($class, true); return $type->config()->get('escape_type'); }
[ "public", "function", "escapeTypeForField", "(", "$", "field", ")", "{", "$", "class", "=", "$", "this", "->", "castingClass", "(", "$", "field", ")", "?", ":", "$", "this", "->", "config", "(", ")", "->", "get", "(", "'default_cast'", ")", ";", "// TODO: It would be quicker not to instantiate the object, but to merely", "// get its class from the Injector", "/** @var DBField $type */", "$", "type", "=", "Injector", "::", "inst", "(", ")", "->", "get", "(", "$", "class", ",", "true", ")", ";", "return", "$", "type", "->", "config", "(", ")", "->", "get", "(", "'escape_type'", ")", ";", "}" ]
Return the string-format type for the given field. @param string $field @return string 'xml'|'raw'
[ "Return", "the", "string", "-", "format", "type", "for", "the", "given", "field", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/ViewableData.php#L365-L374
train
silverstripe/silverstripe-framework
src/View/ViewableData.php
ViewableData.objCacheGet
protected function objCacheGet($key) { if (isset($this->objCache[$key])) { return $this->objCache[$key]; } return null; }
php
protected function objCacheGet($key) { if (isset($this->objCache[$key])) { return $this->objCache[$key]; } return null; }
[ "protected", "function", "objCacheGet", "(", "$", "key", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "objCache", "[", "$", "key", "]", ")", ")", "{", "return", "$", "this", "->", "objCache", "[", "$", "key", "]", ";", "}", "return", "null", ";", "}" ]
Get a cached value from the field cache @param string $key Cache key @return mixed
[ "Get", "a", "cached", "value", "from", "the", "field", "cache" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/ViewableData.php#L429-L435
train
silverstripe/silverstripe-framework
src/View/ViewableData.php
ViewableData.obj
public function obj($fieldName, $arguments = [], $cache = false, $cacheName = null) { if (!$cacheName && $cache) { $cacheName = $this->objCacheName($fieldName, $arguments); } // Check pre-cached value $value = $cache ? $this->objCacheGet($cacheName) : null; if ($value !== null) { return $value; } // Load value from record if ($this->hasMethod($fieldName)) { $value = call_user_func_array(array($this, $fieldName), $arguments ?: []); } else { $value = $this->$fieldName; } // Cast object if (!is_object($value)) { // Force cast $castingHelper = $this->castingHelper($fieldName); $valueObject = Injector::inst()->create($castingHelper, $fieldName); $valueObject->setValue($value, $this); $value = $valueObject; } // Record in cache if ($cache) { $this->objCacheSet($cacheName, $value); } return $value; }
php
public function obj($fieldName, $arguments = [], $cache = false, $cacheName = null) { if (!$cacheName && $cache) { $cacheName = $this->objCacheName($fieldName, $arguments); } // Check pre-cached value $value = $cache ? $this->objCacheGet($cacheName) : null; if ($value !== null) { return $value; } // Load value from record if ($this->hasMethod($fieldName)) { $value = call_user_func_array(array($this, $fieldName), $arguments ?: []); } else { $value = $this->$fieldName; } // Cast object if (!is_object($value)) { // Force cast $castingHelper = $this->castingHelper($fieldName); $valueObject = Injector::inst()->create($castingHelper, $fieldName); $valueObject->setValue($value, $this); $value = $valueObject; } // Record in cache if ($cache) { $this->objCacheSet($cacheName, $value); } return $value; }
[ "public", "function", "obj", "(", "$", "fieldName", ",", "$", "arguments", "=", "[", "]", ",", "$", "cache", "=", "false", ",", "$", "cacheName", "=", "null", ")", "{", "if", "(", "!", "$", "cacheName", "&&", "$", "cache", ")", "{", "$", "cacheName", "=", "$", "this", "->", "objCacheName", "(", "$", "fieldName", ",", "$", "arguments", ")", ";", "}", "// Check pre-cached value", "$", "value", "=", "$", "cache", "?", "$", "this", "->", "objCacheGet", "(", "$", "cacheName", ")", ":", "null", ";", "if", "(", "$", "value", "!==", "null", ")", "{", "return", "$", "value", ";", "}", "// Load value from record", "if", "(", "$", "this", "->", "hasMethod", "(", "$", "fieldName", ")", ")", "{", "$", "value", "=", "call_user_func_array", "(", "array", "(", "$", "this", ",", "$", "fieldName", ")", ",", "$", "arguments", "?", ":", "[", "]", ")", ";", "}", "else", "{", "$", "value", "=", "$", "this", "->", "$", "fieldName", ";", "}", "// Cast object", "if", "(", "!", "is_object", "(", "$", "value", ")", ")", "{", "// Force cast", "$", "castingHelper", "=", "$", "this", "->", "castingHelper", "(", "$", "fieldName", ")", ";", "$", "valueObject", "=", "Injector", "::", "inst", "(", ")", "->", "create", "(", "$", "castingHelper", ",", "$", "fieldName", ")", ";", "$", "valueObject", "->", "setValue", "(", "$", "value", ",", "$", "this", ")", ";", "$", "value", "=", "$", "valueObject", ";", "}", "// Record in cache", "if", "(", "$", "cache", ")", "{", "$", "this", "->", "objCacheSet", "(", "$", "cacheName", ",", "$", "value", ")", ";", "}", "return", "$", "value", ";", "}" ]
Get the value of a field on this object, automatically inserting the value into any available casting objects that have been specified. @param string $fieldName @param array $arguments @param bool $cache Cache this object @param string $cacheName a custom cache name @return Object|DBField
[ "Get", "the", "value", "of", "a", "field", "on", "this", "object", "automatically", "inserting", "the", "value", "into", "any", "available", "casting", "objects", "that", "have", "been", "specified", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/ViewableData.php#L471-L505
train
silverstripe/silverstripe-framework
src/View/ViewableData.php
ViewableData.XML_val
public function XML_val($field, $arguments = [], $cache = false) { $result = $this->obj($field, $arguments, $cache); // Might contain additional formatting over ->XML(). E.g. parse shortcodes, nl2br() return $result->forTemplate(); }
php
public function XML_val($field, $arguments = [], $cache = false) { $result = $this->obj($field, $arguments, $cache); // Might contain additional formatting over ->XML(). E.g. parse shortcodes, nl2br() return $result->forTemplate(); }
[ "public", "function", "XML_val", "(", "$", "field", ",", "$", "arguments", "=", "[", "]", ",", "$", "cache", "=", "false", ")", "{", "$", "result", "=", "$", "this", "->", "obj", "(", "$", "field", ",", "$", "arguments", ",", "$", "cache", ")", ";", "// Might contain additional formatting over ->XML(). E.g. parse shortcodes, nl2br()", "return", "$", "result", "->", "forTemplate", "(", ")", ";", "}" ]
Get the string value of a field on this object that has been suitable escaped to be inserted directly into a template. @param string $field @param array $arguments @param bool $cache @return string
[ "Get", "the", "string", "value", "of", "a", "field", "on", "this", "object", "that", "has", "been", "suitable", "escaped", "to", "be", "inserted", "directly", "into", "a", "template", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/ViewableData.php#L545-L550
train
silverstripe/silverstripe-framework
src/View/ViewableData.php
ViewableData.getXMLValues
public function getXMLValues($fields) { $result = []; foreach ($fields as $field) { $result[$field] = $this->XML_val($field); } return $result; }
php
public function getXMLValues($fields) { $result = []; foreach ($fields as $field) { $result[$field] = $this->XML_val($field); } return $result; }
[ "public", "function", "getXMLValues", "(", "$", "fields", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "fields", "as", "$", "field", ")", "{", "$", "result", "[", "$", "field", "]", "=", "$", "this", "->", "XML_val", "(", "$", "field", ")", ";", "}", "return", "$", "result", ";", "}" ]
Get an array of XML-escaped values by field name @param array $fields an array of field names @return array
[ "Get", "an", "array", "of", "XML", "-", "escaped", "values", "by", "field", "name" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/ViewableData.php#L558-L567
train
silverstripe/silverstripe-framework
src/View/ViewableData.php
ViewableData.CSSClasses
public function CSSClasses($stopAtClass = self::class) { $classes = []; $classAncestry = array_reverse(ClassInfo::ancestry(static::class)); $stopClasses = ClassInfo::ancestry($stopAtClass); foreach ($classAncestry as $class) { if (in_array($class, $stopClasses)) { break; } $classes[] = $class; } // optionally add template identifier if (isset($this->template) && !in_array($this->template, $classes)) { $classes[] = $this->template; } // Strip out namespaces $classes = preg_replace('#.*\\\\#', '', $classes); return Convert::raw2att(implode(' ', $classes)); }
php
public function CSSClasses($stopAtClass = self::class) { $classes = []; $classAncestry = array_reverse(ClassInfo::ancestry(static::class)); $stopClasses = ClassInfo::ancestry($stopAtClass); foreach ($classAncestry as $class) { if (in_array($class, $stopClasses)) { break; } $classes[] = $class; } // optionally add template identifier if (isset($this->template) && !in_array($this->template, $classes)) { $classes[] = $this->template; } // Strip out namespaces $classes = preg_replace('#.*\\\\#', '', $classes); return Convert::raw2att(implode(' ', $classes)); }
[ "public", "function", "CSSClasses", "(", "$", "stopAtClass", "=", "self", "::", "class", ")", "{", "$", "classes", "=", "[", "]", ";", "$", "classAncestry", "=", "array_reverse", "(", "ClassInfo", "::", "ancestry", "(", "static", "::", "class", ")", ")", ";", "$", "stopClasses", "=", "ClassInfo", "::", "ancestry", "(", "$", "stopAtClass", ")", ";", "foreach", "(", "$", "classAncestry", "as", "$", "class", ")", "{", "if", "(", "in_array", "(", "$", "class", ",", "$", "stopClasses", ")", ")", "{", "break", ";", "}", "$", "classes", "[", "]", "=", "$", "class", ";", "}", "// optionally add template identifier", "if", "(", "isset", "(", "$", "this", "->", "template", ")", "&&", "!", "in_array", "(", "$", "this", "->", "template", ",", "$", "classes", ")", ")", "{", "$", "classes", "[", "]", "=", "$", "this", "->", "template", ";", "}", "// Strip out namespaces", "$", "classes", "=", "preg_replace", "(", "'#.*\\\\\\\\#'", ",", "''", ",", "$", "classes", ")", ";", "return", "Convert", "::", "raw2att", "(", "implode", "(", "' '", ",", "$", "classes", ")", ")", ";", "}" ]
Get part of the current classes ancestry to be used as a CSS class. This method returns an escaped string of CSS classes representing the current classes ancestry until it hits a stop point - e.g. "Page DataObject ViewableData". @param string $stopAtClass the class to stop at (default: ViewableData) @return string @uses ClassInfo
[ "Get", "part", "of", "the", "current", "classes", "ancestry", "to", "be", "used", "as", "a", "CSS", "class", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/ViewableData.php#L647-L669
train
silverstripe/silverstripe-framework
src/Core/Config/Config.php
Config.modify
public static function modify() { $instance = static::inst(); if ($instance instanceof MutableConfigCollectionInterface) { return $instance; } // By default nested configs should become mutable $instance = static::nest(); if ($instance instanceof MutableConfigCollectionInterface) { return $instance; } throw new InvalidArgumentException("Nested config could not be made mutable"); }
php
public static function modify() { $instance = static::inst(); if ($instance instanceof MutableConfigCollectionInterface) { return $instance; } // By default nested configs should become mutable $instance = static::nest(); if ($instance instanceof MutableConfigCollectionInterface) { return $instance; } throw new InvalidArgumentException("Nested config could not be made mutable"); }
[ "public", "static", "function", "modify", "(", ")", "{", "$", "instance", "=", "static", "::", "inst", "(", ")", ";", "if", "(", "$", "instance", "instanceof", "MutableConfigCollectionInterface", ")", "{", "return", "$", "instance", ";", "}", "// By default nested configs should become mutable", "$", "instance", "=", "static", "::", "nest", "(", ")", ";", "if", "(", "$", "instance", "instanceof", "MutableConfigCollectionInterface", ")", "{", "return", "$", "instance", ";", "}", "throw", "new", "InvalidArgumentException", "(", "\"Nested config could not be made mutable\"", ")", ";", "}" ]
Make this config available to be modified @return MutableConfigCollectionInterface
[ "Make", "this", "config", "available", "to", "be", "modified" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Config/Config.php#L54-L68
train
silverstripe/silverstripe-framework
src/Core/Config/Config.php
Config.unnest
public static function unnest() { // Unnest unless we would be left at 0 manifests $loader = ConfigLoader::inst(); if ($loader->countManifests() <= 1) { user_error( "Unable to unnest root Config, please make sure you don't have mis-matched nest/unnest", E_USER_WARNING ); } else { $loader->popManifest(); } return static::inst(); }
php
public static function unnest() { // Unnest unless we would be left at 0 manifests $loader = ConfigLoader::inst(); if ($loader->countManifests() <= 1) { user_error( "Unable to unnest root Config, please make sure you don't have mis-matched nest/unnest", E_USER_WARNING ); } else { $loader->popManifest(); } return static::inst(); }
[ "public", "static", "function", "unnest", "(", ")", "{", "// Unnest unless we would be left at 0 manifests", "$", "loader", "=", "ConfigLoader", "::", "inst", "(", ")", ";", "if", "(", "$", "loader", "->", "countManifests", "(", ")", "<=", "1", ")", "{", "user_error", "(", "\"Unable to unnest root Config, please make sure you don't have mis-matched nest/unnest\"", ",", "E_USER_WARNING", ")", ";", "}", "else", "{", "$", "loader", "->", "popManifest", "(", ")", ";", "}", "return", "static", "::", "inst", "(", ")", ";", "}" ]
Change the active Config back to the Config instance the current active Config object was copied from. @return ConfigCollectionInterface
[ "Change", "the", "active", "Config", "back", "to", "the", "Config", "instance", "the", "current", "active", "Config", "object", "was", "copied", "from", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Config/Config.php#L94-L107
train
silverstripe/silverstripe-framework
src/Control/HTTPRequestBuilder.php
HTTPRequestBuilder.createFromEnvironment
public static function createFromEnvironment() { // Clean and update live global variables $variables = static::cleanEnvironment(Environment::getVariables()); Environment::setVariables($variables); // Currently necessary for SSViewer, etc to work // Health-check prior to creating environment return static::createFromVariables($variables, @file_get_contents('php://input')); }
php
public static function createFromEnvironment() { // Clean and update live global variables $variables = static::cleanEnvironment(Environment::getVariables()); Environment::setVariables($variables); // Currently necessary for SSViewer, etc to work // Health-check prior to creating environment return static::createFromVariables($variables, @file_get_contents('php://input')); }
[ "public", "static", "function", "createFromEnvironment", "(", ")", "{", "// Clean and update live global variables", "$", "variables", "=", "static", "::", "cleanEnvironment", "(", "Environment", "::", "getVariables", "(", ")", ")", ";", "Environment", "::", "setVariables", "(", "$", "variables", ")", ";", "// Currently necessary for SSViewer, etc to work", "// Health-check prior to creating environment", "return", "static", "::", "createFromVariables", "(", "$", "variables", ",", "@", "file_get_contents", "(", "'php://input'", ")", ")", ";", "}" ]
Create HTTPRequest instance from the current environment variables. May throw errors if request is invalid. @throws HTTPResponse_Exception @return HTTPRequest
[ "Create", "HTTPRequest", "instance", "from", "the", "current", "environment", "variables", ".", "May", "throw", "errors", "if", "request", "is", "invalid", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/HTTPRequestBuilder.php#L16-L24
train
silverstripe/silverstripe-framework
src/Control/HTTPRequestBuilder.php
HTTPRequestBuilder.createFromVariables
public static function createFromVariables(array $variables, $input, $url = null) { // Infer URL from REQUEST_URI unless explicitly provided if (!isset($url)) { // Remove query parameters (they're retained separately through $server['_GET'] $url = parse_url($variables['_SERVER']['REQUEST_URI'], PHP_URL_PATH); // Remove base folders from the URL if webroot is hosted in a subfolder if (substr(strtolower($url), 0, strlen(BASE_URL)) === strtolower(BASE_URL)) { $url = substr($url, strlen(BASE_URL)); } } // Build request $request = new HTTPRequest( $variables['_SERVER']['REQUEST_METHOD'], $url, $variables['_GET'], $variables['_POST'], $input ); // Set the scheme to HTTPS if needed if ((!empty($variables['_SERVER']['HTTPS']) && $variables['_SERVER']['HTTPS'] != 'off') || isset($variables['_SERVER']['SSL'])) { $request->setScheme('https'); } // Set the client IP if (!empty($variables['_SERVER']['REMOTE_ADDR'])) { $request->setIP($variables['_SERVER']['REMOTE_ADDR']); } // Add headers $headers = static::extractRequestHeaders($variables['_SERVER']); foreach ($headers as $header => $value) { $request->addHeader($header, $value); } // Initiate an empty session - doesn't initialize an actual PHP session (see HTTPApplication) $session = new Session(isset($variables['_SESSION']) ? $variables['_SESSION'] : null); $request->setSession($session); return $request; }
php
public static function createFromVariables(array $variables, $input, $url = null) { // Infer URL from REQUEST_URI unless explicitly provided if (!isset($url)) { // Remove query parameters (they're retained separately through $server['_GET'] $url = parse_url($variables['_SERVER']['REQUEST_URI'], PHP_URL_PATH); // Remove base folders from the URL if webroot is hosted in a subfolder if (substr(strtolower($url), 0, strlen(BASE_URL)) === strtolower(BASE_URL)) { $url = substr($url, strlen(BASE_URL)); } } // Build request $request = new HTTPRequest( $variables['_SERVER']['REQUEST_METHOD'], $url, $variables['_GET'], $variables['_POST'], $input ); // Set the scheme to HTTPS if needed if ((!empty($variables['_SERVER']['HTTPS']) && $variables['_SERVER']['HTTPS'] != 'off') || isset($variables['_SERVER']['SSL'])) { $request->setScheme('https'); } // Set the client IP if (!empty($variables['_SERVER']['REMOTE_ADDR'])) { $request->setIP($variables['_SERVER']['REMOTE_ADDR']); } // Add headers $headers = static::extractRequestHeaders($variables['_SERVER']); foreach ($headers as $header => $value) { $request->addHeader($header, $value); } // Initiate an empty session - doesn't initialize an actual PHP session (see HTTPApplication) $session = new Session(isset($variables['_SESSION']) ? $variables['_SESSION'] : null); $request->setSession($session); return $request; }
[ "public", "static", "function", "createFromVariables", "(", "array", "$", "variables", ",", "$", "input", ",", "$", "url", "=", "null", ")", "{", "// Infer URL from REQUEST_URI unless explicitly provided", "if", "(", "!", "isset", "(", "$", "url", ")", ")", "{", "// Remove query parameters (they're retained separately through $server['_GET']", "$", "url", "=", "parse_url", "(", "$", "variables", "[", "'_SERVER'", "]", "[", "'REQUEST_URI'", "]", ",", "PHP_URL_PATH", ")", ";", "// Remove base folders from the URL if webroot is hosted in a subfolder", "if", "(", "substr", "(", "strtolower", "(", "$", "url", ")", ",", "0", ",", "strlen", "(", "BASE_URL", ")", ")", "===", "strtolower", "(", "BASE_URL", ")", ")", "{", "$", "url", "=", "substr", "(", "$", "url", ",", "strlen", "(", "BASE_URL", ")", ")", ";", "}", "}", "// Build request", "$", "request", "=", "new", "HTTPRequest", "(", "$", "variables", "[", "'_SERVER'", "]", "[", "'REQUEST_METHOD'", "]", ",", "$", "url", ",", "$", "variables", "[", "'_GET'", "]", ",", "$", "variables", "[", "'_POST'", "]", ",", "$", "input", ")", ";", "// Set the scheme to HTTPS if needed", "if", "(", "(", "!", "empty", "(", "$", "variables", "[", "'_SERVER'", "]", "[", "'HTTPS'", "]", ")", "&&", "$", "variables", "[", "'_SERVER'", "]", "[", "'HTTPS'", "]", "!=", "'off'", ")", "||", "isset", "(", "$", "variables", "[", "'_SERVER'", "]", "[", "'SSL'", "]", ")", ")", "{", "$", "request", "->", "setScheme", "(", "'https'", ")", ";", "}", "// Set the client IP", "if", "(", "!", "empty", "(", "$", "variables", "[", "'_SERVER'", "]", "[", "'REMOTE_ADDR'", "]", ")", ")", "{", "$", "request", "->", "setIP", "(", "$", "variables", "[", "'_SERVER'", "]", "[", "'REMOTE_ADDR'", "]", ")", ";", "}", "// Add headers", "$", "headers", "=", "static", "::", "extractRequestHeaders", "(", "$", "variables", "[", "'_SERVER'", "]", ")", ";", "foreach", "(", "$", "headers", "as", "$", "header", "=>", "$", "value", ")", "{", "$", "request", "->", "addHeader", "(", "$", "header", ",", "$", "value", ")", ";", "}", "// Initiate an empty session - doesn't initialize an actual PHP session (see HTTPApplication)", "$", "session", "=", "new", "Session", "(", "isset", "(", "$", "variables", "[", "'_SESSION'", "]", ")", "?", "$", "variables", "[", "'_SESSION'", "]", ":", "null", ")", ";", "$", "request", "->", "setSession", "(", "$", "session", ")", ";", "return", "$", "request", ";", "}" ]
Build HTTPRequest from given variables @param array $variables @param string $input Request body @param string|null $url Provide specific url (relative to base) @return HTTPRequest
[ "Build", "HTTPRequest", "from", "given", "variables" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/HTTPRequestBuilder.php#L34-L78
train
silverstripe/silverstripe-framework
src/ORM/FieldType/DBText.php
DBText.LimitSentences
public function LimitSentences($maxSentences = 2) { if (!is_numeric($maxSentences)) { throw new InvalidArgumentException("Text::LimitSentence() expects one numeric argument"); } $value = $this->Plain(); if (!$value) { return ""; } // Do a word-search $words = preg_split('/\s+/u', $value); $sentences = 0; foreach ($words as $i => $word) { if (preg_match('/(!|\?|\.)$/', $word) && !preg_match('/(Dr|Mr|Mrs|Ms|Miss|Sr|Jr|No)\.$/i', $word)) { $sentences++; if ($sentences >= $maxSentences) { return implode(' ', array_slice($words, 0, $i + 1)); } } } // Failing to find the number of sentences requested, fallback to a logical default if ($maxSentences > 1) { return $value; } else { // If searching for a single sentence (and there are none) just do a text summary return $this->Summary(20); } }
php
public function LimitSentences($maxSentences = 2) { if (!is_numeric($maxSentences)) { throw new InvalidArgumentException("Text::LimitSentence() expects one numeric argument"); } $value = $this->Plain(); if (!$value) { return ""; } // Do a word-search $words = preg_split('/\s+/u', $value); $sentences = 0; foreach ($words as $i => $word) { if (preg_match('/(!|\?|\.)$/', $word) && !preg_match('/(Dr|Mr|Mrs|Ms|Miss|Sr|Jr|No)\.$/i', $word)) { $sentences++; if ($sentences >= $maxSentences) { return implode(' ', array_slice($words, 0, $i + 1)); } } } // Failing to find the number of sentences requested, fallback to a logical default if ($maxSentences > 1) { return $value; } else { // If searching for a single sentence (and there are none) just do a text summary return $this->Summary(20); } }
[ "public", "function", "LimitSentences", "(", "$", "maxSentences", "=", "2", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "maxSentences", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Text::LimitSentence() expects one numeric argument\"", ")", ";", "}", "$", "value", "=", "$", "this", "->", "Plain", "(", ")", ";", "if", "(", "!", "$", "value", ")", "{", "return", "\"\"", ";", "}", "// Do a word-search", "$", "words", "=", "preg_split", "(", "'/\\s+/u'", ",", "$", "value", ")", ";", "$", "sentences", "=", "0", ";", "foreach", "(", "$", "words", "as", "$", "i", "=>", "$", "word", ")", "{", "if", "(", "preg_match", "(", "'/(!|\\?|\\.)$/'", ",", "$", "word", ")", "&&", "!", "preg_match", "(", "'/(Dr|Mr|Mrs|Ms|Miss|Sr|Jr|No)\\.$/i'", ",", "$", "word", ")", ")", "{", "$", "sentences", "++", ";", "if", "(", "$", "sentences", ">=", "$", "maxSentences", ")", "{", "return", "implode", "(", "' '", ",", "array_slice", "(", "$", "words", ",", "0", ",", "$", "i", "+", "1", ")", ")", ";", "}", "}", "}", "// Failing to find the number of sentences requested, fallback to a logical default", "if", "(", "$", "maxSentences", ">", "1", ")", "{", "return", "$", "value", ";", "}", "else", "{", "// If searching for a single sentence (and there are none) just do a text summary", "return", "$", "this", "->", "Summary", "(", "20", ")", ";", "}", "}" ]
Limit sentences, can be controlled by passing an integer. @param int $maxSentences The amount of sentences you want. @return string
[ "Limit", "sentences", "can", "be", "controlled", "by", "passing", "an", "integer", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBText.php#L71-L101
train
silverstripe/silverstripe-framework
src/ORM/FieldType/DBText.php
DBText.Summary
public function Summary($maxWords = 50, $add = '...') { // Get plain-text version $value = $this->Plain(); if (!$value) { return ''; } // Split on sentences (don't remove period) $sentences = array_filter(array_map(function ($str) { return trim($str); }, preg_split('@(?<=\.)@', $value))); $wordCount = count(preg_split('#\s+#u', $sentences[0])); // if the first sentence is too long, show only the first $maxWords words if ($wordCount > $maxWords) { return implode(' ', array_slice(explode(' ', $sentences[0]), 0, $maxWords)) . $add; } // add each sentence while there are enough words to do so $result = ''; do { // Add next sentence $result .= ' ' . array_shift($sentences); // If more sentences to process, count number of words if ($sentences) { $wordCount += count(preg_split('#\s+#u', $sentences[0])); } } while ($wordCount < $maxWords && $sentences && trim($sentences[0])); return trim($result); }
php
public function Summary($maxWords = 50, $add = '...') { // Get plain-text version $value = $this->Plain(); if (!$value) { return ''; } // Split on sentences (don't remove period) $sentences = array_filter(array_map(function ($str) { return trim($str); }, preg_split('@(?<=\.)@', $value))); $wordCount = count(preg_split('#\s+#u', $sentences[0])); // if the first sentence is too long, show only the first $maxWords words if ($wordCount > $maxWords) { return implode(' ', array_slice(explode(' ', $sentences[0]), 0, $maxWords)) . $add; } // add each sentence while there are enough words to do so $result = ''; do { // Add next sentence $result .= ' ' . array_shift($sentences); // If more sentences to process, count number of words if ($sentences) { $wordCount += count(preg_split('#\s+#u', $sentences[0])); } } while ($wordCount < $maxWords && $sentences && trim($sentences[0])); return trim($result); }
[ "public", "function", "Summary", "(", "$", "maxWords", "=", "50", ",", "$", "add", "=", "'...'", ")", "{", "// Get plain-text version", "$", "value", "=", "$", "this", "->", "Plain", "(", ")", ";", "if", "(", "!", "$", "value", ")", "{", "return", "''", ";", "}", "// Split on sentences (don't remove period)", "$", "sentences", "=", "array_filter", "(", "array_map", "(", "function", "(", "$", "str", ")", "{", "return", "trim", "(", "$", "str", ")", ";", "}", ",", "preg_split", "(", "'@(?<=\\.)@'", ",", "$", "value", ")", ")", ")", ";", "$", "wordCount", "=", "count", "(", "preg_split", "(", "'#\\s+#u'", ",", "$", "sentences", "[", "0", "]", ")", ")", ";", "// if the first sentence is too long, show only the first $maxWords words", "if", "(", "$", "wordCount", ">", "$", "maxWords", ")", "{", "return", "implode", "(", "' '", ",", "array_slice", "(", "explode", "(", "' '", ",", "$", "sentences", "[", "0", "]", ")", ",", "0", ",", "$", "maxWords", ")", ")", ".", "$", "add", ";", "}", "// add each sentence while there are enough words to do so", "$", "result", "=", "''", ";", "do", "{", "// Add next sentence", "$", "result", ".=", "' '", ".", "array_shift", "(", "$", "sentences", ")", ";", "// If more sentences to process, count number of words", "if", "(", "$", "sentences", ")", "{", "$", "wordCount", "+=", "count", "(", "preg_split", "(", "'#\\s+#u'", ",", "$", "sentences", "[", "0", "]", ")", ")", ";", "}", "}", "while", "(", "$", "wordCount", "<", "$", "maxWords", "&&", "$", "sentences", "&&", "trim", "(", "$", "sentences", "[", "0", "]", ")", ")", ";", "return", "trim", "(", "$", "result", ")", ";", "}" ]
Builds a basic summary, up to a maximum number of words @param int $maxWords @param string $add @return string
[ "Builds", "a", "basic", "summary", "up", "to", "a", "maximum", "number", "of", "words" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBText.php#L121-L153
train
silverstripe/silverstripe-framework
src/ORM/FieldType/DBText.php
DBText.FirstParagraph
public function FirstParagraph() { $value = $this->Plain(); if (empty($value)) { return ''; } // Split paragraphs and return first $paragraphs = preg_split('#\n{2,}#', $value); return reset($paragraphs); }
php
public function FirstParagraph() { $value = $this->Plain(); if (empty($value)) { return ''; } // Split paragraphs and return first $paragraphs = preg_split('#\n{2,}#', $value); return reset($paragraphs); }
[ "public", "function", "FirstParagraph", "(", ")", "{", "$", "value", "=", "$", "this", "->", "Plain", "(", ")", ";", "if", "(", "empty", "(", "$", "value", ")", ")", "{", "return", "''", ";", "}", "// Split paragraphs and return first", "$", "paragraphs", "=", "preg_split", "(", "'#\\n{2,}#'", ",", "$", "value", ")", ";", "return", "reset", "(", "$", "paragraphs", ")", ";", "}" ]
Get first paragraph @return string
[ "Get", "first", "paragraph" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBText.php#L160-L170
train
silverstripe/silverstripe-framework
src/ORM/FieldType/DBText.php
DBText.ContextSummary
public function ContextSummary( $characters = 500, $keywords = null, $highlight = true, $prefix = "... ", $suffix = "..." ) { if (!$keywords) { // Use the default "Search" request variable (from SearchForm) $keywords = isset($_REQUEST['Search']) ? $_REQUEST['Search'] : ''; } // Get raw text value, but XML encode it (as we'll be merging with HTML tags soon) $text = nl2br(Convert::raw2xml($this->Plain())); $keywords = Convert::raw2xml($keywords); // Find the search string $position = empty($keywords) ? 0 : (int) mb_stripos($text, $keywords); // We want to search string to be in the middle of our block to give it some context $position = max(0, $position - ($characters / 2)); if ($position > 0) { // We don't want to start mid-word $position = max( (int) mb_strrpos(mb_substr($text, 0, $position), ' '), (int) mb_strrpos(mb_substr($text, 0, $position), "\n") ); } $summary = mb_substr($text, $position, $characters); $stringPieces = explode(' ', $keywords); if ($highlight) { // Add a span around all key words from the search term as well if ($stringPieces) { foreach ($stringPieces as $stringPiece) { if (mb_strlen($stringPiece) > 2) { // Maintain case of original string $summary = preg_replace( '/' . preg_quote($stringPiece, '/') . '/i', '<mark>$0</mark>', $summary ); } } } } $summary = trim($summary); // Add leading / trailing '...' if trimmed on either end if ($position > 0) { $summary = $prefix . $summary; } if (strlen($text) > ($characters + $position)) { $summary = $summary . $suffix; } return $summary; }
php
public function ContextSummary( $characters = 500, $keywords = null, $highlight = true, $prefix = "... ", $suffix = "..." ) { if (!$keywords) { // Use the default "Search" request variable (from SearchForm) $keywords = isset($_REQUEST['Search']) ? $_REQUEST['Search'] : ''; } // Get raw text value, but XML encode it (as we'll be merging with HTML tags soon) $text = nl2br(Convert::raw2xml($this->Plain())); $keywords = Convert::raw2xml($keywords); // Find the search string $position = empty($keywords) ? 0 : (int) mb_stripos($text, $keywords); // We want to search string to be in the middle of our block to give it some context $position = max(0, $position - ($characters / 2)); if ($position > 0) { // We don't want to start mid-word $position = max( (int) mb_strrpos(mb_substr($text, 0, $position), ' '), (int) mb_strrpos(mb_substr($text, 0, $position), "\n") ); } $summary = mb_substr($text, $position, $characters); $stringPieces = explode(' ', $keywords); if ($highlight) { // Add a span around all key words from the search term as well if ($stringPieces) { foreach ($stringPieces as $stringPiece) { if (mb_strlen($stringPiece) > 2) { // Maintain case of original string $summary = preg_replace( '/' . preg_quote($stringPiece, '/') . '/i', '<mark>$0</mark>', $summary ); } } } } $summary = trim($summary); // Add leading / trailing '...' if trimmed on either end if ($position > 0) { $summary = $prefix . $summary; } if (strlen($text) > ($characters + $position)) { $summary = $summary . $suffix; } return $summary; }
[ "public", "function", "ContextSummary", "(", "$", "characters", "=", "500", ",", "$", "keywords", "=", "null", ",", "$", "highlight", "=", "true", ",", "$", "prefix", "=", "\"... \"", ",", "$", "suffix", "=", "\"...\"", ")", "{", "if", "(", "!", "$", "keywords", ")", "{", "// Use the default \"Search\" request variable (from SearchForm)", "$", "keywords", "=", "isset", "(", "$", "_REQUEST", "[", "'Search'", "]", ")", "?", "$", "_REQUEST", "[", "'Search'", "]", ":", "''", ";", "}", "// Get raw text value, but XML encode it (as we'll be merging with HTML tags soon)", "$", "text", "=", "nl2br", "(", "Convert", "::", "raw2xml", "(", "$", "this", "->", "Plain", "(", ")", ")", ")", ";", "$", "keywords", "=", "Convert", "::", "raw2xml", "(", "$", "keywords", ")", ";", "// Find the search string", "$", "position", "=", "empty", "(", "$", "keywords", ")", "?", "0", ":", "(", "int", ")", "mb_stripos", "(", "$", "text", ",", "$", "keywords", ")", ";", "// We want to search string to be in the middle of our block to give it some context", "$", "position", "=", "max", "(", "0", ",", "$", "position", "-", "(", "$", "characters", "/", "2", ")", ")", ";", "if", "(", "$", "position", ">", "0", ")", "{", "// We don't want to start mid-word", "$", "position", "=", "max", "(", "(", "int", ")", "mb_strrpos", "(", "mb_substr", "(", "$", "text", ",", "0", ",", "$", "position", ")", ",", "' '", ")", ",", "(", "int", ")", "mb_strrpos", "(", "mb_substr", "(", "$", "text", ",", "0", ",", "$", "position", ")", ",", "\"\\n\"", ")", ")", ";", "}", "$", "summary", "=", "mb_substr", "(", "$", "text", ",", "$", "position", ",", "$", "characters", ")", ";", "$", "stringPieces", "=", "explode", "(", "' '", ",", "$", "keywords", ")", ";", "if", "(", "$", "highlight", ")", "{", "// Add a span around all key words from the search term as well", "if", "(", "$", "stringPieces", ")", "{", "foreach", "(", "$", "stringPieces", "as", "$", "stringPiece", ")", "{", "if", "(", "mb_strlen", "(", "$", "stringPiece", ")", ">", "2", ")", "{", "// Maintain case of original string", "$", "summary", "=", "preg_replace", "(", "'/'", ".", "preg_quote", "(", "$", "stringPiece", ",", "'/'", ")", ".", "'/i'", ",", "'<mark>$0</mark>'", ",", "$", "summary", ")", ";", "}", "}", "}", "}", "$", "summary", "=", "trim", "(", "$", "summary", ")", ";", "// Add leading / trailing '...' if trimmed on either end", "if", "(", "$", "position", ">", "0", ")", "{", "$", "summary", "=", "$", "prefix", ".", "$", "summary", ";", "}", "if", "(", "strlen", "(", "$", "text", ")", ">", "(", "$", "characters", "+", "$", "position", ")", ")", "{", "$", "summary", "=", "$", "summary", ".", "$", "suffix", ";", "}", "return", "$", "summary", ";", "}" ]
Perform context searching to give some context to searches, optionally highlighting the search term. @param int $characters Number of characters in the summary @param string $keywords Supplied string ("keywords"). Will fall back to 'Search' querystring arg. @param bool $highlight Add a highlight <mark> element around search query? @param string $prefix Prefix text @param string $suffix Suffix text @return string HTML string with context
[ "Perform", "context", "searching", "to", "give", "some", "context", "to", "searches", "optionally", "highlighting", "the", "search", "term", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBText.php#L183-L243
train
silverstripe/silverstripe-framework
src/Control/Email/Email.php
Email.mergeConfiguredEmails
protected static function mergeConfiguredEmails($config, $env) { // Normalise config list $normalised = []; $source = (array)static::config()->get($config); foreach ($source as $address => $name) { if ($address && !is_numeric($address)) { $normalised[$address] = $name; } elseif ($name) { $normalised[$name] = null; } } $extra = Environment::getEnv($env); if ($extra) { $normalised[$extra] = null; } return $normalised; }
php
protected static function mergeConfiguredEmails($config, $env) { // Normalise config list $normalised = []; $source = (array)static::config()->get($config); foreach ($source as $address => $name) { if ($address && !is_numeric($address)) { $normalised[$address] = $name; } elseif ($name) { $normalised[$name] = null; } } $extra = Environment::getEnv($env); if ($extra) { $normalised[$extra] = null; } return $normalised; }
[ "protected", "static", "function", "mergeConfiguredEmails", "(", "$", "config", ",", "$", "env", ")", "{", "// Normalise config list", "$", "normalised", "=", "[", "]", ";", "$", "source", "=", "(", "array", ")", "static", "::", "config", "(", ")", "->", "get", "(", "$", "config", ")", ";", "foreach", "(", "$", "source", "as", "$", "address", "=>", "$", "name", ")", "{", "if", "(", "$", "address", "&&", "!", "is_numeric", "(", "$", "address", ")", ")", "{", "$", "normalised", "[", "$", "address", "]", "=", "$", "name", ";", "}", "elseif", "(", "$", "name", ")", "{", "$", "normalised", "[", "$", "name", "]", "=", "null", ";", "}", "}", "$", "extra", "=", "Environment", "::", "getEnv", "(", "$", "env", ")", ";", "if", "(", "$", "extra", ")", "{", "$", "normalised", "[", "$", "extra", "]", "=", "null", ";", "}", "return", "$", "normalised", ";", "}" ]
Normalise email list from config merged with env vars @param string $config Config key @param string $env Env variable key @return array Array of email addresses
[ "Normalise", "email", "list", "from", "config", "merged", "with", "env", "vars" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Email/Email.php#L151-L168
train
silverstripe/silverstripe-framework
src/Control/Email/Email.php
Email.obfuscate
public static function obfuscate($email, $method = 'visible') { switch ($method) { case 'direction': Requirements::customCSS('span.codedirection { unicode-bidi: bidi-override; direction: rtl; }', 'codedirectionCSS'); return '<span class="codedirection">' . strrev($email) . '</span>'; case 'visible': $obfuscated = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] '); return strtr($email, $obfuscated); case 'hex': $encoded = ''; for ($x = 0; $x < strlen($email); $x++) { $encoded .= '&#x' . bin2hex($email{$x}) . ';'; } return $encoded; default: user_error('Email::obfuscate(): Unknown obfuscation method', E_USER_NOTICE); return $email; } }
php
public static function obfuscate($email, $method = 'visible') { switch ($method) { case 'direction': Requirements::customCSS('span.codedirection { unicode-bidi: bidi-override; direction: rtl; }', 'codedirectionCSS'); return '<span class="codedirection">' . strrev($email) . '</span>'; case 'visible': $obfuscated = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] '); return strtr($email, $obfuscated); case 'hex': $encoded = ''; for ($x = 0; $x < strlen($email); $x++) { $encoded .= '&#x' . bin2hex($email{$x}) . ';'; } return $encoded; default: user_error('Email::obfuscate(): Unknown obfuscation method', E_USER_NOTICE); return $email; } }
[ "public", "static", "function", "obfuscate", "(", "$", "email", ",", "$", "method", "=", "'visible'", ")", "{", "switch", "(", "$", "method", ")", "{", "case", "'direction'", ":", "Requirements", "::", "customCSS", "(", "'span.codedirection { unicode-bidi: bidi-override; direction: rtl; }'", ",", "'codedirectionCSS'", ")", ";", "return", "'<span class=\"codedirection\">'", ".", "strrev", "(", "$", "email", ")", ".", "'</span>'", ";", "case", "'visible'", ":", "$", "obfuscated", "=", "array", "(", "'@'", "=>", "' [at] '", ",", "'.'", "=>", "' [dot] '", ",", "'-'", "=>", "' [dash] '", ")", ";", "return", "strtr", "(", "$", "email", ",", "$", "obfuscated", ")", ";", "case", "'hex'", ":", "$", "encoded", "=", "''", ";", "for", "(", "$", "x", "=", "0", ";", "$", "x", "<", "strlen", "(", "$", "email", ")", ";", "$", "x", "++", ")", "{", "$", "encoded", ".=", "'&#x'", ".", "bin2hex", "(", "$", "email", "{", "$", "x", "}", ")", ".", "';'", ";", "}", "return", "$", "encoded", ";", "default", ":", "user_error", "(", "'Email::obfuscate(): Unknown obfuscation method'", ",", "E_USER_NOTICE", ")", ";", "return", "$", "email", ";", "}", "}" ]
Encode an email-address to protect it from spambots. At the moment only simple string substitutions, which are not 100% safe from email harvesting. @param string $email Email-address @param string $method Method for obfuscating/encoding the address - 'direction': Reverse the text and then use CSS to put the text direction back to normal - 'visible': Simple string substitution ('@' to '[at]', '.' to '[dot], '-' to [dash]) - 'hex': Hexadecimal URL-Encoding - useful for mailto: links @return string
[ "Encode", "an", "email", "-", "address", "to", "protect", "it", "from", "spambots", ".", "At", "the", "moment", "only", "simple", "string", "substitutions", "which", "are", "not", "100%", "safe", "from", "email", "harvesting", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Email/Email.php#L182-L205
train
silverstripe/silverstripe-framework
src/Control/Email/Email.php
Email.removeData
public function removeData($name) { if (is_array($this->data)) { unset($this->data[$name]); } else { $this->data->$name = null; } return $this; }
php
public function removeData($name) { if (is_array($this->data)) { unset($this->data[$name]); } else { $this->data->$name = null; } return $this; }
[ "public", "function", "removeData", "(", "$", "name", ")", "{", "if", "(", "is_array", "(", "$", "this", "->", "data", ")", ")", "{", "unset", "(", "$", "this", "->", "data", "[", "$", "name", "]", ")", ";", "}", "else", "{", "$", "this", "->", "data", "->", "$", "name", "=", "null", ";", "}", "return", "$", "this", ";", "}" ]
Remove a datum from the message @param string $name @return $this
[ "Remove", "a", "datum", "from", "the", "message" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Email/Email.php#L599-L608
train
silverstripe/silverstripe-framework
src/Control/Email/Email.php
Email.setHTMLTemplate
public function setHTMLTemplate($template) { if (substr($template, -3) == '.ss') { $template = substr($template, 0, -3); } $this->HTMLTemplate = $template; return $this; }
php
public function setHTMLTemplate($template) { if (substr($template, -3) == '.ss') { $template = substr($template, 0, -3); } $this->HTMLTemplate = $template; return $this; }
[ "public", "function", "setHTMLTemplate", "(", "$", "template", ")", "{", "if", "(", "substr", "(", "$", "template", ",", "-", "3", ")", "==", "'.ss'", ")", "{", "$", "template", "=", "substr", "(", "$", "template", ",", "0", ",", "-", "3", ")", ";", "}", "$", "this", "->", "HTMLTemplate", "=", "$", "template", ";", "return", "$", "this", ";", "}" ]
Set the template to render the email with @param string $template @return $this
[ "Set", "the", "template", "to", "render", "the", "email", "with" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Email/Email.php#L678-L686
train
silverstripe/silverstripe-framework
src/Control/Email/Email.php
Email.setPlainTemplate
public function setPlainTemplate($template) { if (substr($template, -3) == '.ss') { $template = substr($template, 0, -3); } $this->plainTemplate = $template; return $this; }
php
public function setPlainTemplate($template) { if (substr($template, -3) == '.ss') { $template = substr($template, 0, -3); } $this->plainTemplate = $template; return $this; }
[ "public", "function", "setPlainTemplate", "(", "$", "template", ")", "{", "if", "(", "substr", "(", "$", "template", ",", "-", "3", ")", "==", "'.ss'", ")", "{", "$", "template", "=", "substr", "(", "$", "template", ",", "0", ",", "-", "3", ")", ";", "}", "$", "this", "->", "plainTemplate", "=", "$", "template", ";", "return", "$", "this", ";", "}" ]
Set the template to render the plain part with @param string $template @return $this
[ "Set", "the", "template", "to", "render", "the", "plain", "part", "with" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Email/Email.php#L704-L712
train
silverstripe/silverstripe-framework
src/Control/Email/Email.php
Email.send
public function send() { if (!$this->getBody()) { $this->render(); } if (!$this->hasPlainPart()) { $this->generatePlainPartFromBody(); } return Injector::inst()->get(Mailer::class)->send($this); }
php
public function send() { if (!$this->getBody()) { $this->render(); } if (!$this->hasPlainPart()) { $this->generatePlainPartFromBody(); } return Injector::inst()->get(Mailer::class)->send($this); }
[ "public", "function", "send", "(", ")", "{", "if", "(", "!", "$", "this", "->", "getBody", "(", ")", ")", "{", "$", "this", "->", "render", "(", ")", ";", "}", "if", "(", "!", "$", "this", "->", "hasPlainPart", "(", ")", ")", "{", "$", "this", "->", "generatePlainPartFromBody", "(", ")", ";", "}", "return", "Injector", "::", "inst", "(", ")", "->", "get", "(", "Mailer", "::", "class", ")", "->", "send", "(", "$", "this", ")", ";", "}" ]
Send the message to the recipients @return bool true if successful or array of failed recipients
[ "Send", "the", "message", "to", "the", "recipients" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Email/Email.php#L748-L757
train
silverstripe/silverstripe-framework
src/Control/Email/Email.php
Email.render
public function render($plainOnly = false) { if ($existingPlainPart = $this->findPlainPart()) { $this->getSwiftMessage()->detach($existingPlainPart); } unset($existingPlainPart); // Respect explicitly set body $htmlPart = $plainOnly ? null : $this->getBody(); $plainPart = $plainOnly ? $this->getBody() : null; // Ensure we can at least render something $htmlTemplate = $this->getHTMLTemplate(); $plainTemplate = $this->getPlainTemplate(); if (!$htmlTemplate && !$plainTemplate && !$plainPart && !$htmlPart) { return $this; } // Do not interfere with emails styles Requirements::clear(); // Render plain part if ($plainTemplate && !$plainPart) { $plainPart = $this->renderWith($plainTemplate, $this->getData()); } // Render HTML part, either if sending html email, or a plain part is lacking if (!$htmlPart && $htmlTemplate && (!$plainOnly || empty($plainPart))) { $htmlPart = $this->renderWith($htmlTemplate, $this->getData()); } // Plain part fails over to generated from html if (!$plainPart && $htmlPart) { /** @var DBHTMLText $htmlPartObject */ $htmlPartObject = DBField::create_field('HTMLFragment', $htmlPart); $plainPart = $htmlPartObject->Plain(); } // Rendering is finished Requirements::restore(); // Fail if no email to send if (!$plainPart && !$htmlPart) { return $this; } // Build HTML / Plain components if ($htmlPart && !$plainOnly) { $this->setBody($htmlPart); $this->getSwiftMessage()->setContentType('text/html'); $this->getSwiftMessage()->setCharset('utf-8'); if ($plainPart) { $this->getSwiftMessage()->addPart($plainPart, 'text/plain', 'utf-8'); } } else { if ($plainPart) { $this->setBody($plainPart); } $this->getSwiftMessage()->setContentType('text/plain'); $this->getSwiftMessage()->setCharset('utf-8'); } return $this; }
php
public function render($plainOnly = false) { if ($existingPlainPart = $this->findPlainPart()) { $this->getSwiftMessage()->detach($existingPlainPart); } unset($existingPlainPart); // Respect explicitly set body $htmlPart = $plainOnly ? null : $this->getBody(); $plainPart = $plainOnly ? $this->getBody() : null; // Ensure we can at least render something $htmlTemplate = $this->getHTMLTemplate(); $plainTemplate = $this->getPlainTemplate(); if (!$htmlTemplate && !$plainTemplate && !$plainPart && !$htmlPart) { return $this; } // Do not interfere with emails styles Requirements::clear(); // Render plain part if ($plainTemplate && !$plainPart) { $plainPart = $this->renderWith($plainTemplate, $this->getData()); } // Render HTML part, either if sending html email, or a plain part is lacking if (!$htmlPart && $htmlTemplate && (!$plainOnly || empty($plainPart))) { $htmlPart = $this->renderWith($htmlTemplate, $this->getData()); } // Plain part fails over to generated from html if (!$plainPart && $htmlPart) { /** @var DBHTMLText $htmlPartObject */ $htmlPartObject = DBField::create_field('HTMLFragment', $htmlPart); $plainPart = $htmlPartObject->Plain(); } // Rendering is finished Requirements::restore(); // Fail if no email to send if (!$plainPart && !$htmlPart) { return $this; } // Build HTML / Plain components if ($htmlPart && !$plainOnly) { $this->setBody($htmlPart); $this->getSwiftMessage()->setContentType('text/html'); $this->getSwiftMessage()->setCharset('utf-8'); if ($plainPart) { $this->getSwiftMessage()->addPart($plainPart, 'text/plain', 'utf-8'); } } else { if ($plainPart) { $this->setBody($plainPart); } $this->getSwiftMessage()->setContentType('text/plain'); $this->getSwiftMessage()->setCharset('utf-8'); } return $this; }
[ "public", "function", "render", "(", "$", "plainOnly", "=", "false", ")", "{", "if", "(", "$", "existingPlainPart", "=", "$", "this", "->", "findPlainPart", "(", ")", ")", "{", "$", "this", "->", "getSwiftMessage", "(", ")", "->", "detach", "(", "$", "existingPlainPart", ")", ";", "}", "unset", "(", "$", "existingPlainPart", ")", ";", "// Respect explicitly set body", "$", "htmlPart", "=", "$", "plainOnly", "?", "null", ":", "$", "this", "->", "getBody", "(", ")", ";", "$", "plainPart", "=", "$", "plainOnly", "?", "$", "this", "->", "getBody", "(", ")", ":", "null", ";", "// Ensure we can at least render something", "$", "htmlTemplate", "=", "$", "this", "->", "getHTMLTemplate", "(", ")", ";", "$", "plainTemplate", "=", "$", "this", "->", "getPlainTemplate", "(", ")", ";", "if", "(", "!", "$", "htmlTemplate", "&&", "!", "$", "plainTemplate", "&&", "!", "$", "plainPart", "&&", "!", "$", "htmlPart", ")", "{", "return", "$", "this", ";", "}", "// Do not interfere with emails styles", "Requirements", "::", "clear", "(", ")", ";", "// Render plain part", "if", "(", "$", "plainTemplate", "&&", "!", "$", "plainPart", ")", "{", "$", "plainPart", "=", "$", "this", "->", "renderWith", "(", "$", "plainTemplate", ",", "$", "this", "->", "getData", "(", ")", ")", ";", "}", "// Render HTML part, either if sending html email, or a plain part is lacking", "if", "(", "!", "$", "htmlPart", "&&", "$", "htmlTemplate", "&&", "(", "!", "$", "plainOnly", "||", "empty", "(", "$", "plainPart", ")", ")", ")", "{", "$", "htmlPart", "=", "$", "this", "->", "renderWith", "(", "$", "htmlTemplate", ",", "$", "this", "->", "getData", "(", ")", ")", ";", "}", "// Plain part fails over to generated from html", "if", "(", "!", "$", "plainPart", "&&", "$", "htmlPart", ")", "{", "/** @var DBHTMLText $htmlPartObject */", "$", "htmlPartObject", "=", "DBField", "::", "create_field", "(", "'HTMLFragment'", ",", "$", "htmlPart", ")", ";", "$", "plainPart", "=", "$", "htmlPartObject", "->", "Plain", "(", ")", ";", "}", "// Rendering is finished", "Requirements", "::", "restore", "(", ")", ";", "// Fail if no email to send", "if", "(", "!", "$", "plainPart", "&&", "!", "$", "htmlPart", ")", "{", "return", "$", "this", ";", "}", "// Build HTML / Plain components", "if", "(", "$", "htmlPart", "&&", "!", "$", "plainOnly", ")", "{", "$", "this", "->", "setBody", "(", "$", "htmlPart", ")", ";", "$", "this", "->", "getSwiftMessage", "(", ")", "->", "setContentType", "(", "'text/html'", ")", ";", "$", "this", "->", "getSwiftMessage", "(", ")", "->", "setCharset", "(", "'utf-8'", ")", ";", "if", "(", "$", "plainPart", ")", "{", "$", "this", "->", "getSwiftMessage", "(", ")", "->", "addPart", "(", "$", "plainPart", ",", "'text/plain'", ",", "'utf-8'", ")", ";", "}", "}", "else", "{", "if", "(", "$", "plainPart", ")", "{", "$", "this", "->", "setBody", "(", "$", "plainPart", ")", ";", "}", "$", "this", "->", "getSwiftMessage", "(", ")", "->", "setContentType", "(", "'text/plain'", ")", ";", "$", "this", "->", "getSwiftMessage", "(", ")", "->", "setCharset", "(", "'utf-8'", ")", ";", "}", "return", "$", "this", ";", "}" ]
Render the email @param bool $plainOnly Only render the message as plain text @return $this
[ "Render", "the", "email" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Email/Email.php#L775-L838
train
silverstripe/silverstripe-framework
src/Control/Email/Email.php
Email.generatePlainPartFromBody
public function generatePlainPartFromBody() { $plainPart = $this->findPlainPart(); if ($plainPart) { $this->getSwiftMessage()->detach($plainPart); } unset($plainPart); $this->getSwiftMessage()->addPart( Convert::xml2raw($this->getBody()), 'text/plain', 'utf-8' ); return $this; }
php
public function generatePlainPartFromBody() { $plainPart = $this->findPlainPart(); if ($plainPart) { $this->getSwiftMessage()->detach($plainPart); } unset($plainPart); $this->getSwiftMessage()->addPart( Convert::xml2raw($this->getBody()), 'text/plain', 'utf-8' ); return $this; }
[ "public", "function", "generatePlainPartFromBody", "(", ")", "{", "$", "plainPart", "=", "$", "this", "->", "findPlainPart", "(", ")", ";", "if", "(", "$", "plainPart", ")", "{", "$", "this", "->", "getSwiftMessage", "(", ")", "->", "detach", "(", "$", "plainPart", ")", ";", "}", "unset", "(", "$", "plainPart", ")", ";", "$", "this", "->", "getSwiftMessage", "(", ")", "->", "addPart", "(", "Convert", "::", "xml2raw", "(", "$", "this", "->", "getBody", "(", ")", ")", ",", "'text/plain'", ",", "'utf-8'", ")", ";", "return", "$", "this", ";", "}" ]
Automatically adds a plain part to the email generated from the current Body @return $this
[ "Automatically", "adds", "a", "plain", "part", "to", "the", "email", "generated", "from", "the", "current", "Body" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Email/Email.php#L869-L884
train
silverstripe/silverstripe-framework
src/Security/InheritedPermissionFlusher.php
InheritedPermissionFlusher.flushCache
public function flushCache() { $ids = $this->getMemberIDList(); foreach ($this->getServices() as $service) { $service->flushMemberCache($ids); } }
php
public function flushCache() { $ids = $this->getMemberIDList(); foreach ($this->getServices() as $service) { $service->flushMemberCache($ids); } }
[ "public", "function", "flushCache", "(", ")", "{", "$", "ids", "=", "$", "this", "->", "getMemberIDList", "(", ")", ";", "foreach", "(", "$", "this", "->", "getServices", "(", ")", "as", "$", "service", ")", "{", "$", "service", "->", "flushMemberCache", "(", "$", "ids", ")", ";", "}", "}" ]
Flushes all registered MemberCacheFlusher services
[ "Flushes", "all", "registered", "MemberCacheFlusher", "services" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/InheritedPermissionFlusher.php#L77-L83
train
silverstripe/silverstripe-framework
src/Security/InheritedPermissionFlusher.php
InheritedPermissionFlusher.getMemberIDList
protected function getMemberIDList() { if (!$this->owner || !$this->owner->exists()) { return null; } if ($this->owner instanceof Group) { return $this->owner->Members()->column('ID'); } return [$this->owner->ID]; }
php
protected function getMemberIDList() { if (!$this->owner || !$this->owner->exists()) { return null; } if ($this->owner instanceof Group) { return $this->owner->Members()->column('ID'); } return [$this->owner->ID]; }
[ "protected", "function", "getMemberIDList", "(", ")", "{", "if", "(", "!", "$", "this", "->", "owner", "||", "!", "$", "this", "->", "owner", "->", "exists", "(", ")", ")", "{", "return", "null", ";", "}", "if", "(", "$", "this", "->", "owner", "instanceof", "Group", ")", "{", "return", "$", "this", "->", "owner", "->", "Members", "(", ")", "->", "column", "(", "'ID'", ")", ";", "}", "return", "[", "$", "this", "->", "owner", "->", "ID", "]", ";", "}" ]
Get a list of member IDs that need their permissions flushed @return array|null
[ "Get", "a", "list", "of", "member", "IDs", "that", "need", "their", "permissions", "flushed" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/InheritedPermissionFlusher.php#L90-L101
train
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/LoginHandler.php
LoginHandler.redirectAfterSuccessfulLogin
protected function redirectAfterSuccessfulLogin() { $this ->getRequest() ->getSession() ->clear('SessionForms.MemberLoginForm.Email') ->clear('SessionForms.MemberLoginForm.Remember'); $member = Security::getCurrentUser(); if ($member->isPasswordExpired()) { return $this->redirectToChangePassword(); } // Absolute redirection URLs may cause spoofing $backURL = $this->getBackURL(); if ($backURL) { return $this->redirect($backURL); } // If a default login dest has been set, redirect to that. $defaultLoginDest = Security::config()->get('default_login_dest'); if ($defaultLoginDest) { return $this->redirect($defaultLoginDest); } // Redirect the user to the page where they came from if ($member) { // Welcome message $message = _t( 'SilverStripe\\Security\\Member.WELCOMEBACK', 'Welcome Back, {firstname}', ['firstname' => $member->FirstName] ); Security::singleton()->setSessionMessage($message, ValidationResult::TYPE_GOOD); } // Redirect back return $this->redirectBack(); }
php
protected function redirectAfterSuccessfulLogin() { $this ->getRequest() ->getSession() ->clear('SessionForms.MemberLoginForm.Email') ->clear('SessionForms.MemberLoginForm.Remember'); $member = Security::getCurrentUser(); if ($member->isPasswordExpired()) { return $this->redirectToChangePassword(); } // Absolute redirection URLs may cause spoofing $backURL = $this->getBackURL(); if ($backURL) { return $this->redirect($backURL); } // If a default login dest has been set, redirect to that. $defaultLoginDest = Security::config()->get('default_login_dest'); if ($defaultLoginDest) { return $this->redirect($defaultLoginDest); } // Redirect the user to the page where they came from if ($member) { // Welcome message $message = _t( 'SilverStripe\\Security\\Member.WELCOMEBACK', 'Welcome Back, {firstname}', ['firstname' => $member->FirstName] ); Security::singleton()->setSessionMessage($message, ValidationResult::TYPE_GOOD); } // Redirect back return $this->redirectBack(); }
[ "protected", "function", "redirectAfterSuccessfulLogin", "(", ")", "{", "$", "this", "->", "getRequest", "(", ")", "->", "getSession", "(", ")", "->", "clear", "(", "'SessionForms.MemberLoginForm.Email'", ")", "->", "clear", "(", "'SessionForms.MemberLoginForm.Remember'", ")", ";", "$", "member", "=", "Security", "::", "getCurrentUser", "(", ")", ";", "if", "(", "$", "member", "->", "isPasswordExpired", "(", ")", ")", "{", "return", "$", "this", "->", "redirectToChangePassword", "(", ")", ";", "}", "// Absolute redirection URLs may cause spoofing", "$", "backURL", "=", "$", "this", "->", "getBackURL", "(", ")", ";", "if", "(", "$", "backURL", ")", "{", "return", "$", "this", "->", "redirect", "(", "$", "backURL", ")", ";", "}", "// If a default login dest has been set, redirect to that.", "$", "defaultLoginDest", "=", "Security", "::", "config", "(", ")", "->", "get", "(", "'default_login_dest'", ")", ";", "if", "(", "$", "defaultLoginDest", ")", "{", "return", "$", "this", "->", "redirect", "(", "$", "defaultLoginDest", ")", ";", "}", "// Redirect the user to the page where they came from", "if", "(", "$", "member", ")", "{", "// Welcome message", "$", "message", "=", "_t", "(", "'SilverStripe\\\\Security\\\\Member.WELCOMEBACK'", ",", "'Welcome Back, {firstname}'", ",", "[", "'firstname'", "=>", "$", "member", "->", "FirstName", "]", ")", ";", "Security", "::", "singleton", "(", ")", "->", "setSessionMessage", "(", "$", "message", ",", "ValidationResult", "::", "TYPE_GOOD", ")", ";", "}", "// Redirect back", "return", "$", "this", "->", "redirectBack", "(", ")", ";", "}" ]
Login in the user and figure out where to redirect the browser. The $data has this format array( 'AuthenticationMethod' => 'MemberAuthenticator', 'Email' => 'sam@silverstripe.com', 'Password' => '1nitialPassword', 'BackURL' => 'test/link', [Optional: 'Remember' => 1 ] ) @return HTTPResponse
[ "Login", "in", "the", "user", "and", "figure", "out", "where", "to", "redirect", "the", "browser", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/MemberAuthenticator/LoginHandler.php#L173-L211
train
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/LoginHandler.php
LoginHandler.redirectToChangePassword
protected function redirectToChangePassword() { $cp = ChangePasswordForm::create($this, 'ChangePasswordForm'); $cp->sessionMessage( _t('SilverStripe\\Security\\Member.PASSWORDEXPIRED', 'Your password has expired. Please choose a new one.'), 'good' ); $changedPasswordLink = Security::singleton()->Link('changepassword'); return $this->redirect($this->addBackURLParam($changedPasswordLink)); }
php
protected function redirectToChangePassword() { $cp = ChangePasswordForm::create($this, 'ChangePasswordForm'); $cp->sessionMessage( _t('SilverStripe\\Security\\Member.PASSWORDEXPIRED', 'Your password has expired. Please choose a new one.'), 'good' ); $changedPasswordLink = Security::singleton()->Link('changepassword'); return $this->redirect($this->addBackURLParam($changedPasswordLink)); }
[ "protected", "function", "redirectToChangePassword", "(", ")", "{", "$", "cp", "=", "ChangePasswordForm", "::", "create", "(", "$", "this", ",", "'ChangePasswordForm'", ")", ";", "$", "cp", "->", "sessionMessage", "(", "_t", "(", "'SilverStripe\\\\Security\\\\Member.PASSWORDEXPIRED'", ",", "'Your password has expired. Please choose a new one.'", ")", ",", "'good'", ")", ";", "$", "changedPasswordLink", "=", "Security", "::", "singleton", "(", ")", "->", "Link", "(", "'changepassword'", ")", ";", "return", "$", "this", "->", "redirect", "(", "$", "this", "->", "addBackURLParam", "(", "$", "changedPasswordLink", ")", ")", ";", "}" ]
Invoked if password is expired and must be changed @skipUpgrade @return HTTPResponse
[ "Invoked", "if", "password", "is", "expired", "and", "must", "be", "changed" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/MemberAuthenticator/LoginHandler.php#L258-L268
train
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/CMSLoginHandler.php
CMSLoginHandler.redirectToChangePassword
protected function redirectToChangePassword() { // Since this form is loaded via an iframe, this redirect must be performed via javascript $changePasswordForm = ChangePasswordForm::create($this, 'ChangePasswordForm'); $changePasswordForm->sessionMessage( _t('SilverStripe\\Security\\Member.PASSWORDEXPIRED', 'Your password has expired. Please choose a new one.'), 'good' ); // Get redirect url $changePasswordURL = $this->addBackURLParam(Security::singleton()->Link('changepassword')); $changePasswordURLATT = Convert::raw2att($changePasswordURL); $changePasswordURLJS = Convert::raw2js($changePasswordURL); $message = _t( 'SilverStripe\\Security\\CMSMemberLoginForm.PASSWORDEXPIRED', '<p>Your password has expired. <a target="_top" href="{link}">Please choose a new one.</a></p>', 'Message displayed to user if their session cannot be restored', array('link' => $changePasswordURLATT) ); // Redirect to change password page $response = HTTPResponse::create() ->setBody(<<<PHP <!DOCTYPE html> <html><body> $message <script type="application/javascript"> setTimeout(function(){top.location.href = "$changePasswordURLJS";}, 0); </script> </body></html> PHP ); return $response; }
php
protected function redirectToChangePassword() { // Since this form is loaded via an iframe, this redirect must be performed via javascript $changePasswordForm = ChangePasswordForm::create($this, 'ChangePasswordForm'); $changePasswordForm->sessionMessage( _t('SilverStripe\\Security\\Member.PASSWORDEXPIRED', 'Your password has expired. Please choose a new one.'), 'good' ); // Get redirect url $changePasswordURL = $this->addBackURLParam(Security::singleton()->Link('changepassword')); $changePasswordURLATT = Convert::raw2att($changePasswordURL); $changePasswordURLJS = Convert::raw2js($changePasswordURL); $message = _t( 'SilverStripe\\Security\\CMSMemberLoginForm.PASSWORDEXPIRED', '<p>Your password has expired. <a target="_top" href="{link}">Please choose a new one.</a></p>', 'Message displayed to user if their session cannot be restored', array('link' => $changePasswordURLATT) ); // Redirect to change password page $response = HTTPResponse::create() ->setBody(<<<PHP <!DOCTYPE html> <html><body> $message <script type="application/javascript"> setTimeout(function(){top.location.href = "$changePasswordURLJS";}, 0); </script> </body></html> PHP ); return $response; }
[ "protected", "function", "redirectToChangePassword", "(", ")", "{", "// Since this form is loaded via an iframe, this redirect must be performed via javascript", "$", "changePasswordForm", "=", "ChangePasswordForm", "::", "create", "(", "$", "this", ",", "'ChangePasswordForm'", ")", ";", "$", "changePasswordForm", "->", "sessionMessage", "(", "_t", "(", "'SilverStripe\\\\Security\\\\Member.PASSWORDEXPIRED'", ",", "'Your password has expired. Please choose a new one.'", ")", ",", "'good'", ")", ";", "// Get redirect url", "$", "changePasswordURL", "=", "$", "this", "->", "addBackURLParam", "(", "Security", "::", "singleton", "(", ")", "->", "Link", "(", "'changepassword'", ")", ")", ";", "$", "changePasswordURLATT", "=", "Convert", "::", "raw2att", "(", "$", "changePasswordURL", ")", ";", "$", "changePasswordURLJS", "=", "Convert", "::", "raw2js", "(", "$", "changePasswordURL", ")", ";", "$", "message", "=", "_t", "(", "'SilverStripe\\\\Security\\\\CMSMemberLoginForm.PASSWORDEXPIRED'", ",", "'<p>Your password has expired. <a target=\"_top\" href=\"{link}\">Please choose a new one.</a></p>'", ",", "'Message displayed to user if their session cannot be restored'", ",", "array", "(", "'link'", "=>", "$", "changePasswordURLATT", ")", ")", ";", "// Redirect to change password page", "$", "response", "=", "HTTPResponse", "::", "create", "(", ")", "->", "setBody", "(", "<<<PHP\n<!DOCTYPE html>\n<html><body>\n$message\n<script type=\"application/javascript\">\nsetTimeout(function(){top.location.href = \"$changePasswordURLJS\";}, 0);\n</script>\n</body></html>\nPHP", ")", ";", "return", "$", "response", ";", "}" ]
Redirect the user to the change password form. @skipUpgrade @return HTTPResponse
[ "Redirect", "the", "user", "to", "the", "change", "password", "form", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/MemberAuthenticator/CMSLoginHandler.php#L58-L91
train
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/CMSLoginHandler.php
CMSLoginHandler.redirectAfterSuccessfulLogin
protected function redirectAfterSuccessfulLogin() { // Check password expiry if (Security::getCurrentUser()->isPasswordExpired()) { // Redirect the user to the external password change form if necessary return $this->redirectToChangePassword(); } // Link to success template $url = CMSSecurity::singleton()->Link('success'); return $this->redirect($url); }
php
protected function redirectAfterSuccessfulLogin() { // Check password expiry if (Security::getCurrentUser()->isPasswordExpired()) { // Redirect the user to the external password change form if necessary return $this->redirectToChangePassword(); } // Link to success template $url = CMSSecurity::singleton()->Link('success'); return $this->redirect($url); }
[ "protected", "function", "redirectAfterSuccessfulLogin", "(", ")", "{", "// Check password expiry", "if", "(", "Security", "::", "getCurrentUser", "(", ")", "->", "isPasswordExpired", "(", ")", ")", "{", "// Redirect the user to the external password change form if necessary", "return", "$", "this", "->", "redirectToChangePassword", "(", ")", ";", "}", "// Link to success template", "$", "url", "=", "CMSSecurity", "::", "singleton", "(", ")", "->", "Link", "(", "'success'", ")", ";", "return", "$", "this", "->", "redirect", "(", "$", "url", ")", ";", "}" ]
Send user to the right location after login @return HTTPResponse
[ "Send", "user", "to", "the", "right", "location", "after", "login" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/MemberAuthenticator/CMSLoginHandler.php#L98-L109
train
silverstripe/silverstripe-framework
src/Core/Manifest/PrioritySorter.php
PrioritySorter.setItems
public function setItems(array $items) { $this->items = $items; $this->names = array_keys($items); return $this; }
php
public function setItems(array $items) { $this->items = $items; $this->names = array_keys($items); return $this; }
[ "public", "function", "setItems", "(", "array", "$", "items", ")", "{", "$", "this", "->", "items", "=", "$", "items", ";", "$", "this", "->", "names", "=", "array_keys", "(", "$", "items", ")", ";", "return", "$", "this", ";", "}" ]
Sets the list of all items @param array $items @return $this
[ "Sets", "the", "list", "of", "all", "items" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/PrioritySorter.php#L132-L138
train
silverstripe/silverstripe-framework
src/Core/Manifest/PrioritySorter.php
PrioritySorter.addVariables
protected function addVariables() { // Remove variables from the list $varValues = array_values($this->variables); $this->names = array_filter($this->names, function ($name) use ($varValues) { return !in_array($name, $varValues); }); // Replace variables with their values $this->priorities = array_map(function ($name) { return $this->resolveValue($name); }, $this->priorities); }
php
protected function addVariables() { // Remove variables from the list $varValues = array_values($this->variables); $this->names = array_filter($this->names, function ($name) use ($varValues) { return !in_array($name, $varValues); }); // Replace variables with their values $this->priorities = array_map(function ($name) { return $this->resolveValue($name); }, $this->priorities); }
[ "protected", "function", "addVariables", "(", ")", "{", "// Remove variables from the list", "$", "varValues", "=", "array_values", "(", "$", "this", "->", "variables", ")", ";", "$", "this", "->", "names", "=", "array_filter", "(", "$", "this", "->", "names", ",", "function", "(", "$", "name", ")", "use", "(", "$", "varValues", ")", "{", "return", "!", "in_array", "(", "$", "name", ",", "$", "varValues", ")", ";", "}", ")", ";", "// Replace variables with their values", "$", "this", "->", "priorities", "=", "array_map", "(", "function", "(", "$", "name", ")", "{", "return", "$", "this", "->", "resolveValue", "(", "$", "name", ")", ";", "}", ",", "$", "this", "->", "priorities", ")", ";", "}" ]
If variables are defined, interpolate their values
[ "If", "variables", "are", "defined", "interpolate", "their", "values" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/PrioritySorter.php#L170-L182
train
silverstripe/silverstripe-framework
src/Core/Manifest/PrioritySorter.php
PrioritySorter.includeRest
protected function includeRest(array $list) { $otherItemsIndex = false; if ($this->restKey) { $otherItemsIndex = array_search($this->restKey, $this->priorities); } if ($otherItemsIndex !== false) { array_splice($this->priorities, $otherItemsIndex, 1, $list); } else { // Otherwise just jam them on the end $this->priorities = array_merge($this->priorities, $list); } }
php
protected function includeRest(array $list) { $otherItemsIndex = false; if ($this->restKey) { $otherItemsIndex = array_search($this->restKey, $this->priorities); } if ($otherItemsIndex !== false) { array_splice($this->priorities, $otherItemsIndex, 1, $list); } else { // Otherwise just jam them on the end $this->priorities = array_merge($this->priorities, $list); } }
[ "protected", "function", "includeRest", "(", "array", "$", "list", ")", "{", "$", "otherItemsIndex", "=", "false", ";", "if", "(", "$", "this", "->", "restKey", ")", "{", "$", "otherItemsIndex", "=", "array_search", "(", "$", "this", "->", "restKey", ",", "$", "this", "->", "priorities", ")", ";", "}", "if", "(", "$", "otherItemsIndex", "!==", "false", ")", "{", "array_splice", "(", "$", "this", "->", "priorities", ",", "$", "otherItemsIndex", ",", "1", ",", "$", "list", ")", ";", "}", "else", "{", "// Otherwise just jam them on the end", "$", "this", "->", "priorities", "=", "array_merge", "(", "$", "this", "->", "priorities", ",", "$", "list", ")", ";", "}", "}" ]
If the "rest" key exists in the order array, replace it by the unspecified items
[ "If", "the", "rest", "key", "exists", "in", "the", "order", "array", "replace", "it", "by", "the", "unspecified", "items" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/PrioritySorter.php#L188-L200
train
silverstripe/silverstripe-framework
src/Core/Manifest/PrioritySorter.php
PrioritySorter.resolveValue
protected function resolveValue($name) { return isset($this->variables[$name]) ? $this->variables[$name] : $name; }
php
protected function resolveValue($name) { return isset($this->variables[$name]) ? $this->variables[$name] : $name; }
[ "protected", "function", "resolveValue", "(", "$", "name", ")", "{", "return", "isset", "(", "$", "this", "->", "variables", "[", "$", "name", "]", ")", "?", "$", "this", "->", "variables", "[", "$", "name", "]", ":", "$", "name", ";", "}" ]
Ensure variables get converted to their values @param $name @return mixed
[ "Ensure", "variables", "get", "converted", "to", "their", "values" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/PrioritySorter.php#L208-L211
train
silverstripe/silverstripe-framework
src/Dev/Install/MySQLDatabaseConfigurationHelper.php
MySQLDatabaseConfigurationHelper.column
protected function column($results) { $array = array(); if ($results instanceof mysqli_result) { while ($row = $results->fetch_array()) { $array[] = $row[0]; } } else { foreach ($results as $row) { $array[] = $row[0]; } } return $array; }
php
protected function column($results) { $array = array(); if ($results instanceof mysqli_result) { while ($row = $results->fetch_array()) { $array[] = $row[0]; } } else { foreach ($results as $row) { $array[] = $row[0]; } } return $array; }
[ "protected", "function", "column", "(", "$", "results", ")", "{", "$", "array", "=", "array", "(", ")", ";", "if", "(", "$", "results", "instanceof", "mysqli_result", ")", "{", "while", "(", "$", "row", "=", "$", "results", "->", "fetch_array", "(", ")", ")", "{", "$", "array", "[", "]", "=", "$", "row", "[", "0", "]", ";", "}", "}", "else", "{", "foreach", "(", "$", "results", "as", "$", "row", ")", "{", "$", "array", "[", "]", "=", "$", "row", "[", "0", "]", ";", "}", "}", "return", "$", "array", ";", "}" ]
Helper function to quickly extract a column from a mysqi_result @param mixed $results mysqli_result or enumerable list of rows @return array Resulting data
[ "Helper", "function", "to", "quickly", "extract", "a", "column", "from", "a", "mysqi_result" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Install/MySQLDatabaseConfigurationHelper.php#L119-L132
train
silverstripe/silverstripe-framework
src/Dev/Install/MySQLDatabaseConfigurationHelper.php
MySQLDatabaseConfigurationHelper.requireDatabaseVersion
public function requireDatabaseVersion($databaseConfig) { $version = $this->getDatabaseVersion($databaseConfig); $success = false; $error = ''; if ($version) { $success = version_compare($version, '5.0', '>='); if (!$success) { $error = "Your MySQL server version is $version. It's recommended you use at least MySQL 5.0."; } } else { $error = "Could not determine your MySQL version."; } return array( 'success' => $success, 'error' => $error ); }
php
public function requireDatabaseVersion($databaseConfig) { $version = $this->getDatabaseVersion($databaseConfig); $success = false; $error = ''; if ($version) { $success = version_compare($version, '5.0', '>='); if (!$success) { $error = "Your MySQL server version is $version. It's recommended you use at least MySQL 5.0."; } } else { $error = "Could not determine your MySQL version."; } return array( 'success' => $success, 'error' => $error ); }
[ "public", "function", "requireDatabaseVersion", "(", "$", "databaseConfig", ")", "{", "$", "version", "=", "$", "this", "->", "getDatabaseVersion", "(", "$", "databaseConfig", ")", ";", "$", "success", "=", "false", ";", "$", "error", "=", "''", ";", "if", "(", "$", "version", ")", "{", "$", "success", "=", "version_compare", "(", "$", "version", ",", "'5.0'", ",", "'>='", ")", ";", "if", "(", "!", "$", "success", ")", "{", "$", "error", "=", "\"Your MySQL server version is $version. It's recommended you use at least MySQL 5.0.\"", ";", "}", "}", "else", "{", "$", "error", "=", "\"Could not determine your MySQL version.\"", ";", "}", "return", "array", "(", "'success'", "=>", "$", "success", ",", "'error'", "=>", "$", "error", ")", ";", "}" ]
Ensure that the MySQL server version is at least 5.0. @param array $databaseConfig Associative array of db configuration, e.g. "server", "username" etc @return array Result - e.g. array('success' => true, 'error' => 'details of error')
[ "Ensure", "that", "the", "MySQL", "server", "version", "is", "at", "least", "5", ".", "0", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Install/MySQLDatabaseConfigurationHelper.php#L170-L187
train
silverstripe/silverstripe-framework
src/Dev/Install/MySQLDatabaseConfigurationHelper.php
MySQLDatabaseConfigurationHelper.checkDatabasePermissionGrant
public function checkDatabasePermissionGrant($database, $permission, $grant) { // Filter out invalid database names if (!$this->checkValidDatabaseName($database)) { return false; } // Escape all valid database patterns (permission must exist on all tables) $sqlDatabase = addcslashes($database, '_%'); // See http://dev.mysql.com/doc/refman/5.7/en/string-literals.html $dbPattern = sprintf( '((%s)|(%s)|(%s)|(%s))', preg_quote("\"$sqlDatabase\".*"), // Regexp escape sql-escaped db identifier preg_quote("\"$database\".*"), preg_quote('"%".*'), preg_quote('*.*') ); $expression = '/GRANT[ ,\w]+((ALL PRIVILEGES)|(' . $permission . '(?! ((VIEW)|(ROUTINE)))))[ ,\w]+ON ' . $dbPattern . '/i'; return preg_match($expression, $grant); }
php
public function checkDatabasePermissionGrant($database, $permission, $grant) { // Filter out invalid database names if (!$this->checkValidDatabaseName($database)) { return false; } // Escape all valid database patterns (permission must exist on all tables) $sqlDatabase = addcslashes($database, '_%'); // See http://dev.mysql.com/doc/refman/5.7/en/string-literals.html $dbPattern = sprintf( '((%s)|(%s)|(%s)|(%s))', preg_quote("\"$sqlDatabase\".*"), // Regexp escape sql-escaped db identifier preg_quote("\"$database\".*"), preg_quote('"%".*'), preg_quote('*.*') ); $expression = '/GRANT[ ,\w]+((ALL PRIVILEGES)|(' . $permission . '(?! ((VIEW)|(ROUTINE)))))[ ,\w]+ON ' . $dbPattern . '/i'; return preg_match($expression, $grant); }
[ "public", "function", "checkDatabasePermissionGrant", "(", "$", "database", ",", "$", "permission", ",", "$", "grant", ")", "{", "// Filter out invalid database names", "if", "(", "!", "$", "this", "->", "checkValidDatabaseName", "(", "$", "database", ")", ")", "{", "return", "false", ";", "}", "// Escape all valid database patterns (permission must exist on all tables)", "$", "sqlDatabase", "=", "addcslashes", "(", "$", "database", ",", "'_%'", ")", ";", "// See http://dev.mysql.com/doc/refman/5.7/en/string-literals.html", "$", "dbPattern", "=", "sprintf", "(", "'((%s)|(%s)|(%s)|(%s))'", ",", "preg_quote", "(", "\"\\\"$sqlDatabase\\\".*\"", ")", ",", "// Regexp escape sql-escaped db identifier", "preg_quote", "(", "\"\\\"$database\\\".*\"", ")", ",", "preg_quote", "(", "'\"%\".*'", ")", ",", "preg_quote", "(", "'*.*'", ")", ")", ";", "$", "expression", "=", "'/GRANT[ ,\\w]+((ALL PRIVILEGES)|('", ".", "$", "permission", ".", "'(?! ((VIEW)|(ROUTINE)))))[ ,\\w]+ON '", ".", "$", "dbPattern", ".", "'/i'", ";", "return", "preg_match", "(", "$", "expression", ",", "$", "grant", ")", ";", "}" ]
Checks if a specified grant proves that the current user has the specified permission on the specified database @param string $database Database name @param string $permission Permission to check for @param string $grant MySQL syntax grant to check within @return boolean
[ "Checks", "if", "a", "specified", "grant", "proves", "that", "the", "current", "user", "has", "the", "specified", "permission", "on", "the", "specified", "database" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Install/MySQLDatabaseConfigurationHelper.php#L234-L252
train
silverstripe/silverstripe-framework
src/Dev/Install/MySQLDatabaseConfigurationHelper.php
MySQLDatabaseConfigurationHelper.checkDatabasePermission
public function checkDatabasePermission($conn, $database, $permission) { $grants = $this->column($conn->query("SHOW GRANTS FOR CURRENT_USER")); foreach ($grants as $grant) { if ($this->checkDatabasePermissionGrant($database, $permission, $grant)) { return true; } } return false; }
php
public function checkDatabasePermission($conn, $database, $permission) { $grants = $this->column($conn->query("SHOW GRANTS FOR CURRENT_USER")); foreach ($grants as $grant) { if ($this->checkDatabasePermissionGrant($database, $permission, $grant)) { return true; } } return false; }
[ "public", "function", "checkDatabasePermission", "(", "$", "conn", ",", "$", "database", ",", "$", "permission", ")", "{", "$", "grants", "=", "$", "this", "->", "column", "(", "$", "conn", "->", "query", "(", "\"SHOW GRANTS FOR CURRENT_USER\"", ")", ")", ";", "foreach", "(", "$", "grants", "as", "$", "grant", ")", "{", "if", "(", "$", "this", "->", "checkDatabasePermissionGrant", "(", "$", "database", ",", "$", "permission", ",", "$", "grant", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks if the current user has the specified permission on the specified database @param mixed $conn Connection object @param string $database Database name @param string $permission Permission to check @return boolean
[ "Checks", "if", "the", "current", "user", "has", "the", "specified", "permission", "on", "the", "specified", "database" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Install/MySQLDatabaseConfigurationHelper.php#L262-L271
train
silverstripe/silverstripe-framework
src/Core/Convert.php
Convert.raw2htmlname
public static function raw2htmlname($val) { if (is_array($val)) { foreach ($val as $k => $v) { $val[$k] = self::raw2htmlname($v); } return $val; } return self::raw2att($val); }
php
public static function raw2htmlname($val) { if (is_array($val)) { foreach ($val as $k => $v) { $val[$k] = self::raw2htmlname($v); } return $val; } return self::raw2att($val); }
[ "public", "static", "function", "raw2htmlname", "(", "$", "val", ")", "{", "if", "(", "is_array", "(", "$", "val", ")", ")", "{", "foreach", "(", "$", "val", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "val", "[", "$", "k", "]", "=", "self", "::", "raw2htmlname", "(", "$", "v", ")", ";", "}", "return", "$", "val", ";", "}", "return", "self", "::", "raw2att", "(", "$", "val", ")", ";", "}" ]
Convert a value to be suitable for an HTML ID attribute. Replaces non supported characters with a space. @see http://www.w3.org/TR/REC-html40/types.html#type-cdata @param array|string $val String to escape, or array of strings @return array|string
[ "Convert", "a", "value", "to", "be", "suitable", "for", "an", "HTML", "ID", "attribute", ".", "Replaces", "non", "supported", "characters", "with", "a", "space", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Convert.php#L65-L76
train
silverstripe/silverstripe-framework
src/Core/Convert.php
Convert.raw2xml
public static function raw2xml($val) { if (is_array($val)) { foreach ($val as $k => $v) { $val[$k] = self::raw2xml($v); } return $val; } return htmlspecialchars($val, ENT_QUOTES, 'UTF-8'); }
php
public static function raw2xml($val) { if (is_array($val)) { foreach ($val as $k => $v) { $val[$k] = self::raw2xml($v); } return $val; } return htmlspecialchars($val, ENT_QUOTES, 'UTF-8'); }
[ "public", "static", "function", "raw2xml", "(", "$", "val", ")", "{", "if", "(", "is_array", "(", "$", "val", ")", ")", "{", "foreach", "(", "$", "val", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "val", "[", "$", "k", "]", "=", "self", "::", "raw2xml", "(", "$", "v", ")", ";", "}", "return", "$", "val", ";", "}", "return", "htmlspecialchars", "(", "$", "val", ",", "ENT_QUOTES", ",", "'UTF-8'", ")", ";", "}" ]
Ensure that text is properly escaped for XML. @see http://www.w3.org/TR/REC-xml/#dt-escape @param array|string $val String to escape, or array of strings @return array|string
[ "Ensure", "that", "text", "is", "properly", "escaped", "for", "XML", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Convert.php#L115-L125
train
silverstripe/silverstripe-framework
src/Core/Convert.php
Convert.raw2js
public static function raw2js($val) { if (is_array($val)) { foreach ($val as $k => $v) { $val[$k] = self::raw2js($v); } return $val; } return str_replace( // Intercepts some characters such as <, >, and & which can interfere array("\\", '"', "\n", "\r", "'", '<', '>', '&'), array("\\\\", '\"', '\n', '\r', "\\'", "\\x3c", "\\x3e", "\\x26"), $val ); }
php
public static function raw2js($val) { if (is_array($val)) { foreach ($val as $k => $v) { $val[$k] = self::raw2js($v); } return $val; } return str_replace( // Intercepts some characters such as <, >, and & which can interfere array("\\", '"', "\n", "\r", "'", '<', '>', '&'), array("\\\\", '\"', '\n', '\r', "\\'", "\\x3c", "\\x3e", "\\x26"), $val ); }
[ "public", "static", "function", "raw2js", "(", "$", "val", ")", "{", "if", "(", "is_array", "(", "$", "val", ")", ")", "{", "foreach", "(", "$", "val", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "val", "[", "$", "k", "]", "=", "self", "::", "raw2js", "(", "$", "v", ")", ";", "}", "return", "$", "val", ";", "}", "return", "str_replace", "(", "// Intercepts some characters such as <, >, and & which can interfere", "array", "(", "\"\\\\\"", ",", "'\"'", ",", "\"\\n\"", ",", "\"\\r\"", ",", "\"'\"", ",", "'<'", ",", "'>'", ",", "'&'", ")", ",", "array", "(", "\"\\\\\\\\\"", ",", "'\\\"'", ",", "'\\n'", ",", "'\\r'", ",", "\"\\\\'\"", ",", "\"\\\\x3c\"", ",", "\"\\\\x3e\"", ",", "\"\\\\x26\"", ")", ",", "$", "val", ")", ";", "}" ]
Ensure that text is properly escaped for Javascript. @param array|string $val String to escape, or array of strings @return array|string
[ "Ensure", "that", "text", "is", "properly", "escaped", "for", "Javascript", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Convert.php#L133-L148
train
silverstripe/silverstripe-framework
src/Core/Convert.php
Convert.xml2raw
public static function xml2raw($val) { if (is_array($val)) { foreach ($val as $k => $v) { $val[$k] = self::xml2raw($v); } return $val; } // More complex text needs to use html2raw instead if (strpos($val, '<') !== false) { return self::html2raw($val); } return html_entity_decode($val, ENT_QUOTES, 'UTF-8'); }
php
public static function xml2raw($val) { if (is_array($val)) { foreach ($val as $k => $v) { $val[$k] = self::xml2raw($v); } return $val; } // More complex text needs to use html2raw instead if (strpos($val, '<') !== false) { return self::html2raw($val); } return html_entity_decode($val, ENT_QUOTES, 'UTF-8'); }
[ "public", "static", "function", "xml2raw", "(", "$", "val", ")", "{", "if", "(", "is_array", "(", "$", "val", ")", ")", "{", "foreach", "(", "$", "val", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "val", "[", "$", "k", "]", "=", "self", "::", "xml2raw", "(", "$", "v", ")", ";", "}", "return", "$", "val", ";", "}", "// More complex text needs to use html2raw instead", "if", "(", "strpos", "(", "$", "val", ",", "'<'", ")", "!==", "false", ")", "{", "return", "self", "::", "html2raw", "(", "$", "val", ")", ";", "}", "return", "html_entity_decode", "(", "$", "val", ",", "ENT_QUOTES", ",", "'UTF-8'", ")", ";", "}" ]
Convert XML to raw text. @uses html2raw() @todo Currently &#xxx; entries are stripped; they should be converted @param mixed $val @return array|string
[ "Convert", "XML", "to", "raw", "text", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Convert.php#L229-L244
train
silverstripe/silverstripe-framework
src/Core/Convert.php
Convert.html2raw
public static function html2raw($data, $preserveLinks = false, $wordWrap = 0, $config = null) { $defaultConfig = array( 'PreserveLinks' => false, 'ReplaceBoldAsterisk' => true, 'CompressWhitespace' => true, 'ReplaceImagesWithAlt' => true, ); if (isset($config)) { $config = array_merge($defaultConfig, $config); } else { $config = $defaultConfig; } $data = preg_replace("/<style([^A-Za-z0-9>][^>]*)?>.*?<\/style[^>]*>/is", '', $data); $data = preg_replace("/<script([^A-Za-z0-9>][^>]*)?>.*?<\/script[^>]*>/is", '', $data); if ($config['ReplaceBoldAsterisk']) { $data = preg_replace('%<(strong|b)( [^>]*)?>|</(strong|b)>%i', '*', $data); } // Expand hyperlinks if (!$preserveLinks && !$config['PreserveLinks']) { $data = preg_replace_callback('/<a[^>]*href\s*=\s*"([^"]*)">(.*?)<\/a>/ui', function ($matches) { return Convert::html2raw($matches[2]) . "[$matches[1]]"; }, $data); $data = preg_replace_callback('/<a[^>]*href\s*=\s*([^ ]*)>(.*?)<\/a>/ui', function ($matches) { return Convert::html2raw($matches[2]) . "[$matches[1]]"; }, $data); } // Replace images with their alt tags if ($config['ReplaceImagesWithAlt']) { $data = preg_replace('/<img[^>]*alt *= *"([^"]*)"[^>]*>/i', ' \\1 ', $data); $data = preg_replace('/<img[^>]*alt *= *([^ ]*)[^>]*>/i', ' \\1 ', $data); } // Compress whitespace if ($config['CompressWhitespace']) { $data = preg_replace("/\s+/u", ' ', $data); } // Parse newline tags $data = preg_replace("/\s*<[Hh][1-6]([^A-Za-z0-9>][^>]*)?> */u", "\n\n", $data); $data = preg_replace("/\s*<[Pp]([^A-Za-z0-9>][^>]*)?> */u", "\n\n", $data); $data = preg_replace("/\s*<[Dd][Ii][Vv]([^A-Za-z0-9>][^>]*)?> */u", "\n\n", $data); $data = preg_replace("/\n\n\n+/", "\n\n", $data); $data = preg_replace('/<[Bb][Rr]([^A-Za-z0-9>][^>]*)?> */', "\n", $data); $data = preg_replace('/<[Tt][Rr]([^A-Za-z0-9>][^>]*)?> */', "\n", $data); $data = preg_replace("/<\/[Tt][Dd]([^A-Za-z0-9>][^>]*)?> */", ' ', $data); $data = preg_replace('/<\/p>/i', "\n\n", $data); // Replace HTML entities $data = html_entity_decode($data, ENT_QUOTES, 'UTF-8'); // Remove all tags (but optionally keep links) // strip_tags seemed to be restricting the length of the output // arbitrarily. This essentially does the same thing. if (!$preserveLinks && !$config['PreserveLinks']) { $data = preg_replace('/<\/?[^>]*>/', '', $data); } else { $data = strip_tags($data, '<a>'); } // Wrap if ($wordWrap) { $data = wordwrap(trim($data), $wordWrap); } return trim($data); }
php
public static function html2raw($data, $preserveLinks = false, $wordWrap = 0, $config = null) { $defaultConfig = array( 'PreserveLinks' => false, 'ReplaceBoldAsterisk' => true, 'CompressWhitespace' => true, 'ReplaceImagesWithAlt' => true, ); if (isset($config)) { $config = array_merge($defaultConfig, $config); } else { $config = $defaultConfig; } $data = preg_replace("/<style([^A-Za-z0-9>][^>]*)?>.*?<\/style[^>]*>/is", '', $data); $data = preg_replace("/<script([^A-Za-z0-9>][^>]*)?>.*?<\/script[^>]*>/is", '', $data); if ($config['ReplaceBoldAsterisk']) { $data = preg_replace('%<(strong|b)( [^>]*)?>|</(strong|b)>%i', '*', $data); } // Expand hyperlinks if (!$preserveLinks && !$config['PreserveLinks']) { $data = preg_replace_callback('/<a[^>]*href\s*=\s*"([^"]*)">(.*?)<\/a>/ui', function ($matches) { return Convert::html2raw($matches[2]) . "[$matches[1]]"; }, $data); $data = preg_replace_callback('/<a[^>]*href\s*=\s*([^ ]*)>(.*?)<\/a>/ui', function ($matches) { return Convert::html2raw($matches[2]) . "[$matches[1]]"; }, $data); } // Replace images with their alt tags if ($config['ReplaceImagesWithAlt']) { $data = preg_replace('/<img[^>]*alt *= *"([^"]*)"[^>]*>/i', ' \\1 ', $data); $data = preg_replace('/<img[^>]*alt *= *([^ ]*)[^>]*>/i', ' \\1 ', $data); } // Compress whitespace if ($config['CompressWhitespace']) { $data = preg_replace("/\s+/u", ' ', $data); } // Parse newline tags $data = preg_replace("/\s*<[Hh][1-6]([^A-Za-z0-9>][^>]*)?> */u", "\n\n", $data); $data = preg_replace("/\s*<[Pp]([^A-Za-z0-9>][^>]*)?> */u", "\n\n", $data); $data = preg_replace("/\s*<[Dd][Ii][Vv]([^A-Za-z0-9>][^>]*)?> */u", "\n\n", $data); $data = preg_replace("/\n\n\n+/", "\n\n", $data); $data = preg_replace('/<[Bb][Rr]([^A-Za-z0-9>][^>]*)?> */', "\n", $data); $data = preg_replace('/<[Tt][Rr]([^A-Za-z0-9>][^>]*)?> */', "\n", $data); $data = preg_replace("/<\/[Tt][Dd]([^A-Za-z0-9>][^>]*)?> */", ' ', $data); $data = preg_replace('/<\/p>/i', "\n\n", $data); // Replace HTML entities $data = html_entity_decode($data, ENT_QUOTES, 'UTF-8'); // Remove all tags (but optionally keep links) // strip_tags seemed to be restricting the length of the output // arbitrarily. This essentially does the same thing. if (!$preserveLinks && !$config['PreserveLinks']) { $data = preg_replace('/<\/?[^>]*>/', '', $data); } else { $data = strip_tags($data, '<a>'); } // Wrap if ($wordWrap) { $data = wordwrap(trim($data), $wordWrap); } return trim($data); }
[ "public", "static", "function", "html2raw", "(", "$", "data", ",", "$", "preserveLinks", "=", "false", ",", "$", "wordWrap", "=", "0", ",", "$", "config", "=", "null", ")", "{", "$", "defaultConfig", "=", "array", "(", "'PreserveLinks'", "=>", "false", ",", "'ReplaceBoldAsterisk'", "=>", "true", ",", "'CompressWhitespace'", "=>", "true", ",", "'ReplaceImagesWithAlt'", "=>", "true", ",", ")", ";", "if", "(", "isset", "(", "$", "config", ")", ")", "{", "$", "config", "=", "array_merge", "(", "$", "defaultConfig", ",", "$", "config", ")", ";", "}", "else", "{", "$", "config", "=", "$", "defaultConfig", ";", "}", "$", "data", "=", "preg_replace", "(", "\"/<style([^A-Za-z0-9>][^>]*)?>.*?<\\/style[^>]*>/is\"", ",", "''", ",", "$", "data", ")", ";", "$", "data", "=", "preg_replace", "(", "\"/<script([^A-Za-z0-9>][^>]*)?>.*?<\\/script[^>]*>/is\"", ",", "''", ",", "$", "data", ")", ";", "if", "(", "$", "config", "[", "'ReplaceBoldAsterisk'", "]", ")", "{", "$", "data", "=", "preg_replace", "(", "'%<(strong|b)( [^>]*)?>|</(strong|b)>%i'", ",", "'*'", ",", "$", "data", ")", ";", "}", "// Expand hyperlinks", "if", "(", "!", "$", "preserveLinks", "&&", "!", "$", "config", "[", "'PreserveLinks'", "]", ")", "{", "$", "data", "=", "preg_replace_callback", "(", "'/<a[^>]*href\\s*=\\s*\"([^\"]*)\">(.*?)<\\/a>/ui'", ",", "function", "(", "$", "matches", ")", "{", "return", "Convert", "::", "html2raw", "(", "$", "matches", "[", "2", "]", ")", ".", "\"[$matches[1]]\"", ";", "}", ",", "$", "data", ")", ";", "$", "data", "=", "preg_replace_callback", "(", "'/<a[^>]*href\\s*=\\s*([^ ]*)>(.*?)<\\/a>/ui'", ",", "function", "(", "$", "matches", ")", "{", "return", "Convert", "::", "html2raw", "(", "$", "matches", "[", "2", "]", ")", ".", "\"[$matches[1]]\"", ";", "}", ",", "$", "data", ")", ";", "}", "// Replace images with their alt tags", "if", "(", "$", "config", "[", "'ReplaceImagesWithAlt'", "]", ")", "{", "$", "data", "=", "preg_replace", "(", "'/<img[^>]*alt *= *\"([^\"]*)\"[^>]*>/i'", ",", "' \\\\1 '", ",", "$", "data", ")", ";", "$", "data", "=", "preg_replace", "(", "'/<img[^>]*alt *= *([^ ]*)[^>]*>/i'", ",", "' \\\\1 '", ",", "$", "data", ")", ";", "}", "// Compress whitespace", "if", "(", "$", "config", "[", "'CompressWhitespace'", "]", ")", "{", "$", "data", "=", "preg_replace", "(", "\"/\\s+/u\"", ",", "' '", ",", "$", "data", ")", ";", "}", "// Parse newline tags", "$", "data", "=", "preg_replace", "(", "\"/\\s*<[Hh][1-6]([^A-Za-z0-9>][^>]*)?> */u\"", ",", "\"\\n\\n\"", ",", "$", "data", ")", ";", "$", "data", "=", "preg_replace", "(", "\"/\\s*<[Pp]([^A-Za-z0-9>][^>]*)?> */u\"", ",", "\"\\n\\n\"", ",", "$", "data", ")", ";", "$", "data", "=", "preg_replace", "(", "\"/\\s*<[Dd][Ii][Vv]([^A-Za-z0-9>][^>]*)?> */u\"", ",", "\"\\n\\n\"", ",", "$", "data", ")", ";", "$", "data", "=", "preg_replace", "(", "\"/\\n\\n\\n+/\"", ",", "\"\\n\\n\"", ",", "$", "data", ")", ";", "$", "data", "=", "preg_replace", "(", "'/<[Bb][Rr]([^A-Za-z0-9>][^>]*)?> */'", ",", "\"\\n\"", ",", "$", "data", ")", ";", "$", "data", "=", "preg_replace", "(", "'/<[Tt][Rr]([^A-Za-z0-9>][^>]*)?> */'", ",", "\"\\n\"", ",", "$", "data", ")", ";", "$", "data", "=", "preg_replace", "(", "\"/<\\/[Tt][Dd]([^A-Za-z0-9>][^>]*)?> */\"", ",", "' '", ",", "$", "data", ")", ";", "$", "data", "=", "preg_replace", "(", "'/<\\/p>/i'", ",", "\"\\n\\n\"", ",", "$", "data", ")", ";", "// Replace HTML entities", "$", "data", "=", "html_entity_decode", "(", "$", "data", ",", "ENT_QUOTES", ",", "'UTF-8'", ")", ";", "// Remove all tags (but optionally keep links)", "// strip_tags seemed to be restricting the length of the output", "// arbitrarily. This essentially does the same thing.", "if", "(", "!", "$", "preserveLinks", "&&", "!", "$", "config", "[", "'PreserveLinks'", "]", ")", "{", "$", "data", "=", "preg_replace", "(", "'/<\\/?[^>]*>/'", ",", "''", ",", "$", "data", ")", ";", "}", "else", "{", "$", "data", "=", "strip_tags", "(", "$", "data", ",", "'<a>'", ")", ";", "}", "// Wrap", "if", "(", "$", "wordWrap", ")", "{", "$", "data", "=", "wordwrap", "(", "trim", "(", "$", "data", ")", ",", "$", "wordWrap", ")", ";", "}", "return", "trim", "(", "$", "data", ")", ";", "}" ]
Simple conversion of HTML to plaintext. @param string $data Input data @param bool $preserveLinks @param int $wordWrap @param array $config @return string
[ "Simple", "conversion", "of", "HTML", "to", "plaintext", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Convert.php#L376-L446
train
silverstripe/silverstripe-framework
src/Core/Convert.php
Convert.upperCamelToLowerCamel
public static function upperCamelToLowerCamel($str) { $return = null; $matches = null; if (preg_match('/(^[A-Z]{1,})([A-Z]{1})([a-z]+.*)/', $str, $matches)) { // If string has trailing lowercase after more than one leading uppercase characters, // match everything but the last leading uppercase character. $return = implode('', [ strtolower($matches[1]), $matches[2], $matches[3] ]); } elseif (preg_match('/(^[A-Z]{1})([a-z]+.*)/', $str, $matches)) { // If string has trailing lowercase after exactly one leading uppercase characters, // match everything but the last leading uppercase character. $return = implode('', [ strtolower($matches[1]), $matches[2] ]); } elseif (preg_match('/^[A-Z]+$/', $str)) { // If string has leading uppercase without trailing lowercase, // just lowerase the whole thing. $return = strtolower($str); } else { // If string has no leading uppercase, just return. $return = $str; } return $return; }
php
public static function upperCamelToLowerCamel($str) { $return = null; $matches = null; if (preg_match('/(^[A-Z]{1,})([A-Z]{1})([a-z]+.*)/', $str, $matches)) { // If string has trailing lowercase after more than one leading uppercase characters, // match everything but the last leading uppercase character. $return = implode('', [ strtolower($matches[1]), $matches[2], $matches[3] ]); } elseif (preg_match('/(^[A-Z]{1})([a-z]+.*)/', $str, $matches)) { // If string has trailing lowercase after exactly one leading uppercase characters, // match everything but the last leading uppercase character. $return = implode('', [ strtolower($matches[1]), $matches[2] ]); } elseif (preg_match('/^[A-Z]+$/', $str)) { // If string has leading uppercase without trailing lowercase, // just lowerase the whole thing. $return = strtolower($str); } else { // If string has no leading uppercase, just return. $return = $str; } return $return; }
[ "public", "static", "function", "upperCamelToLowerCamel", "(", "$", "str", ")", "{", "$", "return", "=", "null", ";", "$", "matches", "=", "null", ";", "if", "(", "preg_match", "(", "'/(^[A-Z]{1,})([A-Z]{1})([a-z]+.*)/'", ",", "$", "str", ",", "$", "matches", ")", ")", "{", "// If string has trailing lowercase after more than one leading uppercase characters,", "// match everything but the last leading uppercase character.", "$", "return", "=", "implode", "(", "''", ",", "[", "strtolower", "(", "$", "matches", "[", "1", "]", ")", ",", "$", "matches", "[", "2", "]", ",", "$", "matches", "[", "3", "]", "]", ")", ";", "}", "elseif", "(", "preg_match", "(", "'/(^[A-Z]{1})([a-z]+.*)/'", ",", "$", "str", ",", "$", "matches", ")", ")", "{", "// If string has trailing lowercase after exactly one leading uppercase characters,", "// match everything but the last leading uppercase character.", "$", "return", "=", "implode", "(", "''", ",", "[", "strtolower", "(", "$", "matches", "[", "1", "]", ")", ",", "$", "matches", "[", "2", "]", "]", ")", ";", "}", "elseif", "(", "preg_match", "(", "'/^[A-Z]+$/'", ",", "$", "str", ")", ")", "{", "// If string has leading uppercase without trailing lowercase,", "// just lowerase the whole thing.", "$", "return", "=", "strtolower", "(", "$", "str", ")", ";", "}", "else", "{", "// If string has no leading uppercase, just return.", "$", "return", "=", "$", "str", ";", "}", "return", "$", "return", ";", "}" ]
Converts upper camel case names to lower camel case, with leading upper case characters replaced with lower case. Tries to retain word case. Examples: - ID => id - IDField => idField - iDField => iDField @param $str @return string
[ "Converts", "upper", "camel", "case", "names", "to", "lower", "camel", "case", "with", "leading", "upper", "case", "characters", "replaced", "with", "lower", "case", ".", "Tries", "to", "retain", "word", "case", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Convert.php#L534-L563
train
silverstripe/silverstripe-framework
src/Core/Convert.php
Convert.memstring2bytes
public static function memstring2bytes($memString) { // Remove non-unit characters from the size $unit = preg_replace('/[^bkmgtpezy]/i', '', $memString); // Remove non-numeric characters from the size $size = preg_replace('/[^0-9\.\-]/', '', $memString); if ($unit) { // Find the position of the unit in the ordered string which is the power // of magnitude to multiply a kilobyte by return (int)round($size * pow(1024, stripos('bkmgtpezy', $unit[0]))); } return (int)round($size); }
php
public static function memstring2bytes($memString) { // Remove non-unit characters from the size $unit = preg_replace('/[^bkmgtpezy]/i', '', $memString); // Remove non-numeric characters from the size $size = preg_replace('/[^0-9\.\-]/', '', $memString); if ($unit) { // Find the position of the unit in the ordered string which is the power // of magnitude to multiply a kilobyte by return (int)round($size * pow(1024, stripos('bkmgtpezy', $unit[0]))); } return (int)round($size); }
[ "public", "static", "function", "memstring2bytes", "(", "$", "memString", ")", "{", "// Remove non-unit characters from the size", "$", "unit", "=", "preg_replace", "(", "'/[^bkmgtpezy]/i'", ",", "''", ",", "$", "memString", ")", ";", "// Remove non-numeric characters from the size", "$", "size", "=", "preg_replace", "(", "'/[^0-9\\.\\-]/'", ",", "''", ",", "$", "memString", ")", ";", "if", "(", "$", "unit", ")", "{", "// Find the position of the unit in the ordered string which is the power", "// of magnitude to multiply a kilobyte by", "return", "(", "int", ")", "round", "(", "$", "size", "*", "pow", "(", "1024", ",", "stripos", "(", "'bkmgtpezy'", ",", "$", "unit", "[", "0", "]", ")", ")", ")", ";", "}", "return", "(", "int", ")", "round", "(", "$", "size", ")", ";", "}" ]
Turn a memory string, such as 512M into an actual number of bytes. Preserves integer values like "1024" or "-1" @param string $memString A memory limit string, such as "64M" @return int
[ "Turn", "a", "memory", "string", "such", "as", "512M", "into", "an", "actual", "number", "of", "bytes", ".", "Preserves", "integer", "values", "like", "1024", "or", "-", "1" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Convert.php#L572-L586
train
silverstripe/silverstripe-framework
src/Core/Convert.php
Convert.slashes
public static function slashes($path, $separator = DIRECTORY_SEPARATOR, $multiple = true) { if ($multiple) { return preg_replace('#[/\\\\]+#', $separator, $path); } return str_replace(['/', '\\'], $separator, $path); }
php
public static function slashes($path, $separator = DIRECTORY_SEPARATOR, $multiple = true) { if ($multiple) { return preg_replace('#[/\\\\]+#', $separator, $path); } return str_replace(['/', '\\'], $separator, $path); }
[ "public", "static", "function", "slashes", "(", "$", "path", ",", "$", "separator", "=", "DIRECTORY_SEPARATOR", ",", "$", "multiple", "=", "true", ")", "{", "if", "(", "$", "multiple", ")", "{", "return", "preg_replace", "(", "'#[/\\\\\\\\]+#'", ",", "$", "separator", ",", "$", "path", ")", ";", "}", "return", "str_replace", "(", "[", "'/'", ",", "'\\\\'", "]", ",", "$", "separator", ",", "$", "path", ")", ";", "}" ]
Convert slashes in relative or asolute filesystem path. Defaults to DIRECTORY_SEPARATOR @param string $path @param string $separator @param bool $multiple Collapses multiple slashes or not @return string
[ "Convert", "slashes", "in", "relative", "or", "asolute", "filesystem", "path", ".", "Defaults", "to", "DIRECTORY_SEPARATOR" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Convert.php#L615-L621
train
silverstripe/silverstripe-framework
src/Security/AuthenticationMiddleware.php
AuthenticationMiddleware.process
public function process(HTTPRequest $request, callable $delegate) { try { $this ->getAuthenticationHandler() ->authenticateRequest($request); } catch (ValidationException $e) { return new HTTPResponse( "Bad log-in details: " . $e->getMessage(), 400 ); } catch (DatabaseException $e) { // Database isn't ready, carry on. } return $delegate($request); }
php
public function process(HTTPRequest $request, callable $delegate) { try { $this ->getAuthenticationHandler() ->authenticateRequest($request); } catch (ValidationException $e) { return new HTTPResponse( "Bad log-in details: " . $e->getMessage(), 400 ); } catch (DatabaseException $e) { // Database isn't ready, carry on. } return $delegate($request); }
[ "public", "function", "process", "(", "HTTPRequest", "$", "request", ",", "callable", "$", "delegate", ")", "{", "try", "{", "$", "this", "->", "getAuthenticationHandler", "(", ")", "->", "authenticateRequest", "(", "$", "request", ")", ";", "}", "catch", "(", "ValidationException", "$", "e", ")", "{", "return", "new", "HTTPResponse", "(", "\"Bad log-in details: \"", ".", "$", "e", "->", "getMessage", "(", ")", ",", "400", ")", ";", "}", "catch", "(", "DatabaseException", "$", "e", ")", "{", "// Database isn't ready, carry on.", "}", "return", "$", "delegate", "(", "$", "request", ")", ";", "}" ]
Identify the current user from the request @param HTTPRequest $request @param callable $delegate @return HTTPResponse
[ "Identify", "the", "current", "user", "from", "the", "request" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/AuthenticationMiddleware.php#L46-L62
train
silverstripe/silverstripe-framework
src/ORM/FieldType/DBEnum.php
DBEnum.formField
public function formField($title = null, $name = null, $hasEmpty = false, $value = "", $emptyString = null) { if (!$title) { $title = $this->getName(); } if (!$name) { $name = $this->getName(); } $field = new DropdownField($name, $title, $this->enumValues(false), $value); if ($hasEmpty) { $field->setEmptyString($emptyString); } return $field; }
php
public function formField($title = null, $name = null, $hasEmpty = false, $value = "", $emptyString = null) { if (!$title) { $title = $this->getName(); } if (!$name) { $name = $this->getName(); } $field = new DropdownField($name, $title, $this->enumValues(false), $value); if ($hasEmpty) { $field->setEmptyString($emptyString); } return $field; }
[ "public", "function", "formField", "(", "$", "title", "=", "null", ",", "$", "name", "=", "null", ",", "$", "hasEmpty", "=", "false", ",", "$", "value", "=", "\"\"", ",", "$", "emptyString", "=", "null", ")", "{", "if", "(", "!", "$", "title", ")", "{", "$", "title", "=", "$", "this", "->", "getName", "(", ")", ";", "}", "if", "(", "!", "$", "name", ")", "{", "$", "name", "=", "$", "this", "->", "getName", "(", ")", ";", "}", "$", "field", "=", "new", "DropdownField", "(", "$", "name", ",", "$", "title", ",", "$", "this", "->", "enumValues", "(", "false", ")", ",", "$", "value", ")", ";", "if", "(", "$", "hasEmpty", ")", "{", "$", "field", "->", "setEmptyString", "(", "$", "emptyString", ")", ";", "}", "return", "$", "field", ";", "}" ]
Return a dropdown field suitable for editing this field. @param string $title @param string $name @param bool $hasEmpty @param string $value @param string $emptyString @return DropdownField
[ "Return", "a", "dropdown", "field", "suitable", "for", "editing", "this", "field", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBEnum.php#L133-L149
train
silverstripe/silverstripe-framework
src/ORM/FieldType/DBEnum.php
DBEnum.getEnumObsolete
public function getEnumObsolete() { // Without a table or field specified, we can only retrieve known enum values $table = $this->getTable(); $name = $this->getName(); if (empty($table) || empty($name)) { return $this->getEnum(); } // Ensure the table level cache exists if (empty(self::$enum_cache[$table])) { self::$enum_cache[$table] = array(); } // Check existing cache if (!empty(self::$enum_cache[$table][$name])) { return self::$enum_cache[$table][$name]; } // Get all enum values $enumValues = $this->getEnum(); if (DB::get_schema()->hasField($table, $name)) { $existing = DB::query("SELECT DISTINCT \"{$name}\" FROM \"{$table}\"")->column(); $enumValues = array_unique(array_merge($enumValues, $existing)); } // Cache and return self::$enum_cache[$table][$name] = $enumValues; return $enumValues; }
php
public function getEnumObsolete() { // Without a table or field specified, we can only retrieve known enum values $table = $this->getTable(); $name = $this->getName(); if (empty($table) || empty($name)) { return $this->getEnum(); } // Ensure the table level cache exists if (empty(self::$enum_cache[$table])) { self::$enum_cache[$table] = array(); } // Check existing cache if (!empty(self::$enum_cache[$table][$name])) { return self::$enum_cache[$table][$name]; } // Get all enum values $enumValues = $this->getEnum(); if (DB::get_schema()->hasField($table, $name)) { $existing = DB::query("SELECT DISTINCT \"{$name}\" FROM \"{$table}\"")->column(); $enumValues = array_unique(array_merge($enumValues, $existing)); } // Cache and return self::$enum_cache[$table][$name] = $enumValues; return $enumValues; }
[ "public", "function", "getEnumObsolete", "(", ")", "{", "// Without a table or field specified, we can only retrieve known enum values", "$", "table", "=", "$", "this", "->", "getTable", "(", ")", ";", "$", "name", "=", "$", "this", "->", "getName", "(", ")", ";", "if", "(", "empty", "(", "$", "table", ")", "||", "empty", "(", "$", "name", ")", ")", "{", "return", "$", "this", "->", "getEnum", "(", ")", ";", "}", "// Ensure the table level cache exists", "if", "(", "empty", "(", "self", "::", "$", "enum_cache", "[", "$", "table", "]", ")", ")", "{", "self", "::", "$", "enum_cache", "[", "$", "table", "]", "=", "array", "(", ")", ";", "}", "// Check existing cache", "if", "(", "!", "empty", "(", "self", "::", "$", "enum_cache", "[", "$", "table", "]", "[", "$", "name", "]", ")", ")", "{", "return", "self", "::", "$", "enum_cache", "[", "$", "table", "]", "[", "$", "name", "]", ";", "}", "// Get all enum values", "$", "enumValues", "=", "$", "this", "->", "getEnum", "(", ")", ";", "if", "(", "DB", "::", "get_schema", "(", ")", "->", "hasField", "(", "$", "table", ",", "$", "name", ")", ")", "{", "$", "existing", "=", "DB", "::", "query", "(", "\"SELECT DISTINCT \\\"{$name}\\\" FROM \\\"{$table}\\\"\"", ")", "->", "column", "(", ")", ";", "$", "enumValues", "=", "array_unique", "(", "array_merge", "(", "$", "enumValues", ",", "$", "existing", ")", ")", ";", "}", "// Cache and return", "self", "::", "$", "enum_cache", "[", "$", "table", "]", "[", "$", "name", "]", "=", "$", "enumValues", ";", "return", "$", "enumValues", ";", "}" ]
Get the list of enum values, including obsolete values still present in the database If table or name are not set, or if it is not a valid field on the given table, then only known enum values are returned. Values cached in this method can be cleared via `DBEnum::flushCache();` @return array
[ "Get", "the", "list", "of", "enum", "values", "including", "obsolete", "values", "still", "present", "in", "the", "database" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBEnum.php#L203-L232
train
silverstripe/silverstripe-framework
src/ORM/FieldType/DBEnum.php
DBEnum.setEnum
public function setEnum($enum) { if (!is_array($enum)) { $enum = preg_split( '/\s*,\s*/', // trim commas only if they are on the right with a newline following it ltrim(preg_replace('/,\s*\n\s*$/', '', $enum)) ); } $this->enum = array_values($enum); return $this; }
php
public function setEnum($enum) { if (!is_array($enum)) { $enum = preg_split( '/\s*,\s*/', // trim commas only if they are on the right with a newline following it ltrim(preg_replace('/,\s*\n\s*$/', '', $enum)) ); } $this->enum = array_values($enum); return $this; }
[ "public", "function", "setEnum", "(", "$", "enum", ")", "{", "if", "(", "!", "is_array", "(", "$", "enum", ")", ")", "{", "$", "enum", "=", "preg_split", "(", "'/\\s*,\\s*/'", ",", "// trim commas only if they are on the right with a newline following it", "ltrim", "(", "preg_replace", "(", "'/,\\s*\\n\\s*$/'", ",", "''", ",", "$", "enum", ")", ")", ")", ";", "}", "$", "this", "->", "enum", "=", "array_values", "(", "$", "enum", ")", ";", "return", "$", "this", ";", "}" ]
Set enum options @param string|array $enum @return $this
[ "Set", "enum", "options" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBEnum.php#L240-L251
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldAddExistingAutocompleter.php
GridFieldAddExistingAutocompleter.handleAction
public function handleAction(GridField $gridField, $actionName, $arguments, $data) { switch ($actionName) { case 'addto': if (isset($data['relationID']) && $data['relationID']) { $gridField->State->GridFieldAddRelation = $data['relationID']; } break; } }
php
public function handleAction(GridField $gridField, $actionName, $arguments, $data) { switch ($actionName) { case 'addto': if (isset($data['relationID']) && $data['relationID']) { $gridField->State->GridFieldAddRelation = $data['relationID']; } break; } }
[ "public", "function", "handleAction", "(", "GridField", "$", "gridField", ",", "$", "actionName", ",", "$", "arguments", ",", "$", "data", ")", "{", "switch", "(", "$", "actionName", ")", "{", "case", "'addto'", ":", "if", "(", "isset", "(", "$", "data", "[", "'relationID'", "]", ")", "&&", "$", "data", "[", "'relationID'", "]", ")", "{", "$", "gridField", "->", "State", "->", "GridFieldAddRelation", "=", "$", "data", "[", "'relationID'", "]", ";", "}", "break", ";", "}", "}" ]
Manipulate the state to add a new relation @param GridField $gridField @param string $actionName Action identifier, see {@link getActions()}. @param array $arguments Arguments relevant for this @param array $data All form data
[ "Manipulate", "the", "state", "to", "add", "a", "new", "relation" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldAddExistingAutocompleter.php#L173-L182
train
silverstripe/silverstripe-framework
src/Dev/Install/InstallEnvironmentAware.php
InstallEnvironmentAware.initBaseDir
protected function initBaseDir($basePath) { if ($basePath) { $this->setBaseDir($basePath); } elseif (defined('BASE_PATH')) { $this->setBaseDir(BASE_PATH); } else { throw new BadMethodCallException("No BASE_PATH defined"); } }
php
protected function initBaseDir($basePath) { if ($basePath) { $this->setBaseDir($basePath); } elseif (defined('BASE_PATH')) { $this->setBaseDir(BASE_PATH); } else { throw new BadMethodCallException("No BASE_PATH defined"); } }
[ "protected", "function", "initBaseDir", "(", "$", "basePath", ")", "{", "if", "(", "$", "basePath", ")", "{", "$", "this", "->", "setBaseDir", "(", "$", "basePath", ")", ";", "}", "elseif", "(", "defined", "(", "'BASE_PATH'", ")", ")", "{", "$", "this", "->", "setBaseDir", "(", "BASE_PATH", ")", ";", "}", "else", "{", "throw", "new", "BadMethodCallException", "(", "\"No BASE_PATH defined\"", ")", ";", "}", "}" ]
Init base path, or guess if able @param string|null $basePath
[ "Init", "base", "path", "or", "guess", "if", "able" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Install/InstallEnvironmentAware.php#L26-L35
train