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
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.encrypt_secret
public static function encrypt_secret($secret) { global $CFG; if ( startsWith($secret,'AES::') ) return $secret; $encr = AesCtr::encrypt($secret, $CFG->cookiesecret, 256) ; return 'AES::'.$encr; }
php
public static function encrypt_secret($secret) { global $CFG; if ( startsWith($secret,'AES::') ) return $secret; $encr = AesCtr::encrypt($secret, $CFG->cookiesecret, 256) ; return 'AES::'.$encr; }
[ "public", "static", "function", "encrypt_secret", "(", "$", "secret", ")", "{", "global", "$", "CFG", ";", "if", "(", "startsWith", "(", "$", "secret", ",", "'AES::'", ")", ")", "return", "$", "secret", ";", "$", "encr", "=", "AesCtr", "::", "encrypt", "(", "$", "secret", ",", "$", "CFG", "->", "cookiesecret", ",", "256", ")", ";", "return", "'AES::'", ".", "$", "encr", ";", "}" ]
Encrypt a secret to put into the session
[ "Encrypt", "a", "secret", "to", "put", "into", "the", "session" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L127-L133
train
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.decrypt_secret
public static function decrypt_secret($secret) { global $CFG; if ( $secret === null || $secret === false ) return $secret; if ( ! startsWith($secret,'AES::') ) return $secret; $secret = substr($secret, 5); $decr = AesCtr::decrypt($secret, $CFG->cookiesecret, 256) ; return $decr; }
php
public static function decrypt_secret($secret) { global $CFG; if ( $secret === null || $secret === false ) return $secret; if ( ! startsWith($secret,'AES::') ) return $secret; $secret = substr($secret, 5); $decr = AesCtr::decrypt($secret, $CFG->cookiesecret, 256) ; return $decr; }
[ "public", "static", "function", "decrypt_secret", "(", "$", "secret", ")", "{", "global", "$", "CFG", ";", "if", "(", "$", "secret", "===", "null", "||", "$", "secret", "===", "false", ")", "return", "$", "secret", ";", "if", "(", "!", "startsWith", "(", "$", "secret", ",", "'AES::'", ")", ")", "return", "$", "secret", ";", "$", "secret", "=", "substr", "(", "$", "secret", ",", "5", ")", ";", "$", "decr", "=", "AesCtr", "::", "decrypt", "(", "$", "secret", ",", "$", "CFG", "->", "cookiesecret", ",", "256", ")", ";", "return", "$", "decr", ";", "}" ]
Decrypt a secret from the session
[ "Decrypt", "a", "secret", "from", "the", "session" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L138-L146
train
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.wrapped_session_get
public static function wrapped_session_get($session_object,$key,$default=null) { global $TSUGI_SESSION_OBJECT; if ( $session_object === null && isset($TSUGI_SESSION_OBJECT) ) $session_object = $TSUGI_SESSION_OBJECT; if ( is_object($session_object) ) { return $session_object->get($key,$default); } if ( is_array($session_object) ) { if ( isset($session_object[$key]) ) return $session_object[$key]; return $default; } if ( ! isset($_SESSION) ) return $default; if ( ! isset($_SESSION[$key]) ) return $default; return $_SESSION[$key]; }
php
public static function wrapped_session_get($session_object,$key,$default=null) { global $TSUGI_SESSION_OBJECT; if ( $session_object === null && isset($TSUGI_SESSION_OBJECT) ) $session_object = $TSUGI_SESSION_OBJECT; if ( is_object($session_object) ) { return $session_object->get($key,$default); } if ( is_array($session_object) ) { if ( isset($session_object[$key]) ) return $session_object[$key]; return $default; } if ( ! isset($_SESSION) ) return $default; if ( ! isset($_SESSION[$key]) ) return $default; return $_SESSION[$key]; }
[ "public", "static", "function", "wrapped_session_get", "(", "$", "session_object", ",", "$", "key", ",", "$", "default", "=", "null", ")", "{", "global", "$", "TSUGI_SESSION_OBJECT", ";", "if", "(", "$", "session_object", "===", "null", "&&", "isset", "(", "$", "TSUGI_SESSION_OBJECT", ")", ")", "$", "session_object", "=", "$", "TSUGI_SESSION_OBJECT", ";", "if", "(", "is_object", "(", "$", "session_object", ")", ")", "{", "return", "$", "session_object", "->", "get", "(", "$", "key", ",", "$", "default", ")", ";", "}", "if", "(", "is_array", "(", "$", "session_object", ")", ")", "{", "if", "(", "isset", "(", "$", "session_object", "[", "$", "key", "]", ")", ")", "return", "$", "session_object", "[", "$", "key", "]", ";", "return", "$", "default", ";", "}", "if", "(", "!", "isset", "(", "$", "_SESSION", ")", ")", "return", "$", "default", ";", "if", "(", "!", "isset", "(", "$", "_SESSION", "[", "$", "key", "]", ")", ")", "return", "$", "default", ";", "return", "$", "_SESSION", "[", "$", "key", "]", ";", "}" ]
Wrap getting a key from the session
[ "Wrap", "getting", "a", "key", "from", "the", "session" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L151-L165
train
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.wrapped_session_all
public static function wrapped_session_all($session_object) { global $TSUGI_SESSION_OBJECT; if ( $session_object === null && isset($TSUGI_SESSION_OBJECT) ) $session_object = $TSUGI_SESSION_OBJECT; if ( is_object($session_object) ) { return $session_object->all(); } if ( is_array($session_object) ) { $retval = array(); $retval = array_merge($retval,$session_object); // Make a copy return $retval; } if ( ! isset($_SESSION) ) return array(); $retval = array(); $retval = array_merge($retval, $_SESSION); return $retval; }
php
public static function wrapped_session_all($session_object) { global $TSUGI_SESSION_OBJECT; if ( $session_object === null && isset($TSUGI_SESSION_OBJECT) ) $session_object = $TSUGI_SESSION_OBJECT; if ( is_object($session_object) ) { return $session_object->all(); } if ( is_array($session_object) ) { $retval = array(); $retval = array_merge($retval,$session_object); // Make a copy return $retval; } if ( ! isset($_SESSION) ) return array(); $retval = array(); $retval = array_merge($retval, $_SESSION); return $retval; }
[ "public", "static", "function", "wrapped_session_all", "(", "$", "session_object", ")", "{", "global", "$", "TSUGI_SESSION_OBJECT", ";", "if", "(", "$", "session_object", "===", "null", "&&", "isset", "(", "$", "TSUGI_SESSION_OBJECT", ")", ")", "$", "session_object", "=", "$", "TSUGI_SESSION_OBJECT", ";", "if", "(", "is_object", "(", "$", "session_object", ")", ")", "{", "return", "$", "session_object", "->", "all", "(", ")", ";", "}", "if", "(", "is_array", "(", "$", "session_object", ")", ")", "{", "$", "retval", "=", "array", "(", ")", ";", "$", "retval", "=", "array_merge", "(", "$", "retval", ",", "$", "session_object", ")", ";", "// Make a copy", "return", "$", "retval", ";", "}", "if", "(", "!", "isset", "(", "$", "_SESSION", ")", ")", "return", "array", "(", ")", ";", "$", "retval", "=", "array", "(", ")", ";", "$", "retval", "=", "array_merge", "(", "$", "retval", ",", "$", "_SESSION", ")", ";", "return", "$", "retval", ";", "}" ]
Get all session values
[ "Get", "all", "session", "values" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L170-L186
train
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.wrapped_session_put
public static function wrapped_session_put(&$session_object,$key,$value) { global $TSUGI_SESSION_OBJECT; if ( $session_object === null && isset($TSUGI_SESSION_OBJECT) ) $session_object = $TSUGI_SESSION_OBJECT; if ( is_object($session_object) ) { $session_object->put($key,$value); return; } if ( is_array($session_object) ) { $session_object[$key] = $value; return; } if ( isset($_SESSION) ) $_SESSION[$key] = $value; }
php
public static function wrapped_session_put(&$session_object,$key,$value) { global $TSUGI_SESSION_OBJECT; if ( $session_object === null && isset($TSUGI_SESSION_OBJECT) ) $session_object = $TSUGI_SESSION_OBJECT; if ( is_object($session_object) ) { $session_object->put($key,$value); return; } if ( is_array($session_object) ) { $session_object[$key] = $value; return; } if ( isset($_SESSION) ) $_SESSION[$key] = $value; }
[ "public", "static", "function", "wrapped_session_put", "(", "&", "$", "session_object", ",", "$", "key", ",", "$", "value", ")", "{", "global", "$", "TSUGI_SESSION_OBJECT", ";", "if", "(", "$", "session_object", "===", "null", "&&", "isset", "(", "$", "TSUGI_SESSION_OBJECT", ")", ")", "$", "session_object", "=", "$", "TSUGI_SESSION_OBJECT", ";", "if", "(", "is_object", "(", "$", "session_object", ")", ")", "{", "$", "session_object", "->", "put", "(", "$", "key", ",", "$", "value", ")", ";", "return", ";", "}", "if", "(", "is_array", "(", "$", "session_object", ")", ")", "{", "$", "session_object", "[", "$", "key", "]", "=", "$", "value", ";", "return", ";", "}", "if", "(", "isset", "(", "$", "_SESSION", ")", ")", "$", "_SESSION", "[", "$", "key", "]", "=", "$", "value", ";", "}" ]
Wrap setting a key from the session
[ "Wrap", "setting", "a", "key", "from", "the", "session" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L191-L204
train
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.wrapped_session_forget
public static function wrapped_session_forget(&$session_object,$key) { global $TSUGI_SESSION_OBJECT; if ( $session_object === null && isset($TSUGI_SESSION_OBJECT) ) $session_object = $TSUGI_SESSION_OBJECT; if ( is_object($session_object) ) { $session_object->forget($key); return; } if ( is_array($session_object) ) { if ( isset($session_object[$key]) ) unset($session_object[$key]); return; } if ( isset($_SESSION) && isset($_SESSION[$key]) ) unset($_SESSION[$key]); }
php
public static function wrapped_session_forget(&$session_object,$key) { global $TSUGI_SESSION_OBJECT; if ( $session_object === null && isset($TSUGI_SESSION_OBJECT) ) $session_object = $TSUGI_SESSION_OBJECT; if ( is_object($session_object) ) { $session_object->forget($key); return; } if ( is_array($session_object) ) { if ( isset($session_object[$key]) ) unset($session_object[$key]); return; } if ( isset($_SESSION) && isset($_SESSION[$key]) ) unset($_SESSION[$key]); }
[ "public", "static", "function", "wrapped_session_forget", "(", "&", "$", "session_object", ",", "$", "key", ")", "{", "global", "$", "TSUGI_SESSION_OBJECT", ";", "if", "(", "$", "session_object", "===", "null", "&&", "isset", "(", "$", "TSUGI_SESSION_OBJECT", ")", ")", "$", "session_object", "=", "$", "TSUGI_SESSION_OBJECT", ";", "if", "(", "is_object", "(", "$", "session_object", ")", ")", "{", "$", "session_object", "->", "forget", "(", "$", "key", ")", ";", "return", ";", "}", "if", "(", "is_array", "(", "$", "session_object", ")", ")", "{", "if", "(", "isset", "(", "$", "session_object", "[", "$", "key", "]", ")", ")", "unset", "(", "$", "session_object", "[", "$", "key", "]", ")", ";", "return", ";", "}", "if", "(", "isset", "(", "$", "_SESSION", ")", "&&", "isset", "(", "$", "_SESSION", "[", "$", "key", "]", ")", ")", "unset", "(", "$", "_SESSION", "[", "$", "key", "]", ")", ";", "}" ]
Wrap forgetting a key from the session
[ "Wrap", "forgetting", "a", "key", "from", "the", "session" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L209-L222
train
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.wrapped_session_flush
public static function wrapped_session_flush(&$session_object) { global $TSUGI_SESSION_OBJECT; if ( $session_object === null && isset($TSUGI_SESSION_OBJECT) ) $session_object = $TSUGI_SESSION_OBJECT; if ( is_object($session_object) ) { $session_object->flush(); return; } if ( is_array($session_object) ) { foreach($session_object as $k => $v ) { unset($session_object[$k]); } for ($i = 0; $i < count($session_object); $i++) { unset($session_object[$i]); } } session_unset(); }
php
public static function wrapped_session_flush(&$session_object) { global $TSUGI_SESSION_OBJECT; if ( $session_object === null && isset($TSUGI_SESSION_OBJECT) ) $session_object = $TSUGI_SESSION_OBJECT; if ( is_object($session_object) ) { $session_object->flush(); return; } if ( is_array($session_object) ) { foreach($session_object as $k => $v ) { unset($session_object[$k]); } for ($i = 0; $i < count($session_object); $i++) { unset($session_object[$i]); } } session_unset(); }
[ "public", "static", "function", "wrapped_session_flush", "(", "&", "$", "session_object", ")", "{", "global", "$", "TSUGI_SESSION_OBJECT", ";", "if", "(", "$", "session_object", "===", "null", "&&", "isset", "(", "$", "TSUGI_SESSION_OBJECT", ")", ")", "$", "session_object", "=", "$", "TSUGI_SESSION_OBJECT", ";", "if", "(", "is_object", "(", "$", "session_object", ")", ")", "{", "$", "session_object", "->", "flush", "(", ")", ";", "return", ";", "}", "if", "(", "is_array", "(", "$", "session_object", ")", ")", "{", "foreach", "(", "$", "session_object", "as", "$", "k", "=>", "$", "v", ")", "{", "unset", "(", "$", "session_object", "[", "$", "k", "]", ")", ";", "}", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "session_object", ")", ";", "$", "i", "++", ")", "{", "unset", "(", "$", "session_object", "[", "$", "i", "]", ")", ";", "}", "}", "session_unset", "(", ")", ";", "}" ]
Wrap flushing the session
[ "Wrap", "flushing", "the", "session" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L227-L244
train
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.oauth_parameters
public static function oauth_parameters() { // Find request headers $request_headers = OAuthUtil::get_headers(); // Parse the query-string to find GET parameters if ( isset($_SERVER['QUERY_STRING']) ) { $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']); } else { $parameters = array(); } // Add POST Parameters if they exist $parameters = array_merge($parameters, $_POST); // We have a Authorization-header with OAuth data. Parse the header // and add those overriding any duplicates from GET or POST if (isset($request_headers['Authorization']) && substr($request_headers['Authorization'], 0, 6) == "OAuth ") { $header_parameters = OAuthUtil::split_header( $request_headers['Authorization'] ); $parameters = array_merge($parameters, $header_parameters); } return $parameters; }
php
public static function oauth_parameters() { // Find request headers $request_headers = OAuthUtil::get_headers(); // Parse the query-string to find GET parameters if ( isset($_SERVER['QUERY_STRING']) ) { $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']); } else { $parameters = array(); } // Add POST Parameters if they exist $parameters = array_merge($parameters, $_POST); // We have a Authorization-header with OAuth data. Parse the header // and add those overriding any duplicates from GET or POST if (isset($request_headers['Authorization']) && substr($request_headers['Authorization'], 0, 6) == "OAuth ") { $header_parameters = OAuthUtil::split_header( $request_headers['Authorization'] ); $parameters = array_merge($parameters, $header_parameters); } return $parameters; }
[ "public", "static", "function", "oauth_parameters", "(", ")", "{", "// Find request headers", "$", "request_headers", "=", "OAuthUtil", "::", "get_headers", "(", ")", ";", "// Parse the query-string to find GET parameters", "if", "(", "isset", "(", "$", "_SERVER", "[", "'QUERY_STRING'", "]", ")", ")", "{", "$", "parameters", "=", "OAuthUtil", "::", "parse_parameters", "(", "$", "_SERVER", "[", "'QUERY_STRING'", "]", ")", ";", "}", "else", "{", "$", "parameters", "=", "array", "(", ")", ";", "}", "// Add POST Parameters if they exist", "$", "parameters", "=", "array_merge", "(", "$", "parameters", ",", "$", "_POST", ")", ";", "// We have a Authorization-header with OAuth data. Parse the header", "// and add those overriding any duplicates from GET or POST", "if", "(", "isset", "(", "$", "request_headers", "[", "'Authorization'", "]", ")", "&&", "substr", "(", "$", "request_headers", "[", "'Authorization'", "]", ",", "0", ",", "6", ")", "==", "\"OAuth \"", ")", "{", "$", "header_parameters", "=", "OAuthUtil", "::", "split_header", "(", "$", "request_headers", "[", "'Authorization'", "]", ")", ";", "$", "parameters", "=", "array_merge", "(", "$", "parameters", ",", "$", "header_parameters", ")", ";", "}", "return", "$", "parameters", ";", "}" ]
The LTI parameter data This code is taken from OAuthRequest
[ "The", "LTI", "parameter", "data" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L310-L334
train
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.getCompositeKey
public static function getCompositeKey($post, $session_secret) { $comp = $session_secret .'::'. $post['key'] .'::'. $post['context_id'] .'::'. U::get($post,'link_id') .'::'. $post['user_id'] .'::'. intval(time() / 1800) . $_SERVER['HTTP_USER_AGENT'] . '::' . __FILE__; return md5($comp); }
php
public static function getCompositeKey($post, $session_secret) { $comp = $session_secret .'::'. $post['key'] .'::'. $post['context_id'] .'::'. U::get($post,'link_id') .'::'. $post['user_id'] .'::'. intval(time() / 1800) . $_SERVER['HTTP_USER_AGENT'] . '::' . __FILE__; return md5($comp); }
[ "public", "static", "function", "getCompositeKey", "(", "$", "post", ",", "$", "session_secret", ")", "{", "$", "comp", "=", "$", "session_secret", ".", "'::'", ".", "$", "post", "[", "'key'", "]", ".", "'::'", ".", "$", "post", "[", "'context_id'", "]", ".", "'::'", ".", "U", "::", "get", "(", "$", "post", ",", "'link_id'", ")", ".", "'::'", ".", "$", "post", "[", "'user_id'", "]", ".", "'::'", ".", "intval", "(", "time", "(", ")", "/", "1800", ")", ".", "$", "_SERVER", "[", "'HTTP_USER_AGENT'", "]", ".", "'::'", ".", "__FILE__", ";", "return", "md5", "(", "$", "comp", ")", ";", "}" ]
session secret. Also make these change every 30 minutes
[ "session", "secret", ".", "Also", "make", "these", "change", "every", "30", "minutes" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L1026-L1031
train
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.patchNeeded
private static function patchNeeded($needed) { if ( $needed == self::NONE ) $needed = array(); if ( $needed == self::ALL ) { $needed = array(self::CONTEXT, self::LINK, self::USER); } if ( is_string($needed) ) $needed = array($needed); return $needed; }
php
private static function patchNeeded($needed) { if ( $needed == self::NONE ) $needed = array(); if ( $needed == self::ALL ) { $needed = array(self::CONTEXT, self::LINK, self::USER); } if ( is_string($needed) ) $needed = array($needed); return $needed; }
[ "private", "static", "function", "patchNeeded", "(", "$", "needed", ")", "{", "if", "(", "$", "needed", "==", "self", "::", "NONE", ")", "$", "needed", "=", "array", "(", ")", ";", "if", "(", "$", "needed", "==", "self", "::", "ALL", ")", "{", "$", "needed", "=", "array", "(", "self", "::", "CONTEXT", ",", "self", "::", "LINK", ",", "self", "::", "USER", ")", ";", "}", "if", "(", "is_string", "(", "$", "needed", ")", ")", "$", "needed", "=", "array", "(", "$", "needed", ")", ";", "return", "$", "needed", ";", "}" ]
Patch the value for the list of needed features Note - causes no harm if called more than once.
[ "Patch", "the", "value", "for", "the", "list", "of", "needed", "features" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L1450-L1457
train
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.requireDataOverride
public static function requireDataOverride($needed, $pdox, $session_object, $current_url, $request_data) { return self::requireDataPrivate($needed, $pdox, $session_object, $current_url, $request_data); }
php
public static function requireDataOverride($needed, $pdox, $session_object, $current_url, $request_data) { return self::requireDataPrivate($needed, $pdox, $session_object, $current_url, $request_data); }
[ "public", "static", "function", "requireDataOverride", "(", "$", "needed", ",", "$", "pdox", ",", "$", "session_object", ",", "$", "current_url", ",", "$", "request_data", ")", "{", "return", "self", "::", "requireDataPrivate", "(", "$", "needed", ",", "$", "pdox", ",", "$", "session_object", ",", "$", "current_url", ",", "$", "request_data", ")", ";", "}" ]
Handle the launch, but with the caller given the chance to override defaults @param $pdox array - aproperly initialized PDO object. Can be null. @param $request_data array - This must merge the $_POST, $_GET, and OAuth Header data (in that order - header data has highest priority). See self::oauth_parameters() for the way this data is normally pulled from the three sources and merged into a single array. Can be null.
[ "Handle", "the", "launch", "but", "with", "the", "caller", "given", "the", "chance", "to", "override", "defaults" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L1505-L1510
train
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.launchAuthorizationFlow
public static function launchAuthorizationFlow($request_data) { global $CFG, $PDOX; $key = U::get($request_data, 'oauth_consumer_key'); if ( ! $key ) return false; if ( U::get($request_data, 'oauth_signature_method') && U::get($request_data, 'oauth_timestamp') && U::get($request_data, 'oauth_nonce') && U::get($request_data, 'oauth_version') && U::get($request_data, 'oauth_signature') ) { // pass } else { return false; } // Handle second half of the pre LTI 1.3 Launch Authorization Flow $tool_state = U::get($request_data, 'tool_state'); if ( $tool_state && $tool_state != self::getBrowserSignature() ) { self::abort_with_error_log('Incorrect tool_state'); } // Handle first half of the pre LTI 1.3 Launch Authorization Flow $relaunch_url = U::get($request_data, 'relaunch_url'); if ( ! $relaunch_url ) return false; $key_sha256 = U::lti_sha256($key); $row = $PDOX->rowDie("SELECT key_id, key_key, secret FROM {$CFG->dbprefix}lti_key WHERE key_sha256 = :SHA", array(':SHA' => $key_sha256) ); if ( ! $row ) { self::abort_with_error_log('Could not load oauth_consumer_key'); } $valid = LTI::verifyKeyAndSecret($key,$row['secret'],self::curPageUrl(), $request_data); if ( $valid !== true ) { self::abort_with_error_log('OAuth validation fail key='.$key.' error='.$valid[0],$valid[1]); } $platform_state = U::get($request_data, 'platform_state'); if ( $platform_state) $relaunch_url = U::add_url_parm($relaunch_url, "platform_state", $platform_state); $tool_state = self::getBrowserSignature(); $relaunch_url = U::add_url_parm($relaunch_url, "tool_state", $tool_state); echo("Relaunching ".$relaunch_url); if ( headers_sent() ) { echo('<p><a href="'.$relaunch_url.'">Click to continue</a></p>'); } else { header('Location: '.$relaunch_url); } return true; }
php
public static function launchAuthorizationFlow($request_data) { global $CFG, $PDOX; $key = U::get($request_data, 'oauth_consumer_key'); if ( ! $key ) return false; if ( U::get($request_data, 'oauth_signature_method') && U::get($request_data, 'oauth_timestamp') && U::get($request_data, 'oauth_nonce') && U::get($request_data, 'oauth_version') && U::get($request_data, 'oauth_signature') ) { // pass } else { return false; } // Handle second half of the pre LTI 1.3 Launch Authorization Flow $tool_state = U::get($request_data, 'tool_state'); if ( $tool_state && $tool_state != self::getBrowserSignature() ) { self::abort_with_error_log('Incorrect tool_state'); } // Handle first half of the pre LTI 1.3 Launch Authorization Flow $relaunch_url = U::get($request_data, 'relaunch_url'); if ( ! $relaunch_url ) return false; $key_sha256 = U::lti_sha256($key); $row = $PDOX->rowDie("SELECT key_id, key_key, secret FROM {$CFG->dbprefix}lti_key WHERE key_sha256 = :SHA", array(':SHA' => $key_sha256) ); if ( ! $row ) { self::abort_with_error_log('Could not load oauth_consumer_key'); } $valid = LTI::verifyKeyAndSecret($key,$row['secret'],self::curPageUrl(), $request_data); if ( $valid !== true ) { self::abort_with_error_log('OAuth validation fail key='.$key.' error='.$valid[0],$valid[1]); } $platform_state = U::get($request_data, 'platform_state'); if ( $platform_state) $relaunch_url = U::add_url_parm($relaunch_url, "platform_state", $platform_state); $tool_state = self::getBrowserSignature(); $relaunch_url = U::add_url_parm($relaunch_url, "tool_state", $tool_state); echo("Relaunching ".$relaunch_url); if ( headers_sent() ) { echo('<p><a href="'.$relaunch_url.'">Click to continue</a></p>'); } else { header('Location: '.$relaunch_url); } return true; }
[ "public", "static", "function", "launchAuthorizationFlow", "(", "$", "request_data", ")", "{", "global", "$", "CFG", ",", "$", "PDOX", ";", "$", "key", "=", "U", "::", "get", "(", "$", "request_data", ",", "'oauth_consumer_key'", ")", ";", "if", "(", "!", "$", "key", ")", "return", "false", ";", "if", "(", "U", "::", "get", "(", "$", "request_data", ",", "'oauth_signature_method'", ")", "&&", "U", "::", "get", "(", "$", "request_data", ",", "'oauth_timestamp'", ")", "&&", "U", "::", "get", "(", "$", "request_data", ",", "'oauth_nonce'", ")", "&&", "U", "::", "get", "(", "$", "request_data", ",", "'oauth_version'", ")", "&&", "U", "::", "get", "(", "$", "request_data", ",", "'oauth_signature'", ")", ")", "{", "// pass", "}", "else", "{", "return", "false", ";", "}", "// Handle second half of the pre LTI 1.3 Launch Authorization Flow", "$", "tool_state", "=", "U", "::", "get", "(", "$", "request_data", ",", "'tool_state'", ")", ";", "if", "(", "$", "tool_state", "&&", "$", "tool_state", "!=", "self", "::", "getBrowserSignature", "(", ")", ")", "{", "self", "::", "abort_with_error_log", "(", "'Incorrect tool_state'", ")", ";", "}", "// Handle first half of the pre LTI 1.3 Launch Authorization Flow", "$", "relaunch_url", "=", "U", "::", "get", "(", "$", "request_data", ",", "'relaunch_url'", ")", ";", "if", "(", "!", "$", "relaunch_url", ")", "return", "false", ";", "$", "key_sha256", "=", "U", "::", "lti_sha256", "(", "$", "key", ")", ";", "$", "row", "=", "$", "PDOX", "->", "rowDie", "(", "\"SELECT key_id, key_key, secret\n FROM {$CFG->dbprefix}lti_key WHERE key_sha256 = :SHA\"", ",", "array", "(", "':SHA'", "=>", "$", "key_sha256", ")", ")", ";", "if", "(", "!", "$", "row", ")", "{", "self", "::", "abort_with_error_log", "(", "'Could not load oauth_consumer_key'", ")", ";", "}", "$", "valid", "=", "LTI", "::", "verifyKeyAndSecret", "(", "$", "key", ",", "$", "row", "[", "'secret'", "]", ",", "self", "::", "curPageUrl", "(", ")", ",", "$", "request_data", ")", ";", "if", "(", "$", "valid", "!==", "true", ")", "{", "self", "::", "abort_with_error_log", "(", "'OAuth validation fail key='", ".", "$", "key", ".", "' error='", ".", "$", "valid", "[", "0", "]", ",", "$", "valid", "[", "1", "]", ")", ";", "}", "$", "platform_state", "=", "U", "::", "get", "(", "$", "request_data", ",", "'platform_state'", ")", ";", "if", "(", "$", "platform_state", ")", "$", "relaunch_url", "=", "U", "::", "add_url_parm", "(", "$", "relaunch_url", ",", "\"platform_state\"", ",", "$", "platform_state", ")", ";", "$", "tool_state", "=", "self", "::", "getBrowserSignature", "(", ")", ";", "$", "relaunch_url", "=", "U", "::", "add_url_parm", "(", "$", "relaunch_url", ",", "\"tool_state\"", ",", "$", "tool_state", ")", ";", "echo", "(", "\"Relaunching \"", ".", "$", "relaunch_url", ")", ";", "if", "(", "headers_sent", "(", ")", ")", "{", "echo", "(", "'<p><a href=\"'", ".", "$", "relaunch_url", ".", "'\">Click to continue</a></p>'", ")", ";", "}", "else", "{", "header", "(", "'Location: '", ".", "$", "relaunch_url", ")", ";", "}", "return", "true", ";", "}" ]
Handle the optional LTI pre 1.3 Launch Authorization flow
[ "Handle", "the", "optional", "LTI", "pre", "1", ".", "3", "Launch", "Authorization", "flow" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L1757-L1806
train
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.var_dump
public static function var_dump() { global $USER, $CONTEXT, $LINK, $RESULT; echo('$USER:'."\n"); if ( ! isset($USER) ) { echo("Not set\n"); } else { var_dump($USER); } echo('$CONTEXT:'."\n"); if ( ! isset($CONTEXT) ) { echo("Not set\n"); } else { var_dump($CONTEXT); } echo('$LINK:'."\n"); if ( ! isset($LINK) ) { echo("Not set\n"); } else { var_dump($LINK); } echo('$RESULT:'."\n"); if ( ! isset($RESULT) ) { echo("Not set\n"); } else { var_dump($RESULT); } echo("\n<hr/>\n"); }
php
public static function var_dump() { global $USER, $CONTEXT, $LINK, $RESULT; echo('$USER:'."\n"); if ( ! isset($USER) ) { echo("Not set\n"); } else { var_dump($USER); } echo('$CONTEXT:'."\n"); if ( ! isset($CONTEXT) ) { echo("Not set\n"); } else { var_dump($CONTEXT); } echo('$LINK:'."\n"); if ( ! isset($LINK) ) { echo("Not set\n"); } else { var_dump($LINK); } echo('$RESULT:'."\n"); if ( ! isset($RESULT) ) { echo("Not set\n"); } else { var_dump($RESULT); } echo("\n<hr/>\n"); }
[ "public", "static", "function", "var_dump", "(", ")", "{", "global", "$", "USER", ",", "$", "CONTEXT", ",", "$", "LINK", ",", "$", "RESULT", ";", "echo", "(", "'$USER:'", ".", "\"\\n\"", ")", ";", "if", "(", "!", "isset", "(", "$", "USER", ")", ")", "{", "echo", "(", "\"Not set\\n\"", ")", ";", "}", "else", "{", "var_dump", "(", "$", "USER", ")", ";", "}", "echo", "(", "'$CONTEXT:'", ".", "\"\\n\"", ")", ";", "if", "(", "!", "isset", "(", "$", "CONTEXT", ")", ")", "{", "echo", "(", "\"Not set\\n\"", ")", ";", "}", "else", "{", "var_dump", "(", "$", "CONTEXT", ")", ";", "}", "echo", "(", "'$LINK:'", ".", "\"\\n\"", ")", ";", "if", "(", "!", "isset", "(", "$", "LINK", ")", ")", "{", "echo", "(", "\"Not set\\n\"", ")", ";", "}", "else", "{", "var_dump", "(", "$", "LINK", ")", ";", "}", "echo", "(", "'$RESULT:'", ".", "\"\\n\"", ")", ";", "if", "(", "!", "isset", "(", "$", "RESULT", ")", ")", "{", "echo", "(", "\"Not set\\n\"", ")", ";", "}", "else", "{", "var_dump", "(", "$", "RESULT", ")", ";", "}", "echo", "(", "\"\\n<hr/>\\n\"", ")", ";", "}" ]
Dump out the internal data structures adssociated with the current launch. Best if used within a pre tag.
[ "Dump", "out", "the", "internal", "data", "structures", "adssociated", "with", "the", "current", "launch", ".", "Best", "if", "used", "within", "a", "pre", "tag", "." ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L1812-L1839
train
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.signParameters
public static function signParameters($oldparms, $endpoint, $method, $submit_text = false, $org_id = false, $org_desc = false) { $oauth_consumer_key = self::ltiParameter('key_key'); $oauth_consumer_secret = self::decrypt_secret(self::ltiParameter('secret')); return LTI::signParameters($oldparms, $endpoint, $method, $oauth_consumer_key, $oauth_consumer_secret, $submit_text, $org_id, $org_desc); }
php
public static function signParameters($oldparms, $endpoint, $method, $submit_text = false, $org_id = false, $org_desc = false) { $oauth_consumer_key = self::ltiParameter('key_key'); $oauth_consumer_secret = self::decrypt_secret(self::ltiParameter('secret')); return LTI::signParameters($oldparms, $endpoint, $method, $oauth_consumer_key, $oauth_consumer_secret, $submit_text, $org_id, $org_desc); }
[ "public", "static", "function", "signParameters", "(", "$", "oldparms", ",", "$", "endpoint", ",", "$", "method", ",", "$", "submit_text", "=", "false", ",", "$", "org_id", "=", "false", ",", "$", "org_desc", "=", "false", ")", "{", "$", "oauth_consumer_key", "=", "self", "::", "ltiParameter", "(", "'key_key'", ")", ";", "$", "oauth_consumer_secret", "=", "self", "::", "decrypt_secret", "(", "self", "::", "ltiParameter", "(", "'secret'", ")", ")", ";", "return", "LTI", "::", "signParameters", "(", "$", "oldparms", ",", "$", "endpoint", ",", "$", "method", ",", "$", "oauth_consumer_key", ",", "$", "oauth_consumer_secret", ",", "$", "submit_text", ",", "$", "org_id", ",", "$", "org_desc", ")", ";", "}" ]
signParameters - Look up the key and secret and call the underlying code in LTI
[ "signParameters", "-", "Look", "up", "the", "key", "and", "secret", "and", "call", "the", "underlying", "code", "in", "LTI" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L1914-L1922
train
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.settingsSend
public static function settingsSend($settings, $settings_url, &$debug_log=false) { $key_key = self::ltiParameter('key_key'); $secret = self::decrypt_secret(self::ltiParameter('secret')); $retval = LTI::sendJSONSettings($settings, $settings_url, $key_key, $secret, $debug_log); return $retval; }
php
public static function settingsSend($settings, $settings_url, &$debug_log=false) { $key_key = self::ltiParameter('key_key'); $secret = self::decrypt_secret(self::ltiParameter('secret')); $retval = LTI::sendJSONSettings($settings, $settings_url, $key_key, $secret, $debug_log); return $retval; }
[ "public", "static", "function", "settingsSend", "(", "$", "settings", ",", "$", "settings_url", ",", "&", "$", "debug_log", "=", "false", ")", "{", "$", "key_key", "=", "self", "::", "ltiParameter", "(", "'key_key'", ")", ";", "$", "secret", "=", "self", "::", "decrypt_secret", "(", "self", "::", "ltiParameter", "(", "'secret'", ")", ")", ";", "$", "retval", "=", "LTI", "::", "sendJSONSettings", "(", "$", "settings", ",", "$", "settings_url", ",", "$", "key_key", ",", "$", "secret", ",", "$", "debug_log", ")", ";", "return", "$", "retval", ";", "}" ]
Send settings to the LMS using the simple JSON approach
[ "Send", "settings", "to", "the", "LMS", "using", "the", "simple", "JSON", "approach" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L1926-L1933
train
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.caliperSend
public static function caliperSend($caliperBody, $content_type='application/json', &$debug_log=false) { $caliperURL = LTIX::ltiRawParameter('custom_sub_canvas_xapi_url'); if ( strlen($caliperURL) == 0 ) { if ( is_array($debug_log) ) $debug_log[] = array('custom_sub_canvas_xapi_url not found in launch data'); return false; } $key_key = self::ltiParameter('key_key'); $secret = self::decrypt_secret(self::ltiParameter('secret')); $retval = LTI::sendJSONBody("POST", $caliperBody, $content_type, $caliperURL, $key_key, $secret, $debug_log); return $retval; }
php
public static function caliperSend($caliperBody, $content_type='application/json', &$debug_log=false) { $caliperURL = LTIX::ltiRawParameter('custom_sub_canvas_xapi_url'); if ( strlen($caliperURL) == 0 ) { if ( is_array($debug_log) ) $debug_log[] = array('custom_sub_canvas_xapi_url not found in launch data'); return false; } $key_key = self::ltiParameter('key_key'); $secret = self::decrypt_secret(self::ltiParameter('secret')); $retval = LTI::sendJSONBody("POST", $caliperBody, $content_type, $caliperURL, $key_key, $secret, $debug_log); return $retval; }
[ "public", "static", "function", "caliperSend", "(", "$", "caliperBody", ",", "$", "content_type", "=", "'application/json'", ",", "&", "$", "debug_log", "=", "false", ")", "{", "$", "caliperURL", "=", "LTIX", "::", "ltiRawParameter", "(", "'custom_sub_canvas_xapi_url'", ")", ";", "if", "(", "strlen", "(", "$", "caliperURL", ")", "==", "0", ")", "{", "if", "(", "is_array", "(", "$", "debug_log", ")", ")", "$", "debug_log", "[", "]", "=", "array", "(", "'custom_sub_canvas_xapi_url not found in launch data'", ")", ";", "return", "false", ";", "}", "$", "key_key", "=", "self", "::", "ltiParameter", "(", "'key_key'", ")", ";", "$", "secret", "=", "self", "::", "decrypt_secret", "(", "self", "::", "ltiParameter", "(", "'secret'", ")", ")", ";", "$", "retval", "=", "LTI", "::", "sendJSONBody", "(", "\"POST\"", ",", "$", "caliperBody", ",", "$", "content_type", ",", "$", "caliperURL", ",", "$", "key_key", ",", "$", "secret", ",", "$", "debug_log", ")", ";", "return", "$", "retval", ";", "}" ]
Send a Caliper Body to the correct URL using the key and secret This is not yet a standard or production - it uses the Canvas extension only.
[ "Send", "a", "Caliper", "Body", "to", "the", "correct", "URL", "using", "the", "key", "and", "secret" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L1942-L1957
train
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.jsonSend
public static function jsonSend($method, $postBody, $content_type, $service_url, &$debug_log=false) { $key_key = self::ltiParameter('key_key'); $secret = self::decrypt_secret(self::ltiParameter('secret')); $retval = LTI::sendJSONBody($method, $postBody, $content_type, $service_url, $key_key, $secret, $debug_log); return $retval; }
php
public static function jsonSend($method, $postBody, $content_type, $service_url, &$debug_log=false) { $key_key = self::ltiParameter('key_key'); $secret = self::decrypt_secret(self::ltiParameter('secret')); $retval = LTI::sendJSONBody($method, $postBody, $content_type, $service_url, $key_key, $secret, $debug_log); return $retval; }
[ "public", "static", "function", "jsonSend", "(", "$", "method", ",", "$", "postBody", ",", "$", "content_type", ",", "$", "service_url", ",", "&", "$", "debug_log", "=", "false", ")", "{", "$", "key_key", "=", "self", "::", "ltiParameter", "(", "'key_key'", ")", ";", "$", "secret", "=", "self", "::", "decrypt_secret", "(", "self", "::", "ltiParameter", "(", "'secret'", ")", ")", ";", "$", "retval", "=", "LTI", "::", "sendJSONBody", "(", "$", "method", ",", "$", "postBody", ",", "$", "content_type", ",", "$", "service_url", ",", "$", "key_key", ",", "$", "secret", ",", "$", "debug_log", ")", ";", "return", "$", "retval", ";", "}" ]
Send a JSON Body to a URL after looking up the key and secret @param $method The HTTP Method to use @param $postBody @param $content_type @param $service_url @param bool $debug_log @return mixed
[ "Send", "a", "JSON", "Body", "to", "a", "URL", "after", "looking", "up", "the", "key", "and", "secret" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L1969-L1978
train
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.removeQueryString
public static function removeQueryString($url) { $pos = strpos($url, '?'); if ( $pos === false ) return $url; $url = substr($url,0,$pos); return $url; }
php
public static function removeQueryString($url) { $pos = strpos($url, '?'); if ( $pos === false ) return $url; $url = substr($url,0,$pos); return $url; }
[ "public", "static", "function", "removeQueryString", "(", "$", "url", ")", "{", "$", "pos", "=", "strpos", "(", "$", "url", ",", "'?'", ")", ";", "if", "(", "$", "pos", "===", "false", ")", "return", "$", "url", ";", "$", "url", "=", "substr", "(", "$", "url", ",", "0", ",", "$", "pos", ")", ";", "return", "$", "url", ";", "}" ]
removeQueryString - Drop a query string from a url
[ "removeQueryString", "-", "Drop", "a", "query", "string", "from", "a", "url" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L2052-L2057
train
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.curPageUrlFolder
public static function curPageUrlFolder() { $folder = self::curPageUrlBase() . $_SERVER['REQUEST_URI']; $folder = self::removeQueryString($folder); if ( preg_match('/\/$/', $folder) ) return $folder; return dirname($folder); }
php
public static function curPageUrlFolder() { $folder = self::curPageUrlBase() . $_SERVER['REQUEST_URI']; $folder = self::removeQueryString($folder); if ( preg_match('/\/$/', $folder) ) return $folder; return dirname($folder); }
[ "public", "static", "function", "curPageUrlFolder", "(", ")", "{", "$", "folder", "=", "self", "::", "curPageUrlBase", "(", ")", ".", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ";", "$", "folder", "=", "self", "::", "removeQueryString", "(", "$", "folder", ")", ";", "if", "(", "preg_match", "(", "'/\\/$/'", ",", "$", "folder", ")", ")", "return", "$", "folder", ";", "return", "dirname", "(", "$", "folder", ")", ";", "}" ]
curPageUrlFolder - Returns the URL to the folder currently executing This is useful when rest-style files want to link back to "index.php" Note - this will not go up to a parent. URL Result http://x.com/data/ http://x.com/data/ http://x.com/data/keys http://x.com/data/
[ "curPageUrlFolder", "-", "Returns", "the", "URL", "to", "the", "folder", "currently", "executing" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L2069-L2074
train
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.curPageUrlBase
public static function curPageUrlBase() { global $CFG; $pieces = parse_url($CFG->wwwroot); if ( isset($pieces['scheme']) ) { $scheme = $pieces['scheme']; } else { $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") ? 'http' : 'https'; } if ( isset($pieces['port']) ) { $port = ':'.$pieces['port']; } else { $port = ''; if ( $_SERVER['SERVER_PORT'] != "80" && $_SERVER['SERVER_PORT'] != "443" && strpos(':', $_SERVER['HTTP_HOST']) < 0 ) { $port = ':' . $_SERVER['SERVER_PORT'] ; } } $host = isset($pieces['host']) ? $pieces['host'] : $_SERVER['HTTP_HOST']; $http_url = $scheme . '://' . $host . $port; return $http_url; }
php
public static function curPageUrlBase() { global $CFG; $pieces = parse_url($CFG->wwwroot); if ( isset($pieces['scheme']) ) { $scheme = $pieces['scheme']; } else { $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") ? 'http' : 'https'; } if ( isset($pieces['port']) ) { $port = ':'.$pieces['port']; } else { $port = ''; if ( $_SERVER['SERVER_PORT'] != "80" && $_SERVER['SERVER_PORT'] != "443" && strpos(':', $_SERVER['HTTP_HOST']) < 0 ) { $port = ':' . $_SERVER['SERVER_PORT'] ; } } $host = isset($pieces['host']) ? $pieces['host'] : $_SERVER['HTTP_HOST']; $http_url = $scheme . '://' . $host . $port; return $http_url; }
[ "public", "static", "function", "curPageUrlBase", "(", ")", "{", "global", "$", "CFG", ";", "$", "pieces", "=", "parse_url", "(", "$", "CFG", "->", "wwwroot", ")", ";", "if", "(", "isset", "(", "$", "pieces", "[", "'scheme'", "]", ")", ")", "{", "$", "scheme", "=", "$", "pieces", "[", "'scheme'", "]", ";", "}", "else", "{", "$", "scheme", "=", "(", "!", "isset", "(", "$", "_SERVER", "[", "'HTTPS'", "]", ")", "||", "$", "_SERVER", "[", "'HTTPS'", "]", "!=", "\"on\"", ")", "?", "'http'", ":", "'https'", ";", "}", "if", "(", "isset", "(", "$", "pieces", "[", "'port'", "]", ")", ")", "{", "$", "port", "=", "':'", ".", "$", "pieces", "[", "'port'", "]", ";", "}", "else", "{", "$", "port", "=", "''", ";", "if", "(", "$", "_SERVER", "[", "'SERVER_PORT'", "]", "!=", "\"80\"", "&&", "$", "_SERVER", "[", "'SERVER_PORT'", "]", "!=", "\"443\"", "&&", "strpos", "(", "':'", ",", "$", "_SERVER", "[", "'HTTP_HOST'", "]", ")", "<", "0", ")", "{", "$", "port", "=", "':'", ".", "$", "_SERVER", "[", "'SERVER_PORT'", "]", ";", "}", "}", "$", "host", "=", "isset", "(", "$", "pieces", "[", "'host'", "]", ")", "?", "$", "pieces", "[", "'host'", "]", ":", "$", "_SERVER", "[", "'HTTP_HOST'", "]", ";", "$", "http_url", "=", "$", "scheme", ".", "'://'", ".", "$", "host", ".", "$", "port", ";", "return", "$", "http_url", ";", "}" ]
curPageUrlBase - Returns the protocol, host, and port for the current URL This is useful when we are running behind a proxy like ngrok or CloudFlare. These proxies will accept with the http or https version of the URL but our web server will likely only se the incoming request as http. So we need to fall back to $CFG->wwwroot and reconstruct the right URL from there. Since the wwwroot might have some of the request URI, like http://tsugi.ngrok.com/tsugi We need to parse the wwwroot and put things back together. URL Result http://x.com/data http://x.com http://x.com/data/index.php http://x.com http://x.com/data/index.php?y=1 http://x.com @return string The current page protocol, host, and optionally port URL
[ "curPageUrlBase", "-", "Returns", "the", "protocol", "host", "and", "port", "for", "the", "current", "URL" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L2119-L2144
train
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.checkCSRF
private static function checkCSRF($session_object=null) { global $CFG; $token = self::wrapped_session_get($session_object,'CSRF_TOKEN'); if ( ! $token ) return false; if ( isset($_POST['CSRF_TOKEN']) && $token == $_POST['CSRF_TOKEN'] ) return true; $headers = array_change_key_case(apache_request_headers()); if ( isset($headers['x-csrf-token']) && $token == $headers['x-csrf-token'] ) return true; if ( isset($headers['x-csrftoken']) && $token == $headers['x-csrftoken'] ) return true; return false; }
php
private static function checkCSRF($session_object=null) { global $CFG; $token = self::wrapped_session_get($session_object,'CSRF_TOKEN'); if ( ! $token ) return false; if ( isset($_POST['CSRF_TOKEN']) && $token == $_POST['CSRF_TOKEN'] ) return true; $headers = array_change_key_case(apache_request_headers()); if ( isset($headers['x-csrf-token']) && $token == $headers['x-csrf-token'] ) return true; if ( isset($headers['x-csrftoken']) && $token == $headers['x-csrftoken'] ) return true; return false; }
[ "private", "static", "function", "checkCSRF", "(", "$", "session_object", "=", "null", ")", "{", "global", "$", "CFG", ";", "$", "token", "=", "self", "::", "wrapped_session_get", "(", "$", "session_object", ",", "'CSRF_TOKEN'", ")", ";", "if", "(", "!", "$", "token", ")", "return", "false", ";", "if", "(", "isset", "(", "$", "_POST", "[", "'CSRF_TOKEN'", "]", ")", "&&", "$", "token", "==", "$", "_POST", "[", "'CSRF_TOKEN'", "]", ")", "return", "true", ";", "$", "headers", "=", "array_change_key_case", "(", "apache_request_headers", "(", ")", ")", ";", "if", "(", "isset", "(", "$", "headers", "[", "'x-csrf-token'", "]", ")", "&&", "$", "token", "==", "$", "headers", "[", "'x-csrf-token'", "]", ")", "return", "true", ";", "if", "(", "isset", "(", "$", "headers", "[", "'x-csrftoken'", "]", ")", "&&", "$", "token", "==", "$", "headers", "[", "'x-csrftoken'", "]", ")", "return", "true", ";", "return", "false", ";", "}" ]
Returns true for a good CSRF and false if we could not verify it
[ "Returns", "true", "for", "a", "good", "CSRF", "and", "false", "if", "we", "could", "not", "verify", "it" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L2180-L2189
train
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.getCoreLaunchData
public static function getCoreLaunchData() { global $CFG, $CONTEXT, $USER, $CONTEXT, $LINK; $ltiProps = array(); $ltiProps[LTIConstants::LTI_VERSION] = LTIConstants::LTI_VERSION_1; $ltiProps[LTIConstants::CONTEXT_ID] = $CONTEXT->id; $ltiProps[LTIConstants::ROLES] = $USER->instructor ? LTIConstants::ROLE_INSTRUCTOR : LTIConstants::ROLE_LEARNER; $ltiProps[LTIConstants::USER_ID] = $USER->id; $ltiProps[LTIConstants::LIS_PERSON_NAME_FULL] = $USER->displayname; $ltiProps[LTIConstants::LIS_PERSON_CONTACT_EMAIL_PRIMARY] = $USER->email; $ltiProps['tool_consumer_instance_guid'] = $CFG->product_instance_guid; $ltiProps['tool_consumer_instance_description'] = $CFG->servicename; return $ltiProps; }
php
public static function getCoreLaunchData() { global $CFG, $CONTEXT, $USER, $CONTEXT, $LINK; $ltiProps = array(); $ltiProps[LTIConstants::LTI_VERSION] = LTIConstants::LTI_VERSION_1; $ltiProps[LTIConstants::CONTEXT_ID] = $CONTEXT->id; $ltiProps[LTIConstants::ROLES] = $USER->instructor ? LTIConstants::ROLE_INSTRUCTOR : LTIConstants::ROLE_LEARNER; $ltiProps[LTIConstants::USER_ID] = $USER->id; $ltiProps[LTIConstants::LIS_PERSON_NAME_FULL] = $USER->displayname; $ltiProps[LTIConstants::LIS_PERSON_CONTACT_EMAIL_PRIMARY] = $USER->email; $ltiProps['tool_consumer_instance_guid'] = $CFG->product_instance_guid; $ltiProps['tool_consumer_instance_description'] = $CFG->servicename; return $ltiProps; }
[ "public", "static", "function", "getCoreLaunchData", "(", ")", "{", "global", "$", "CFG", ",", "$", "CONTEXT", ",", "$", "USER", ",", "$", "CONTEXT", ",", "$", "LINK", ";", "$", "ltiProps", "=", "array", "(", ")", ";", "$", "ltiProps", "[", "LTIConstants", "::", "LTI_VERSION", "]", "=", "LTIConstants", "::", "LTI_VERSION_1", ";", "$", "ltiProps", "[", "LTIConstants", "::", "CONTEXT_ID", "]", "=", "$", "CONTEXT", "->", "id", ";", "$", "ltiProps", "[", "LTIConstants", "::", "ROLES", "]", "=", "$", "USER", "->", "instructor", "?", "LTIConstants", "::", "ROLE_INSTRUCTOR", ":", "LTIConstants", "::", "ROLE_LEARNER", ";", "$", "ltiProps", "[", "LTIConstants", "::", "USER_ID", "]", "=", "$", "USER", "->", "id", ";", "$", "ltiProps", "[", "LTIConstants", "::", "LIS_PERSON_NAME_FULL", "]", "=", "$", "USER", "->", "displayname", ";", "$", "ltiProps", "[", "LTIConstants", "::", "LIS_PERSON_CONTACT_EMAIL_PRIMARY", "]", "=", "$", "USER", "->", "email", ";", "$", "ltiProps", "[", "'tool_consumer_instance_guid'", "]", "=", "$", "CFG", "->", "product_instance_guid", ";", "$", "ltiProps", "[", "'tool_consumer_instance_description'", "]", "=", "$", "CFG", "->", "servicename", ";", "return", "$", "ltiProps", ";", "}" ]
getCoreLaunchData - Get the launch data common across launch types
[ "getCoreLaunchData", "-", "Get", "the", "launch", "data", "common", "across", "launch", "types" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L2308-L2323
train
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.getLaunchData
public static function getLaunchData() { global $CFG, $CONTEXT, $USER, $CONTEXT, $LINK; $ltiProps = self::getCoreLaunchData(); $ltiProps[LTIConstants::LTI_MESSAGE_TYPE] = LTIConstants::LTI_MESSAGE_TYPE_BASICLTILAUNCHREQUEST; $ltiProps[LTIConstants::RESOURCE_LINK_ID] = $LINK->id; $ltiProps['tool_consumer_instance_guid'] = $CFG->product_instance_guid; $ltiProps['tool_consumer_instance_description'] = $CFG->servicename; return $ltiProps; }
php
public static function getLaunchData() { global $CFG, $CONTEXT, $USER, $CONTEXT, $LINK; $ltiProps = self::getCoreLaunchData(); $ltiProps[LTIConstants::LTI_MESSAGE_TYPE] = LTIConstants::LTI_MESSAGE_TYPE_BASICLTILAUNCHREQUEST; $ltiProps[LTIConstants::RESOURCE_LINK_ID] = $LINK->id; $ltiProps['tool_consumer_instance_guid'] = $CFG->product_instance_guid; $ltiProps['tool_consumer_instance_description'] = $CFG->servicename; return $ltiProps; }
[ "public", "static", "function", "getLaunchData", "(", ")", "{", "global", "$", "CFG", ",", "$", "CONTEXT", ",", "$", "USER", ",", "$", "CONTEXT", ",", "$", "LINK", ";", "$", "ltiProps", "=", "self", "::", "getCoreLaunchData", "(", ")", ";", "$", "ltiProps", "[", "LTIConstants", "::", "LTI_MESSAGE_TYPE", "]", "=", "LTIConstants", "::", "LTI_MESSAGE_TYPE_BASICLTILAUNCHREQUEST", ";", "$", "ltiProps", "[", "LTIConstants", "::", "RESOURCE_LINK_ID", "]", "=", "$", "LINK", "->", "id", ";", "$", "ltiProps", "[", "'tool_consumer_instance_guid'", "]", "=", "$", "CFG", "->", "product_instance_guid", ";", "$", "ltiProps", "[", "'tool_consumer_instance_description'", "]", "=", "$", "CFG", "->", "servicename", ";", "return", "$", "ltiProps", ";", "}" ]
getLaunchData - Get the launch data for a normal LTI 1.x launch
[ "getLaunchData", "-", "Get", "the", "launch", "data", "for", "a", "normal", "LTI", "1", ".", "x", "launch" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L2328-L2339
train
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.getLaunchContent
public static function getLaunchContent($endpoint, $debug=false) { $info = LTIX::getKeySecretForLaunch($endpoint); if ( $info === false ) { return '<p style="color:red">Unable to load key/secret for '.htmlentities($endpoint)."</p>\n"; } $key = $info['key']; $secret = self::decrypt_secret($info['secret']); $parms = LTIX::getLaunchData(); $parms = LTI::signParameters($parms, $endpoint, "POST", $key, $secret, "Button"); $content = LTI::postLaunchHTML($parms, $endpoint, false); return $content; }
php
public static function getLaunchContent($endpoint, $debug=false) { $info = LTIX::getKeySecretForLaunch($endpoint); if ( $info === false ) { return '<p style="color:red">Unable to load key/secret for '.htmlentities($endpoint)."</p>\n"; } $key = $info['key']; $secret = self::decrypt_secret($info['secret']); $parms = LTIX::getLaunchData(); $parms = LTI::signParameters($parms, $endpoint, "POST", $key, $secret, "Button"); $content = LTI::postLaunchHTML($parms, $endpoint, false); return $content; }
[ "public", "static", "function", "getLaunchContent", "(", "$", "endpoint", ",", "$", "debug", "=", "false", ")", "{", "$", "info", "=", "LTIX", "::", "getKeySecretForLaunch", "(", "$", "endpoint", ")", ";", "if", "(", "$", "info", "===", "false", ")", "{", "return", "'<p style=\"color:red\">Unable to load key/secret for '", ".", "htmlentities", "(", "$", "endpoint", ")", ".", "\"</p>\\n\"", ";", "}", "$", "key", "=", "$", "info", "[", "'key'", "]", ";", "$", "secret", "=", "self", "::", "decrypt_secret", "(", "$", "info", "[", "'secret'", "]", ")", ";", "$", "parms", "=", "LTIX", "::", "getLaunchData", "(", ")", ";", "$", "parms", "=", "LTI", "::", "signParameters", "(", "$", "parms", ",", "$", "endpoint", ",", "\"POST\"", ",", "$", "key", ",", "$", "secret", ",", "\"Button\"", ")", ";", "$", "content", "=", "LTI", "::", "postLaunchHTML", "(", "$", "parms", ",", "$", "endpoint", ",", "false", ")", ";", "return", "$", "content", ";", "}" ]
getLaunchContent - Get the launch data for am LTI ContentItem launch
[ "getLaunchContent", "-", "Get", "the", "launch", "data", "for", "am", "LTI", "ContentItem", "launch" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L2381-L2396
train
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.abort_with_error_log
private static function abort_with_error_log($msg, $extra=false, $prefix="DIE:") { $return_url = isset($_POST['launch_presentation_return_url']) ? $_POST['launch_presentation_return_url'] : null; if ( is_array($extra) ) $extra = Output::safe_var_dump($extra); if ($return_url === null) { // make the msg a bit friendlier header('X-Tsugi-Test-Harness: https://www.tsugi.org/lti-test/'); header('X-Tsugi-Base-String-Checker: https://www.tsugi.org/lti-test/basecheck.php'); if ( $extra && ! headers_sent() ) { header('X-Tsugi-Error-Detail: '.str_replace("\n"," -- ",$extra)); } error_log($prefix.' '.$msg.' '.$extra); print_stack_trace(); $url = "https://www.tsugi.org/launcherror"; $url = U::add_url_parm($url, "detail", $msg); Output::htmlError("The LTI Lauch Failed", "Detail: $msg", $url); exit(); } $return_url .= ( strpos($return_url,'?') > 0 ) ? '&' : '?'; $return_url .= 'lti_errormsg=' . urlencode($msg); if ( $extra !== false ) { if ( strlen($extra) < 200 ) $return_url .= '&detail=' . urlencode($extra); header('X-Tsugi-Error-Detail: '.str_replace("\n"," -- ",$extra)); } header("Location: ".$return_url); error_log($prefix.' '.$msg.' '.$extra); exit(); }
php
private static function abort_with_error_log($msg, $extra=false, $prefix="DIE:") { $return_url = isset($_POST['launch_presentation_return_url']) ? $_POST['launch_presentation_return_url'] : null; if ( is_array($extra) ) $extra = Output::safe_var_dump($extra); if ($return_url === null) { // make the msg a bit friendlier header('X-Tsugi-Test-Harness: https://www.tsugi.org/lti-test/'); header('X-Tsugi-Base-String-Checker: https://www.tsugi.org/lti-test/basecheck.php'); if ( $extra && ! headers_sent() ) { header('X-Tsugi-Error-Detail: '.str_replace("\n"," -- ",$extra)); } error_log($prefix.' '.$msg.' '.$extra); print_stack_trace(); $url = "https://www.tsugi.org/launcherror"; $url = U::add_url_parm($url, "detail", $msg); Output::htmlError("The LTI Lauch Failed", "Detail: $msg", $url); exit(); } $return_url .= ( strpos($return_url,'?') > 0 ) ? '&' : '?'; $return_url .= 'lti_errormsg=' . urlencode($msg); if ( $extra !== false ) { if ( strlen($extra) < 200 ) $return_url .= '&detail=' . urlencode($extra); header('X-Tsugi-Error-Detail: '.str_replace("\n"," -- ",$extra)); } header("Location: ".$return_url); error_log($prefix.' '.$msg.' '.$extra); exit(); }
[ "private", "static", "function", "abort_with_error_log", "(", "$", "msg", ",", "$", "extra", "=", "false", ",", "$", "prefix", "=", "\"DIE:\"", ")", "{", "$", "return_url", "=", "isset", "(", "$", "_POST", "[", "'launch_presentation_return_url'", "]", ")", "?", "$", "_POST", "[", "'launch_presentation_return_url'", "]", ":", "null", ";", "if", "(", "is_array", "(", "$", "extra", ")", ")", "$", "extra", "=", "Output", "::", "safe_var_dump", "(", "$", "extra", ")", ";", "if", "(", "$", "return_url", "===", "null", ")", "{", "// make the msg a bit friendlier", "header", "(", "'X-Tsugi-Test-Harness: https://www.tsugi.org/lti-test/'", ")", ";", "header", "(", "'X-Tsugi-Base-String-Checker: https://www.tsugi.org/lti-test/basecheck.php'", ")", ";", "if", "(", "$", "extra", "&&", "!", "headers_sent", "(", ")", ")", "{", "header", "(", "'X-Tsugi-Error-Detail: '", ".", "str_replace", "(", "\"\\n\"", ",", "\" -- \"", ",", "$", "extra", ")", ")", ";", "}", "error_log", "(", "$", "prefix", ".", "' '", ".", "$", "msg", ".", "' '", ".", "$", "extra", ")", ";", "print_stack_trace", "(", ")", ";", "$", "url", "=", "\"https://www.tsugi.org/launcherror\"", ";", "$", "url", "=", "U", "::", "add_url_parm", "(", "$", "url", ",", "\"detail\"", ",", "$", "msg", ")", ";", "Output", "::", "htmlError", "(", "\"The LTI Lauch Failed\"", ",", "\"Detail: $msg\"", ",", "$", "url", ")", ";", "exit", "(", ")", ";", "}", "$", "return_url", ".=", "(", "strpos", "(", "$", "return_url", ",", "'?'", ")", ">", "0", ")", "?", "'&'", ":", "'?'", ";", "$", "return_url", ".=", "'lti_errormsg='", ".", "urlencode", "(", "$", "msg", ")", ";", "if", "(", "$", "extra", "!==", "false", ")", "{", "if", "(", "strlen", "(", "$", "extra", ")", "<", "200", ")", "$", "return_url", ".=", "'&detail='", ".", "urlencode", "(", "$", "extra", ")", ";", "header", "(", "'X-Tsugi-Error-Detail: '", ".", "str_replace", "(", "\"\\n\"", ",", "\" -- \"", ",", "$", "extra", ")", ")", ";", "}", "header", "(", "\"Location: \"", ".", "$", "return_url", ")", ";", "error_log", "(", "$", "prefix", ".", "' '", ".", "$", "msg", ".", "' '", ".", "$", "extra", ")", ";", "exit", "(", ")", ";", "}" ]
We are aborting this request. If this is a launch, redirect back
[ "We", "are", "aborting", "this", "request", ".", "If", "this", "is", "a", "launch", "redirect", "back" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L2401-L2427
train
tsugiproject/tsugi-php
src/Core/LTIX.php
LTIX.noteLoggedIn
public static function noteLoggedIn($row) { global $CFG, $PDOX; if ( ! isset($row['user_id']) ) return; if ( ! isset($PDOX) || ! $PDOX ) return; if ( Net::getIP() !== NULL ) { $sql = "UPDATE {$CFG->dbprefix}lti_user SET login_at=NOW(), login_count=login_count+1, ipaddr=:IP WHERE user_id = :user_id"; $stmt = $PDOX->queryReturnError($sql, array( ':IP' => Net::getIP(), ':user_id' => $row['user_id'])); } else { $sql = "UPDATE {$CFG->dbprefix}lti_user SET login_at=NOW(), login_count=login_count+1 WHERE user_id = :user_id"; $stmt = $PDOX->queryReturnError($sql, array( ':user_id' => $row['user_id'])); } if ( ! $stmt->success ) { error_log("Unable to update login_at user_id=".$row['user_id']); } if ( isset($row['context_id']) ) { $sql = "UPDATE {$CFG->dbprefix}lti_context SET login_at=NOW(), login_count=login_count+1 WHERE context_id = :context_id"; $stmt = $PDOX->queryReturnError($sql, array( ':context_id' => $row['context_id'])); if ( ! $stmt->success ) { error_log("Unable to update login_at context_id=".$row['context_id']); } } // We do an update of login_at for the key if ( array_key_exists('key_id', $row) ) { $sql = "UPDATE {$CFG->dbprefix}lti_key SET login_at=NOW(),login_count=login_count+1 WHERE key_id = :key_id"; $stmt = $PDOX->queryReturnError($sql, array( ':key_id' => $row['key_id'])); if ( ! $stmt->success ) { error_log("Unable to update login_at key_id=".$row['context_id']); } } }
php
public static function noteLoggedIn($row) { global $CFG, $PDOX; if ( ! isset($row['user_id']) ) return; if ( ! isset($PDOX) || ! $PDOX ) return; if ( Net::getIP() !== NULL ) { $sql = "UPDATE {$CFG->dbprefix}lti_user SET login_at=NOW(), login_count=login_count+1, ipaddr=:IP WHERE user_id = :user_id"; $stmt = $PDOX->queryReturnError($sql, array( ':IP' => Net::getIP(), ':user_id' => $row['user_id'])); } else { $sql = "UPDATE {$CFG->dbprefix}lti_user SET login_at=NOW(), login_count=login_count+1 WHERE user_id = :user_id"; $stmt = $PDOX->queryReturnError($sql, array( ':user_id' => $row['user_id'])); } if ( ! $stmt->success ) { error_log("Unable to update login_at user_id=".$row['user_id']); } if ( isset($row['context_id']) ) { $sql = "UPDATE {$CFG->dbprefix}lti_context SET login_at=NOW(), login_count=login_count+1 WHERE context_id = :context_id"; $stmt = $PDOX->queryReturnError($sql, array( ':context_id' => $row['context_id'])); if ( ! $stmt->success ) { error_log("Unable to update login_at context_id=".$row['context_id']); } } // We do an update of login_at for the key if ( array_key_exists('key_id', $row) ) { $sql = "UPDATE {$CFG->dbprefix}lti_key SET login_at=NOW(),login_count=login_count+1 WHERE key_id = :key_id"; $stmt = $PDOX->queryReturnError($sql, array( ':key_id' => $row['key_id'])); if ( ! $stmt->success ) { error_log("Unable to update login_at key_id=".$row['context_id']); } } }
[ "public", "static", "function", "noteLoggedIn", "(", "$", "row", ")", "{", "global", "$", "CFG", ",", "$", "PDOX", ";", "if", "(", "!", "isset", "(", "$", "row", "[", "'user_id'", "]", ")", ")", "return", ";", "if", "(", "!", "isset", "(", "$", "PDOX", ")", "||", "!", "$", "PDOX", ")", "return", ";", "if", "(", "Net", "::", "getIP", "(", ")", "!==", "NULL", ")", "{", "$", "sql", "=", "\"UPDATE {$CFG->dbprefix}lti_user\n SET login_at=NOW(), login_count=login_count+1, ipaddr=:IP WHERE user_id = :user_id\"", ";", "$", "stmt", "=", "$", "PDOX", "->", "queryReturnError", "(", "$", "sql", ",", "array", "(", "':IP'", "=>", "Net", "::", "getIP", "(", ")", ",", "':user_id'", "=>", "$", "row", "[", "'user_id'", "]", ")", ")", ";", "}", "else", "{", "$", "sql", "=", "\"UPDATE {$CFG->dbprefix}lti_user\n SET login_at=NOW(), login_count=login_count+1 WHERE user_id = :user_id\"", ";", "$", "stmt", "=", "$", "PDOX", "->", "queryReturnError", "(", "$", "sql", ",", "array", "(", "':user_id'", "=>", "$", "row", "[", "'user_id'", "]", ")", ")", ";", "}", "if", "(", "!", "$", "stmt", "->", "success", ")", "{", "error_log", "(", "\"Unable to update login_at user_id=\"", ".", "$", "row", "[", "'user_id'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "row", "[", "'context_id'", "]", ")", ")", "{", "$", "sql", "=", "\"UPDATE {$CFG->dbprefix}lti_context\n SET login_at=NOW(), login_count=login_count+1 WHERE context_id = :context_id\"", ";", "$", "stmt", "=", "$", "PDOX", "->", "queryReturnError", "(", "$", "sql", ",", "array", "(", "':context_id'", "=>", "$", "row", "[", "'context_id'", "]", ")", ")", ";", "if", "(", "!", "$", "stmt", "->", "success", ")", "{", "error_log", "(", "\"Unable to update login_at context_id=\"", ".", "$", "row", "[", "'context_id'", "]", ")", ";", "}", "}", "// We do an update of login_at for the key", "if", "(", "array_key_exists", "(", "'key_id'", ",", "$", "row", ")", ")", "{", "$", "sql", "=", "\"UPDATE {$CFG->dbprefix}lti_key\n SET login_at=NOW(),login_count=login_count+1 WHERE key_id = :key_id\"", ";", "$", "stmt", "=", "$", "PDOX", "->", "queryReturnError", "(", "$", "sql", ",", "array", "(", "':key_id'", "=>", "$", "row", "[", "'key_id'", "]", ")", ")", ";", "if", "(", "!", "$", "stmt", "->", "success", ")", "{", "error_log", "(", "\"Unable to update login_at key_id=\"", ".", "$", "row", "[", "'context_id'", "]", ")", ";", "}", "}", "}" ]
Update the login_at fields as appropriate
[ "Update", "the", "login_at", "fields", "as", "appropriate" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/LTIX.php#L2432-L2478
train
tsugiproject/tsugi-php
src/UI/Lessons.php
Lessons.header
public static function header($buffer=false) { global $CFG; ob_start(); ?> <style> .card { display: inline-block; padding: 0.5em; margin: 12px; border: 1px solid black; height: 9em; overflow-y: hidden; } .card div { height: 8em; overflow-y: hidden; text-overflow: ellipsis; } #loader { position: fixed; left: 0px; top: 0px; width: 100%; height: 100%; background-color: white; margin: 0; z-index: 100; } </style> <link rel="stylesheet" href="<?= $CFG->staticroot ?>/plugins/jquery.bxslider/jquery.bxslider.css" type="text/css"/> <?php $ob_output = ob_get_contents(); ob_end_clean(); if ( $buffer ) return $ob_output; echo($ob_output); }
php
public static function header($buffer=false) { global $CFG; ob_start(); ?> <style> .card { display: inline-block; padding: 0.5em; margin: 12px; border: 1px solid black; height: 9em; overflow-y: hidden; } .card div { height: 8em; overflow-y: hidden; text-overflow: ellipsis; } #loader { position: fixed; left: 0px; top: 0px; width: 100%; height: 100%; background-color: white; margin: 0; z-index: 100; } </style> <link rel="stylesheet" href="<?= $CFG->staticroot ?>/plugins/jquery.bxslider/jquery.bxslider.css" type="text/css"/> <?php $ob_output = ob_get_contents(); ob_end_clean(); if ( $buffer ) return $ob_output; echo($ob_output); }
[ "public", "static", "function", "header", "(", "$", "buffer", "=", "false", ")", "{", "global", "$", "CFG", ";", "ob_start", "(", ")", ";", "?>\n<style>\n .card {\n display: inline-block;\n padding: 0.5em;\n margin: 12px;\n border: 1px solid black;\n height: 9em;\n overflow-y: hidden;\n}\n .card div {\n height: 8em;\n overflow-y: hidden;\n text-overflow: ellipsis;\n}\n\n#loader {\n position: fixed;\n left: 0px;\n top: 0px;\n width: 100%;\n height: 100%;\n background-color: white;\n margin: 0;\n z-index: 100;\n}\n</style>\n<link rel=\"stylesheet\" href=\"<?=", "$", "CFG", "->", "staticroot", "?>/plugins/jquery.bxslider/jquery.bxslider.css\" type=\"text/css\"/>\n<?php", "$", "ob_output", "=", "ob_get_contents", "(", ")", ";", "ob_end_clean", "(", ")", ";", "if", "(", "$", "buffer", ")", "return", "$", "ob_output", ";", "echo", "(", "$", "ob_output", ")", ";", "}" ]
emit the header material
[ "emit", "the", "header", "material" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/UI/Lessons.php#L41-L77
train
tsugiproject/tsugi-php
src/UI/Lessons.php
Lessons.adjustArray
public static function adjustArray(&$entry) { global $CFG; if ( isset($entry) && !is_array($entry) ) { $entry = array($entry); } for($i=0; $i < count($entry); $i++ ) { if ( is_string($entry[$i]) ) U::absolute_url_ref($entry[$i]); if ( isset($entry[$i]->href) && is_string($entry[$i]->href) ) U::absolute_url_ref($entry[$i]->href); if ( isset($entry[$i]->launch) && is_string($entry[$i]->launch) ) U::absolute_url_ref($entry[$i]->launch); } }
php
public static function adjustArray(&$entry) { global $CFG; if ( isset($entry) && !is_array($entry) ) { $entry = array($entry); } for($i=0; $i < count($entry); $i++ ) { if ( is_string($entry[$i]) ) U::absolute_url_ref($entry[$i]); if ( isset($entry[$i]->href) && is_string($entry[$i]->href) ) U::absolute_url_ref($entry[$i]->href); if ( isset($entry[$i]->launch) && is_string($entry[$i]->launch) ) U::absolute_url_ref($entry[$i]->launch); } }
[ "public", "static", "function", "adjustArray", "(", "&", "$", "entry", ")", "{", "global", "$", "CFG", ";", "if", "(", "isset", "(", "$", "entry", ")", "&&", "!", "is_array", "(", "$", "entry", ")", ")", "{", "$", "entry", "=", "array", "(", "$", "entry", ")", ";", "}", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "entry", ")", ";", "$", "i", "++", ")", "{", "if", "(", "is_string", "(", "$", "entry", "[", "$", "i", "]", ")", ")", "U", "::", "absolute_url_ref", "(", "$", "entry", "[", "$", "i", "]", ")", ";", "if", "(", "isset", "(", "$", "entry", "[", "$", "i", "]", "->", "href", ")", "&&", "is_string", "(", "$", "entry", "[", "$", "i", "]", "->", "href", ")", ")", "U", "::", "absolute_url_ref", "(", "$", "entry", "[", "$", "i", "]", "->", "href", ")", ";", "if", "(", "isset", "(", "$", "entry", "[", "$", "i", "]", "->", "launch", ")", "&&", "is_string", "(", "$", "entry", "[", "$", "i", "]", "->", "launch", ")", ")", "U", "::", "absolute_url_ref", "(", "$", "entry", "[", "$", "i", "]", "->", "launch", ")", ";", "}", "}" ]
Make non-array into an array and adjust paths
[ "Make", "non", "-", "array", "into", "an", "array", "and", "adjust", "paths" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/UI/Lessons.php#L203-L213
train
tsugiproject/tsugi-php
src/UI/Lessons.php
Lessons.getModuleByAnchor
public function getModuleByAnchor($anchor) { foreach($this->lessons->modules as $mod) { if ( $mod->anchor == $anchor) return $mod; } return null; }
php
public function getModuleByAnchor($anchor) { foreach($this->lessons->modules as $mod) { if ( $mod->anchor == $anchor) return $mod; } return null; }
[ "public", "function", "getModuleByAnchor", "(", "$", "anchor", ")", "{", "foreach", "(", "$", "this", "->", "lessons", "->", "modules", "as", "$", "mod", ")", "{", "if", "(", "$", "mod", "->", "anchor", "==", "$", "anchor", ")", "return", "$", "mod", ";", "}", "return", "null", ";", "}" ]
Get a module associated with an anchor
[ "Get", "a", "module", "associated", "with", "an", "anchor" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/UI/Lessons.php#L225-L231
train
tsugiproject/tsugi-php
src/UI/Lessons.php
Lessons.getLtiByRlid
public function getLtiByRlid($resource_link_id) { foreach($this->lessons->modules as $mod) { if ( ! isset($mod->lti) ) continue; foreach($mod->lti as $lti ) { if ( $lti->resource_link_id == $resource_link_id) return $lti; } } return null; }
php
public function getLtiByRlid($resource_link_id) { foreach($this->lessons->modules as $mod) { if ( ! isset($mod->lti) ) continue; foreach($mod->lti as $lti ) { if ( $lti->resource_link_id == $resource_link_id) return $lti; } } return null; }
[ "public", "function", "getLtiByRlid", "(", "$", "resource_link_id", ")", "{", "foreach", "(", "$", "this", "->", "lessons", "->", "modules", "as", "$", "mod", ")", "{", "if", "(", "!", "isset", "(", "$", "mod", "->", "lti", ")", ")", "continue", ";", "foreach", "(", "$", "mod", "->", "lti", "as", "$", "lti", ")", "{", "if", "(", "$", "lti", "->", "resource_link_id", "==", "$", "resource_link_id", ")", "return", "$", "lti", ";", "}", "}", "return", "null", ";", "}" ]
Get an LTI associated with a resource link ID
[ "Get", "an", "LTI", "associated", "with", "a", "resource", "link", "ID" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/UI/Lessons.php#L236-L245
train
tsugiproject/tsugi-php
src/UI/Lessons.php
Lessons.renderAll
public function renderAll($buffer=false) { ob_start(); echo('<div typeof="Course">'."\n"); echo('<h1>'.$this->lessons->title."</h1>\n"); echo('<p property="description">'.$this->lessons->description."</p>\n"); echo('<div id="box">'."\n"); $count = 0; foreach($this->lessons->modules as $module) { if ( isset($module->login) && $module->login && !isset($_SESSION['id']) ) continue; $count++; echo('<div class="card"><div>'."\n"); $href = U::get_rest_path() . '/' . urlencode($module->anchor); if ( isset($module->icon) ) { echo('<i class="fa '.$module->icon.' fa-2x" aria-hidden="true" style="float: left; padding-right: 5px;"></i>'); } echo('<a href="'.$href.'">'."\n"); echo($count.': '.$module->title."<br clear=\"all\"/>\n"); if ( isset($module->description) ) { $desc = $module->description; if ( strlen($desc) > 1000 ) $desc = substr($desc, 0, 1000); echo('<br/>'.$desc."\n"); } echo("</a></div></div>\n"); } echo('</div> <!-- box -->'."\n"); echo('</div> <!-- typeof="Course" -->'."\n"); $ob_output = ob_get_contents(); ob_end_clean(); if ( $buffer ) return $ob_output; echo($ob_output); }
php
public function renderAll($buffer=false) { ob_start(); echo('<div typeof="Course">'."\n"); echo('<h1>'.$this->lessons->title."</h1>\n"); echo('<p property="description">'.$this->lessons->description."</p>\n"); echo('<div id="box">'."\n"); $count = 0; foreach($this->lessons->modules as $module) { if ( isset($module->login) && $module->login && !isset($_SESSION['id']) ) continue; $count++; echo('<div class="card"><div>'."\n"); $href = U::get_rest_path() . '/' . urlencode($module->anchor); if ( isset($module->icon) ) { echo('<i class="fa '.$module->icon.' fa-2x" aria-hidden="true" style="float: left; padding-right: 5px;"></i>'); } echo('<a href="'.$href.'">'."\n"); echo($count.': '.$module->title."<br clear=\"all\"/>\n"); if ( isset($module->description) ) { $desc = $module->description; if ( strlen($desc) > 1000 ) $desc = substr($desc, 0, 1000); echo('<br/>'.$desc."\n"); } echo("</a></div></div>\n"); } echo('</div> <!-- box -->'."\n"); echo('</div> <!-- typeof="Course" -->'."\n"); $ob_output = ob_get_contents(); ob_end_clean(); if ( $buffer ) return $ob_output; echo($ob_output); }
[ "public", "function", "renderAll", "(", "$", "buffer", "=", "false", ")", "{", "ob_start", "(", ")", ";", "echo", "(", "'<div typeof=\"Course\">'", ".", "\"\\n\"", ")", ";", "echo", "(", "'<h1>'", ".", "$", "this", "->", "lessons", "->", "title", ".", "\"</h1>\\n\"", ")", ";", "echo", "(", "'<p property=\"description\">'", ".", "$", "this", "->", "lessons", "->", "description", ".", "\"</p>\\n\"", ")", ";", "echo", "(", "'<div id=\"box\">'", ".", "\"\\n\"", ")", ";", "$", "count", "=", "0", ";", "foreach", "(", "$", "this", "->", "lessons", "->", "modules", "as", "$", "module", ")", "{", "if", "(", "isset", "(", "$", "module", "->", "login", ")", "&&", "$", "module", "->", "login", "&&", "!", "isset", "(", "$", "_SESSION", "[", "'id'", "]", ")", ")", "continue", ";", "$", "count", "++", ";", "echo", "(", "'<div class=\"card\"><div>'", ".", "\"\\n\"", ")", ";", "$", "href", "=", "U", "::", "get_rest_path", "(", ")", ".", "'/'", ".", "urlencode", "(", "$", "module", "->", "anchor", ")", ";", "if", "(", "isset", "(", "$", "module", "->", "icon", ")", ")", "{", "echo", "(", "'<i class=\"fa '", ".", "$", "module", "->", "icon", ".", "' fa-2x\" aria-hidden=\"true\" style=\"float: left; padding-right: 5px;\"></i>'", ")", ";", "}", "echo", "(", "'<a href=\"'", ".", "$", "href", ".", "'\">'", ".", "\"\\n\"", ")", ";", "echo", "(", "$", "count", ".", "': '", ".", "$", "module", "->", "title", ".", "\"<br clear=\\\"all\\\"/>\\n\"", ")", ";", "if", "(", "isset", "(", "$", "module", "->", "description", ")", ")", "{", "$", "desc", "=", "$", "module", "->", "description", ";", "if", "(", "strlen", "(", "$", "desc", ")", ">", "1000", ")", "$", "desc", "=", "substr", "(", "$", "desc", ",", "0", ",", "1000", ")", ";", "echo", "(", "'<br/>'", ".", "$", "desc", ".", "\"\\n\"", ")", ";", "}", "echo", "(", "\"</a></div></div>\\n\"", ")", ";", "}", "echo", "(", "'</div> <!-- box -->'", ".", "\"\\n\"", ")", ";", "echo", "(", "'</div> <!-- typeof=\"Course\" -->'", ".", "\"\\n\"", ")", ";", "$", "ob_output", "=", "ob_get_contents", "(", ")", ";", "ob_end_clean", "(", ")", ";", "if", "(", "$", "buffer", ")", "return", "$", "ob_output", ";", "echo", "(", "$", "ob_output", ")", ";", "}" ]
End of renderSingle
[ "End", "of", "renderSingle" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/UI/Lessons.php#L498-L529
train
tsugiproject/tsugi-php
src/UI/Lessons.php
Lessons.getCustomWithInherit
public function getCustomWithInherit($key, $rlid=false) { global $CFG; $custom = LTIX::ltiCustomGet($key); if ( strlen($custom) > 0 ) return $custom; if ( $rlid === false ) return false; $lti = $this->getLtiByRlid($rlid); if ( isset($lti->custom) ) foreach($lti->custom as $custom ) { if (isset($custom->key) && isset($custom->value) && $custom->key == $key ) { return $custom->value; } } return false; }
php
public function getCustomWithInherit($key, $rlid=false) { global $CFG; $custom = LTIX::ltiCustomGet($key); if ( strlen($custom) > 0 ) return $custom; if ( $rlid === false ) return false; $lti = $this->getLtiByRlid($rlid); if ( isset($lti->custom) ) foreach($lti->custom as $custom ) { if (isset($custom->key) && isset($custom->value) && $custom->key == $key ) { return $custom->value; } } return false; }
[ "public", "function", "getCustomWithInherit", "(", "$", "key", ",", "$", "rlid", "=", "false", ")", "{", "global", "$", "CFG", ";", "$", "custom", "=", "LTIX", "::", "ltiCustomGet", "(", "$", "key", ")", ";", "if", "(", "strlen", "(", "$", "custom", ")", ">", "0", ")", "return", "$", "custom", ";", "if", "(", "$", "rlid", "===", "false", ")", "return", "false", ";", "$", "lti", "=", "$", "this", "->", "getLtiByRlid", "(", "$", "rlid", ")", ";", "if", "(", "isset", "(", "$", "lti", "->", "custom", ")", ")", "foreach", "(", "$", "lti", "->", "custom", "as", "$", "custom", ")", "{", "if", "(", "isset", "(", "$", "custom", "->", "key", ")", "&&", "isset", "(", "$", "custom", "->", "value", ")", "&&", "$", "custom", "->", "key", "==", "$", "key", ")", "{", "return", "$", "custom", "->", "value", ";", "}", "}", "return", "false", ";", "}" ]
Check if a setting value is in a resource in a Lesson This solves the problems that (a) most LMS systems do not handle custom well for Common Cartridge Imports and (b) some systems do not handle custom at all when links are installed via ContentItem. Canvas has this problem for sure and others might as well. The solution is to add the resource link from the Lesson as a GET parameter on the launchurl URL to be a fallback: https://../mod/zap/?inherit=assn03 Say the tool has custom key of "exercise" that it wants a default for when the tool has not yet been configured. First we check if the LMS sent us a custom parameter and use it if present. If not, load up the LTI launch for the resource link id (assn03) in the above example and see if there is a custom parameter set in that launch and assume it was passed to us. Sample call: $assn = Settings::linkGet('exercise'); if ( ! $assn || ! isset($assignments[$assn]) ) { $rlid = isset($_GET['inherit']) ? $_GET['inherit'] : false; if ( $rlid && isset($CFG->lessons) ) { $l = new Lessons($CFG->lessons); $assn = $l->getCustomWithInherit($rlid, 'exercise'); } else { $assn = LTIX::ltiCustomGet('exercise'); } Settings::linkSet('exercise', $assn); }
[ "Check", "if", "a", "setting", "value", "is", "in", "a", "resource", "in", "a", "Lesson" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/UI/Lessons.php#L833-L847
train
tsugiproject/tsugi-php
src/Util/Net.php
Net.parseHeaders
public static function parseHeaders($headerstr=false) { if ( $headerstr === false ) $headerstr = self::getLastHeadersReceived(); $lines = explode("\n",$headerstr); $headermap = array(); foreach ($lines as $line) { $pos = strpos($line, ':'); if ( $pos < 1 ) continue; $key = substr($line,0,$pos); $value = trim(substr($line, $pos+1)); if ( strlen($key) < 1 || strlen($value) < 1 ) continue; $headermap[$key] = $value; } return $headermap; }
php
public static function parseHeaders($headerstr=false) { if ( $headerstr === false ) $headerstr = self::getLastHeadersReceived(); $lines = explode("\n",$headerstr); $headermap = array(); foreach ($lines as $line) { $pos = strpos($line, ':'); if ( $pos < 1 ) continue; $key = substr($line,0,$pos); $value = trim(substr($line, $pos+1)); if ( strlen($key) < 1 || strlen($value) < 1 ) continue; $headermap[$key] = $value; } return $headermap; }
[ "public", "static", "function", "parseHeaders", "(", "$", "headerstr", "=", "false", ")", "{", "if", "(", "$", "headerstr", "===", "false", ")", "$", "headerstr", "=", "self", "::", "getLastHeadersReceived", "(", ")", ";", "$", "lines", "=", "explode", "(", "\"\\n\"", ",", "$", "headerstr", ")", ";", "$", "headermap", "=", "array", "(", ")", ";", "foreach", "(", "$", "lines", "as", "$", "line", ")", "{", "$", "pos", "=", "strpos", "(", "$", "line", ",", "':'", ")", ";", "if", "(", "$", "pos", "<", "1", ")", "continue", ";", "$", "key", "=", "substr", "(", "$", "line", ",", "0", ",", "$", "pos", ")", ";", "$", "value", "=", "trim", "(", "substr", "(", "$", "line", ",", "$", "pos", "+", "1", ")", ")", ";", "if", "(", "strlen", "(", "$", "key", ")", "<", "1", "||", "strlen", "(", "$", "value", ")", "<", "1", ")", "continue", ";", "$", "headermap", "[", "$", "key", "]", "=", "$", "value", ";", "}", "return", "$", "headermap", ";", "}" ]
Extract a set of header lines into an array Takes a newline separated header sting and returns a key/value array
[ "Extract", "a", "set", "of", "header", "lines", "into", "an", "array" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Util/Net.php#L89-L103
train
tsugiproject/tsugi-php
src/Util/Net.php
Net.getIP
public static function getIP() { //Just get the headers if we can or else use the SERVER global if ( function_exists( 'apache_request_headers' ) ) { $headers = apache_request_headers(); } else { $headers = $_SERVER; } // $filter_option = FILTER_FLAG_IPV4; // $filter_option = FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE; $filter_option = 0; $the_ip = false; // Check Cloudflare headers if ( $the_ip === false && array_key_exists( 'HTTP_CF_CONNECTING_IP', $headers ) ) { $pieces = explode(',',$headers['HTTP_CF_CONNECTING_IP']); $the_ip = filter_var(current($pieces),FILTER_VALIDATE_IP, $filter_option ); } if ( $the_ip === false && array_key_exists( 'CF-Connecting-IP', $headers ) ) { $pieces = explode(',',$headers['CF-Connecting-IP']); $the_ip = filter_var(current($pieces),FILTER_VALIDATE_IP, $filter_option ); } // Get the forwarded IP from more traditional places if ( $the_ip == false && array_key_exists( 'X-Forwarded-For', $headers ) ) { $pieces = explode(',',$headers['X-Forwarded-For']); $the_ip = filter_var(current($pieces),FILTER_VALIDATE_IP, $filter_option ); } if ( $the_ip === false && array_key_exists( 'HTTP_X_FORWARDED_FOR', $headers ) ) { $pieces = explode(',',$headers['HTTP_X_FORWARDED_FOR']); $the_ip = filter_var(current($pieces),FILTER_VALIDATE_IP, $filter_option ); } if ( $the_ip === false && array_key_exists( 'REMOTE_ADDR', $headers ) ) { $the_ip = filter_var( $headers['REMOTE_ADDR'], FILTER_VALIDATE_IP, $filter_option ); } // Fall through and get *something* if ( $the_ip === false && array_key_exists( 'REMOTE_ADDR', $_SERVER ) ) { $the_ip = filter_var( $_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP, $filter_option ); } if ( $the_ip === false ) $the_ip = NULL; return $the_ip; }
php
public static function getIP() { //Just get the headers if we can or else use the SERVER global if ( function_exists( 'apache_request_headers' ) ) { $headers = apache_request_headers(); } else { $headers = $_SERVER; } // $filter_option = FILTER_FLAG_IPV4; // $filter_option = FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE; $filter_option = 0; $the_ip = false; // Check Cloudflare headers if ( $the_ip === false && array_key_exists( 'HTTP_CF_CONNECTING_IP', $headers ) ) { $pieces = explode(',',$headers['HTTP_CF_CONNECTING_IP']); $the_ip = filter_var(current($pieces),FILTER_VALIDATE_IP, $filter_option ); } if ( $the_ip === false && array_key_exists( 'CF-Connecting-IP', $headers ) ) { $pieces = explode(',',$headers['CF-Connecting-IP']); $the_ip = filter_var(current($pieces),FILTER_VALIDATE_IP, $filter_option ); } // Get the forwarded IP from more traditional places if ( $the_ip == false && array_key_exists( 'X-Forwarded-For', $headers ) ) { $pieces = explode(',',$headers['X-Forwarded-For']); $the_ip = filter_var(current($pieces),FILTER_VALIDATE_IP, $filter_option ); } if ( $the_ip === false && array_key_exists( 'HTTP_X_FORWARDED_FOR', $headers ) ) { $pieces = explode(',',$headers['HTTP_X_FORWARDED_FOR']); $the_ip = filter_var(current($pieces),FILTER_VALIDATE_IP, $filter_option ); } if ( $the_ip === false && array_key_exists( 'REMOTE_ADDR', $headers ) ) { $the_ip = filter_var( $headers['REMOTE_ADDR'], FILTER_VALIDATE_IP, $filter_option ); } // Fall through and get *something* if ( $the_ip === false && array_key_exists( 'REMOTE_ADDR', $_SERVER ) ) { $the_ip = filter_var( $_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP, $filter_option ); } if ( $the_ip === false ) $the_ip = NULL; return $the_ip; }
[ "public", "static", "function", "getIP", "(", ")", "{", "//Just get the headers if we can or else use the SERVER global", "if", "(", "function_exists", "(", "'apache_request_headers'", ")", ")", "{", "$", "headers", "=", "apache_request_headers", "(", ")", ";", "}", "else", "{", "$", "headers", "=", "$", "_SERVER", ";", "}", "// $filter_option = FILTER_FLAG_IPV4;", "// $filter_option = FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE;", "$", "filter_option", "=", "0", ";", "$", "the_ip", "=", "false", ";", "// Check Cloudflare headers", "if", "(", "$", "the_ip", "===", "false", "&&", "array_key_exists", "(", "'HTTP_CF_CONNECTING_IP'", ",", "$", "headers", ")", ")", "{", "$", "pieces", "=", "explode", "(", "','", ",", "$", "headers", "[", "'HTTP_CF_CONNECTING_IP'", "]", ")", ";", "$", "the_ip", "=", "filter_var", "(", "current", "(", "$", "pieces", ")", ",", "FILTER_VALIDATE_IP", ",", "$", "filter_option", ")", ";", "}", "if", "(", "$", "the_ip", "===", "false", "&&", "array_key_exists", "(", "'CF-Connecting-IP'", ",", "$", "headers", ")", ")", "{", "$", "pieces", "=", "explode", "(", "','", ",", "$", "headers", "[", "'CF-Connecting-IP'", "]", ")", ";", "$", "the_ip", "=", "filter_var", "(", "current", "(", "$", "pieces", ")", ",", "FILTER_VALIDATE_IP", ",", "$", "filter_option", ")", ";", "}", "// Get the forwarded IP from more traditional places", "if", "(", "$", "the_ip", "==", "false", "&&", "array_key_exists", "(", "'X-Forwarded-For'", ",", "$", "headers", ")", ")", "{", "$", "pieces", "=", "explode", "(", "','", ",", "$", "headers", "[", "'X-Forwarded-For'", "]", ")", ";", "$", "the_ip", "=", "filter_var", "(", "current", "(", "$", "pieces", ")", ",", "FILTER_VALIDATE_IP", ",", "$", "filter_option", ")", ";", "}", "if", "(", "$", "the_ip", "===", "false", "&&", "array_key_exists", "(", "'HTTP_X_FORWARDED_FOR'", ",", "$", "headers", ")", ")", "{", "$", "pieces", "=", "explode", "(", "','", ",", "$", "headers", "[", "'HTTP_X_FORWARDED_FOR'", "]", ")", ";", "$", "the_ip", "=", "filter_var", "(", "current", "(", "$", "pieces", ")", ",", "FILTER_VALIDATE_IP", ",", "$", "filter_option", ")", ";", "}", "if", "(", "$", "the_ip", "===", "false", "&&", "array_key_exists", "(", "'REMOTE_ADDR'", ",", "$", "headers", ")", ")", "{", "$", "the_ip", "=", "filter_var", "(", "$", "headers", "[", "'REMOTE_ADDR'", "]", ",", "FILTER_VALIDATE_IP", ",", "$", "filter_option", ")", ";", "}", "// Fall through and get *something*", "if", "(", "$", "the_ip", "===", "false", "&&", "array_key_exists", "(", "'REMOTE_ADDR'", ",", "$", "_SERVER", ")", ")", "{", "$", "the_ip", "=", "filter_var", "(", "$", "_SERVER", "[", "'REMOTE_ADDR'", "]", ",", "FILTER_VALIDATE_IP", ",", "$", "filter_option", ")", ";", "}", "if", "(", "$", "the_ip", "===", "false", ")", "$", "the_ip", "=", "NULL", ";", "return", "$", "the_ip", ";", "}" ]
Get the actual IP address of the incoming request. Handle being behind a load balancer or a proxy like Cloudflare. This will often return NULL when talking to localhost to make sure to test code using this ona real IP address. Adapted from: https://www.chriswiegman.com/2014/05/getting-correct-ip-address-php/ With some additional explode goodness via: http://stackoverflow.com/a/25193833/1994792 @return string The IP address of the incoming request or NULL if it cannot be determined.
[ "Get", "the", "actual", "IP", "address", "of", "the", "incoming", "request", "." ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Util/Net.php#L439-L487
train
MetaModels/contao-frontend-editing
src/FrontendEditHybrid.php
FrontendEditHybrid.compile
protected function compile(): void { $metaModel = $this->factory->translateIdToMetaModelName($this->metamodel); try { $this->Template->editor = $this->editor->editFor($metaModel, 'create'); } catch (NotEditableException $exception) { throw new AccessDeniedException($exception->getMessage()); } catch (NotCreatableException $exception) { throw new AccessDeniedException($exception->getMessage()); } }
php
protected function compile(): void { $metaModel = $this->factory->translateIdToMetaModelName($this->metamodel); try { $this->Template->editor = $this->editor->editFor($metaModel, 'create'); } catch (NotEditableException $exception) { throw new AccessDeniedException($exception->getMessage()); } catch (NotCreatableException $exception) { throw new AccessDeniedException($exception->getMessage()); } }
[ "protected", "function", "compile", "(", ")", ":", "void", "{", "$", "metaModel", "=", "$", "this", "->", "factory", "->", "translateIdToMetaModelName", "(", "$", "this", "->", "metamodel", ")", ";", "try", "{", "$", "this", "->", "Template", "->", "editor", "=", "$", "this", "->", "editor", "->", "editFor", "(", "$", "metaModel", ",", "'create'", ")", ";", "}", "catch", "(", "NotEditableException", "$", "exception", ")", "{", "throw", "new", "AccessDeniedException", "(", "$", "exception", "->", "getMessage", "(", ")", ")", ";", "}", "catch", "(", "NotCreatableException", "$", "exception", ")", "{", "throw", "new", "AccessDeniedException", "(", "$", "exception", "->", "getMessage", "(", ")", ")", ";", "}", "}" ]
Compile the content element. @return void @throws AccessDeniedException In case the data container is not allowed to edit.
[ "Compile", "the", "content", "element", "." ]
f11c841ef2e6d27f313b4a31db0c5fe8ac38c692
https://github.com/MetaModels/contao-frontend-editing/blob/f11c841ef2e6d27f313b4a31db0c5fe8ac38c692/src/FrontendEditHybrid.php#L89-L100
train
tsugiproject/tsugi-php
src/Core/WebSocket.php
WebSocket.enabled
public static function enabled() { global $CFG; $config = isset($CFG->websocket_url) && isset($CFG->websocket_secret); if ( ! $config ) return false; $pieces = parse_url($CFG->websocket_url); $port = U::get($pieces,'port'); $host = U::get($pieces,'host'); if ( ! $port ) return false; if ( ! $host ) return false; return true; }
php
public static function enabled() { global $CFG; $config = isset($CFG->websocket_url) && isset($CFG->websocket_secret); if ( ! $config ) return false; $pieces = parse_url($CFG->websocket_url); $port = U::get($pieces,'port'); $host = U::get($pieces,'host'); if ( ! $port ) return false; if ( ! $host ) return false; return true; }
[ "public", "static", "function", "enabled", "(", ")", "{", "global", "$", "CFG", ";", "$", "config", "=", "isset", "(", "$", "CFG", "->", "websocket_url", ")", "&&", "isset", "(", "$", "CFG", "->", "websocket_secret", ")", ";", "if", "(", "!", "$", "config", ")", "return", "false", ";", "$", "pieces", "=", "parse_url", "(", "$", "CFG", "->", "websocket_url", ")", ";", "$", "port", "=", "U", "::", "get", "(", "$", "pieces", ",", "'port'", ")", ";", "$", "host", "=", "U", "::", "get", "(", "$", "pieces", ",", "'host'", ")", ";", "if", "(", "!", "$", "port", ")", "return", "false", ";", "if", "(", "!", "$", "host", ")", "return", "false", ";", "return", "true", ";", "}" ]
Determine if this server is configured for web sockets. Set these values in your config.php: $CFG->websocket_secret = 'opensource'; $CFG->websocket_url = 'ws://localhost:2021'; You can run a local notification service for your development by doing the following: cd tsugi/admin php rachet.php You need to keep the rachet.php running for websockets to work. The web socket server does not have to be on the same server as the Tsugi hosting server. You can support more than one Tsugi server with a single rachet server as long as all of the Tsugi servers have the websocket_url and websocket_secret. $CFG->websocket_url = 'wss://socket.tsugicloud.org:443'; If the Tsugi tool server is running https, then it needs a socket server that runs wss. The TsugiCloud server uses CloudFlare to converts its ws server to a wss server.
[ "Determine", "if", "this", "server", "is", "configured", "for", "web", "sockets", "." ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/WebSocket.php#L83-L93
train
tsugiproject/tsugi-php
src/Core/WebSocket.php
WebSocket.getPort
public static function getPort() { global $CFG; if ( ! self::enabled() ) return null; $pieces = parse_url($CFG->websocket_url); return U::get($pieces,'port'); }
php
public static function getPort() { global $CFG; if ( ! self::enabled() ) return null; $pieces = parse_url($CFG->websocket_url); return U::get($pieces,'port'); }
[ "public", "static", "function", "getPort", "(", ")", "{", "global", "$", "CFG", ";", "if", "(", "!", "self", "::", "enabled", "(", ")", ")", "return", "null", ";", "$", "pieces", "=", "parse_url", "(", "$", "CFG", "->", "websocket_url", ")", ";", "return", "U", "::", "get", "(", "$", "pieces", ",", "'port'", ")", ";", "}" ]
Returns the port that the configured web socket server
[ "Returns", "the", "port", "that", "the", "configured", "web", "socket", "server" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/WebSocket.php#L98-L103
train
tsugiproject/tsugi-php
src/Core/WebSocket.php
WebSocket.makeToken
public static function makeToken($launch) { global $CFG; if ( ! isset($launch->link->id) ) return false; $token = $CFG->wwwroot . '::' . $launch->link->id . '::'; $token .= isset($launch->context->id) ? $launch->context->id : 'no_context'; $token .= '::'; $token .= isset($launch->user->id) ? $launch->context->id : 'no_user'; return $token; }
php
public static function makeToken($launch) { global $CFG; if ( ! isset($launch->link->id) ) return false; $token = $CFG->wwwroot . '::' . $launch->link->id . '::'; $token .= isset($launch->context->id) ? $launch->context->id : 'no_context'; $token .= '::'; $token .= isset($launch->user->id) ? $launch->context->id : 'no_user'; return $token; }
[ "public", "static", "function", "makeToken", "(", "$", "launch", ")", "{", "global", "$", "CFG", ";", "if", "(", "!", "isset", "(", "$", "launch", "->", "link", "->", "id", ")", ")", "return", "false", ";", "$", "token", "=", "$", "CFG", "->", "wwwroot", ".", "'::'", ".", "$", "launch", "->", "link", "->", "id", ".", "'::'", ";", "$", "token", ".=", "isset", "(", "$", "launch", "->", "context", "->", "id", ")", "?", "$", "launch", "->", "context", "->", "id", ":", "'no_context'", ";", "$", "token", ".=", "'::'", ";", "$", "token", ".=", "isset", "(", "$", "launch", "->", "user", "->", "id", ")", "?", "$", "launch", "->", "context", "->", "id", ":", "'no_user'", ";", "return", "$", "token", ";", "}" ]
Build a plaintext token for a particular link_id The token includes the host, link_id, context_id, and user_id @param string $launch The LTI launch object @return string The plaintext token or false if we cannot make a token
[ "Build", "a", "plaintext", "token", "for", "a", "particular", "link_id" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/WebSocket.php#L124-L132
train
tsugiproject/tsugi-php
src/Core/WebSocket.php
WebSocket.getToken
public static function getToken($launch) { global $CFG; if ( ! isset($CFG->websocket_secret) || strlen($CFG->websocket_secret) < 1 ) return false; $plain = self::makeToken($launch); if ( ! $plain ) return $plain; $encrypted = AesCtr::encrypt($plain, $CFG->websocket_secret, 256) ; return $encrypted; }
php
public static function getToken($launch) { global $CFG; if ( ! isset($CFG->websocket_secret) || strlen($CFG->websocket_secret) < 1 ) return false; $plain = self::makeToken($launch); if ( ! $plain ) return $plain; $encrypted = AesCtr::encrypt($plain, $CFG->websocket_secret, 256) ; return $encrypted; }
[ "public", "static", "function", "getToken", "(", "$", "launch", ")", "{", "global", "$", "CFG", ";", "if", "(", "!", "isset", "(", "$", "CFG", "->", "websocket_secret", ")", "||", "strlen", "(", "$", "CFG", "->", "websocket_secret", ")", "<", "1", ")", "return", "false", ";", "$", "plain", "=", "self", "::", "makeToken", "(", "$", "launch", ")", ";", "if", "(", "!", "$", "plain", ")", "return", "$", "plain", ";", "$", "encrypted", "=", "AesCtr", "::", "encrypt", "(", "$", "plain", ",", "$", "CFG", "->", "websocket_secret", ",", "256", ")", ";", "return", "$", "encrypted", ";", "}" ]
Build and sign a token for a particular link_id @param string $launch The LTI launch object @return string The encrypted token or false if we cannot make a token
[ "Build", "and", "sign", "a", "token", "for", "a", "particular", "link_id" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/WebSocket.php#L141-L148
train
tsugiproject/tsugi-php
src/Core/WebSocket.php
WebSocket.decodeToken
public static function decodeToken($token) { global $CFG; $plain = AesCtr::decrypt($token, $CFG->websocket_secret, 256) ; $pieces = explode('::', $plain); if ( count($pieces) != 4 ) return false; return $plain; }
php
public static function decodeToken($token) { global $CFG; $plain = AesCtr::decrypt($token, $CFG->websocket_secret, 256) ; $pieces = explode('::', $plain); if ( count($pieces) != 4 ) return false; return $plain; }
[ "public", "static", "function", "decodeToken", "(", "$", "token", ")", "{", "global", "$", "CFG", ";", "$", "plain", "=", "AesCtr", "::", "decrypt", "(", "$", "token", ",", "$", "CFG", "->", "websocket_secret", ",", "256", ")", ";", "$", "pieces", "=", "explode", "(", "'::'", ",", "$", "plain", ")", ";", "if", "(", "count", "(", "$", "pieces", ")", "!=", "4", ")", "return", "false", ";", "return", "$", "plain", ";", "}" ]
Decode and parse a token to make sure it is valid @param string $token The encrypted token @return string The plaintext token (or false on failure)
[ "Decode", "and", "parse", "a", "token", "to", "make", "sure", "it", "is", "valid" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/WebSocket.php#L157-L163
train
tsugiproject/tsugi-php
src/Core/WebSocket.php
WebSocket.getSpaceFromToken
public static function getSpaceFromToken($token) { $pieces = explode('::', $token); if ( count($pieces) != 4 ) return false; $space = implode('::', array_slice($pieces,0,2)); return $space; }
php
public static function getSpaceFromToken($token) { $pieces = explode('::', $token); if ( count($pieces) != 4 ) return false; $space = implode('::', array_slice($pieces,0,2)); return $space; }
[ "public", "static", "function", "getSpaceFromToken", "(", "$", "token", ")", "{", "$", "pieces", "=", "explode", "(", "'::'", ",", "$", "token", ")", ";", "if", "(", "count", "(", "$", "pieces", ")", "!=", "4", ")", "return", "false", ";", "$", "space", "=", "implode", "(", "'::'", ",", "array_slice", "(", "$", "pieces", ",", "0", ",", "2", ")", ")", ";", "return", "$", "space", ";", "}" ]
Pull out the host and link_id so as to create the "space" The token includes the host, link_id, context_id, and user_id. The space includes the host and link_id. @param string $token The plaintext token @return string The space for this link_id
[ "Pull", "out", "the", "host", "and", "link_id", "so", "as", "to", "create", "the", "space" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/WebSocket.php#L175-L180
train
tsugiproject/tsugi-php
src/UI/CrudForm.php
CrudForm.insertForm
public static function insertForm($fields, $from_location, $titles=false) { echo('<form method="post">'."\n"); for($i=0; $i < count($fields); $i++ ) { $field = $fields[$i]; // Don't allow setting of these fields if ( strpos($field, "_at") > 0 ) continue; if ( strpos($field, "_sha256") > 0 ) continue; echo('<div class="form-group">'."\n"); echo('<label for="'.$field.'">'.self::fieldToTitle($field, $titles)."<br/>\n"); if ( strpos($field, "secret") !== false ) { echo('<input id="'.$field.'" type="password" autocomplete="off" size="80" name="'.$field.'"'); echo("onclick=\"if ( $(this).attr('type') == 'text' ) $(this).attr('type','password'); else $(this).attr('type','text'); return false;\">\n"); } else { echo('<input type="text" size="80" id="'.$field.'" name="'.$field.'">'."\n"); } echo("</label>\n</div>"); } echo('<input type="submit" name="doSave" class="btn btn-normal" value="'._m("Save").'">'."\n"); echo('<a href="'.$from_location.'" class="btn btn-default">Cancel</a>'."\n"); echo('</form>'."\n"); }
php
public static function insertForm($fields, $from_location, $titles=false) { echo('<form method="post">'."\n"); for($i=0; $i < count($fields); $i++ ) { $field = $fields[$i]; // Don't allow setting of these fields if ( strpos($field, "_at") > 0 ) continue; if ( strpos($field, "_sha256") > 0 ) continue; echo('<div class="form-group">'."\n"); echo('<label for="'.$field.'">'.self::fieldToTitle($field, $titles)."<br/>\n"); if ( strpos($field, "secret") !== false ) { echo('<input id="'.$field.'" type="password" autocomplete="off" size="80" name="'.$field.'"'); echo("onclick=\"if ( $(this).attr('type') == 'text' ) $(this).attr('type','password'); else $(this).attr('type','text'); return false;\">\n"); } else { echo('<input type="text" size="80" id="'.$field.'" name="'.$field.'">'."\n"); } echo("</label>\n</div>"); } echo('<input type="submit" name="doSave" class="btn btn-normal" value="'._m("Save").'">'."\n"); echo('<a href="'.$from_location.'" class="btn btn-default">Cancel</a>'."\n"); echo('</form>'."\n"); }
[ "public", "static", "function", "insertForm", "(", "$", "fields", ",", "$", "from_location", ",", "$", "titles", "=", "false", ")", "{", "echo", "(", "'<form method=\"post\">'", ".", "\"\\n\"", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "fields", ")", ";", "$", "i", "++", ")", "{", "$", "field", "=", "$", "fields", "[", "$", "i", "]", ";", "// Don't allow setting of these fields", "if", "(", "strpos", "(", "$", "field", ",", "\"_at\"", ")", ">", "0", ")", "continue", ";", "if", "(", "strpos", "(", "$", "field", ",", "\"_sha256\"", ")", ">", "0", ")", "continue", ";", "echo", "(", "'<div class=\"form-group\">'", ".", "\"\\n\"", ")", ";", "echo", "(", "'<label for=\"'", ".", "$", "field", ".", "'\">'", ".", "self", "::", "fieldToTitle", "(", "$", "field", ",", "$", "titles", ")", ".", "\"<br/>\\n\"", ")", ";", "if", "(", "strpos", "(", "$", "field", ",", "\"secret\"", ")", "!==", "false", ")", "{", "echo", "(", "'<input id=\"'", ".", "$", "field", ".", "'\" type=\"password\" autocomplete=\"off\" size=\"80\" name=\"'", ".", "$", "field", ".", "'\"'", ")", ";", "echo", "(", "\"onclick=\\\"if ( $(this).attr('type') == 'text' ) $(this).attr('type','password'); else $(this).attr('type','text'); return false;\\\">\\n\"", ")", ";", "}", "else", "{", "echo", "(", "'<input type=\"text\" size=\"80\" id=\"'", ".", "$", "field", ".", "'\" name=\"'", ".", "$", "field", ".", "'\">'", ".", "\"\\n\"", ")", ";", "}", "echo", "(", "\"</label>\\n</div>\"", ")", ";", "}", "echo", "(", "'<input type=\"submit\" name=\"doSave\" class=\"btn btn-normal\" value=\"'", ".", "_m", "(", "\"Save\"", ")", ".", "'\">'", ".", "\"\\n\"", ")", ";", "echo", "(", "'<a href=\"'", ".", "$", "from_location", ".", "'\" class=\"btn btn-default\">Cancel</a>'", ".", "\"\\n\"", ")", ";", "echo", "(", "'</form>'", ".", "\"\\n\"", ")", ";", "}" ]
Generate the HTML for an insert form. Here is a sample call: $from_location = "keys.php"; $fields = array("key_key", "key_sha256", "secret", "created_at", "updated_at"); CrudForm::insertForm($fields, $from_location); @param $fields An array of fields to prompt for. @param $from_location A URL to jump to when the user presses 'Cancel'. @param $titles An array of fields->titles
[ "Generate", "the", "HTML", "for", "an", "insert", "form", "." ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/UI/CrudForm.php#L57-L82
train
tsugiproject/tsugi-php
src/UI/CrudForm.php
CrudForm.fieldToTitle
public static function fieldToTitle($name, $titles=false) { if ( is_array($titles) && U::get($titles, $name) ) return U::get($titles, $name); return ucwords(str_replace('_',' ',$name)); }
php
public static function fieldToTitle($name, $titles=false) { if ( is_array($titles) && U::get($titles, $name) ) return U::get($titles, $name); return ucwords(str_replace('_',' ',$name)); }
[ "public", "static", "function", "fieldToTitle", "(", "$", "name", ",", "$", "titles", "=", "false", ")", "{", "if", "(", "is_array", "(", "$", "titles", ")", "&&", "U", "::", "get", "(", "$", "titles", ",", "$", "name", ")", ")", "return", "U", "::", "get", "(", "$", "titles", ",", "$", "name", ")", ";", "return", "ucwords", "(", "str_replace", "(", "'_'", ",", "' '", ",", "$", "name", ")", ")", ";", "}" ]
Maps a field name to a presentable title. @todo Make this translatable and pretty
[ "Maps", "a", "field", "name", "to", "a", "presentable", "title", "." ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/UI/CrudForm.php#L355-L358
train
tsugiproject/tsugi-php
src/UI/CrudForm.php
CrudForm.selectSql
public static function selectSql($tablename, $fields, $where_clause=false) { $sql = "SELECT "; $first = true; foreach ( $fields as $field ) { if ( ! $first ) $sql .= ', '; $sql .= $field; $first = false; } $sql .= "\n FROM ".$tablename; if ( $where_clause && strlen($where_clause) > 0 ) $sql .= "\nWHERE ".$where_clause; return $sql; }
php
public static function selectSql($tablename, $fields, $where_clause=false) { $sql = "SELECT "; $first = true; foreach ( $fields as $field ) { if ( ! $first ) $sql .= ', '; $sql .= $field; $first = false; } $sql .= "\n FROM ".$tablename; if ( $where_clause && strlen($where_clause) > 0 ) $sql .= "\nWHERE ".$where_clause; return $sql; }
[ "public", "static", "function", "selectSql", "(", "$", "tablename", ",", "$", "fields", ",", "$", "where_clause", "=", "false", ")", "{", "$", "sql", "=", "\"SELECT \"", ";", "$", "first", "=", "true", ";", "foreach", "(", "$", "fields", "as", "$", "field", ")", "{", "if", "(", "!", "$", "first", ")", "$", "sql", ".=", "', '", ";", "$", "sql", ".=", "$", "field", ";", "$", "first", "=", "false", ";", "}", "$", "sql", ".=", "\"\\n FROM \"", ".", "$", "tablename", ";", "if", "(", "$", "where_clause", "&&", "strlen", "(", "$", "where_clause", ")", ">", "0", ")", "$", "sql", ".=", "\"\\nWHERE \"", ".", "$", "where_clause", ";", "return", "$", "sql", ";", "}" ]
Produce the SELECT statement for a table, set of fields and where clause. @param $fields An array of field names to select. @param $where_clause This is the WHERE clause but should not include the WHERE keyword.
[ "Produce", "the", "SELECT", "statement", "for", "a", "table", "set", "of", "fields", "and", "where", "clause", "." ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/UI/CrudForm.php#L367-L378
train
JayBizzle/Laravel-Migrations-Organiser
src/Migrator.php
Migrator.getRecursiveFolders
public function getRecursiveFolders($folders) { if (! is_array($folders)) { $folders = [$folders]; } $paths = []; foreach ($folders as $folder) { $iter = new Iterator( new DirectoryIterator($folder, DirectoryIterator::SKIP_DOTS), Iterator::SELF_FIRST, Iterator::CATCH_GET_CHILD // Ignore "Permission denied" ); $subPaths = [$folder]; foreach ($iter as $path => $dir) { if ($dir->isDir()) { $subPaths[] = $path; } } $paths = array_merge($paths, $subPaths); } return $paths; }
php
public function getRecursiveFolders($folders) { if (! is_array($folders)) { $folders = [$folders]; } $paths = []; foreach ($folders as $folder) { $iter = new Iterator( new DirectoryIterator($folder, DirectoryIterator::SKIP_DOTS), Iterator::SELF_FIRST, Iterator::CATCH_GET_CHILD // Ignore "Permission denied" ); $subPaths = [$folder]; foreach ($iter as $path => $dir) { if ($dir->isDir()) { $subPaths[] = $path; } } $paths = array_merge($paths, $subPaths); } return $paths; }
[ "public", "function", "getRecursiveFolders", "(", "$", "folders", ")", "{", "if", "(", "!", "is_array", "(", "$", "folders", ")", ")", "{", "$", "folders", "=", "[", "$", "folders", "]", ";", "}", "$", "paths", "=", "[", "]", ";", "foreach", "(", "$", "folders", "as", "$", "folder", ")", "{", "$", "iter", "=", "new", "Iterator", "(", "new", "DirectoryIterator", "(", "$", "folder", ",", "DirectoryIterator", "::", "SKIP_DOTS", ")", ",", "Iterator", "::", "SELF_FIRST", ",", "Iterator", "::", "CATCH_GET_CHILD", "// Ignore \"Permission denied\"", ")", ";", "$", "subPaths", "=", "[", "$", "folder", "]", ";", "foreach", "(", "$", "iter", "as", "$", "path", "=>", "$", "dir", ")", "{", "if", "(", "$", "dir", "->", "isDir", "(", ")", ")", "{", "$", "subPaths", "[", "]", "=", "$", "path", ";", "}", "}", "$", "paths", "=", "array_merge", "(", "$", "paths", ",", "$", "subPaths", ")", ";", "}", "return", "$", "paths", ";", "}" ]
Get all subdirectories located in an array of folders. @param array $folders @return array
[ "Get", "all", "subdirectories", "located", "in", "an", "array", "of", "folders", "." ]
571ba7fc00869f9641eda1c26c1959e292aefbe4
https://github.com/JayBizzle/Laravel-Migrations-Organiser/blob/571ba7fc00869f9641eda1c26c1959e292aefbe4/src/Migrator.php#L37-L63
train
bearsunday/BEAR.Resource
src/ResourceObject.php
ResourceObject.getIterator
public function getIterator() { $isTraversal = (is_array($this->body) || $this->body instanceof \Traversable); return $isTraversal ? new \ArrayIterator($this->body) : new \ArrayIterator([]); }
php
public function getIterator() { $isTraversal = (is_array($this->body) || $this->body instanceof \Traversable); return $isTraversal ? new \ArrayIterator($this->body) : new \ArrayIterator([]); }
[ "public", "function", "getIterator", "(", ")", "{", "$", "isTraversal", "=", "(", "is_array", "(", "$", "this", "->", "body", ")", "||", "$", "this", "->", "body", "instanceof", "\\", "Traversable", ")", ";", "return", "$", "isTraversal", "?", "new", "\\", "ArrayIterator", "(", "$", "this", "->", "body", ")", ":", "new", "\\", "ArrayIterator", "(", "[", "]", ")", ";", "}" ]
Get array iterator @return \ArrayIterator
[ "Get", "array", "iterator" ]
c3b396a6c725ecce9345565b1e4d563d95e11bec
https://github.com/bearsunday/BEAR.Resource/blob/c3b396a6c725ecce9345565b1e4d563d95e11bec/src/ResourceObject.php#L171-L176
train
tsugiproject/tsugi-php
src/Image/Png.php
Png.removeTextChunks
public static function removeTextChunks($key,$png) { // Read the magic bytes and verify $retval = substr($png,0,8); $ipos = 8; if ($retval != "\x89PNG\x0d\x0a\x1a\x0a") throw new Exception('Is not a valid PNG image'); // Loop through the chunks. Byte 0-3 is length, Byte 4-7 is type $chunkHeader = substr($png,$ipos,8); $ipos = $ipos + 8; while ($chunkHeader) { // Extract length and type from binary data $chunk = @unpack('Nsize/a4type', $chunkHeader); $skip = false; if ( $chunk['type'] == 'tEXt' ) { $data = substr($png,$ipos,$chunk['size']); $sections = explode("\0", $data); print_r($sections); if ( $sections[0] == $key ) $skip = true; } // Extract the data and the CRC $data = substr($png,$ipos,$chunk['size']+4); $ipos = $ipos + $chunk['size'] + 4; // Add in the header, data, and CRC if ( ! $skip ) $retval = $retval . $chunkHeader . $data; // Read next chunk header $chunkHeader = substr($png,$ipos,8); $ipos = $ipos + 8; } return $retval; }
php
public static function removeTextChunks($key,$png) { // Read the magic bytes and verify $retval = substr($png,0,8); $ipos = 8; if ($retval != "\x89PNG\x0d\x0a\x1a\x0a") throw new Exception('Is not a valid PNG image'); // Loop through the chunks. Byte 0-3 is length, Byte 4-7 is type $chunkHeader = substr($png,$ipos,8); $ipos = $ipos + 8; while ($chunkHeader) { // Extract length and type from binary data $chunk = @unpack('Nsize/a4type', $chunkHeader); $skip = false; if ( $chunk['type'] == 'tEXt' ) { $data = substr($png,$ipos,$chunk['size']); $sections = explode("\0", $data); print_r($sections); if ( $sections[0] == $key ) $skip = true; } // Extract the data and the CRC $data = substr($png,$ipos,$chunk['size']+4); $ipos = $ipos + $chunk['size'] + 4; // Add in the header, data, and CRC if ( ! $skip ) $retval = $retval . $chunkHeader . $data; // Read next chunk header $chunkHeader = substr($png,$ipos,8); $ipos = $ipos + 8; } return $retval; }
[ "public", "static", "function", "removeTextChunks", "(", "$", "key", ",", "$", "png", ")", "{", "// Read the magic bytes and verify", "$", "retval", "=", "substr", "(", "$", "png", ",", "0", ",", "8", ")", ";", "$", "ipos", "=", "8", ";", "if", "(", "$", "retval", "!=", "\"\\x89PNG\\x0d\\x0a\\x1a\\x0a\"", ")", "throw", "new", "Exception", "(", "'Is not a valid PNG image'", ")", ";", "// Loop through the chunks. Byte 0-3 is length, Byte 4-7 is type", "$", "chunkHeader", "=", "substr", "(", "$", "png", ",", "$", "ipos", ",", "8", ")", ";", "$", "ipos", "=", "$", "ipos", "+", "8", ";", "while", "(", "$", "chunkHeader", ")", "{", "// Extract length and type from binary data", "$", "chunk", "=", "@", "unpack", "(", "'Nsize/a4type'", ",", "$", "chunkHeader", ")", ";", "$", "skip", "=", "false", ";", "if", "(", "$", "chunk", "[", "'type'", "]", "==", "'tEXt'", ")", "{", "$", "data", "=", "substr", "(", "$", "png", ",", "$", "ipos", ",", "$", "chunk", "[", "'size'", "]", ")", ";", "$", "sections", "=", "explode", "(", "\"\\0\"", ",", "$", "data", ")", ";", "print_r", "(", "$", "sections", ")", ";", "if", "(", "$", "sections", "[", "0", "]", "==", "$", "key", ")", "$", "skip", "=", "true", ";", "}", "// Extract the data and the CRC", "$", "data", "=", "substr", "(", "$", "png", ",", "$", "ipos", ",", "$", "chunk", "[", "'size'", "]", "+", "4", ")", ";", "$", "ipos", "=", "$", "ipos", "+", "$", "chunk", "[", "'size'", "]", "+", "4", ";", "// Add in the header, data, and CRC", "if", "(", "!", "$", "skip", ")", "$", "retval", "=", "$", "retval", ".", "$", "chunkHeader", ".", "$", "data", ";", "// Read next chunk header", "$", "chunkHeader", "=", "substr", "(", "$", "png", ",", "$", "ipos", ",", "8", ")", ";", "$", "ipos", "=", "$", "ipos", "+", "8", ";", "}", "return", "$", "retval", ";", "}" ]
Strip out any existing text chunks with a particular key
[ "Strip", "out", "any", "existing", "text", "chunks", "with", "a", "particular", "key" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Image/Png.php#L20-L53
train
tsugiproject/tsugi-php
src/UI/Menu.php
Menu.add
public function add($entry, $push=false) { if ( $push ) { array_unshift($this->menu, $entry); } else { $this->menu[] = $entry; } return $this; }
php
public function add($entry, $push=false) { if ( $push ) { array_unshift($this->menu, $entry); } else { $this->menu[] = $entry; } return $this; }
[ "public", "function", "add", "(", "$", "entry", ",", "$", "push", "=", "false", ")", "{", "if", "(", "$", "push", ")", "{", "array_unshift", "(", "$", "this", "->", "menu", ",", "$", "entry", ")", ";", "}", "else", "{", "$", "this", "->", "menu", "[", "]", "=", "$", "entry", ";", "}", "return", "$", "this", ";", "}" ]
Add an entry to the menu @param $entry a MenuEntry @param $push true if this is to be put before the rest of the items in the menue @return Menu The instance is returned to allow chaining syntax
[ "Add", "an", "entry", "to", "the", "menu" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/UI/Menu.php#L26-L34
train
tsugiproject/tsugi-php
src/UI/Menu.php
Menu.addLink
public function addLink($link, $href, $push=false) { $entry = new MenuEntry($link, $href); return $this->add($entry, $push); }
php
public function addLink($link, $href, $push=false) { $entry = new MenuEntry($link, $href); return $this->add($entry, $push); }
[ "public", "function", "addLink", "(", "$", "link", ",", "$", "href", ",", "$", "push", "=", "false", ")", "{", "$", "entry", "=", "new", "MenuEntry", "(", "$", "link", ",", "$", "href", ")", ";", "return", "$", "this", "->", "add", "(", "$", "entry", ",", "$", "push", ")", ";", "}" ]
Add an link to the menu @param $link The text of the link - can be text, HTML, or even an img tag @param $href An optional place to go when the link is clicked. Also can be a Menu. @param $push true if this is to be put before the rest of the items in the menue @return Menu The instance is returned to allow chaining syntax
[ "Add", "an", "link", "to", "the", "menu" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/UI/Menu.php#L46-L50
train
tsugiproject/tsugi-php
src/UI/Menu.php
Menu.addSeparator
public function addSeparator($push=false) { $entry = MenuEntry::separator(); return $this->add($entry, $push); }
php
public function addSeparator($push=false) { $entry = MenuEntry::separator(); return $this->add($entry, $push); }
[ "public", "function", "addSeparator", "(", "$", "push", "=", "false", ")", "{", "$", "entry", "=", "MenuEntry", "::", "separator", "(", ")", ";", "return", "$", "this", "->", "add", "(", "$", "entry", ",", "$", "push", ")", ";", "}" ]
Add a separator to the menu @param $push true if this is to be put before the rest of the items in the menue @return Menu The instance is returned to allow chaining syntax
[ "Add", "a", "separator", "to", "the", "menu" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/UI/Menu.php#L59-L63
train
tsugiproject/tsugi-php
src/Core/User.php
User.getFirstName
function getFirstName($displayname=null) { if ( $displayname === null ) $displayname = $this->getNameAndEmail(); if ( $displayname === null ) return null; $pieces = explode(' ',$displayname); if ( count($pieces) > 0 ) return $pieces[0]; return null; }
php
function getFirstName($displayname=null) { if ( $displayname === null ) $displayname = $this->getNameAndEmail(); if ( $displayname === null ) return null; $pieces = explode(' ',$displayname); if ( count($pieces) > 0 ) return $pieces[0]; return null; }
[ "function", "getFirstName", "(", "$", "displayname", "=", "null", ")", "{", "if", "(", "$", "displayname", "===", "null", ")", "$", "displayname", "=", "$", "this", "->", "getNameAndEmail", "(", ")", ";", "if", "(", "$", "displayname", "===", "null", ")", "return", "null", ";", "$", "pieces", "=", "explode", "(", "' '", ",", "$", "displayname", ")", ";", "if", "(", "count", "(", "$", "pieces", ")", ">", "0", ")", "return", "$", "pieces", "[", "0", "]", ";", "return", "null", ";", "}" ]
Get the user's first name, falling back to email
[ "Get", "the", "user", "s", "first", "name", "falling", "back", "to", "email" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/User.php#L93-L99
train
tsugiproject/tsugi-php
src/Core/User.php
User.loadUserInfoBypass
public static function loadUserInfoBypass($user_id) { global $CFG, $PDOX, $CONTEXT; $cacheloc = 'lti_user'; $row = Cache::check($cacheloc, $user_id); if ( $row != false ) return $row; $stmt = $PDOX->queryDie( "SELECT displayname, email, user_key FROM {$CFG->dbprefix}lti_user AS U JOIN {$CFG->dbprefix}lti_membership AS M ON U.user_id = M.user_id AND M.context_id = :CID WHERE U.user_id = :UID", array(":UID" => $user_id, ":CID" => $CONTEXT->id) ); $row = $stmt->fetch(\PDO::FETCH_ASSOC); if ( strlen($row['displayname']) < 1 && strlen($row['user_key']) > 0 ) { $row['displayname'] = 'user_key:'.substr($row['user_key'],0,25); } Cache::set($cacheloc, $user_id, $row); return $row; }
php
public static function loadUserInfoBypass($user_id) { global $CFG, $PDOX, $CONTEXT; $cacheloc = 'lti_user'; $row = Cache::check($cacheloc, $user_id); if ( $row != false ) return $row; $stmt = $PDOX->queryDie( "SELECT displayname, email, user_key FROM {$CFG->dbprefix}lti_user AS U JOIN {$CFG->dbprefix}lti_membership AS M ON U.user_id = M.user_id AND M.context_id = :CID WHERE U.user_id = :UID", array(":UID" => $user_id, ":CID" => $CONTEXT->id) ); $row = $stmt->fetch(\PDO::FETCH_ASSOC); if ( strlen($row['displayname']) < 1 && strlen($row['user_key']) > 0 ) { $row['displayname'] = 'user_key:'.substr($row['user_key'],0,25); } Cache::set($cacheloc, $user_id, $row); return $row; }
[ "public", "static", "function", "loadUserInfoBypass", "(", "$", "user_id", ")", "{", "global", "$", "CFG", ",", "$", "PDOX", ",", "$", "CONTEXT", ";", "$", "cacheloc", "=", "'lti_user'", ";", "$", "row", "=", "Cache", "::", "check", "(", "$", "cacheloc", ",", "$", "user_id", ")", ";", "if", "(", "$", "row", "!=", "false", ")", "return", "$", "row", ";", "$", "stmt", "=", "$", "PDOX", "->", "queryDie", "(", "\"SELECT displayname, email, user_key FROM {$CFG->dbprefix}lti_user AS U\n JOIN {$CFG->dbprefix}lti_membership AS M\n ON U.user_id = M.user_id AND M.context_id = :CID\n WHERE U.user_id = :UID\"", ",", "array", "(", "\":UID\"", "=>", "$", "user_id", ",", "\":CID\"", "=>", "$", "CONTEXT", "->", "id", ")", ")", ";", "$", "row", "=", "$", "stmt", "->", "fetch", "(", "\\", "PDO", "::", "FETCH_ASSOC", ")", ";", "if", "(", "strlen", "(", "$", "row", "[", "'displayname'", "]", ")", "<", "1", "&&", "strlen", "(", "$", "row", "[", "'user_key'", "]", ")", ">", "0", ")", "{", "$", "row", "[", "'displayname'", "]", "=", "'user_key:'", ".", "substr", "(", "$", "row", "[", "'user_key'", "]", ",", "0", ",", "25", ")", ";", "}", "Cache", "::", "set", "(", "$", "cacheloc", ",", "$", "user_id", ",", "$", "row", ")", ";", "return", "$", "row", ";", "}" ]
Load a user's info from the user_id We make sure that the user is a member of the current context so as not to slide across silos.
[ "Load", "a", "user", "s", "info", "from", "the", "user_id" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/User.php#L107-L126
train
tsugiproject/tsugi-php
src/Crypt/SecureCookie.php
SecureCookie.create
public static function create($id,$guid,$context_id,$debug=false) { global $CFG; $pt = $CFG->cookiepad.'::'.$id.'::'.$guid.'::'.$context_id; if ( $debug ) echo("PT1: $pt\n"); $ct = \Tsugi\Crypt\AesCtr::encrypt($pt, $CFG->cookiesecret, 256) ; return $ct; }
php
public static function create($id,$guid,$context_id,$debug=false) { global $CFG; $pt = $CFG->cookiepad.'::'.$id.'::'.$guid.'::'.$context_id; if ( $debug ) echo("PT1: $pt\n"); $ct = \Tsugi\Crypt\AesCtr::encrypt($pt, $CFG->cookiesecret, 256) ; return $ct; }
[ "public", "static", "function", "create", "(", "$", "id", ",", "$", "guid", ",", "$", "context_id", ",", "$", "debug", "=", "false", ")", "{", "global", "$", "CFG", ";", "$", "pt", "=", "$", "CFG", "->", "cookiepad", ".", "'::'", ".", "$", "id", ".", "'::'", ".", "$", "guid", ".", "'::'", ".", "$", "context_id", ";", "if", "(", "$", "debug", ")", "echo", "(", "\"PT1: $pt\\n\"", ")", ";", "$", "ct", "=", "\\", "Tsugi", "\\", "Crypt", "\\", "AesCtr", "::", "encrypt", "(", "$", "pt", ",", "$", "CFG", "->", "cookiesecret", ",", "256", ")", ";", "return", "$", "ct", ";", "}" ]
Utility code to deal with Secure Cookies.
[ "Utility", "code", "to", "deal", "with", "Secure", "Cookies", "." ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Crypt/SecureCookie.php#L10-L16
train
tsugiproject/tsugi-php
src/Crypt/SecureCookie.php
SecureCookie.set
public static function set($user_id, $userEmail, $context_id) { global $CFG; $ct = self::create($user_id,$userEmail, $context_id); setcookie($CFG->cookiename,$ct,time() + (86400 * 45), '/'); // 86400 = 1 day }
php
public static function set($user_id, $userEmail, $context_id) { global $CFG; $ct = self::create($user_id,$userEmail, $context_id); setcookie($CFG->cookiename,$ct,time() + (86400 * 45), '/'); // 86400 = 1 day }
[ "public", "static", "function", "set", "(", "$", "user_id", ",", "$", "userEmail", ",", "$", "context_id", ")", "{", "global", "$", "CFG", ";", "$", "ct", "=", "self", "::", "create", "(", "$", "user_id", ",", "$", "userEmail", ",", "$", "context_id", ")", ";", "setcookie", "(", "$", "CFG", "->", "cookiename", ",", "$", "ct", ",", "time", "(", ")", "+", "(", "86400", "*", "45", ")", ",", "'/'", ")", ";", "// 86400 = 1 day", "}" ]
We have a user - set their secure cookie
[ "We", "have", "a", "user", "-", "set", "their", "secure", "cookie" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Crypt/SecureCookie.php#L37-L41
train
tsugiproject/tsugi-php
src/Core/Debug.php
Debug.dump
public static function dump() { global $DEBUG_STRING; $retval = ''; $sess = (strlen(session_id()) > 0 ); if ( $sess ) { // echo("<br/>=== DUMP ====<br/>".$_SESSION['__zzz_debug']."<br/>\n");flush(); if (strlen($_SESSION['__zzz_debug']) > 0) { $retval = $_SESSION['__zzz_debug']; unset($_SESSION['__zzz_debug']); } } if ( strlen($retval) > 0 && strlen($DEBUG_STRING) > 0) { $retval .= "\n"; } if (strlen($DEBUG_STRING) > 0) { $retval .= $DEBUG_STRING; $DEBUG_STRING = ''; } return $retval; }
php
public static function dump() { global $DEBUG_STRING; $retval = ''; $sess = (strlen(session_id()) > 0 ); if ( $sess ) { // echo("<br/>=== DUMP ====<br/>".$_SESSION['__zzz_debug']."<br/>\n");flush(); if (strlen($_SESSION['__zzz_debug']) > 0) { $retval = $_SESSION['__zzz_debug']; unset($_SESSION['__zzz_debug']); } } if ( strlen($retval) > 0 && strlen($DEBUG_STRING) > 0) { $retval .= "\n"; } if (strlen($DEBUG_STRING) > 0) { $retval .= $DEBUG_STRING; $DEBUG_STRING = ''; } return $retval; }
[ "public", "static", "function", "dump", "(", ")", "{", "global", "$", "DEBUG_STRING", ";", "$", "retval", "=", "''", ";", "$", "sess", "=", "(", "strlen", "(", "session_id", "(", ")", ")", ">", "0", ")", ";", "if", "(", "$", "sess", ")", "{", "// echo(\"<br/>=== DUMP ====<br/>\".$_SESSION['__zzz_debug'].\"<br/>\\n\");flush();", "if", "(", "strlen", "(", "$", "_SESSION", "[", "'__zzz_debug'", "]", ")", ">", "0", ")", "{", "$", "retval", "=", "$", "_SESSION", "[", "'__zzz_debug'", "]", ";", "unset", "(", "$", "_SESSION", "[", "'__zzz_debug'", "]", ")", ";", "}", "}", "if", "(", "strlen", "(", "$", "retval", ")", ">", "0", "&&", "strlen", "(", "$", "DEBUG_STRING", ")", ">", "0", ")", "{", "$", "retval", ".=", "\"\\n\"", ";", "}", "if", "(", "strlen", "(", "$", "DEBUG_STRING", ")", ">", "0", ")", "{", "$", "retval", ".=", "$", "DEBUG_STRING", ";", "$", "DEBUG_STRING", "=", "''", ";", "}", "return", "$", "retval", ";", "}" ]
Calling this clears debug buffer...
[ "Calling", "this", "clears", "debug", "buffer", "..." ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/Debug.php#L66-L85
train
tsugiproject/tsugi-php
src/Core/Cache.php
Cache.set
public static function set($cacheloc, $cachekey, $cacheval, $expiresec=false) { $cacheloc = "cache_" . $cacheloc; if ( $cacheval === null || $cacheval === false ) { unset($_SESSION[$cacheloc]); return; } if ( $expiresec !== false ) $expiresec = time() + $expiresec; $_SESSION[$cacheloc] = array($cachekey, $cacheval, $expiresec); }
php
public static function set($cacheloc, $cachekey, $cacheval, $expiresec=false) { $cacheloc = "cache_" . $cacheloc; if ( $cacheval === null || $cacheval === false ) { unset($_SESSION[$cacheloc]); return; } if ( $expiresec !== false ) $expiresec = time() + $expiresec; $_SESSION[$cacheloc] = array($cachekey, $cacheval, $expiresec); }
[ "public", "static", "function", "set", "(", "$", "cacheloc", ",", "$", "cachekey", ",", "$", "cacheval", ",", "$", "expiresec", "=", "false", ")", "{", "$", "cacheloc", "=", "\"cache_\"", ".", "$", "cacheloc", ";", "if", "(", "$", "cacheval", "===", "null", "||", "$", "cacheval", "===", "false", ")", "{", "unset", "(", "$", "_SESSION", "[", "$", "cacheloc", "]", ")", ";", "return", ";", "}", "if", "(", "$", "expiresec", "!==", "false", ")", "$", "expiresec", "=", "time", "(", ")", "+", "$", "expiresec", ";", "$", "_SESSION", "[", "$", "cacheloc", "]", "=", "array", "(", "$", "cachekey", ",", "$", "cacheval", ",", "$", "expiresec", ")", ";", "}" ]
Place an entry in the cache. We don't cache null or false if that was our value.
[ "Place", "an", "entry", "in", "the", "cache", "." ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/Cache.php#L43-L52
train
tsugiproject/tsugi-php
src/Core/Cache.php
Cache.check
public static function check($cacheloc, $cachekey) { $cacheloc = "cache_" . $cacheloc; if ( isset($_SESSION[$cacheloc]) ) { $cache_row = $_SESSION[$cacheloc]; if ( time() >= $cache_row[2] ) { unset($_SESSION[$cacheloc]); return false; } if ( $cache_row[0] == $cachekey ) { // error_log("Cache hit $cacheloc"); return $cache_row[1]; } unset($_SESSION[$cacheloc]); } return false; }
php
public static function check($cacheloc, $cachekey) { $cacheloc = "cache_" . $cacheloc; if ( isset($_SESSION[$cacheloc]) ) { $cache_row = $_SESSION[$cacheloc]; if ( time() >= $cache_row[2] ) { unset($_SESSION[$cacheloc]); return false; } if ( $cache_row[0] == $cachekey ) { // error_log("Cache hit $cacheloc"); return $cache_row[1]; } unset($_SESSION[$cacheloc]); } return false; }
[ "public", "static", "function", "check", "(", "$", "cacheloc", ",", "$", "cachekey", ")", "{", "$", "cacheloc", "=", "\"cache_\"", ".", "$", "cacheloc", ";", "if", "(", "isset", "(", "$", "_SESSION", "[", "$", "cacheloc", "]", ")", ")", "{", "$", "cache_row", "=", "$", "_SESSION", "[", "$", "cacheloc", "]", ";", "if", "(", "time", "(", ")", ">=", "$", "cache_row", "[", "2", "]", ")", "{", "unset", "(", "$", "_SESSION", "[", "$", "cacheloc", "]", ")", ";", "return", "false", ";", "}", "if", "(", "$", "cache_row", "[", "0", "]", "==", "$", "cachekey", ")", "{", "// error_log(\"Cache hit $cacheloc\");", "return", "$", "cache_row", "[", "1", "]", ";", "}", "unset", "(", "$", "_SESSION", "[", "$", "cacheloc", "]", ")", ";", "}", "return", "false", ";", "}" ]
Check and return a value from the cache. Returns false if there is no entry.
[ "Check", "and", "return", "a", "value", "from", "the", "cache", "." ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/Cache.php#L59-L75
train
tsugiproject/tsugi-php
src/Core/Cache.php
Cache.expires
public static function expires($cacheloc, $cachekey) { $cacheloc = "cache_" . $cacheloc; if ( isset($_SESSION[$cacheloc]) ) { $cache_row = $_SESSION[$cacheloc]; if ( time() >= $cache_row[2] ) { unset($_SESSION[$cacheloc]); return false; } if ( $cache_row[0] != $cachekey ) return false; if ( $cache_row[0] === false ) return false; return $cache_row[2] - time(); } return false; }
php
public static function expires($cacheloc, $cachekey) { $cacheloc = "cache_" . $cacheloc; if ( isset($_SESSION[$cacheloc]) ) { $cache_row = $_SESSION[$cacheloc]; if ( time() >= $cache_row[2] ) { unset($_SESSION[$cacheloc]); return false; } if ( $cache_row[0] != $cachekey ) return false; if ( $cache_row[0] === false ) return false; return $cache_row[2] - time(); } return false; }
[ "public", "static", "function", "expires", "(", "$", "cacheloc", ",", "$", "cachekey", ")", "{", "$", "cacheloc", "=", "\"cache_\"", ".", "$", "cacheloc", ";", "if", "(", "isset", "(", "$", "_SESSION", "[", "$", "cacheloc", "]", ")", ")", "{", "$", "cache_row", "=", "$", "_SESSION", "[", "$", "cacheloc", "]", ";", "if", "(", "time", "(", ")", ">=", "$", "cache_row", "[", "2", "]", ")", "{", "unset", "(", "$", "_SESSION", "[", "$", "cacheloc", "]", ")", ";", "return", "false", ";", "}", "if", "(", "$", "cache_row", "[", "0", "]", "!=", "$", "cachekey", ")", "return", "false", ";", "if", "(", "$", "cache_row", "[", "0", "]", "===", "false", ")", "return", "false", ";", "return", "$", "cache_row", "[", "2", "]", "-", "time", "(", ")", ";", "}", "return", "false", ";", "}" ]
Check when value in the cache expires Returns false if there is no entry.
[ "Check", "when", "value", "in", "the", "cache", "expires" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/Cache.php#L82-L96
train
tsugiproject/tsugi-php
src/UI/SettingsForm.php
SettingsForm.handleSettingsPost
public static function handleSettingsPost() { global $USER; if ( ! $USER ) return false; if ( isset($_POST['settings_internal_post']) && $USER->instructor ) { $newsettings = array(); foreach ( $_POST as $k => $v ) { if ( $k == session_name() ) continue; if ( $k == 'settings_internal_post' ) continue; if ( strpos('_ignore',$k) > 0 ) continue; $newsettings[$k] = $v; } // Merge these with the existing settings Settings::linkUpdate($newsettings); return true; } return false; }
php
public static function handleSettingsPost() { global $USER; if ( ! $USER ) return false; if ( isset($_POST['settings_internal_post']) && $USER->instructor ) { $newsettings = array(); foreach ( $_POST as $k => $v ) { if ( $k == session_name() ) continue; if ( $k == 'settings_internal_post' ) continue; if ( strpos('_ignore',$k) > 0 ) continue; $newsettings[$k] = $v; } // Merge these with the existing settings Settings::linkUpdate($newsettings); return true; } return false; }
[ "public", "static", "function", "handleSettingsPost", "(", ")", "{", "global", "$", "USER", ";", "if", "(", "!", "$", "USER", ")", "return", "false", ";", "if", "(", "isset", "(", "$", "_POST", "[", "'settings_internal_post'", "]", ")", "&&", "$", "USER", "->", "instructor", ")", "{", "$", "newsettings", "=", "array", "(", ")", ";", "foreach", "(", "$", "_POST", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "$", "k", "==", "session_name", "(", ")", ")", "continue", ";", "if", "(", "$", "k", "==", "'settings_internal_post'", ")", "continue", ";", "if", "(", "strpos", "(", "'_ignore'", ",", "$", "k", ")", ">", "0", ")", "continue", ";", "$", "newsettings", "[", "$", "k", "]", "=", "$", "v", ";", "}", "// Merge these with the existing settings", "Settings", "::", "linkUpdate", "(", "$", "newsettings", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Handle incoming settings post data @return boolean Returns true if there were settings to handle and false if there was nothing done. Generally the calling tool will redirect when true is returned. if ( SettingsForm::handleSettingsPost() ) { header( 'Location: '.U::addSession('index.php?howdysuppress=1') ) ; return; }
[ "Handle", "incoming", "settings", "post", "data" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/UI/SettingsForm.php#L47-L65
train
tsugiproject/tsugi-php
src/UI/SettingsForm.php
SettingsForm.select
public static function select($name, $default=false, $fields) { global $USER; if ( ! $USER ) return; $oldsettings = Settings::linkGetAll(); if ( ! $USER->instructor ) { $configured = false; foreach ( $fields as $k => $v ) { $index = $k; $display = $v; if ( is_int($index) ) $index = $display; // No keys if ( ! is_string($display) ) $display = $index; if ( isset($oldsettings[$name]) && $k == $oldsettings[$name] ) { $configured = $display; } } if ( $configured === false ) { echo('<p>'._m('Setting').' '.htmlent_utf8($name).' '._m('is not set').'</p>'); } else { echo('<p>'.htmlent_utf8(ucwords($name)).' '._m('is set to').' '.htmlent_utf8($configured).'</p>'); } return; } // Instructor view if ( $default === false ) $default = _m('Please Select'); echo('<select name="'.$name.'">'); echo('<option value="0">'.$default.'</option>'); foreach ( $fields as $k => $v ) { $index = $k; $display = $v; if ( is_int($index) ) $index = $display; // No keys if ( ! is_string($display) ) $display = $index; echo('<option value="'.$index.'"'); if ( isset($oldsettings[$name]) && $index == $oldsettings[$name] ) { echo(' selected'); } echo('>'.$display.'</option>'."\n"); } echo('</select>'); }
php
public static function select($name, $default=false, $fields) { global $USER; if ( ! $USER ) return; $oldsettings = Settings::linkGetAll(); if ( ! $USER->instructor ) { $configured = false; foreach ( $fields as $k => $v ) { $index = $k; $display = $v; if ( is_int($index) ) $index = $display; // No keys if ( ! is_string($display) ) $display = $index; if ( isset($oldsettings[$name]) && $k == $oldsettings[$name] ) { $configured = $display; } } if ( $configured === false ) { echo('<p>'._m('Setting').' '.htmlent_utf8($name).' '._m('is not set').'</p>'); } else { echo('<p>'.htmlent_utf8(ucwords($name)).' '._m('is set to').' '.htmlent_utf8($configured).'</p>'); } return; } // Instructor view if ( $default === false ) $default = _m('Please Select'); echo('<select name="'.$name.'">'); echo('<option value="0">'.$default.'</option>'); foreach ( $fields as $k => $v ) { $index = $k; $display = $v; if ( is_int($index) ) $index = $display; // No keys if ( ! is_string($display) ) $display = $index; echo('<option value="'.$index.'"'); if ( isset($oldsettings[$name]) && $index == $oldsettings[$name] ) { echo(' selected'); } echo('>'.$display.'</option>'."\n"); } echo('</select>'); }
[ "public", "static", "function", "select", "(", "$", "name", ",", "$", "default", "=", "false", ",", "$", "fields", ")", "{", "global", "$", "USER", ";", "if", "(", "!", "$", "USER", ")", "return", ";", "$", "oldsettings", "=", "Settings", "::", "linkGetAll", "(", ")", ";", "if", "(", "!", "$", "USER", "->", "instructor", ")", "{", "$", "configured", "=", "false", ";", "foreach", "(", "$", "fields", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "index", "=", "$", "k", ";", "$", "display", "=", "$", "v", ";", "if", "(", "is_int", "(", "$", "index", ")", ")", "$", "index", "=", "$", "display", ";", "// No keys", "if", "(", "!", "is_string", "(", "$", "display", ")", ")", "$", "display", "=", "$", "index", ";", "if", "(", "isset", "(", "$", "oldsettings", "[", "$", "name", "]", ")", "&&", "$", "k", "==", "$", "oldsettings", "[", "$", "name", "]", ")", "{", "$", "configured", "=", "$", "display", ";", "}", "}", "if", "(", "$", "configured", "===", "false", ")", "{", "echo", "(", "'<p>'", ".", "_m", "(", "'Setting'", ")", ".", "' '", ".", "htmlent_utf8", "(", "$", "name", ")", ".", "' '", ".", "_m", "(", "'is not set'", ")", ".", "'</p>'", ")", ";", "}", "else", "{", "echo", "(", "'<p>'", ".", "htmlent_utf8", "(", "ucwords", "(", "$", "name", ")", ")", ".", "' '", ".", "_m", "(", "'is set to'", ")", ".", "' '", ".", "htmlent_utf8", "(", "$", "configured", ")", ".", "'</p>'", ")", ";", "}", "return", ";", "}", "// Instructor view", "if", "(", "$", "default", "===", "false", ")", "$", "default", "=", "_m", "(", "'Please Select'", ")", ";", "echo", "(", "'<select name=\"'", ".", "$", "name", ".", "'\">'", ")", ";", "echo", "(", "'<option value=\"0\">'", ".", "$", "default", ".", "'</option>'", ")", ";", "foreach", "(", "$", "fields", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "index", "=", "$", "k", ";", "$", "display", "=", "$", "v", ";", "if", "(", "is_int", "(", "$", "index", ")", ")", "$", "index", "=", "$", "display", ";", "// No keys", "if", "(", "!", "is_string", "(", "$", "display", ")", ")", "$", "display", "=", "$", "index", ";", "echo", "(", "'<option value=\"'", ".", "$", "index", ".", "'\"'", ")", ";", "if", "(", "isset", "(", "$", "oldsettings", "[", "$", "name", "]", ")", "&&", "$", "index", "==", "$", "oldsettings", "[", "$", "name", "]", ")", "{", "echo", "(", "' selected'", ")", ";", "}", "echo", "(", "'>'", ".", "$", "display", ".", "'</option>'", ".", "\"\\n\"", ")", ";", "}", "echo", "(", "'</select>'", ")", ";", "}" ]
Handle a settings selector box
[ "Handle", "a", "settings", "selector", "box" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/UI/SettingsForm.php#L121-L161
train
tsugiproject/tsugi-php
src/UI/SettingsForm.php
SettingsForm.text
public static function text($name, $title=false) { global $USER; if ( ! $USER ) return false; $oldsettings = Settings::linkGetAll(); $configured = isset($oldsettings[$name]) ? $oldsettings[$name] : false; if ( $title === false ) $title = $name; if ( ! $USER->instructor ) { if ( $configured === false || strlen($configured) < 1 ) { echo('<p>'._m('Setting').' '.htmlent_utf8($name).' '._m('is not set').'</p>'); } else { echo('<p>'.htmlent_utf8(ucwords($name)).' '._m('is set to').' '.htmlent_utf8($configured).'</p>'); } return; } // Instructor view echo('<label style="width:100%;" for="'.$name.'">'.htmlent_utf8($title)."\n"); echo('<input type="text" class="form-control" style="width:100%;" name="'.$name.'"'); echo('value="'.htmlent_utf8($configured).'"></label>'."\n"); }
php
public static function text($name, $title=false) { global $USER; if ( ! $USER ) return false; $oldsettings = Settings::linkGetAll(); $configured = isset($oldsettings[$name]) ? $oldsettings[$name] : false; if ( $title === false ) $title = $name; if ( ! $USER->instructor ) { if ( $configured === false || strlen($configured) < 1 ) { echo('<p>'._m('Setting').' '.htmlent_utf8($name).' '._m('is not set').'</p>'); } else { echo('<p>'.htmlent_utf8(ucwords($name)).' '._m('is set to').' '.htmlent_utf8($configured).'</p>'); } return; } // Instructor view echo('<label style="width:100%;" for="'.$name.'">'.htmlent_utf8($title)."\n"); echo('<input type="text" class="form-control" style="width:100%;" name="'.$name.'"'); echo('value="'.htmlent_utf8($configured).'"></label>'."\n"); }
[ "public", "static", "function", "text", "(", "$", "name", ",", "$", "title", "=", "false", ")", "{", "global", "$", "USER", ";", "if", "(", "!", "$", "USER", ")", "return", "false", ";", "$", "oldsettings", "=", "Settings", "::", "linkGetAll", "(", ")", ";", "$", "configured", "=", "isset", "(", "$", "oldsettings", "[", "$", "name", "]", ")", "?", "$", "oldsettings", "[", "$", "name", "]", ":", "false", ";", "if", "(", "$", "title", "===", "false", ")", "$", "title", "=", "$", "name", ";", "if", "(", "!", "$", "USER", "->", "instructor", ")", "{", "if", "(", "$", "configured", "===", "false", "||", "strlen", "(", "$", "configured", ")", "<", "1", ")", "{", "echo", "(", "'<p>'", ".", "_m", "(", "'Setting'", ")", ".", "' '", ".", "htmlent_utf8", "(", "$", "name", ")", ".", "' '", ".", "_m", "(", "'is not set'", ")", ".", "'</p>'", ")", ";", "}", "else", "{", "echo", "(", "'<p>'", ".", "htmlent_utf8", "(", "ucwords", "(", "$", "name", ")", ")", ".", "' '", ".", "_m", "(", "'is set to'", ")", ".", "' '", ".", "htmlent_utf8", "(", "$", "configured", ")", ".", "'</p>'", ")", ";", "}", "return", ";", "}", "// Instructor view", "echo", "(", "'<label style=\"width:100%;\" for=\"'", ".", "$", "name", ".", "'\">'", ".", "htmlent_utf8", "(", "$", "title", ")", ".", "\"\\n\"", ")", ";", "echo", "(", "'<input type=\"text\" class=\"form-control\" style=\"width:100%;\" name=\"'", ".", "$", "name", ".", "'\"'", ")", ";", "echo", "(", "'value=\"'", ".", "htmlent_utf8", "(", "$", "configured", ")", ".", "'\"></label>'", ".", "\"\\n\"", ")", ";", "}" ]
Handle a settings text box
[ "Handle", "a", "settings", "text", "box" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/UI/SettingsForm.php#L166-L187
train
tsugiproject/tsugi-php
src/UI/SettingsForm.php
SettingsForm.getDueDate
public static function getDueDate() { $retval = new \stdClass(); $retval->penaltyinfo = false; // Details about the penalty irrespective of the current date $retval->message = false; $retval->penalty = 0; $retval->dayspastdue = 0; $retval->percent = 0; $retval->duedate = false; $retval->duedatestr = false; $duedatestr = Settings::linkGet('due'); if ( $duedatestr === false ) return $retval; $duedate = strtotime($duedatestr); $diff = -1; $penalty = false; date_default_timezone_set('Pacific/Honolulu'); // Lets be generous if ( Settings::linkGet('timezone') ) { date_default_timezone_set(Settings::linkGet('timezone')); } if ( $duedate === false ) return $retval; $penalty_time = Settings::linkGet('penalty_time') ? Settings::linkGet('penalty_time') + 0 : 24*60*60; $penalty_cost = Settings::linkGet('penalty_cost') ? Settings::linkGet('penalty_cost') + 0.0 : 0.2; $retval->penaltyinfo = sprintf(_m("Once the due date has passed your score will be reduced by %f percent and each %s after the due date, your score will be further reduced by %s percent."), htmlent_utf8($penalty_cost*100), htmlent_utf8(self::getDueDateDelta($penalty_time)), htmlent_utf8($penalty_cost*100) ); // If it is just a date - add nearly an entire day of time... if ( strlen($duedatestr) <= 10 ) $duedate = $duedate + 24*60*60 - 1; $diff = time() - $duedate; $retval->duedate = $duedate; $retval->duedatestr = $duedatestr; // Should be a percentage off between 0.0 and 1.0 if ( $diff > 0 ) { $penalty_exact = $diff / $penalty_time; $penalties = intval($penalty_exact) + 1; $penalty = $penalties * $penalty_cost; if ( $penalty < 0 ) $penalty = 0; if ( $penalty > 1 ) $penalty = 1; $retval->penalty = $penalty; $retval->dayspastdue = $diff / (24*60*60); $retval->percent = intval($penalty * 100); $retval->message = sprintf( _m("It is currently %s past the due date (%s) so your late penalty is %f percent."), self::getDueDateDelta($diff), htmlentities($duedatestr),$retval->percent); } return $retval; }
php
public static function getDueDate() { $retval = new \stdClass(); $retval->penaltyinfo = false; // Details about the penalty irrespective of the current date $retval->message = false; $retval->penalty = 0; $retval->dayspastdue = 0; $retval->percent = 0; $retval->duedate = false; $retval->duedatestr = false; $duedatestr = Settings::linkGet('due'); if ( $duedatestr === false ) return $retval; $duedate = strtotime($duedatestr); $diff = -1; $penalty = false; date_default_timezone_set('Pacific/Honolulu'); // Lets be generous if ( Settings::linkGet('timezone') ) { date_default_timezone_set(Settings::linkGet('timezone')); } if ( $duedate === false ) return $retval; $penalty_time = Settings::linkGet('penalty_time') ? Settings::linkGet('penalty_time') + 0 : 24*60*60; $penalty_cost = Settings::linkGet('penalty_cost') ? Settings::linkGet('penalty_cost') + 0.0 : 0.2; $retval->penaltyinfo = sprintf(_m("Once the due date has passed your score will be reduced by %f percent and each %s after the due date, your score will be further reduced by %s percent."), htmlent_utf8($penalty_cost*100), htmlent_utf8(self::getDueDateDelta($penalty_time)), htmlent_utf8($penalty_cost*100) ); // If it is just a date - add nearly an entire day of time... if ( strlen($duedatestr) <= 10 ) $duedate = $duedate + 24*60*60 - 1; $diff = time() - $duedate; $retval->duedate = $duedate; $retval->duedatestr = $duedatestr; // Should be a percentage off between 0.0 and 1.0 if ( $diff > 0 ) { $penalty_exact = $diff / $penalty_time; $penalties = intval($penalty_exact) + 1; $penalty = $penalties * $penalty_cost; if ( $penalty < 0 ) $penalty = 0; if ( $penalty > 1 ) $penalty = 1; $retval->penalty = $penalty; $retval->dayspastdue = $diff / (24*60*60); $retval->percent = intval($penalty * 100); $retval->message = sprintf( _m("It is currently %s past the due date (%s) so your late penalty is %f percent."), self::getDueDateDelta($diff), htmlentities($duedatestr),$retval->percent); } return $retval; }
[ "public", "static", "function", "getDueDate", "(", ")", "{", "$", "retval", "=", "new", "\\", "stdClass", "(", ")", ";", "$", "retval", "->", "penaltyinfo", "=", "false", ";", "// Details about the penalty irrespective of the current date", "$", "retval", "->", "message", "=", "false", ";", "$", "retval", "->", "penalty", "=", "0", ";", "$", "retval", "->", "dayspastdue", "=", "0", ";", "$", "retval", "->", "percent", "=", "0", ";", "$", "retval", "->", "duedate", "=", "false", ";", "$", "retval", "->", "duedatestr", "=", "false", ";", "$", "duedatestr", "=", "Settings", "::", "linkGet", "(", "'due'", ")", ";", "if", "(", "$", "duedatestr", "===", "false", ")", "return", "$", "retval", ";", "$", "duedate", "=", "strtotime", "(", "$", "duedatestr", ")", ";", "$", "diff", "=", "-", "1", ";", "$", "penalty", "=", "false", ";", "date_default_timezone_set", "(", "'Pacific/Honolulu'", ")", ";", "// Lets be generous", "if", "(", "Settings", "::", "linkGet", "(", "'timezone'", ")", ")", "{", "date_default_timezone_set", "(", "Settings", "::", "linkGet", "(", "'timezone'", ")", ")", ";", "}", "if", "(", "$", "duedate", "===", "false", ")", "return", "$", "retval", ";", "$", "penalty_time", "=", "Settings", "::", "linkGet", "(", "'penalty_time'", ")", "?", "Settings", "::", "linkGet", "(", "'penalty_time'", ")", "+", "0", ":", "24", "*", "60", "*", "60", ";", "$", "penalty_cost", "=", "Settings", "::", "linkGet", "(", "'penalty_cost'", ")", "?", "Settings", "::", "linkGet", "(", "'penalty_cost'", ")", "+", "0.0", ":", "0.2", ";", "$", "retval", "->", "penaltyinfo", "=", "sprintf", "(", "_m", "(", "\"Once the due date has passed your \n score will be reduced by %f percent and each %s after the due date, \n your score will be further reduced by %s percent.\"", ")", ",", "htmlent_utf8", "(", "$", "penalty_cost", "*", "100", ")", ",", "htmlent_utf8", "(", "self", "::", "getDueDateDelta", "(", "$", "penalty_time", ")", ")", ",", "htmlent_utf8", "(", "$", "penalty_cost", "*", "100", ")", ")", ";", "// If it is just a date - add nearly an entire day of time...", "if", "(", "strlen", "(", "$", "duedatestr", ")", "<=", "10", ")", "$", "duedate", "=", "$", "duedate", "+", "24", "*", "60", "*", "60", "-", "1", ";", "$", "diff", "=", "time", "(", ")", "-", "$", "duedate", ";", "$", "retval", "->", "duedate", "=", "$", "duedate", ";", "$", "retval", "->", "duedatestr", "=", "$", "duedatestr", ";", "// Should be a percentage off between 0.0 and 1.0", "if", "(", "$", "diff", ">", "0", ")", "{", "$", "penalty_exact", "=", "$", "diff", "/", "$", "penalty_time", ";", "$", "penalties", "=", "intval", "(", "$", "penalty_exact", ")", "+", "1", ";", "$", "penalty", "=", "$", "penalties", "*", "$", "penalty_cost", ";", "if", "(", "$", "penalty", "<", "0", ")", "$", "penalty", "=", "0", ";", "if", "(", "$", "penalty", ">", "1", ")", "$", "penalty", "=", "1", ";", "$", "retval", "->", "penalty", "=", "$", "penalty", ";", "$", "retval", "->", "dayspastdue", "=", "$", "diff", "/", "(", "24", "*", "60", "*", "60", ")", ";", "$", "retval", "->", "percent", "=", "intval", "(", "$", "penalty", "*", "100", ")", ";", "$", "retval", "->", "message", "=", "sprintf", "(", "_m", "(", "\"It is currently %s past the due date (%s) so your late penalty is %f percent.\"", ")", ",", "self", "::", "getDueDateDelta", "(", "$", "diff", ")", ",", "htmlentities", "(", "$", "duedatestr", ")", ",", "$", "retval", "->", "percent", ")", ";", "}", "return", "$", "retval", ";", "}" ]
Get the due data data in an object
[ "Get", "the", "due", "data", "data", "in", "an", "object" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/UI/SettingsForm.php#L262-L316
train
tsugiproject/tsugi-php
src/UI/SettingsForm.php
SettingsForm.getDueDateDelta
public static function getDueDateDelta($time) { if ( $time < 600 ) { $delta = $time . ' seconds'; } else if ($time < 3600) { $delta = sprintf("%0.0f",($time/60.0)) . ' ' . _m('minutes'); } else if ($time <= 86400 ) { $delta = sprintf("%0.2f",($time/3600.0)) . ' ' . _m('hours'); } else { $delta = sprintf("%0.2f",($time/86400.0)) . ' ' . _m('days'); } return $delta; }
php
public static function getDueDateDelta($time) { if ( $time < 600 ) { $delta = $time . ' seconds'; } else if ($time < 3600) { $delta = sprintf("%0.0f",($time/60.0)) . ' ' . _m('minutes'); } else if ($time <= 86400 ) { $delta = sprintf("%0.2f",($time/3600.0)) . ' ' . _m('hours'); } else { $delta = sprintf("%0.2f",($time/86400.0)) . ' ' . _m('days'); } return $delta; }
[ "public", "static", "function", "getDueDateDelta", "(", "$", "time", ")", "{", "if", "(", "$", "time", "<", "600", ")", "{", "$", "delta", "=", "$", "time", ".", "' seconds'", ";", "}", "else", "if", "(", "$", "time", "<", "3600", ")", "{", "$", "delta", "=", "sprintf", "(", "\"%0.0f\"", ",", "(", "$", "time", "/", "60.0", ")", ")", ".", "' '", ".", "_m", "(", "'minutes'", ")", ";", "}", "else", "if", "(", "$", "time", "<=", "86400", ")", "{", "$", "delta", "=", "sprintf", "(", "\"%0.2f\"", ",", "(", "$", "time", "/", "3600.0", ")", ")", ".", "' '", ".", "_m", "(", "'hours'", ")", ";", "}", "else", "{", "$", "delta", "=", "sprintf", "(", "\"%0.2f\"", ",", "(", "$", "time", "/", "86400.0", ")", ")", ".", "' '", ".", "_m", "(", "'days'", ")", ";", "}", "return", "$", "delta", ";", "}" ]
Show a due date delta in reasonable units
[ "Show", "a", "due", "date", "delta", "in", "reasonable", "units" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/UI/SettingsForm.php#L321-L333
train
tsugiproject/tsugi-php
src/UI/SettingsForm.php
SettingsForm.dueDate
public static function dueDate() { global $USER; if ( ! $USER ) return false; $due = Settings::linkGet('due', ''); $timezone = Settings::linkGet('timezone', 'Pacific/Honolulu'); $time = Settings::linkGet('penalty_time', 86400); $cost = Settings::linkGet('penalty_cost', 0.2); if ( ! $USER->instructor ) { if ( strlen($due) < 1 ) { echo("<p>"._m("There is currently no due date/time for this assignment.")."</p>\n"); return; } $dueDate = self::getDueDate(); echo("<p>"._m("Due date: ").htmlent_utf8($due)."</p>\n"); echo("<p>".$dueDate->penaltyinfo."</p>\n"); if ( $dueDate->message ) { echo('<p style="color:red;">'.$dueDate->message.'</p>'."\n"); } return; } ?> <label for="due"> <?= _m("Please enter a due date in ISO 8601 format (2015-01-30T20:30) or leave blank for no due date. You can leave off the time to allow the assignment to be turned in any time during the day.") ?><br/> <input type="text" class="form-control" value="<?php echo(htmlspec_utf8($due)); ?>" name="due"></label> <label for="timezone"> <?= _m("Please enter a valid PHP Time Zone like 'Pacific/Honolulu' (default). If you are teaching in many time zones around the world, 'Pacific/Honolulu' is a good time zone to choose - this is why it is the default.") ?><br/> <input type="text" class="form-control" value="<?php echo(htmlspec_utf8($timezone)); ?>" name="timezone"></label> <p><?= _m("The next two fields determine the 'overall penalty' for being late. We define a time period (in seconds) and a fractional penalty per time period. The penalty is assessed for each full or partial time period past the due date. For example to deduct 20% per day, you would set the period to be 86400 (24*60*60) and the penalty to be 0.2.") ?> </p> <label for="penalty_time"><?= _m("Please enter the penalty time period in seconds.") ?><br/> <input type="text" class="form-control" value="<?php echo(htmlspec_utf8($time)); ?>" name="penalty_time"></label> <label for="penalty_cost"><?= _m("Please enter the penalty deduction as a decimal between 0.0 and 1.0.") ?><br/> <input type="text" class="form-control" value="<?php echo(htmlspec_utf8($cost)); ?>" name="penalty_cost"></label> <?php }
php
public static function dueDate() { global $USER; if ( ! $USER ) return false; $due = Settings::linkGet('due', ''); $timezone = Settings::linkGet('timezone', 'Pacific/Honolulu'); $time = Settings::linkGet('penalty_time', 86400); $cost = Settings::linkGet('penalty_cost', 0.2); if ( ! $USER->instructor ) { if ( strlen($due) < 1 ) { echo("<p>"._m("There is currently no due date/time for this assignment.")."</p>\n"); return; } $dueDate = self::getDueDate(); echo("<p>"._m("Due date: ").htmlent_utf8($due)."</p>\n"); echo("<p>".$dueDate->penaltyinfo."</p>\n"); if ( $dueDate->message ) { echo('<p style="color:red;">'.$dueDate->message.'</p>'."\n"); } return; } ?> <label for="due"> <?= _m("Please enter a due date in ISO 8601 format (2015-01-30T20:30) or leave blank for no due date. You can leave off the time to allow the assignment to be turned in any time during the day.") ?><br/> <input type="text" class="form-control" value="<?php echo(htmlspec_utf8($due)); ?>" name="due"></label> <label for="timezone"> <?= _m("Please enter a valid PHP Time Zone like 'Pacific/Honolulu' (default). If you are teaching in many time zones around the world, 'Pacific/Honolulu' is a good time zone to choose - this is why it is the default.") ?><br/> <input type="text" class="form-control" value="<?php echo(htmlspec_utf8($timezone)); ?>" name="timezone"></label> <p><?= _m("The next two fields determine the 'overall penalty' for being late. We define a time period (in seconds) and a fractional penalty per time period. The penalty is assessed for each full or partial time period past the due date. For example to deduct 20% per day, you would set the period to be 86400 (24*60*60) and the penalty to be 0.2.") ?> </p> <label for="penalty_time"><?= _m("Please enter the penalty time period in seconds.") ?><br/> <input type="text" class="form-control" value="<?php echo(htmlspec_utf8($time)); ?>" name="penalty_time"></label> <label for="penalty_cost"><?= _m("Please enter the penalty deduction as a decimal between 0.0 and 1.0.") ?><br/> <input type="text" class="form-control" value="<?php echo(htmlspec_utf8($cost)); ?>" name="penalty_cost"></label> <?php }
[ "public", "static", "function", "dueDate", "(", ")", "{", "global", "$", "USER", ";", "if", "(", "!", "$", "USER", ")", "return", "false", ";", "$", "due", "=", "Settings", "::", "linkGet", "(", "'due'", ",", "''", ")", ";", "$", "timezone", "=", "Settings", "::", "linkGet", "(", "'timezone'", ",", "'Pacific/Honolulu'", ")", ";", "$", "time", "=", "Settings", "::", "linkGet", "(", "'penalty_time'", ",", "86400", ")", ";", "$", "cost", "=", "Settings", "::", "linkGet", "(", "'penalty_cost'", ",", "0.2", ")", ";", "if", "(", "!", "$", "USER", "->", "instructor", ")", "{", "if", "(", "strlen", "(", "$", "due", ")", "<", "1", ")", "{", "echo", "(", "\"<p>\"", ".", "_m", "(", "\"There is currently no due date/time for this assignment.\"", ")", ".", "\"</p>\\n\"", ")", ";", "return", ";", "}", "$", "dueDate", "=", "self", "::", "getDueDate", "(", ")", ";", "echo", "(", "\"<p>\"", ".", "_m", "(", "\"Due date: \"", ")", ".", "htmlent_utf8", "(", "$", "due", ")", ".", "\"</p>\\n\"", ")", ";", "echo", "(", "\"<p>\"", ".", "$", "dueDate", "->", "penaltyinfo", ".", "\"</p>\\n\"", ")", ";", "if", "(", "$", "dueDate", "->", "message", ")", "{", "echo", "(", "'<p style=\"color:red;\">'", ".", "$", "dueDate", "->", "message", ".", "'</p>'", ".", "\"\\n\"", ")", ";", "}", "return", ";", "}", "?>\n <label for=\"due\">\n <?=", "_m", "(", "\"Please enter a due date in ISO 8601 format (2015-01-30T20:30) or leave blank for no due date.\n You can leave off the time to allow the assignment to be turned in any time during the day.\"", ")", "?><br/>\n <input type=\"text\" class=\"form-control\" value=\"<?php", "echo", "(", "htmlspec_utf8", "(", "$", "due", ")", ")", ";", "?>\" name=\"due\"></label>\n <label for=\"timezone\">\n <?=", "_m", "(", "\"Please enter a valid PHP Time Zone like 'Pacific/Honolulu' (default). If you are\n teaching in many time zones around the world, 'Pacific/Honolulu' is a good time\n zone to choose - this is why it is the default.\"", ")", "?><br/>\n <input type=\"text\" class=\"form-control\" value=\"<?php", "echo", "(", "htmlspec_utf8", "(", "$", "timezone", ")", ")", ";", "?>\" name=\"timezone\"></label>\n <p><?=", "_m", "(", "\"The next two fields determine the 'overall penalty' for being late. We define a time period\n (in seconds) and a fractional penalty per time period. The penalty is assessed for each\n full or partial time period past the due date. For example to deduct 20% per day, you would\n set the period to be 86400 (24*60*60) and the penalty to be 0.2.\"", ")", "?>\n </p>\n <label for=\"penalty_time\"><?=", "_m", "(", "\"Please enter the penalty time period in seconds.\"", ")", "?><br/>\n <input type=\"text\" class=\"form-control\" value=\"<?php", "echo", "(", "htmlspec_utf8", "(", "$", "time", ")", ")", ";", "?>\" name=\"penalty_time\"></label>\n <label for=\"penalty_cost\"><?=", "_m", "(", "\"Please enter the penalty deduction as a decimal between 0.0 and 1.0.\"", ")", "?><br/>\n <input type=\"text\" class=\"form-control\" value=\"<?php", "echo", "(", "htmlspec_utf8", "(", "$", "cost", ")", ")", ";", "?>\" name=\"penalty_cost\"></label>\n<?php", "}" ]
Emit the text and form fields to support due dates
[ "Emit", "the", "text", "and", "form", "fields", "to", "support", "due", "dates" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/UI/SettingsForm.php#L338-L380
train
rokka-io/rokka-client-php
src/Image.php
Image.deleteSourceImage
public function deleteSourceImage($hash, $organization = '') { try { $response = $this->call('DELETE', implode('/', [self::SOURCEIMAGE_RESOURCE, $this->getOrganizationName($organization), $hash])); } catch (GuzzleException $e) { if (404 == $e->getCode()) { return false; } throw $e; } return '204' == $response->getStatusCode(); }
php
public function deleteSourceImage($hash, $organization = '') { try { $response = $this->call('DELETE', implode('/', [self::SOURCEIMAGE_RESOURCE, $this->getOrganizationName($organization), $hash])); } catch (GuzzleException $e) { if (404 == $e->getCode()) { return false; } throw $e; } return '204' == $response->getStatusCode(); }
[ "public", "function", "deleteSourceImage", "(", "$", "hash", ",", "$", "organization", "=", "''", ")", "{", "try", "{", "$", "response", "=", "$", "this", "->", "call", "(", "'DELETE'", ",", "implode", "(", "'/'", ",", "[", "self", "::", "SOURCEIMAGE_RESOURCE", ",", "$", "this", "->", "getOrganizationName", "(", "$", "organization", ")", ",", "$", "hash", "]", ")", ")", ";", "}", "catch", "(", "GuzzleException", "$", "e", ")", "{", "if", "(", "404", "==", "$", "e", "->", "getCode", "(", ")", ")", "{", "return", "false", ";", "}", "throw", "$", "e", ";", "}", "return", "'204'", "==", "$", "response", "->", "getStatusCode", "(", ")", ";", "}" ]
Delete a source image. @param string $hash Hash of the image @param string $organization Optional organization name @throws GuzzleException If the request fails for a different reason than image not found @throws \Exception @return bool True if successful, false if image not found
[ "Delete", "a", "source", "image", "." ]
ab037e0fd38b110211a0f7afb70f379e30756bdc
https://github.com/rokka-io/rokka-client-php/blob/ab037e0fd38b110211a0f7afb70f379e30756bdc/src/Image.php#L116-L129
train
rokka-io/rokka-client-php
src/Image.php
Image.copySourceImage
public function copySourceImage($hash, $destinationOrg, $overwrite = true, $sourceOrg = '') { try { $headers = ['Destination' => $destinationOrg]; if (false === $overwrite) { $headers['Overwrite'] = 'F'; } $response = $this->call('COPY', implode('/', [self::SOURCEIMAGE_RESOURCE, $this->getOrganizationName($sourceOrg), $hash]), ['headers' => $headers] ); } catch (GuzzleException $e) { if (404 == $e->getCode()) { return false; } throw $e; } $statusCode = $response->getStatusCode(); return $statusCode >= 200 && $statusCode < 300; }
php
public function copySourceImage($hash, $destinationOrg, $overwrite = true, $sourceOrg = '') { try { $headers = ['Destination' => $destinationOrg]; if (false === $overwrite) { $headers['Overwrite'] = 'F'; } $response = $this->call('COPY', implode('/', [self::SOURCEIMAGE_RESOURCE, $this->getOrganizationName($sourceOrg), $hash]), ['headers' => $headers] ); } catch (GuzzleException $e) { if (404 == $e->getCode()) { return false; } throw $e; } $statusCode = $response->getStatusCode(); return $statusCode >= 200 && $statusCode < 300; }
[ "public", "function", "copySourceImage", "(", "$", "hash", ",", "$", "destinationOrg", ",", "$", "overwrite", "=", "true", ",", "$", "sourceOrg", "=", "''", ")", "{", "try", "{", "$", "headers", "=", "[", "'Destination'", "=>", "$", "destinationOrg", "]", ";", "if", "(", "false", "===", "$", "overwrite", ")", "{", "$", "headers", "[", "'Overwrite'", "]", "=", "'F'", ";", "}", "$", "response", "=", "$", "this", "->", "call", "(", "'COPY'", ",", "implode", "(", "'/'", ",", "[", "self", "::", "SOURCEIMAGE_RESOURCE", ",", "$", "this", "->", "getOrganizationName", "(", "$", "sourceOrg", ")", ",", "$", "hash", "]", ")", ",", "[", "'headers'", "=>", "$", "headers", "]", ")", ";", "}", "catch", "(", "GuzzleException", "$", "e", ")", "{", "if", "(", "404", "==", "$", "e", "->", "getCode", "(", ")", ")", "{", "return", "false", ";", "}", "throw", "$", "e", ";", "}", "$", "statusCode", "=", "$", "response", "->", "getStatusCode", "(", ")", ";", "return", "$", "statusCode", ">=", "200", "&&", "$", "statusCode", "<", "300", ";", "}" ]
Copy a source image to another org. Needs read permissions on the source organization and write permissions on the write organization. @param string $hash Hash of the image @param string $destinationOrg The destination organization @param bool $overwrite If an existing image should be overwritten @param string $sourceOrg Optional source organization name @throws GuzzleException If the request fails for a different reason than image not found @return bool True if successful, false if source image not found
[ "Copy", "a", "source", "image", "to", "another", "org", "." ]
ab037e0fd38b110211a0f7afb70f379e30756bdc
https://github.com/rokka-io/rokka-client-php/blob/ab037e0fd38b110211a0f7afb70f379e30756bdc/src/Image.php#L170-L191
train
rokka-io/rokka-client-php
src/Image.php
Image.copySourceImages
public function copySourceImages($hashes, $destinationOrg, $overwrite = true, $sourceOrg = '') { try { $headers = ['Destination' => $destinationOrg]; if (false === $overwrite) { $headers['Overwrite'] = 'F'; } $response = $this->call('POST', implode('/', [self::SOURCEIMAGE_RESOURCE, $this->getOrganizationName($sourceOrg), 'copy']), ['headers' => $headers, 'json' => $hashes] ); } catch (GuzzleException $e) { if (404 == $e->getCode()) { return ['existing' => [], 'created' => []]; } throw $e; } return json_decode($response->getBody()->getContents(), true); }
php
public function copySourceImages($hashes, $destinationOrg, $overwrite = true, $sourceOrg = '') { try { $headers = ['Destination' => $destinationOrg]; if (false === $overwrite) { $headers['Overwrite'] = 'F'; } $response = $this->call('POST', implode('/', [self::SOURCEIMAGE_RESOURCE, $this->getOrganizationName($sourceOrg), 'copy']), ['headers' => $headers, 'json' => $hashes] ); } catch (GuzzleException $e) { if (404 == $e->getCode()) { return ['existing' => [], 'created' => []]; } throw $e; } return json_decode($response->getBody()->getContents(), true); }
[ "public", "function", "copySourceImages", "(", "$", "hashes", ",", "$", "destinationOrg", ",", "$", "overwrite", "=", "true", ",", "$", "sourceOrg", "=", "''", ")", "{", "try", "{", "$", "headers", "=", "[", "'Destination'", "=>", "$", "destinationOrg", "]", ";", "if", "(", "false", "===", "$", "overwrite", ")", "{", "$", "headers", "[", "'Overwrite'", "]", "=", "'F'", ";", "}", "$", "response", "=", "$", "this", "->", "call", "(", "'POST'", ",", "implode", "(", "'/'", ",", "[", "self", "::", "SOURCEIMAGE_RESOURCE", ",", "$", "this", "->", "getOrganizationName", "(", "$", "sourceOrg", ")", ",", "'copy'", "]", ")", ",", "[", "'headers'", "=>", "$", "headers", ",", "'json'", "=>", "$", "hashes", "]", ")", ";", "}", "catch", "(", "GuzzleException", "$", "e", ")", "{", "if", "(", "404", "==", "$", "e", "->", "getCode", "(", ")", ")", "{", "return", "[", "'existing'", "=>", "[", "]", ",", "'created'", "=>", "[", "]", "]", ";", "}", "throw", "$", "e", ";", "}", "return", "json_decode", "(", "$", "response", "->", "getBody", "(", ")", "->", "getContents", "(", ")", ",", "true", ")", ";", "}" ]
Copy multiple sources image to another org. Needs read permissions on the source organization and write permissions on the write organization. @param array $hashes Hashes of the images as array (max. 100) @param string $destinationOrg The destination organization @param bool $overwrite If an existing image should be overwritten @param string $sourceOrg Optional source organization name @throws GuzzleException If the request fails for a different reason than image not found @throws \RuntimeException @return array An array in the form of ['existing' => [...], 'created' => [..]] with all the hashes in it
[ "Copy", "multiple", "sources", "image", "to", "another", "org", "." ]
ab037e0fd38b110211a0f7afb70f379e30756bdc
https://github.com/rokka-io/rokka-client-php/blob/ab037e0fd38b110211a0f7afb70f379e30756bdc/src/Image.php#L208-L228
train
rokka-io/rokka-client-php
src/Image.php
Image.deleteSourceImagesWithBinaryHash
public function deleteSourceImagesWithBinaryHash($binaryHash, $organization = '') { try { $response = $this->call('DELETE', implode('/', [self::SOURCEIMAGE_RESOURCE, $this->getOrganizationName($organization)]), ['query' => ['binaryHash' => $binaryHash]]); } catch (GuzzleException $e) { if (404 == $e->getCode()) { return false; } throw $e; } return '204' == $response->getStatusCode(); }
php
public function deleteSourceImagesWithBinaryHash($binaryHash, $organization = '') { try { $response = $this->call('DELETE', implode('/', [self::SOURCEIMAGE_RESOURCE, $this->getOrganizationName($organization)]), ['query' => ['binaryHash' => $binaryHash]]); } catch (GuzzleException $e) { if (404 == $e->getCode()) { return false; } throw $e; } return '204' == $response->getStatusCode(); }
[ "public", "function", "deleteSourceImagesWithBinaryHash", "(", "$", "binaryHash", ",", "$", "organization", "=", "''", ")", "{", "try", "{", "$", "response", "=", "$", "this", "->", "call", "(", "'DELETE'", ",", "implode", "(", "'/'", ",", "[", "self", "::", "SOURCEIMAGE_RESOURCE", ",", "$", "this", "->", "getOrganizationName", "(", "$", "organization", ")", "]", ")", ",", "[", "'query'", "=>", "[", "'binaryHash'", "=>", "$", "binaryHash", "]", "]", ")", ";", "}", "catch", "(", "GuzzleException", "$", "e", ")", "{", "if", "(", "404", "==", "$", "e", "->", "getCode", "(", ")", ")", "{", "return", "false", ";", "}", "throw", "$", "e", ";", "}", "return", "'204'", "==", "$", "response", "->", "getStatusCode", "(", ")", ";", "}" ]
Delete source images by binaryhash. Since the same binaryhash can have different images in rokka, this may delete more than one picture. @param string $binaryHash Hash of the image @param string $organization Optional organization name @throws GuzzleException If the request fails for a different reason than image not found @throws \Exception @return bool True if successful, false if image not found
[ "Delete", "source", "images", "by", "binaryhash", "." ]
ab037e0fd38b110211a0f7afb70f379e30756bdc
https://github.com/rokka-io/rokka-client-php/blob/ab037e0fd38b110211a0f7afb70f379e30756bdc/src/Image.php#L243-L256
train
rokka-io/rokka-client-php
src/Image.php
Image.searchSourceImages
public function searchSourceImages($search = [], $sorts = [], $limit = null, $offset = null, $organization = '') { $options = ['query' => []]; $sort = SearchHelper::buildSearchSortParameter($sorts); if (!empty($sort)) { $options['query']['sort'] = $sort; } if (\is_array($search) && !empty($search)) { foreach ($search as $field => $value) { if (!SearchHelper::validateFieldName((string) $field)) { throw new \LogicException(sprintf('Invalid field name "%s" as search field', $field)); } $options['query'][$field] = $value; } } if (isset($limit)) { $options['query']['limit'] = $limit; } if (isset($offset)) { $options['query']['offset'] = $offset; } $contents = $this ->call('GET', self::SOURCEIMAGE_RESOURCE.'/'.$this->getOrganizationName($organization), $options) ->getBody() ->getContents(); return SourceImageCollection::createFromJsonResponse($contents); }
php
public function searchSourceImages($search = [], $sorts = [], $limit = null, $offset = null, $organization = '') { $options = ['query' => []]; $sort = SearchHelper::buildSearchSortParameter($sorts); if (!empty($sort)) { $options['query']['sort'] = $sort; } if (\is_array($search) && !empty($search)) { foreach ($search as $field => $value) { if (!SearchHelper::validateFieldName((string) $field)) { throw new \LogicException(sprintf('Invalid field name "%s" as search field', $field)); } $options['query'][$field] = $value; } } if (isset($limit)) { $options['query']['limit'] = $limit; } if (isset($offset)) { $options['query']['offset'] = $offset; } $contents = $this ->call('GET', self::SOURCEIMAGE_RESOURCE.'/'.$this->getOrganizationName($organization), $options) ->getBody() ->getContents(); return SourceImageCollection::createFromJsonResponse($contents); }
[ "public", "function", "searchSourceImages", "(", "$", "search", "=", "[", "]", ",", "$", "sorts", "=", "[", "]", ",", "$", "limit", "=", "null", ",", "$", "offset", "=", "null", ",", "$", "organization", "=", "''", ")", "{", "$", "options", "=", "[", "'query'", "=>", "[", "]", "]", ";", "$", "sort", "=", "SearchHelper", "::", "buildSearchSortParameter", "(", "$", "sorts", ")", ";", "if", "(", "!", "empty", "(", "$", "sort", ")", ")", "{", "$", "options", "[", "'query'", "]", "[", "'sort'", "]", "=", "$", "sort", ";", "}", "if", "(", "\\", "is_array", "(", "$", "search", ")", "&&", "!", "empty", "(", "$", "search", ")", ")", "{", "foreach", "(", "$", "search", "as", "$", "field", "=>", "$", "value", ")", "{", "if", "(", "!", "SearchHelper", "::", "validateFieldName", "(", "(", "string", ")", "$", "field", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'Invalid field name \"%s\" as search field'", ",", "$", "field", ")", ")", ";", "}", "$", "options", "[", "'query'", "]", "[", "$", "field", "]", "=", "$", "value", ";", "}", "}", "if", "(", "isset", "(", "$", "limit", ")", ")", "{", "$", "options", "[", "'query'", "]", "[", "'limit'", "]", "=", "$", "limit", ";", "}", "if", "(", "isset", "(", "$", "offset", ")", ")", "{", "$", "options", "[", "'query'", "]", "[", "'offset'", "]", "=", "$", "offset", ";", "}", "$", "contents", "=", "$", "this", "->", "call", "(", "'GET'", ",", "self", "::", "SOURCEIMAGE_RESOURCE", ".", "'/'", ".", "$", "this", "->", "getOrganizationName", "(", "$", "organization", ")", ",", "$", "options", ")", "->", "getBody", "(", ")", "->", "getContents", "(", ")", ";", "return", "SourceImageCollection", "::", "createFromJsonResponse", "(", "$", "contents", ")", ";", "}" ]
Search and list source images. Sort direction can either be: "asc", "desc" (or the boolean TRUE value, treated as "asc") @param array $search The search query, as an associative array "field => value" @param array $sorts The sorting parameters, as an associative array "field => sort-direction" @param int|null $limit Optional limit @param int|string|null $offset Optional offset, either integer or the "Cursor" value @param string $organization Optional organization name @throws GuzzleException @throws \RuntimeException @return SourceImageCollection
[ "Search", "and", "list", "source", "images", "." ]
ab037e0fd38b110211a0f7afb70f379e30756bdc
https://github.com/rokka-io/rokka-client-php/blob/ab037e0fd38b110211a0f7afb70f379e30756bdc/src/Image.php#L274-L306
train
rokka-io/rokka-client-php
src/Image.php
Image.listSourceImages
public function listSourceImages($limit = null, $offset = null, $organization = '') { return $this->searchSourceImages([], [], $limit, $offset, $organization); }
php
public function listSourceImages($limit = null, $offset = null, $organization = '') { return $this->searchSourceImages([], [], $limit, $offset, $organization); }
[ "public", "function", "listSourceImages", "(", "$", "limit", "=", "null", ",", "$", "offset", "=", "null", ",", "$", "organization", "=", "''", ")", "{", "return", "$", "this", "->", "searchSourceImages", "(", "[", "]", ",", "[", "]", ",", "$", "limit", ",", "$", "offset", ",", "$", "organization", ")", ";", "}" ]
List source images. @deprecated 2.0.0 Use Image::searchSourceImages() @see Image::searchSourceImages() @param null|int $limit Optional limit @param null|int|string $offset Optional offset, either integer or the "Cursor" value @param string $organization Optional organization name @throws GuzzleException @throws \RuntimeException @return SourceImageCollection
[ "List", "source", "images", "." ]
ab037e0fd38b110211a0f7afb70f379e30756bdc
https://github.com/rokka-io/rokka-client-php/blob/ab037e0fd38b110211a0f7afb70f379e30756bdc/src/Image.php#L323-L326
train
rokka-io/rokka-client-php
src/Image.php
Image.getSourceImage
public function getSourceImage($hash, $organization = '') { $path = self::SOURCEIMAGE_RESOURCE.'/'.$this->getOrganizationName($organization); $path .= '/'.$hash; $contents = $this ->call('GET', $path) ->getBody() ->getContents(); return SourceImage::createFromJsonResponse($contents); }
php
public function getSourceImage($hash, $organization = '') { $path = self::SOURCEIMAGE_RESOURCE.'/'.$this->getOrganizationName($organization); $path .= '/'.$hash; $contents = $this ->call('GET', $path) ->getBody() ->getContents(); return SourceImage::createFromJsonResponse($contents); }
[ "public", "function", "getSourceImage", "(", "$", "hash", ",", "$", "organization", "=", "''", ")", "{", "$", "path", "=", "self", "::", "SOURCEIMAGE_RESOURCE", ".", "'/'", ".", "$", "this", "->", "getOrganizationName", "(", "$", "organization", ")", ";", "$", "path", ".=", "'/'", ".", "$", "hash", ";", "$", "contents", "=", "$", "this", "->", "call", "(", "'GET'", ",", "$", "path", ")", "->", "getBody", "(", ")", "->", "getContents", "(", ")", ";", "return", "SourceImage", "::", "createFromJsonResponse", "(", "$", "contents", ")", ";", "}" ]
Load a source image's metadata from Rokka. @param string $hash Hash of the image @param string $organization Optional organization name @throws GuzzleException @throws \RuntimeException @return SourceImage
[ "Load", "a", "source", "image", "s", "metadata", "from", "Rokka", "." ]
ab037e0fd38b110211a0f7afb70f379e30756bdc
https://github.com/rokka-io/rokka-client-php/blob/ab037e0fd38b110211a0f7afb70f379e30756bdc/src/Image.php#L339-L351
train
rokka-io/rokka-client-php
src/Image.php
Image.getSourceImagesWithBinaryHash
public function getSourceImagesWithBinaryHash($binaryHash, $organization = '') { $path = self::SOURCEIMAGE_RESOURCE.'/'.$this->getOrganizationName($organization); $options['query'] = ['binaryHash' => $binaryHash]; $contents = $this ->call('GET', $path, $options) ->getBody() ->getContents(); return SourceImageCollection::createFromJsonResponse($contents); }
php
public function getSourceImagesWithBinaryHash($binaryHash, $organization = '') { $path = self::SOURCEIMAGE_RESOURCE.'/'.$this->getOrganizationName($organization); $options['query'] = ['binaryHash' => $binaryHash]; $contents = $this ->call('GET', $path, $options) ->getBody() ->getContents(); return SourceImageCollection::createFromJsonResponse($contents); }
[ "public", "function", "getSourceImagesWithBinaryHash", "(", "$", "binaryHash", ",", "$", "organization", "=", "''", ")", "{", "$", "path", "=", "self", "::", "SOURCEIMAGE_RESOURCE", ".", "'/'", ".", "$", "this", "->", "getOrganizationName", "(", "$", "organization", ")", ";", "$", "options", "[", "'query'", "]", "=", "[", "'binaryHash'", "=>", "$", "binaryHash", "]", ";", "$", "contents", "=", "$", "this", "->", "call", "(", "'GET'", ",", "$", "path", ",", "$", "options", ")", "->", "getBody", "(", ")", "->", "getContents", "(", ")", ";", "return", "SourceImageCollection", "::", "createFromJsonResponse", "(", "$", "contents", ")", ";", "}" ]
Loads source images metadata from Rokka by binaryhash. Since the same binaryhash can have different images in rokka, this may return more than one picture. @param string $binaryHash Hash of the image @param string $organization Optional organization name @throws GuzzleException @throws \RuntimeException @return SourceImageCollection
[ "Loads", "source", "images", "metadata", "from", "Rokka", "by", "binaryhash", "." ]
ab037e0fd38b110211a0f7afb70f379e30756bdc
https://github.com/rokka-io/rokka-client-php/blob/ab037e0fd38b110211a0f7afb70f379e30756bdc/src/Image.php#L366-L377
train
rokka-io/rokka-client-php
src/Image.php
Image.getSourceImageContents
public function getSourceImageContents($hash, $organization = '') { $path = implode('/', [ self::SOURCEIMAGE_RESOURCE, $this->getOrganizationName($organization), $hash, 'download', ] ); return $this ->call('GET', $path) ->getBody() ->getContents(); }
php
public function getSourceImageContents($hash, $organization = '') { $path = implode('/', [ self::SOURCEIMAGE_RESOURCE, $this->getOrganizationName($organization), $hash, 'download', ] ); return $this ->call('GET', $path) ->getBody() ->getContents(); }
[ "public", "function", "getSourceImageContents", "(", "$", "hash", ",", "$", "organization", "=", "''", ")", "{", "$", "path", "=", "implode", "(", "'/'", ",", "[", "self", "::", "SOURCEIMAGE_RESOURCE", ",", "$", "this", "->", "getOrganizationName", "(", "$", "organization", ")", ",", "$", "hash", ",", "'download'", ",", "]", ")", ";", "return", "$", "this", "->", "call", "(", "'GET'", ",", "$", "path", ")", "->", "getBody", "(", ")", "->", "getContents", "(", ")", ";", "}" ]
Get a source image's binary contents from Rokka. @param string $hash Hash of the image @param string $organization Optional organization name @throws GuzzleException @throws \RuntimeException @return string
[ "Get", "a", "source", "image", "s", "binary", "contents", "from", "Rokka", "." ]
ab037e0fd38b110211a0f7afb70f379e30756bdc
https://github.com/rokka-io/rokka-client-php/blob/ab037e0fd38b110211a0f7afb70f379e30756bdc/src/Image.php#L390-L403
train
rokka-io/rokka-client-php
src/Image.php
Image.listOperations
public function listOperations() { $contents = $this ->call('GET', self::OPERATIONS_RESOURCE) ->getBody() ->getContents(); return OperationCollection::createFromJsonResponse($contents); }
php
public function listOperations() { $contents = $this ->call('GET', self::OPERATIONS_RESOURCE) ->getBody() ->getContents(); return OperationCollection::createFromJsonResponse($contents); }
[ "public", "function", "listOperations", "(", ")", "{", "$", "contents", "=", "$", "this", "->", "call", "(", "'GET'", ",", "self", "::", "OPERATIONS_RESOURCE", ")", "->", "getBody", "(", ")", "->", "getContents", "(", ")", ";", "return", "OperationCollection", "::", "createFromJsonResponse", "(", "$", "contents", ")", ";", "}" ]
List operations. @throws GuzzleException @throws \RuntimeException @return OperationCollection
[ "List", "operations", "." ]
ab037e0fd38b110211a0f7afb70f379e30756bdc
https://github.com/rokka-io/rokka-client-php/blob/ab037e0fd38b110211a0f7afb70f379e30756bdc/src/Image.php#L413-L421
train
rokka-io/rokka-client-php
src/Image.php
Image.createStack
public function createStack( $stackName, array $stackOperations, $organization = '', array $stackOptions = [], $overwrite = false ) { $stackData = [ 'operations' => $stackOperations, 'options' => $stackOptions, ]; $stack = Stack::createFromConfig($stackName, $stackData, $organization); return $this->saveStack($stack, ['overwrite' => $overwrite]); }
php
public function createStack( $stackName, array $stackOperations, $organization = '', array $stackOptions = [], $overwrite = false ) { $stackData = [ 'operations' => $stackOperations, 'options' => $stackOptions, ]; $stack = Stack::createFromConfig($stackName, $stackData, $organization); return $this->saveStack($stack, ['overwrite' => $overwrite]); }
[ "public", "function", "createStack", "(", "$", "stackName", ",", "array", "$", "stackOperations", ",", "$", "organization", "=", "''", ",", "array", "$", "stackOptions", "=", "[", "]", ",", "$", "overwrite", "=", "false", ")", "{", "$", "stackData", "=", "[", "'operations'", "=>", "$", "stackOperations", ",", "'options'", "=>", "$", "stackOptions", ",", "]", ";", "$", "stack", "=", "Stack", "::", "createFromConfig", "(", "$", "stackName", ",", "$", "stackData", ",", "$", "organization", ")", ";", "return", "$", "this", "->", "saveStack", "(", "$", "stack", ",", "[", "'overwrite'", "=>", "$", "overwrite", "]", ")", ";", "}" ]
Create a stack. @deprecated 2.0.0 Use Image::saveStack() instead @see Image::saveStack() @param string $stackName Name of the stack @param array $stackOperations Stack operations @param string $organization Optional organization name @param array $stackOptions Stack options @param bool $overwrite If an existing stack should be overwritten @throws GuzzleException @throws \RuntimeException @return Stack
[ "Create", "a", "stack", "." ]
ab037e0fd38b110211a0f7afb70f379e30756bdc
https://github.com/rokka-io/rokka-client-php/blob/ab037e0fd38b110211a0f7afb70f379e30756bdc/src/Image.php#L440-L454
train
rokka-io/rokka-client-php
src/Image.php
Image.saveStack
public function saveStack(Stack $stack, array $requestConfig = []) { if (empty($stack->getName())) { throw new \LogicException('Stack has no name, please set one.'); } if (empty($stack->getOrganization())) { $stack->setOrganization($this->defaultOrganization); } $queryString = []; if (isset($requestConfig['overwrite']) && true === $requestConfig['overwrite']) { $queryString['overwrite'] = 'true'; } $contents = $this ->call( 'PUT', implode('/', [self::STACK_RESOURCE, $stack->getOrganization(), $stack->getName()]), ['json' => $stack->getConfig(), 'query' => $queryString] ) ->getBody() ->getContents(); return Stack::createFromJsonResponse($contents); }
php
public function saveStack(Stack $stack, array $requestConfig = []) { if (empty($stack->getName())) { throw new \LogicException('Stack has no name, please set one.'); } if (empty($stack->getOrganization())) { $stack->setOrganization($this->defaultOrganization); } $queryString = []; if (isset($requestConfig['overwrite']) && true === $requestConfig['overwrite']) { $queryString['overwrite'] = 'true'; } $contents = $this ->call( 'PUT', implode('/', [self::STACK_RESOURCE, $stack->getOrganization(), $stack->getName()]), ['json' => $stack->getConfig(), 'query' => $queryString] ) ->getBody() ->getContents(); return Stack::createFromJsonResponse($contents); }
[ "public", "function", "saveStack", "(", "Stack", "$", "stack", ",", "array", "$", "requestConfig", "=", "[", "]", ")", "{", "if", "(", "empty", "(", "$", "stack", "->", "getName", "(", ")", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "'Stack has no name, please set one.'", ")", ";", "}", "if", "(", "empty", "(", "$", "stack", "->", "getOrganization", "(", ")", ")", ")", "{", "$", "stack", "->", "setOrganization", "(", "$", "this", "->", "defaultOrganization", ")", ";", "}", "$", "queryString", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "requestConfig", "[", "'overwrite'", "]", ")", "&&", "true", "===", "$", "requestConfig", "[", "'overwrite'", "]", ")", "{", "$", "queryString", "[", "'overwrite'", "]", "=", "'true'", ";", "}", "$", "contents", "=", "$", "this", "->", "call", "(", "'PUT'", ",", "implode", "(", "'/'", ",", "[", "self", "::", "STACK_RESOURCE", ",", "$", "stack", "->", "getOrganization", "(", ")", ",", "$", "stack", "->", "getName", "(", ")", "]", ")", ",", "[", "'json'", "=>", "$", "stack", "->", "getConfig", "(", ")", ",", "'query'", "=>", "$", "queryString", "]", ")", "->", "getBody", "(", ")", "->", "getContents", "(", ")", ";", "return", "Stack", "::", "createFromJsonResponse", "(", "$", "contents", ")", ";", "}" ]
Save a stack on rokka. Example: ```language-php $stack = new Stack(null, 'teststack'); $stack->addStackOperation(new StackOperation('resize', ['width' => 200, 'height' => 200])); $stack->addStackOperation(new StackOperation('rotate', ['angle' => 45])); $stack->setStackOptions(['jpg.quality' => 80]); $requestConfig = ['overwrite' => true]; $stack = $client->saveStack($stack, $requestConfig); echo 'Created stack ' . $stack->getName() . PHP_EOL; ``` The only requestConfig option currently can be ['overwrite' => true|false] (false is the default) @since 1.1.0 @param Stack $stack the Stack object to be saved @param array $requestConfig options for the request @throws GuzzleException @throws \LogicException when stack name is not set @throws \RuntimeException @return Stack
[ "Save", "a", "stack", "on", "rokka", "." ]
ab037e0fd38b110211a0f7afb70f379e30756bdc
https://github.com/rokka-io/rokka-client-php/blob/ab037e0fd38b110211a0f7afb70f379e30756bdc/src/Image.php#L483-L506
train
rokka-io/rokka-client-php
src/Image.php
Image.listStacks
public function listStacks($limit = null, $offset = null, $organization = '') { $options = []; if ($limit || $offset) { $options = ['query' => ['limit' => $limit, 'offset' => $offset]]; } $contents = $this ->call('GET', self::STACK_RESOURCE.'/'.$this->getOrganizationName($organization), $options) ->getBody() ->getContents(); return StackCollection::createFromJsonResponse($contents); }
php
public function listStacks($limit = null, $offset = null, $organization = '') { $options = []; if ($limit || $offset) { $options = ['query' => ['limit' => $limit, 'offset' => $offset]]; } $contents = $this ->call('GET', self::STACK_RESOURCE.'/'.$this->getOrganizationName($organization), $options) ->getBody() ->getContents(); return StackCollection::createFromJsonResponse($contents); }
[ "public", "function", "listStacks", "(", "$", "limit", "=", "null", ",", "$", "offset", "=", "null", ",", "$", "organization", "=", "''", ")", "{", "$", "options", "=", "[", "]", ";", "if", "(", "$", "limit", "||", "$", "offset", ")", "{", "$", "options", "=", "[", "'query'", "=>", "[", "'limit'", "=>", "$", "limit", ",", "'offset'", "=>", "$", "offset", "]", "]", ";", "}", "$", "contents", "=", "$", "this", "->", "call", "(", "'GET'", ",", "self", "::", "STACK_RESOURCE", ".", "'/'", ".", "$", "this", "->", "getOrganizationName", "(", "$", "organization", ")", ",", "$", "options", ")", "->", "getBody", "(", ")", "->", "getContents", "(", ")", ";", "return", "StackCollection", "::", "createFromJsonResponse", "(", "$", "contents", ")", ";", "}" ]
List stacks. ```language-php use Rokka\Client\Core\Stack; $client = \Rokka\Client\Factory::getImageClient('testorganization', 'apiKey'); $stacks = $client->listStacks(); foreach ($stacks as $stack) { echo 'Stack ' . $stack->getName() . PHP_EOL; } ``` @param null|int $limit Optional limit @param null|int $offset Optional offset @param string $organization Optional organization name @throws GuzzleException @throws \RuntimeException @return StackCollection
[ "List", "stacks", "." ]
ab037e0fd38b110211a0f7afb70f379e30756bdc
https://github.com/rokka-io/rokka-client-php/blob/ab037e0fd38b110211a0f7afb70f379e30756bdc/src/Image.php#L529-L543
train
rokka-io/rokka-client-php
src/Image.php
Image.getStack
public function getStack($stackName, $organization = '') { $contents = $this ->call('GET', implode('/', [self::STACK_RESOURCE, $this->getOrganizationName($organization), $stackName])) ->getBody() ->getContents(); return Stack::createFromJsonResponse($contents); }
php
public function getStack($stackName, $organization = '') { $contents = $this ->call('GET', implode('/', [self::STACK_RESOURCE, $this->getOrganizationName($organization), $stackName])) ->getBody() ->getContents(); return Stack::createFromJsonResponse($contents); }
[ "public", "function", "getStack", "(", "$", "stackName", ",", "$", "organization", "=", "''", ")", "{", "$", "contents", "=", "$", "this", "->", "call", "(", "'GET'", ",", "implode", "(", "'/'", ",", "[", "self", "::", "STACK_RESOURCE", ",", "$", "this", "->", "getOrganizationName", "(", "$", "organization", ")", ",", "$", "stackName", "]", ")", ")", "->", "getBody", "(", ")", "->", "getContents", "(", ")", ";", "return", "Stack", "::", "createFromJsonResponse", "(", "$", "contents", ")", ";", "}" ]
Return a stack. @param string $stackName Stack name @param string $organization Optional organization name @throws GuzzleException @throws \RuntimeException @return Stack
[ "Return", "a", "stack", "." ]
ab037e0fd38b110211a0f7afb70f379e30756bdc
https://github.com/rokka-io/rokka-client-php/blob/ab037e0fd38b110211a0f7afb70f379e30756bdc/src/Image.php#L556-L564
train
rokka-io/rokka-client-php
src/Image.php
Image.deleteStack
public function deleteStack($stackName, $organization = '') { $response = $this->call('DELETE', implode('/', [self::STACK_RESOURCE, $this->getOrganizationName($organization), $stackName])); return '204' == $response->getStatusCode(); }
php
public function deleteStack($stackName, $organization = '') { $response = $this->call('DELETE', implode('/', [self::STACK_RESOURCE, $this->getOrganizationName($organization), $stackName])); return '204' == $response->getStatusCode(); }
[ "public", "function", "deleteStack", "(", "$", "stackName", ",", "$", "organization", "=", "''", ")", "{", "$", "response", "=", "$", "this", "->", "call", "(", "'DELETE'", ",", "implode", "(", "'/'", ",", "[", "self", "::", "STACK_RESOURCE", ",", "$", "this", "->", "getOrganizationName", "(", "$", "organization", ")", ",", "$", "stackName", "]", ")", ")", ";", "return", "'204'", "==", "$", "response", "->", "getStatusCode", "(", ")", ";", "}" ]
Delete a stack. @param string $stackName Delete the stack @param string $organization Optional organization name @throws GuzzleException @return bool True if successful
[ "Delete", "a", "stack", "." ]
ab037e0fd38b110211a0f7afb70f379e30756bdc
https://github.com/rokka-io/rokka-client-php/blob/ab037e0fd38b110211a0f7afb70f379e30756bdc/src/Image.php#L576-L581
train
rokka-io/rokka-client-php
src/Image.php
Image.setDynamicMetadata
public function setDynamicMetadata($dynamicMetadata, $hash, $organization = '', $options = []) { if (!\is_array($dynamicMetadata)) { $dynamicMetadata = [$dynamicMetadata]; } $count = 0; $response = null; foreach ($dynamicMetadata as $value => $data) { $callOptions = []; if ($data instanceof DynamicMetadataInterface) { $name = $data::getName(); $callOptions['json'] = $data->getForJson(); } else { $name = $value; $callOptions['json'] = $data; } $path = implode('/', [ self::SOURCEIMAGE_RESOURCE, $this->getOrganizationName($organization), $hash, self::DYNAMIC_META_RESOURCE, $name, ]); // delete the previous, if we're not on the first one anymore, or if we want to delete it. if ($count > 0 || (0 === $count && isset($options['deletePrevious']) && $options['deletePrevious'])) { $callOptions['query'] = ['deletePrevious' => 'true']; } ++$count; $response = $this->call('PUT', $path, $callOptions); if (!($response->getStatusCode() >= 200 && $response->getStatusCode() < 300)) { throw new \LogicException($response->getBody()->getContents(), $response->getStatusCode()); } $hash = $this->extractHashFromLocationHeader($response->getHeader('Location')); } if ($response instanceof ResponseInterface) { if ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300) { return $hash; } // Throw an exception to be handled by the caller. throw new \LogicException($response->getBody()->getContents(), $response->getStatusCode()); } throw new \LogicException('Something went wrong with the call/response to the rokka API', 0); }
php
public function setDynamicMetadata($dynamicMetadata, $hash, $organization = '', $options = []) { if (!\is_array($dynamicMetadata)) { $dynamicMetadata = [$dynamicMetadata]; } $count = 0; $response = null; foreach ($dynamicMetadata as $value => $data) { $callOptions = []; if ($data instanceof DynamicMetadataInterface) { $name = $data::getName(); $callOptions['json'] = $data->getForJson(); } else { $name = $value; $callOptions['json'] = $data; } $path = implode('/', [ self::SOURCEIMAGE_RESOURCE, $this->getOrganizationName($organization), $hash, self::DYNAMIC_META_RESOURCE, $name, ]); // delete the previous, if we're not on the first one anymore, or if we want to delete it. if ($count > 0 || (0 === $count && isset($options['deletePrevious']) && $options['deletePrevious'])) { $callOptions['query'] = ['deletePrevious' => 'true']; } ++$count; $response = $this->call('PUT', $path, $callOptions); if (!($response->getStatusCode() >= 200 && $response->getStatusCode() < 300)) { throw new \LogicException($response->getBody()->getContents(), $response->getStatusCode()); } $hash = $this->extractHashFromLocationHeader($response->getHeader('Location')); } if ($response instanceof ResponseInterface) { if ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300) { return $hash; } // Throw an exception to be handled by the caller. throw new \LogicException($response->getBody()->getContents(), $response->getStatusCode()); } throw new \LogicException('Something went wrong with the call/response to the rokka API', 0); }
[ "public", "function", "setDynamicMetadata", "(", "$", "dynamicMetadata", ",", "$", "hash", ",", "$", "organization", "=", "''", ",", "$", "options", "=", "[", "]", ")", "{", "if", "(", "!", "\\", "is_array", "(", "$", "dynamicMetadata", ")", ")", "{", "$", "dynamicMetadata", "=", "[", "$", "dynamicMetadata", "]", ";", "}", "$", "count", "=", "0", ";", "$", "response", "=", "null", ";", "foreach", "(", "$", "dynamicMetadata", "as", "$", "value", "=>", "$", "data", ")", "{", "$", "callOptions", "=", "[", "]", ";", "if", "(", "$", "data", "instanceof", "DynamicMetadataInterface", ")", "{", "$", "name", "=", "$", "data", "::", "getName", "(", ")", ";", "$", "callOptions", "[", "'json'", "]", "=", "$", "data", "->", "getForJson", "(", ")", ";", "}", "else", "{", "$", "name", "=", "$", "value", ";", "$", "callOptions", "[", "'json'", "]", "=", "$", "data", ";", "}", "$", "path", "=", "implode", "(", "'/'", ",", "[", "self", "::", "SOURCEIMAGE_RESOURCE", ",", "$", "this", "->", "getOrganizationName", "(", "$", "organization", ")", ",", "$", "hash", ",", "self", "::", "DYNAMIC_META_RESOURCE", ",", "$", "name", ",", "]", ")", ";", "// delete the previous, if we're not on the first one anymore, or if we want to delete it.", "if", "(", "$", "count", ">", "0", "||", "(", "0", "===", "$", "count", "&&", "isset", "(", "$", "options", "[", "'deletePrevious'", "]", ")", "&&", "$", "options", "[", "'deletePrevious'", "]", ")", ")", "{", "$", "callOptions", "[", "'query'", "]", "=", "[", "'deletePrevious'", "=>", "'true'", "]", ";", "}", "++", "$", "count", ";", "$", "response", "=", "$", "this", "->", "call", "(", "'PUT'", ",", "$", "path", ",", "$", "callOptions", ")", ";", "if", "(", "!", "(", "$", "response", "->", "getStatusCode", "(", ")", ">=", "200", "&&", "$", "response", "->", "getStatusCode", "(", ")", "<", "300", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "$", "response", "->", "getBody", "(", ")", "->", "getContents", "(", ")", ",", "$", "response", "->", "getStatusCode", "(", ")", ")", ";", "}", "$", "hash", "=", "$", "this", "->", "extractHashFromLocationHeader", "(", "$", "response", "->", "getHeader", "(", "'Location'", ")", ")", ";", "}", "if", "(", "$", "response", "instanceof", "ResponseInterface", ")", "{", "if", "(", "$", "response", "->", "getStatusCode", "(", ")", ">=", "200", "&&", "$", "response", "->", "getStatusCode", "(", ")", "<", "300", ")", "{", "return", "$", "hash", ";", "}", "// Throw an exception to be handled by the caller.", "throw", "new", "\\", "LogicException", "(", "$", "response", "->", "getBody", "(", ")", "->", "getContents", "(", ")", ",", "$", "response", "->", "getStatusCode", "(", ")", ")", ";", "}", "throw", "new", "\\", "LogicException", "(", "'Something went wrong with the call/response to the rokka API'", ",", "0", ")", ";", "}" ]
Add the given DynamicMetadata to a SourceImage. Returns the new Hash for the SourceImage, it could be the same as the input one if the operation did not change it. The only option currently can be ['deletePrevious' => true] which deletes the previous image from rokka (but not the binary, since that's still used) If not set, the original image is kept in rokka. @param DynamicMetadataInterface|array $dynamicMetadata A Dynamic Metadata object, an array with all the needed info. Or an array with more than one of those. @param string $hash The Image hash @param string $organization Optional organization name @param array $options Optional options @throws GuzzleException @throws \RuntimeException @return string|false
[ "Add", "the", "given", "DynamicMetadata", "to", "a", "SourceImage", ".", "Returns", "the", "new", "Hash", "for", "the", "SourceImage", "it", "could", "be", "the", "same", "as", "the", "input", "one", "if", "the", "operation", "did", "not", "change", "it", "." ]
ab037e0fd38b110211a0f7afb70f379e30756bdc
https://github.com/rokka-io/rokka-client-php/blob/ab037e0fd38b110211a0f7afb70f379e30756bdc/src/Image.php#L605-L652
train
rokka-io/rokka-client-php
src/Image.php
Image.deleteDynamicMetadata
public function deleteDynamicMetadata($dynamicMetadataName, $hash, $organization = '', $options = []) { if (empty($hash)) { throw new \LogicException('Missing image Hash.'); } if (empty($dynamicMetadataName)) { throw new \LogicException('Missing DynamicMetadata name.'); } $path = implode('/', [ self::SOURCEIMAGE_RESOURCE, $this->getOrganizationName($organization), $hash, self::DYNAMIC_META_RESOURCE, $dynamicMetadataName, ]); $callOptions = []; if (isset($options['deletePrevious']) && $options['deletePrevious']) { $callOptions['query'] = ['deletePrevious' => 'true']; } $response = $this->call('DELETE', $path, $callOptions); if ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300) { return $this->extractHashFromLocationHeader($response->getHeader('Location')); } // Throw an exception to be handled by the caller. throw new \LogicException($response->getBody()->getContents(), $response->getStatusCode()); }
php
public function deleteDynamicMetadata($dynamicMetadataName, $hash, $organization = '', $options = []) { if (empty($hash)) { throw new \LogicException('Missing image Hash.'); } if (empty($dynamicMetadataName)) { throw new \LogicException('Missing DynamicMetadata name.'); } $path = implode('/', [ self::SOURCEIMAGE_RESOURCE, $this->getOrganizationName($organization), $hash, self::DYNAMIC_META_RESOURCE, $dynamicMetadataName, ]); $callOptions = []; if (isset($options['deletePrevious']) && $options['deletePrevious']) { $callOptions['query'] = ['deletePrevious' => 'true']; } $response = $this->call('DELETE', $path, $callOptions); if ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300) { return $this->extractHashFromLocationHeader($response->getHeader('Location')); } // Throw an exception to be handled by the caller. throw new \LogicException($response->getBody()->getContents(), $response->getStatusCode()); }
[ "public", "function", "deleteDynamicMetadata", "(", "$", "dynamicMetadataName", ",", "$", "hash", ",", "$", "organization", "=", "''", ",", "$", "options", "=", "[", "]", ")", "{", "if", "(", "empty", "(", "$", "hash", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "'Missing image Hash.'", ")", ";", "}", "if", "(", "empty", "(", "$", "dynamicMetadataName", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "'Missing DynamicMetadata name.'", ")", ";", "}", "$", "path", "=", "implode", "(", "'/'", ",", "[", "self", "::", "SOURCEIMAGE_RESOURCE", ",", "$", "this", "->", "getOrganizationName", "(", "$", "organization", ")", ",", "$", "hash", ",", "self", "::", "DYNAMIC_META_RESOURCE", ",", "$", "dynamicMetadataName", ",", "]", ")", ";", "$", "callOptions", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "options", "[", "'deletePrevious'", "]", ")", "&&", "$", "options", "[", "'deletePrevious'", "]", ")", "{", "$", "callOptions", "[", "'query'", "]", "=", "[", "'deletePrevious'", "=>", "'true'", "]", ";", "}", "$", "response", "=", "$", "this", "->", "call", "(", "'DELETE'", ",", "$", "path", ",", "$", "callOptions", ")", ";", "if", "(", "$", "response", "->", "getStatusCode", "(", ")", ">=", "200", "&&", "$", "response", "->", "getStatusCode", "(", ")", "<", "300", ")", "{", "return", "$", "this", "->", "extractHashFromLocationHeader", "(", "$", "response", "->", "getHeader", "(", "'Location'", ")", ")", ";", "}", "// Throw an exception to be handled by the caller.", "throw", "new", "\\", "LogicException", "(", "$", "response", "->", "getBody", "(", ")", "->", "getContents", "(", ")", ",", "$", "response", "->", "getStatusCode", "(", ")", ")", ";", "}" ]
Delete the given DynamicMetadata from a SourceImage. Returns the new Hash for the SourceImage, it could be the same as the input one if the operation did not change it. The only option currently can be ['deletePrevious' => true] which deletes the previous image from rokka (but not the binary, since that's still used) If not set, the original image is kept in rokka. @param string $dynamicMetadataName The DynamicMetadata name @param string $hash The Image hash @param string $organization Optional organization name @param array $options Optional options @throws GuzzleException @throws \RuntimeException @return string|false
[ "Delete", "the", "given", "DynamicMetadata", "from", "a", "SourceImage", ".", "Returns", "the", "new", "Hash", "for", "the", "SourceImage", "it", "could", "be", "the", "same", "as", "the", "input", "one", "if", "the", "operation", "did", "not", "change", "it", "." ]
ab037e0fd38b110211a0f7afb70f379e30756bdc
https://github.com/rokka-io/rokka-client-php/blob/ab037e0fd38b110211a0f7afb70f379e30756bdc/src/Image.php#L674-L705
train
rokka-io/rokka-client-php
src/Image.php
Image.deleteUserMetadataField
public function deleteUserMetadataField($field, $hash, $organization = '') { return $this->doUserMetadataRequest([$field => null], $hash, 'PATCH', $organization); }
php
public function deleteUserMetadataField($field, $hash, $organization = '') { return $this->doUserMetadataRequest([$field => null], $hash, 'PATCH', $organization); }
[ "public", "function", "deleteUserMetadataField", "(", "$", "field", ",", "$", "hash", ",", "$", "organization", "=", "''", ")", "{", "return", "$", "this", "->", "doUserMetadataRequest", "(", "[", "$", "field", "=>", "null", "]", ",", "$", "hash", ",", "'PATCH'", ",", "$", "organization", ")", ";", "}" ]
Delete the given field from the user-metadata of the image. @param string $field The field name @param string $hash The image hash @param string $organization The organization name @throws GuzzleException @return bool
[ "Delete", "the", "given", "field", "from", "the", "user", "-", "metadata", "of", "the", "image", "." ]
ab037e0fd38b110211a0f7afb70f379e30756bdc
https://github.com/rokka-io/rokka-client-php/blob/ab037e0fd38b110211a0f7afb70f379e30756bdc/src/Image.php#L782-L785
train
rokka-io/rokka-client-php
src/Image.php
Image.deleteUserMetadataFields
public function deleteUserMetadataFields($fields, $hash, $organization = '') { $data = []; foreach ($fields as $value) { $data[$value] = null; } return $this->doUserMetadataRequest($data, $hash, 'PATCH', $organization); }
php
public function deleteUserMetadataFields($fields, $hash, $organization = '') { $data = []; foreach ($fields as $value) { $data[$value] = null; } return $this->doUserMetadataRequest($data, $hash, 'PATCH', $organization); }
[ "public", "function", "deleteUserMetadataFields", "(", "$", "fields", ",", "$", "hash", ",", "$", "organization", "=", "''", ")", "{", "$", "data", "=", "[", "]", ";", "foreach", "(", "$", "fields", "as", "$", "value", ")", "{", "$", "data", "[", "$", "value", "]", "=", "null", ";", "}", "return", "$", "this", "->", "doUserMetadataRequest", "(", "$", "data", ",", "$", "hash", ",", "'PATCH'", ",", "$", "organization", ")", ";", "}" ]
Delete the given fields from the user-metadata of the image. @param array $fields The fields name @param string $hash The image hash @param string $organization The organization name @throws GuzzleException @return bool
[ "Delete", "the", "given", "fields", "from", "the", "user", "-", "metadata", "of", "the", "image", "." ]
ab037e0fd38b110211a0f7afb70f379e30756bdc
https://github.com/rokka-io/rokka-client-php/blob/ab037e0fd38b110211a0f7afb70f379e30756bdc/src/Image.php#L798-L806
train
rokka-io/rokka-client-php
src/Image.php
Image.getSourceImageUri
public function getSourceImageUri($hash, $stack, $format = 'jpg', $name = null, $organization = null) { $apiUri = new Uri($this->client->getConfig('base_uri')); $format = strtolower($format); // Removing the 'api.' part (third domain level) $parts = explode('.', $apiUri->getHost(), 2); $baseHost = array_pop($parts); $path = UriHelper::composeUri(['stack' => $stack, 'hash' => $hash, 'format' => $format, 'filename' => $name]); // Building the URI as "{scheme}://{organization}.{baseHost}[:{port}]/{stackName}/{hash}[/{name}].{format}" $parts = [ 'scheme' => $apiUri->getScheme(), 'port' => $apiUri->getPort(), 'host' => $this->getOrganizationName($organization).'.'.$baseHost, 'path' => $path->getPath(), ]; return Uri::fromParts($parts); }
php
public function getSourceImageUri($hash, $stack, $format = 'jpg', $name = null, $organization = null) { $apiUri = new Uri($this->client->getConfig('base_uri')); $format = strtolower($format); // Removing the 'api.' part (third domain level) $parts = explode('.', $apiUri->getHost(), 2); $baseHost = array_pop($parts); $path = UriHelper::composeUri(['stack' => $stack, 'hash' => $hash, 'format' => $format, 'filename' => $name]); // Building the URI as "{scheme}://{organization}.{baseHost}[:{port}]/{stackName}/{hash}[/{name}].{format}" $parts = [ 'scheme' => $apiUri->getScheme(), 'port' => $apiUri->getPort(), 'host' => $this->getOrganizationName($organization).'.'.$baseHost, 'path' => $path->getPath(), ]; return Uri::fromParts($parts); }
[ "public", "function", "getSourceImageUri", "(", "$", "hash", ",", "$", "stack", ",", "$", "format", "=", "'jpg'", ",", "$", "name", "=", "null", ",", "$", "organization", "=", "null", ")", "{", "$", "apiUri", "=", "new", "Uri", "(", "$", "this", "->", "client", "->", "getConfig", "(", "'base_uri'", ")", ")", ";", "$", "format", "=", "strtolower", "(", "$", "format", ")", ";", "// Removing the 'api.' part (third domain level)", "$", "parts", "=", "explode", "(", "'.'", ",", "$", "apiUri", "->", "getHost", "(", ")", ",", "2", ")", ";", "$", "baseHost", "=", "array_pop", "(", "$", "parts", ")", ";", "$", "path", "=", "UriHelper", "::", "composeUri", "(", "[", "'stack'", "=>", "$", "stack", ",", "'hash'", "=>", "$", "hash", ",", "'format'", "=>", "$", "format", ",", "'filename'", "=>", "$", "name", "]", ")", ";", "// Building the URI as \"{scheme}://{organization}.{baseHost}[:{port}]/{stackName}/{hash}[/{name}].{format}\"", "$", "parts", "=", "[", "'scheme'", "=>", "$", "apiUri", "->", "getScheme", "(", ")", ",", "'port'", "=>", "$", "apiUri", "->", "getPort", "(", ")", ",", "'host'", "=>", "$", "this", "->", "getOrganizationName", "(", "$", "organization", ")", ".", "'.'", ".", "$", "baseHost", ",", "'path'", "=>", "$", "path", "->", "getPath", "(", ")", ",", "]", ";", "return", "Uri", "::", "fromParts", "(", "$", "parts", ")", ";", "}" ]
Returns url for accessing the image. @param string $hash Identifier Hash @param string|StackUri $stack Stack to apply (name or StackUri object) @param string $format Image format for output [jpg|png|gif] @param string $name Optional image name for SEO purposes @param string $organization Optional organization name (if different from default in client) @throws \RuntimeException @return UriInterface
[ "Returns", "url", "for", "accessing", "the", "image", "." ]
ab037e0fd38b110211a0f7afb70f379e30756bdc
https://github.com/rokka-io/rokka-client-php/blob/ab037e0fd38b110211a0f7afb70f379e30756bdc/src/Image.php#L821-L840
train
rokka-io/rokka-client-php
src/Image.php
Image.extractHashFromLocationHeader
protected function extractHashFromLocationHeader(array $headers) { $location = reset($headers); // Check if we got a Location header, otherwise something went wrong here. if (empty($location)) { return false; } $uri = new Uri($location); $parts = explode('/', $uri->getPath()); // Returning just the HASH part for "api.rokka.io/organization/sourceimages/{HASH}" $return = array_pop($parts); if (null === $return) { return false; } return $return; }
php
protected function extractHashFromLocationHeader(array $headers) { $location = reset($headers); // Check if we got a Location header, otherwise something went wrong here. if (empty($location)) { return false; } $uri = new Uri($location); $parts = explode('/', $uri->getPath()); // Returning just the HASH part for "api.rokka.io/organization/sourceimages/{HASH}" $return = array_pop($parts); if (null === $return) { return false; } return $return; }
[ "protected", "function", "extractHashFromLocationHeader", "(", "array", "$", "headers", ")", "{", "$", "location", "=", "reset", "(", "$", "headers", ")", ";", "// Check if we got a Location header, otherwise something went wrong here.", "if", "(", "empty", "(", "$", "location", ")", ")", "{", "return", "false", ";", "}", "$", "uri", "=", "new", "Uri", "(", "$", "location", ")", ";", "$", "parts", "=", "explode", "(", "'/'", ",", "$", "uri", "->", "getPath", "(", ")", ")", ";", "// Returning just the HASH part for \"api.rokka.io/organization/sourceimages/{HASH}\"", "$", "return", "=", "array_pop", "(", "$", "parts", ")", ";", "if", "(", "null", "===", "$", "return", ")", "{", "return", "false", ";", "}", "return", "$", "return", ";", "}" ]
Helper function to extract from a Location header the image hash, only the first Location is used. @param array $headers The collection of Location headers @return string|false
[ "Helper", "function", "to", "extract", "from", "a", "Location", "header", "the", "image", "hash", "only", "the", "first", "Location", "is", "used", "." ]
ab037e0fd38b110211a0f7afb70f379e30756bdc
https://github.com/rokka-io/rokka-client-php/blob/ab037e0fd38b110211a0f7afb70f379e30756bdc/src/Image.php#L849-L868
train
rokka-io/rokka-client-php
src/Core/StackUri.php
StackUri.addOverridingOptions
public function addOverridingOptions($options) { $part = 0; // if stack already has operations we assume we don't want to add more, it's just overriding parameters if (\count($this->getStackOperations()) > 0) { ++$part; } foreach (explode('/', $options) as $option) { ++$part; foreach (explode('--', $option) as $stringOperation) { $stringOperationWithOptions = explode('-', $stringOperation); $stringOperationName = $stringOperationWithOptions[0]; if ('' == $stringOperationName) { continue; } $parsedOptions = self::parseOptions(\array_slice($stringOperationWithOptions, 1)); if ('options' === $stringOperationName || 'o' === $stringOperationName) { $this->setStackOptions(array_merge($this->getStackOptions(), $parsedOptions)); } elseif ('variables' === $stringOperationName || 'v' === $stringOperationName) { $this->setStackVariables(array_merge($this->getStackVariables(), $parsedOptions)); } else { // move options with [] as start and end to expressions $expressions = []; foreach ($parsedOptions as $_k => $_v) { if ('[' === substr($_v, 0, 1) && ']' === substr($_v, -1, 1)) { $expressions[$_k] = substr($_v, 1, -1); unset($parsedOptions[$_k]); continue; } // it may be urlencoded, try that and decode if ('%5B' === substr($_v, 0, 3) && '%5D' === substr($_v, -3, 3)) { $expressions[$_k] = urldecode(substr($_v, 3, -3)); unset($parsedOptions[$_k]); } // only add as stack operation everything before the first / } if (1 === $part) { $stackOperation = new StackOperation($stringOperationName, $parsedOptions, $expressions); $this->addStackOperation($stackOperation); } else { $stackOperations = $this->getStackOperationsByName($stringOperationName); foreach ($stackOperations as $stackOperation) { $stackOperation->options = array_merge($stackOperation->options, $parsedOptions, $expressions); } } } } } return $this; }
php
public function addOverridingOptions($options) { $part = 0; // if stack already has operations we assume we don't want to add more, it's just overriding parameters if (\count($this->getStackOperations()) > 0) { ++$part; } foreach (explode('/', $options) as $option) { ++$part; foreach (explode('--', $option) as $stringOperation) { $stringOperationWithOptions = explode('-', $stringOperation); $stringOperationName = $stringOperationWithOptions[0]; if ('' == $stringOperationName) { continue; } $parsedOptions = self::parseOptions(\array_slice($stringOperationWithOptions, 1)); if ('options' === $stringOperationName || 'o' === $stringOperationName) { $this->setStackOptions(array_merge($this->getStackOptions(), $parsedOptions)); } elseif ('variables' === $stringOperationName || 'v' === $stringOperationName) { $this->setStackVariables(array_merge($this->getStackVariables(), $parsedOptions)); } else { // move options with [] as start and end to expressions $expressions = []; foreach ($parsedOptions as $_k => $_v) { if ('[' === substr($_v, 0, 1) && ']' === substr($_v, -1, 1)) { $expressions[$_k] = substr($_v, 1, -1); unset($parsedOptions[$_k]); continue; } // it may be urlencoded, try that and decode if ('%5B' === substr($_v, 0, 3) && '%5D' === substr($_v, -3, 3)) { $expressions[$_k] = urldecode(substr($_v, 3, -3)); unset($parsedOptions[$_k]); } // only add as stack operation everything before the first / } if (1 === $part) { $stackOperation = new StackOperation($stringOperationName, $parsedOptions, $expressions); $this->addStackOperation($stackOperation); } else { $stackOperations = $this->getStackOperationsByName($stringOperationName); foreach ($stackOperations as $stackOperation) { $stackOperation->options = array_merge($stackOperation->options, $parsedOptions, $expressions); } } } } } return $this; }
[ "public", "function", "addOverridingOptions", "(", "$", "options", ")", "{", "$", "part", "=", "0", ";", "// if stack already has operations we assume we don't want to add more, it's just overriding parameters", "if", "(", "\\", "count", "(", "$", "this", "->", "getStackOperations", "(", ")", ")", ">", "0", ")", "{", "++", "$", "part", ";", "}", "foreach", "(", "explode", "(", "'/'", ",", "$", "options", ")", "as", "$", "option", ")", "{", "++", "$", "part", ";", "foreach", "(", "explode", "(", "'--'", ",", "$", "option", ")", "as", "$", "stringOperation", ")", "{", "$", "stringOperationWithOptions", "=", "explode", "(", "'-'", ",", "$", "stringOperation", ")", ";", "$", "stringOperationName", "=", "$", "stringOperationWithOptions", "[", "0", "]", ";", "if", "(", "''", "==", "$", "stringOperationName", ")", "{", "continue", ";", "}", "$", "parsedOptions", "=", "self", "::", "parseOptions", "(", "\\", "array_slice", "(", "$", "stringOperationWithOptions", ",", "1", ")", ")", ";", "if", "(", "'options'", "===", "$", "stringOperationName", "||", "'o'", "===", "$", "stringOperationName", ")", "{", "$", "this", "->", "setStackOptions", "(", "array_merge", "(", "$", "this", "->", "getStackOptions", "(", ")", ",", "$", "parsedOptions", ")", ")", ";", "}", "elseif", "(", "'variables'", "===", "$", "stringOperationName", "||", "'v'", "===", "$", "stringOperationName", ")", "{", "$", "this", "->", "setStackVariables", "(", "array_merge", "(", "$", "this", "->", "getStackVariables", "(", ")", ",", "$", "parsedOptions", ")", ")", ";", "}", "else", "{", "// move options with [] as start and end to expressions", "$", "expressions", "=", "[", "]", ";", "foreach", "(", "$", "parsedOptions", "as", "$", "_k", "=>", "$", "_v", ")", "{", "if", "(", "'['", "===", "substr", "(", "$", "_v", ",", "0", ",", "1", ")", "&&", "']'", "===", "substr", "(", "$", "_v", ",", "-", "1", ",", "1", ")", ")", "{", "$", "expressions", "[", "$", "_k", "]", "=", "substr", "(", "$", "_v", ",", "1", ",", "-", "1", ")", ";", "unset", "(", "$", "parsedOptions", "[", "$", "_k", "]", ")", ";", "continue", ";", "}", "// it may be urlencoded, try that and decode", "if", "(", "'%5B'", "===", "substr", "(", "$", "_v", ",", "0", ",", "3", ")", "&&", "'%5D'", "===", "substr", "(", "$", "_v", ",", "-", "3", ",", "3", ")", ")", "{", "$", "expressions", "[", "$", "_k", "]", "=", "urldecode", "(", "substr", "(", "$", "_v", ",", "3", ",", "-", "3", ")", ")", ";", "unset", "(", "$", "parsedOptions", "[", "$", "_k", "]", ")", ";", "}", "// only add as stack operation everything before the first /", "}", "if", "(", "1", "===", "$", "part", ")", "{", "$", "stackOperation", "=", "new", "StackOperation", "(", "$", "stringOperationName", ",", "$", "parsedOptions", ",", "$", "expressions", ")", ";", "$", "this", "->", "addStackOperation", "(", "$", "stackOperation", ")", ";", "}", "else", "{", "$", "stackOperations", "=", "$", "this", "->", "getStackOperationsByName", "(", "$", "stringOperationName", ")", ";", "foreach", "(", "$", "stackOperations", "as", "$", "stackOperation", ")", "{", "$", "stackOperation", "->", "options", "=", "array_merge", "(", "$", "stackOperation", "->", "options", ",", "$", "parsedOptions", ",", "$", "expressions", ")", ";", "}", "}", "}", "}", "}", "return", "$", "this", ";", "}" ]
For overwriting stack operation options or adding stack options. The format of the $options parameter is the same as you would use for overwriting ooptions via a render URL. Example: 'resize-width-200--options-dpr-2-autoformat-true' Using '/' instead of '--' is also valid, but if the object doesn't have operations defined already, the behaviour is different Examples: 'resize-width-200--crop-width-200-height-200' <- resizes and crops and image 'resize-width-200/crop-width-200-height-200' <- only resized the image, since the crop is an overwrite and the operation doesnt exist But if there's already stack operations for resize and crop defined in the object, both above examples do the same. @see https://rokka.io/documentation/references/render.html#overwriting-stack-operation-options @since 1.2.0 @param string $options The same format as overwriting stack operations options via url @return StackUri
[ "For", "overwriting", "stack", "operation", "options", "or", "adding", "stack", "options", "." ]
ab037e0fd38b110211a0f7afb70f379e30756bdc
https://github.com/rokka-io/rokka-client-php/blob/ab037e0fd38b110211a0f7afb70f379e30756bdc/src/Core/StackUri.php#L140-L191
train
tsugiproject/tsugi-php
src/Util/KVS.php
KVS.validate
public static function validate($data) { if ( ! is_array($data) ) return '$data must be an array'; $id = U::get($data, 'id'); if ( $id ) { if ( ! is_int($id) ) return "id must be an an integer"; } $uk1 = U::get($data, 'uk1'); if ( $uk1 ) { if ( ! is_string($uk1) ) return "uk1 must be a string"; if ( strlen($uk1) < 1 || strlen($uk1) > 150 ) return "uk1 must be no more than 150 characters"; } $sk1 = U::get($data, 'sk1'); if ( $sk1 ) { if ( ! is_string($sk1) ) return "sk1 must be a string"; if ( strlen($sk1) < 1 || strlen($sk1) > 75 ) return "sk1 must be no more than 75 characters"; } $tk1 = U::get($data, 'tk1'); if ( $tk1 ) { if ( ! is_string($tk1) ) return "tk1 must be a string"; if ( strlen($tk1) < 1 ) return "tk1 cannot be empty"; } $co1 = U::get($data, 'co1'); if ( $co1 ) { if ( ! is_string($co1) ) return "co1 must be a string"; if ( strlen($co1) < 1 || strlen($co1) > 150 ) return "co1 must be no more than 150 characters"; } $co2 = U::get($data, 'co2'); if ( $co2 ) { if ( ! is_string($co2) ) return "co2 must be a string"; if ( strlen($co2) < 1 || strlen($co2) > 150 ) return "co2 must be no more than 150 characters"; } return true; }
php
public static function validate($data) { if ( ! is_array($data) ) return '$data must be an array'; $id = U::get($data, 'id'); if ( $id ) { if ( ! is_int($id) ) return "id must be an an integer"; } $uk1 = U::get($data, 'uk1'); if ( $uk1 ) { if ( ! is_string($uk1) ) return "uk1 must be a string"; if ( strlen($uk1) < 1 || strlen($uk1) > 150 ) return "uk1 must be no more than 150 characters"; } $sk1 = U::get($data, 'sk1'); if ( $sk1 ) { if ( ! is_string($sk1) ) return "sk1 must be a string"; if ( strlen($sk1) < 1 || strlen($sk1) > 75 ) return "sk1 must be no more than 75 characters"; } $tk1 = U::get($data, 'tk1'); if ( $tk1 ) { if ( ! is_string($tk1) ) return "tk1 must be a string"; if ( strlen($tk1) < 1 ) return "tk1 cannot be empty"; } $co1 = U::get($data, 'co1'); if ( $co1 ) { if ( ! is_string($co1) ) return "co1 must be a string"; if ( strlen($co1) < 1 || strlen($co1) > 150 ) return "co1 must be no more than 150 characters"; } $co2 = U::get($data, 'co2'); if ( $co2 ) { if ( ! is_string($co2) ) return "co2 must be a string"; if ( strlen($co2) < 1 || strlen($co2) > 150 ) return "co2 must be no more than 150 characters"; } return true; }
[ "public", "static", "function", "validate", "(", "$", "data", ")", "{", "if", "(", "!", "is_array", "(", "$", "data", ")", ")", "return", "'$data must be an array'", ";", "$", "id", "=", "U", "::", "get", "(", "$", "data", ",", "'id'", ")", ";", "if", "(", "$", "id", ")", "{", "if", "(", "!", "is_int", "(", "$", "id", ")", ")", "return", "\"id must be an an integer\"", ";", "}", "$", "uk1", "=", "U", "::", "get", "(", "$", "data", ",", "'uk1'", ")", ";", "if", "(", "$", "uk1", ")", "{", "if", "(", "!", "is_string", "(", "$", "uk1", ")", ")", "return", "\"uk1 must be a string\"", ";", "if", "(", "strlen", "(", "$", "uk1", ")", "<", "1", "||", "strlen", "(", "$", "uk1", ")", ">", "150", ")", "return", "\"uk1 must be no more than 150 characters\"", ";", "}", "$", "sk1", "=", "U", "::", "get", "(", "$", "data", ",", "'sk1'", ")", ";", "if", "(", "$", "sk1", ")", "{", "if", "(", "!", "is_string", "(", "$", "sk1", ")", ")", "return", "\"sk1 must be a string\"", ";", "if", "(", "strlen", "(", "$", "sk1", ")", "<", "1", "||", "strlen", "(", "$", "sk1", ")", ">", "75", ")", "return", "\"sk1 must be no more than 75 characters\"", ";", "}", "$", "tk1", "=", "U", "::", "get", "(", "$", "data", ",", "'tk1'", ")", ";", "if", "(", "$", "tk1", ")", "{", "if", "(", "!", "is_string", "(", "$", "tk1", ")", ")", "return", "\"tk1 must be a string\"", ";", "if", "(", "strlen", "(", "$", "tk1", ")", "<", "1", ")", "return", "\"tk1 cannot be empty\"", ";", "}", "$", "co1", "=", "U", "::", "get", "(", "$", "data", ",", "'co1'", ")", ";", "if", "(", "$", "co1", ")", "{", "if", "(", "!", "is_string", "(", "$", "co1", ")", ")", "return", "\"co1 must be a string\"", ";", "if", "(", "strlen", "(", "$", "co1", ")", "<", "1", "||", "strlen", "(", "$", "co1", ")", ">", "150", ")", "return", "\"co1 must be no more than 150 characters\"", ";", "}", "$", "co2", "=", "U", "::", "get", "(", "$", "data", ",", "'co2'", ")", ";", "if", "(", "$", "co2", ")", "{", "if", "(", "!", "is_string", "(", "$", "co2", ")", ")", "return", "\"co2 must be a string\"", ";", "if", "(", "strlen", "(", "$", "co2", ")", "<", "1", "||", "strlen", "(", "$", "co2", ")", ">", "150", ")", "return", "\"co2 must be no more than 150 characters\"", ";", "}", "return", "true", ";", "}" ]
Validate a kvs record
[ "Validate", "a", "kvs", "record" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Util/KVS.php#L335-L367
train
bearsunday/BEAR.Resource
src/Meta.php
Meta.getOptions
private function getOptions(string $class) : Options { $ref = new \ReflectionClass($class); $allows = $this->getAllows($ref->getMethods()); $params = []; foreach ($allows as $method) { $params[] = $this->getParams($class, $method); } return new Options($allows, $params); }
php
private function getOptions(string $class) : Options { $ref = new \ReflectionClass($class); $allows = $this->getAllows($ref->getMethods()); $params = []; foreach ($allows as $method) { $params[] = $this->getParams($class, $method); } return new Options($allows, $params); }
[ "private", "function", "getOptions", "(", "string", "$", "class", ")", ":", "Options", "{", "$", "ref", "=", "new", "\\", "ReflectionClass", "(", "$", "class", ")", ";", "$", "allows", "=", "$", "this", "->", "getAllows", "(", "$", "ref", "->", "getMethods", "(", ")", ")", ";", "$", "params", "=", "[", "]", ";", "foreach", "(", "$", "allows", "as", "$", "method", ")", "{", "$", "params", "[", "]", "=", "$", "this", "->", "getParams", "(", "$", "class", ",", "$", "method", ")", ";", "}", "return", "new", "Options", "(", "$", "allows", ",", "$", "params", ")", ";", "}" ]
Return available resource request method
[ "Return", "available", "resource", "request", "method" ]
c3b396a6c725ecce9345565b1e4d563d95e11bec
https://github.com/bearsunday/BEAR.Resource/blob/c3b396a6c725ecce9345565b1e4d563d95e11bec/src/Meta.php#L49-L59
train
MetaModels/contao-frontend-editing
src/EventListener/RenderItemListListener.php
RenderItemListListener.handleForItemRendering
public function handleForItemRendering(ParseItemEvent $event): void { $settings = $event->getRenderSettings(); if (!$settings->get(self::FRONTEND_EDITING_ENABLED_FLAG)) { return; } $parsed = $event->getResult(); $item = $event->getItem(); $tableName = $item->getMetaModel()->getTableName(); $definition = $this->frontendEditor->createDcGeneral($tableName)->getDataDefinition(); $basicDefinition = $definition->getBasicDefinition(); $editingPage = $settings->get(self::FRONTEND_EDITING_PAGE); $modelId = ModelId::fromValues($tableName, $item->get('id'))->getSerialized(); // Add edit action if ($basicDefinition->isEditable()) { $parsed['actions']['edit'] = [ 'label' => $this->translateLabel('metamodel_edit_item', $definition->getName()), 'href' => $this->generateEditUrl($editingPage, $modelId), 'class' => 'edit', ]; } // Add copy action if ($basicDefinition->isCreatable()) { $parsed['actions']['copy'] = [ 'label' => $this->translateLabel('metamodel_copy_item', $definition->getName()), 'href' => $this->generateCopyUrl($editingPage, $modelId), 'class' => 'copy', ]; } // Add create variant action if (false === $item->isVariant() && $basicDefinition->isCreatable() && $item->getMetaModel()->hasVariants()) { $parsed['actions']['createvariant'] = [ 'label' => $this->translateLabel('metamodel_create_variant', $definition->getName()), 'href' => $this->generateCreateVariantUrl($editingPage, $modelId), 'class' => 'createvariant', ]; } // Add delete action if ($basicDefinition->isDeletable()) { $parsed['actions']['delete'] = [ 'label' => $this->translateLabel('metamodel_delete_item', $definition->getName()), 'href' => $this->generateDeleteUrl($editingPage, $modelId), 'attribute' => sprintf( 'onclick="if (!confirm(\'%s\')) return false;"', $this->translator->trans('MSC.deleteConfirm', [$item->get('id')], 'contao_default') ), 'class' => 'delete', ]; } $event->setResult($parsed); }
php
public function handleForItemRendering(ParseItemEvent $event): void { $settings = $event->getRenderSettings(); if (!$settings->get(self::FRONTEND_EDITING_ENABLED_FLAG)) { return; } $parsed = $event->getResult(); $item = $event->getItem(); $tableName = $item->getMetaModel()->getTableName(); $definition = $this->frontendEditor->createDcGeneral($tableName)->getDataDefinition(); $basicDefinition = $definition->getBasicDefinition(); $editingPage = $settings->get(self::FRONTEND_EDITING_PAGE); $modelId = ModelId::fromValues($tableName, $item->get('id'))->getSerialized(); // Add edit action if ($basicDefinition->isEditable()) { $parsed['actions']['edit'] = [ 'label' => $this->translateLabel('metamodel_edit_item', $definition->getName()), 'href' => $this->generateEditUrl($editingPage, $modelId), 'class' => 'edit', ]; } // Add copy action if ($basicDefinition->isCreatable()) { $parsed['actions']['copy'] = [ 'label' => $this->translateLabel('metamodel_copy_item', $definition->getName()), 'href' => $this->generateCopyUrl($editingPage, $modelId), 'class' => 'copy', ]; } // Add create variant action if (false === $item->isVariant() && $basicDefinition->isCreatable() && $item->getMetaModel()->hasVariants()) { $parsed['actions']['createvariant'] = [ 'label' => $this->translateLabel('metamodel_create_variant', $definition->getName()), 'href' => $this->generateCreateVariantUrl($editingPage, $modelId), 'class' => 'createvariant', ]; } // Add delete action if ($basicDefinition->isDeletable()) { $parsed['actions']['delete'] = [ 'label' => $this->translateLabel('metamodel_delete_item', $definition->getName()), 'href' => $this->generateDeleteUrl($editingPage, $modelId), 'attribute' => sprintf( 'onclick="if (!confirm(\'%s\')) return false;"', $this->translator->trans('MSC.deleteConfirm', [$item->get('id')], 'contao_default') ), 'class' => 'delete', ]; } $event->setResult($parsed); }
[ "public", "function", "handleForItemRendering", "(", "ParseItemEvent", "$", "event", ")", ":", "void", "{", "$", "settings", "=", "$", "event", "->", "getRenderSettings", "(", ")", ";", "if", "(", "!", "$", "settings", "->", "get", "(", "self", "::", "FRONTEND_EDITING_ENABLED_FLAG", ")", ")", "{", "return", ";", "}", "$", "parsed", "=", "$", "event", "->", "getResult", "(", ")", ";", "$", "item", "=", "$", "event", "->", "getItem", "(", ")", ";", "$", "tableName", "=", "$", "item", "->", "getMetaModel", "(", ")", "->", "getTableName", "(", ")", ";", "$", "definition", "=", "$", "this", "->", "frontendEditor", "->", "createDcGeneral", "(", "$", "tableName", ")", "->", "getDataDefinition", "(", ")", ";", "$", "basicDefinition", "=", "$", "definition", "->", "getBasicDefinition", "(", ")", ";", "$", "editingPage", "=", "$", "settings", "->", "get", "(", "self", "::", "FRONTEND_EDITING_PAGE", ")", ";", "$", "modelId", "=", "ModelId", "::", "fromValues", "(", "$", "tableName", ",", "$", "item", "->", "get", "(", "'id'", ")", ")", "->", "getSerialized", "(", ")", ";", "// Add edit action", "if", "(", "$", "basicDefinition", "->", "isEditable", "(", ")", ")", "{", "$", "parsed", "[", "'actions'", "]", "[", "'edit'", "]", "=", "[", "'label'", "=>", "$", "this", "->", "translateLabel", "(", "'metamodel_edit_item'", ",", "$", "definition", "->", "getName", "(", ")", ")", ",", "'href'", "=>", "$", "this", "->", "generateEditUrl", "(", "$", "editingPage", ",", "$", "modelId", ")", ",", "'class'", "=>", "'edit'", ",", "]", ";", "}", "// Add copy action", "if", "(", "$", "basicDefinition", "->", "isCreatable", "(", ")", ")", "{", "$", "parsed", "[", "'actions'", "]", "[", "'copy'", "]", "=", "[", "'label'", "=>", "$", "this", "->", "translateLabel", "(", "'metamodel_copy_item'", ",", "$", "definition", "->", "getName", "(", ")", ")", ",", "'href'", "=>", "$", "this", "->", "generateCopyUrl", "(", "$", "editingPage", ",", "$", "modelId", ")", ",", "'class'", "=>", "'copy'", ",", "]", ";", "}", "// Add create variant action", "if", "(", "false", "===", "$", "item", "->", "isVariant", "(", ")", "&&", "$", "basicDefinition", "->", "isCreatable", "(", ")", "&&", "$", "item", "->", "getMetaModel", "(", ")", "->", "hasVariants", "(", ")", ")", "{", "$", "parsed", "[", "'actions'", "]", "[", "'createvariant'", "]", "=", "[", "'label'", "=>", "$", "this", "->", "translateLabel", "(", "'metamodel_create_variant'", ",", "$", "definition", "->", "getName", "(", ")", ")", ",", "'href'", "=>", "$", "this", "->", "generateCreateVariantUrl", "(", "$", "editingPage", ",", "$", "modelId", ")", ",", "'class'", "=>", "'createvariant'", ",", "]", ";", "}", "// Add delete action", "if", "(", "$", "basicDefinition", "->", "isDeletable", "(", ")", ")", "{", "$", "parsed", "[", "'actions'", "]", "[", "'delete'", "]", "=", "[", "'label'", "=>", "$", "this", "->", "translateLabel", "(", "'metamodel_delete_item'", ",", "$", "definition", "->", "getName", "(", ")", ")", ",", "'href'", "=>", "$", "this", "->", "generateDeleteUrl", "(", "$", "editingPage", ",", "$", "modelId", ")", ",", "'attribute'", "=>", "sprintf", "(", "'onclick=\"if (!confirm(\\'%s\\')) return false;\"'", ",", "$", "this", "->", "translator", "->", "trans", "(", "'MSC.deleteConfirm'", ",", "[", "$", "item", "->", "get", "(", "'id'", ")", "]", ",", "'contao_default'", ")", ")", ",", "'class'", "=>", "'delete'", ",", "]", ";", "}", "$", "event", "->", "setResult", "(", "$", "parsed", ")", ";", "}" ]
Handle the url injection for item rendering. @param ParseItemEvent $event The event to process. @return void
[ "Handle", "the", "url", "injection", "for", "item", "rendering", "." ]
f11c841ef2e6d27f313b4a31db0c5fe8ac38c692
https://github.com/MetaModels/contao-frontend-editing/blob/f11c841ef2e6d27f313b4a31db0c5fe8ac38c692/src/EventListener/RenderItemListListener.php#L107-L163
train
MetaModels/contao-frontend-editing
src/EventListener/RenderItemListListener.php
RenderItemListListener.generateAddUrl
private function generateAddUrl(array $page): string { $event = new GenerateFrontendUrlEvent($page, null, $page['language']); $this->dispatcher->dispatch(ContaoEvents::CONTROLLER_GENERATE_FRONTEND_URL, $event); $url = UrlBuilder::fromUrl($event->getUrl() . '?') ->setQueryParameter('act', 'create'); return $url->getUrl(); }
php
private function generateAddUrl(array $page): string { $event = new GenerateFrontendUrlEvent($page, null, $page['language']); $this->dispatcher->dispatch(ContaoEvents::CONTROLLER_GENERATE_FRONTEND_URL, $event); $url = UrlBuilder::fromUrl($event->getUrl() . '?') ->setQueryParameter('act', 'create'); return $url->getUrl(); }
[ "private", "function", "generateAddUrl", "(", "array", "$", "page", ")", ":", "string", "{", "$", "event", "=", "new", "GenerateFrontendUrlEvent", "(", "$", "page", ",", "null", ",", "$", "page", "[", "'language'", "]", ")", ";", "$", "this", "->", "dispatcher", "->", "dispatch", "(", "ContaoEvents", "::", "CONTROLLER_GENERATE_FRONTEND_URL", ",", "$", "event", ")", ";", "$", "url", "=", "UrlBuilder", "::", "fromUrl", "(", "$", "event", "->", "getUrl", "(", ")", ".", "'?'", ")", "->", "setQueryParameter", "(", "'act'", ",", "'create'", ")", ";", "return", "$", "url", "->", "getUrl", "(", ")", ";", "}" ]
Generate the url to add an item. @param array $page The page details. @return string
[ "Generate", "the", "url", "to", "add", "an", "item", "." ]
f11c841ef2e6d27f313b4a31db0c5fe8ac38c692
https://github.com/MetaModels/contao-frontend-editing/blob/f11c841ef2e6d27f313b4a31db0c5fe8ac38c692/src/EventListener/RenderItemListListener.php#L215-L225
train
MetaModels/contao-frontend-editing
src/EventListener/RenderItemListListener.php
RenderItemListListener.getPageDetails
private function getPageDetails($pageId): ?array { if (empty($pageId)) { return null; } $event = new GetPageDetailsEvent($pageId); $this->dispatcher->dispatch(ContaoEvents::CONTROLLER_GET_PAGE_DETAILS, $event); return $event->getPageDetails(); }
php
private function getPageDetails($pageId): ?array { if (empty($pageId)) { return null; } $event = new GetPageDetailsEvent($pageId); $this->dispatcher->dispatch(ContaoEvents::CONTROLLER_GET_PAGE_DETAILS, $event); return $event->getPageDetails(); }
[ "private", "function", "getPageDetails", "(", "$", "pageId", ")", ":", "?", "array", "{", "if", "(", "empty", "(", "$", "pageId", ")", ")", "{", "return", "null", ";", "}", "$", "event", "=", "new", "GetPageDetailsEvent", "(", "$", "pageId", ")", ";", "$", "this", "->", "dispatcher", "->", "dispatch", "(", "ContaoEvents", "::", "CONTROLLER_GET_PAGE_DETAILS", ",", "$", "event", ")", ";", "return", "$", "event", "->", "getPageDetails", "(", ")", ";", "}" ]
Retrieve the details for the page with the given id. @param string $pageId The id of the page to retrieve the details for. @return array
[ "Retrieve", "the", "details", "for", "the", "page", "with", "the", "given", "id", "." ]
f11c841ef2e6d27f313b4a31db0c5fe8ac38c692
https://github.com/MetaModels/contao-frontend-editing/blob/f11c841ef2e6d27f313b4a31db0c5fe8ac38c692/src/EventListener/RenderItemListListener.php#L322-L331
train
MetaModels/contao-frontend-editing
src/EventListener/RenderItemListListener.php
RenderItemListListener.translateLabel
private function translateLabel($transString, $definitionName, array $parameters = []): string { $translator = $this->translator; $label = $translator->trans($definitionName . '.' . $transString, $parameters, 'contao_' . $definitionName); if ($label !== $definitionName . '.' . $transString) { return $label; } $label = $translator->trans('MSC.' . $transString, $parameters, 'contao_default'); if ($label !== $transString) { return $label; } // Fallback, just return the key as is it. return $transString; }
php
private function translateLabel($transString, $definitionName, array $parameters = []): string { $translator = $this->translator; $label = $translator->trans($definitionName . '.' . $transString, $parameters, 'contao_' . $definitionName); if ($label !== $definitionName . '.' . $transString) { return $label; } $label = $translator->trans('MSC.' . $transString, $parameters, 'contao_default'); if ($label !== $transString) { return $label; } // Fallback, just return the key as is it. return $transString; }
[ "private", "function", "translateLabel", "(", "$", "transString", ",", "$", "definitionName", ",", "array", "$", "parameters", "=", "[", "]", ")", ":", "string", "{", "$", "translator", "=", "$", "this", "->", "translator", ";", "$", "label", "=", "$", "translator", "->", "trans", "(", "$", "definitionName", ".", "'.'", ".", "$", "transString", ",", "$", "parameters", ",", "'contao_'", ".", "$", "definitionName", ")", ";", "if", "(", "$", "label", "!==", "$", "definitionName", ".", "'.'", ".", "$", "transString", ")", "{", "return", "$", "label", ";", "}", "$", "label", "=", "$", "translator", "->", "trans", "(", "'MSC.'", ".", "$", "transString", ",", "$", "parameters", ",", "'contao_default'", ")", ";", "if", "(", "$", "label", "!==", "$", "transString", ")", "{", "return", "$", "label", ";", "}", "// Fallback, just return the key as is it.", "return", "$", "transString", ";", "}" ]
Get a translated label from the translator. The fallback is as follows: 1. Try to translate via the data definition name as translation section. 2. Try to translate with the prefix 'MSC.'. 3. Return the input value as nothing worked out. @param string $transString The non translated label for the button. @param string $definitionName The data definition of the current item. @param array $parameters The parameters to pass to the translator. @return string
[ "Get", "a", "translated", "label", "from", "the", "translator", "." ]
f11c841ef2e6d27f313b4a31db0c5fe8ac38c692
https://github.com/MetaModels/contao-frontend-editing/blob/f11c841ef2e6d27f313b4a31db0c5fe8ac38c692/src/EventListener/RenderItemListListener.php#L349-L365
train
tsugiproject/tsugi-php
src/Core/SettingsTrait.php
SettingsTrait.settingsGetAll
public function settingsGetAll() { global $CFG; $name = $this->ENTITY_NAME; $retval = $this->ltiParameter($name."_settings", false); // Null means in the session - false means not in the session if ( $retval === null || ( is_string($retval) && strlen($retval) < 1 ) ) { $retval = array(); } else if ( strlen($retval) > 0 ) { try { $retval = json_decode($retval, true); } catch(Exception $e) { $retval = array(); } } // echo("Session $name: "); var_dump($retval); if ( is_array($retval) ) return $retval; $row = $this->launch->pdox->rowDie("SELECT settings FROM {$CFG->dbprefix}{$this->TABLE_NAME} WHERE {$name}_id = :ID", array(":ID" => $this->id)); if ( $row === false ) return array(); $json = $row['settings']; if ( $json === null ) return array(); try { $retval = json_decode($json, true); } catch(Exception $e) { $retval = array(); } // Put in session for quicker retrieval $this->ltiParameterUpdate($name."_settings", json_encode($retval)); // echo("<hr>From DB\n");var_dump($retval); return $retval; }
php
public function settingsGetAll() { global $CFG; $name = $this->ENTITY_NAME; $retval = $this->ltiParameter($name."_settings", false); // Null means in the session - false means not in the session if ( $retval === null || ( is_string($retval) && strlen($retval) < 1 ) ) { $retval = array(); } else if ( strlen($retval) > 0 ) { try { $retval = json_decode($retval, true); } catch(Exception $e) { $retval = array(); } } // echo("Session $name: "); var_dump($retval); if ( is_array($retval) ) return $retval; $row = $this->launch->pdox->rowDie("SELECT settings FROM {$CFG->dbprefix}{$this->TABLE_NAME} WHERE {$name}_id = :ID", array(":ID" => $this->id)); if ( $row === false ) return array(); $json = $row['settings']; if ( $json === null ) return array(); try { $retval = json_decode($json, true); } catch(Exception $e) { $retval = array(); } // Put in session for quicker retrieval $this->ltiParameterUpdate($name."_settings", json_encode($retval)); // echo("<hr>From DB\n");var_dump($retval); return $retval; }
[ "public", "function", "settingsGetAll", "(", ")", "{", "global", "$", "CFG", ";", "$", "name", "=", "$", "this", "->", "ENTITY_NAME", ";", "$", "retval", "=", "$", "this", "->", "ltiParameter", "(", "$", "name", ".", "\"_settings\"", ",", "false", ")", ";", "// Null means in the session - false means not in the session", "if", "(", "$", "retval", "===", "null", "||", "(", "is_string", "(", "$", "retval", ")", "&&", "strlen", "(", "$", "retval", ")", "<", "1", ")", ")", "{", "$", "retval", "=", "array", "(", ")", ";", "}", "else", "if", "(", "strlen", "(", "$", "retval", ")", ">", "0", ")", "{", "try", "{", "$", "retval", "=", "json_decode", "(", "$", "retval", ",", "true", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "$", "retval", "=", "array", "(", ")", ";", "}", "}", "// echo(\"Session $name: \"); var_dump($retval);", "if", "(", "is_array", "(", "$", "retval", ")", ")", "return", "$", "retval", ";", "$", "row", "=", "$", "this", "->", "launch", "->", "pdox", "->", "rowDie", "(", "\"SELECT settings FROM {$CFG->dbprefix}{$this->TABLE_NAME}\n WHERE {$name}_id = :ID\"", ",", "array", "(", "\":ID\"", "=>", "$", "this", "->", "id", ")", ")", ";", "if", "(", "$", "row", "===", "false", ")", "return", "array", "(", ")", ";", "$", "json", "=", "$", "row", "[", "'settings'", "]", ";", "if", "(", "$", "json", "===", "null", ")", "return", "array", "(", ")", ";", "try", "{", "$", "retval", "=", "json_decode", "(", "$", "json", ",", "true", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "$", "retval", "=", "array", "(", ")", ";", "}", "// Put in session for quicker retrieval", "$", "this", "->", "ltiParameterUpdate", "(", "$", "name", ".", "\"_settings\"", ",", "json_encode", "(", "$", "retval", ")", ")", ";", "// echo(\"<hr>From DB\\n\");var_dump($retval);", "return", "$", "retval", ";", "}" ]
Retrieve an array of all of the settings If there are no settings, return an empty array.
[ "Retrieve", "an", "array", "of", "all", "of", "the", "settings" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/SettingsTrait.php#L23-L59
train
tsugiproject/tsugi-php
src/Core/SettingsTrait.php
SettingsTrait.settingsGet
public function settingsGet($key, $default=false) { $allSettings = $this->settingsGetAll(); if ( array_key_exists ($key, $allSettings ) ) { return $allSettings[$key]; } else { return $default; } }
php
public function settingsGet($key, $default=false) { $allSettings = $this->settingsGetAll(); if ( array_key_exists ($key, $allSettings ) ) { return $allSettings[$key]; } else { return $default; } }
[ "public", "function", "settingsGet", "(", "$", "key", ",", "$", "default", "=", "false", ")", "{", "$", "allSettings", "=", "$", "this", "->", "settingsGetAll", "(", ")", ";", "if", "(", "array_key_exists", "(", "$", "key", ",", "$", "allSettings", ")", ")", "{", "return", "$", "allSettings", "[", "$", "key", "]", ";", "}", "else", "{", "return", "$", "default", ";", "}", "}" ]
Retrieve a particular key from the settings. Returns the value found in settings or false if the key was not found. @param $key - The key to get from the settings. @param $default - What to return if the key is not present
[ "Retrieve", "a", "particular", "key", "from", "the", "settings", "." ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/SettingsTrait.php#L69-L77
train
tsugiproject/tsugi-php
src/Core/SettingsTrait.php
SettingsTrait.settingsSet
public function settingsSet($key, $value) { $allSettings = $this->settingsGetAll(); $allSettings[$key] = $value; $this->settingsSetAll($allSettings); }
php
public function settingsSet($key, $value) { $allSettings = $this->settingsGetAll(); $allSettings[$key] = $value; $this->settingsSetAll($allSettings); }
[ "public", "function", "settingsSet", "(", "$", "key", ",", "$", "value", ")", "{", "$", "allSettings", "=", "$", "this", "->", "settingsGetAll", "(", ")", ";", "$", "allSettings", "[", "$", "key", "]", "=", "$", "value", ";", "$", "this", "->", "settingsSetAll", "(", "$", "allSettings", ")", ";", "}" ]
Update a single key in settings
[ "Update", "a", "single", "key", "in", "settings" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/SettingsTrait.php#L82-L87
train
tsugiproject/tsugi-php
src/Core/SettingsTrait.php
SettingsTrait.settingsUpdate
public function settingsUpdate($keyvals) { $allSettings = $this->settingsGetAll(); $different = false; foreach ( $keyvals as $k => $v ) { if ( array_key_exists ($k, $allSettings ) ) { if ( $v != $allSettings[$k] ) { $different = true; break; } } else { $different = true; break; } } if ( ! $different ) return; $newSettings = array_merge($allSettings, $keyvals); return $this->settingsSetAll($newSettings); }
php
public function settingsUpdate($keyvals) { $allSettings = $this->settingsGetAll(); $different = false; foreach ( $keyvals as $k => $v ) { if ( array_key_exists ($k, $allSettings ) ) { if ( $v != $allSettings[$k] ) { $different = true; break; } } else { $different = true; break; } } if ( ! $different ) return; $newSettings = array_merge($allSettings, $keyvals); return $this->settingsSetAll($newSettings); }
[ "public", "function", "settingsUpdate", "(", "$", "keyvals", ")", "{", "$", "allSettings", "=", "$", "this", "->", "settingsGetAll", "(", ")", ";", "$", "different", "=", "false", ";", "foreach", "(", "$", "keyvals", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "array_key_exists", "(", "$", "k", ",", "$", "allSettings", ")", ")", "{", "if", "(", "$", "v", "!=", "$", "allSettings", "[", "$", "k", "]", ")", "{", "$", "different", "=", "true", ";", "break", ";", "}", "}", "else", "{", "$", "different", "=", "true", ";", "break", ";", "}", "}", "if", "(", "!", "$", "different", ")", "return", ";", "$", "newSettings", "=", "array_merge", "(", "$", "allSettings", ",", "$", "keyvals", ")", ";", "return", "$", "this", "->", "settingsSetAll", "(", "$", "newSettings", ")", ";", "}" ]
Set or update a number of keys to new values in link settings. @params $keyvals An array of key value pairs that are to be placed in the settings.
[ "Set", "or", "update", "a", "number", "of", "keys", "to", "new", "values", "in", "link", "settings", "." ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/SettingsTrait.php#L95-L113
train
tsugiproject/tsugi-php
src/Core/I18N.php
I18N.__
public static function __($message, $textdomain=false) { global $CFG, $PDOX, $TSUGI_LOCALE, $TSUGI_LOCALE_RELOAD, $TSUGI_TRANSLATE; // If we have been asked to do some translation if ( isset($CFG->checktranslation) && $CFG->checktranslation && isset($PDOX) ) { $string_sha = U::lti_sha256($message); $domain = $textdomain; if ( ! $domain ) $domain = textdomain(NULL); if ( $domain ) { $stmt = $PDOX->queryReturnError("INSERT INTO {$CFG->dbprefix}tsugi_string (domain, string_text, string_sha256) VALUES ( :DOM, :TEXT, :SHA) ON DUPLICATE KEY UPDATE updated_at = NOW()", array( ':DOM' => $domain, ':TEXT' => $message, ':SHA' => $string_sha ) ); } } // Setup Text domain late... if ( $TSUGI_LOCALE_RELOAD ) { self::setupTextDomain(); } if ( isset($TSUGI_TRANSLATE) && $TSUGI_TRANSLATE ) { $retval = $TSUGI_TRANSLATE->trans($message); // error_log("DOM=$TSUGI_LOCALE msg=$message trans=$retval"); return $retval; } if ( ! function_exists('gettext')) return $message; if ( $textdomain === false ) { return gettext($message); } else { return dgettext($textdomain, $message); } }
php
public static function __($message, $textdomain=false) { global $CFG, $PDOX, $TSUGI_LOCALE, $TSUGI_LOCALE_RELOAD, $TSUGI_TRANSLATE; // If we have been asked to do some translation if ( isset($CFG->checktranslation) && $CFG->checktranslation && isset($PDOX) ) { $string_sha = U::lti_sha256($message); $domain = $textdomain; if ( ! $domain ) $domain = textdomain(NULL); if ( $domain ) { $stmt = $PDOX->queryReturnError("INSERT INTO {$CFG->dbprefix}tsugi_string (domain, string_text, string_sha256) VALUES ( :DOM, :TEXT, :SHA) ON DUPLICATE KEY UPDATE updated_at = NOW()", array( ':DOM' => $domain, ':TEXT' => $message, ':SHA' => $string_sha ) ); } } // Setup Text domain late... if ( $TSUGI_LOCALE_RELOAD ) { self::setupTextDomain(); } if ( isset($TSUGI_TRANSLATE) && $TSUGI_TRANSLATE ) { $retval = $TSUGI_TRANSLATE->trans($message); // error_log("DOM=$TSUGI_LOCALE msg=$message trans=$retval"); return $retval; } if ( ! function_exists('gettext')) return $message; if ( $textdomain === false ) { return gettext($message); } else { return dgettext($textdomain, $message); } }
[ "public", "static", "function", "__", "(", "$", "message", ",", "$", "textdomain", "=", "false", ")", "{", "global", "$", "CFG", ",", "$", "PDOX", ",", "$", "TSUGI_LOCALE", ",", "$", "TSUGI_LOCALE_RELOAD", ",", "$", "TSUGI_TRANSLATE", ";", "// If we have been asked to do some translation", "if", "(", "isset", "(", "$", "CFG", "->", "checktranslation", ")", "&&", "$", "CFG", "->", "checktranslation", "&&", "isset", "(", "$", "PDOX", ")", ")", "{", "$", "string_sha", "=", "U", "::", "lti_sha256", "(", "$", "message", ")", ";", "$", "domain", "=", "$", "textdomain", ";", "if", "(", "!", "$", "domain", ")", "$", "domain", "=", "textdomain", "(", "NULL", ")", ";", "if", "(", "$", "domain", ")", "{", "$", "stmt", "=", "$", "PDOX", "->", "queryReturnError", "(", "\"INSERT INTO {$CFG->dbprefix}tsugi_string\n (domain, string_text, string_sha256) VALUES ( :DOM, :TEXT, :SHA)\n ON DUPLICATE KEY UPDATE updated_at = NOW()\"", ",", "array", "(", "':DOM'", "=>", "$", "domain", ",", "':TEXT'", "=>", "$", "message", ",", "':SHA'", "=>", "$", "string_sha", ")", ")", ";", "}", "}", "// Setup Text domain late...", "if", "(", "$", "TSUGI_LOCALE_RELOAD", ")", "{", "self", "::", "setupTextDomain", "(", ")", ";", "}", "if", "(", "isset", "(", "$", "TSUGI_TRANSLATE", ")", "&&", "$", "TSUGI_TRANSLATE", ")", "{", "$", "retval", "=", "$", "TSUGI_TRANSLATE", "->", "trans", "(", "$", "message", ")", ";", "// error_log(\"DOM=$TSUGI_LOCALE msg=$message trans=$retval\");", "return", "$", "retval", ";", "}", "if", "(", "!", "function_exists", "(", "'gettext'", ")", ")", "return", "$", "message", ";", "if", "(", "$", "textdomain", "===", "false", ")", "{", "return", "gettext", "(", "$", "message", ")", ";", "}", "else", "{", "return", "dgettext", "(", "$", "textdomain", ",", "$", "message", ")", ";", "}", "}" ]
Translate a messege from the master domain Pattern borrowed from WordPress
[ "Translate", "a", "messege", "from", "the", "master", "domain" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/I18N.php#L43-L82
train
tsugiproject/tsugi-php
src/Core/I18N.php
I18N.setLocale
public static function setLocale($locale=null) { global $CFG, $TSUGI_LOCALE, $TSUGI_LOCALE_RELOAD; // No internationalization support if ( isset($CFG->legacytranslation) ) { if ( ! function_exists('bindtextdomain') ) return; if ( ! function_exists('textdomain') ) return; } if ( isset($CFG->legacytranslation) && $locale && strpos($locale, 'UTF-8') === false ) $locale = $locale . '.UTF-8'; if ( $locale === null && isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ) { if ( class_exists('\Locale') ) { try { // Symfony may implement a stub for this function that throws an exception $locale = \Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']); } catch (exception $e) { } } if ($locale === null) { // Crude fallback if we can't use Locale::acceptFromHttp $pieces = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']); $locale = $pieces[0]; } } if ( $locale === null && isset($CFG->fallbacklocale) && $CFG->fallbacklocale ) { $locale = $CFG->fallbacklocale; } if ( $locale === null ) return; $locale = str_replace('-','_',$locale); if ( isset($CFG->legacytranslation) ) { putenv('LC_ALL='.$locale); setlocale(LC_ALL, $locale); } // error_log("setLocale=$locale"); if ( $TSUGI_LOCALE != $locale ) $TSUGI_LOCALE_RELOAD = true; $TSUGI_LOCALE = $locale; }
php
public static function setLocale($locale=null) { global $CFG, $TSUGI_LOCALE, $TSUGI_LOCALE_RELOAD; // No internationalization support if ( isset($CFG->legacytranslation) ) { if ( ! function_exists('bindtextdomain') ) return; if ( ! function_exists('textdomain') ) return; } if ( isset($CFG->legacytranslation) && $locale && strpos($locale, 'UTF-8') === false ) $locale = $locale . '.UTF-8'; if ( $locale === null && isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ) { if ( class_exists('\Locale') ) { try { // Symfony may implement a stub for this function that throws an exception $locale = \Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']); } catch (exception $e) { } } if ($locale === null) { // Crude fallback if we can't use Locale::acceptFromHttp $pieces = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']); $locale = $pieces[0]; } } if ( $locale === null && isset($CFG->fallbacklocale) && $CFG->fallbacklocale ) { $locale = $CFG->fallbacklocale; } if ( $locale === null ) return; $locale = str_replace('-','_',$locale); if ( isset($CFG->legacytranslation) ) { putenv('LC_ALL='.$locale); setlocale(LC_ALL, $locale); } // error_log("setLocale=$locale"); if ( $TSUGI_LOCALE != $locale ) $TSUGI_LOCALE_RELOAD = true; $TSUGI_LOCALE = $locale; }
[ "public", "static", "function", "setLocale", "(", "$", "locale", "=", "null", ")", "{", "global", "$", "CFG", ",", "$", "TSUGI_LOCALE", ",", "$", "TSUGI_LOCALE_RELOAD", ";", "// No internationalization support", "if", "(", "isset", "(", "$", "CFG", "->", "legacytranslation", ")", ")", "{", "if", "(", "!", "function_exists", "(", "'bindtextdomain'", ")", ")", "return", ";", "if", "(", "!", "function_exists", "(", "'textdomain'", ")", ")", "return", ";", "}", "if", "(", "isset", "(", "$", "CFG", "->", "legacytranslation", ")", "&&", "$", "locale", "&&", "strpos", "(", "$", "locale", ",", "'UTF-8'", ")", "===", "false", ")", "$", "locale", "=", "$", "locale", ".", "'.UTF-8'", ";", "if", "(", "$", "locale", "===", "null", "&&", "isset", "(", "$", "_SERVER", "[", "'HTTP_ACCEPT_LANGUAGE'", "]", ")", ")", "{", "if", "(", "class_exists", "(", "'\\Locale'", ")", ")", "{", "try", "{", "// Symfony may implement a stub for this function that throws an exception", "$", "locale", "=", "\\", "Locale", "::", "acceptFromHttp", "(", "$", "_SERVER", "[", "'HTTP_ACCEPT_LANGUAGE'", "]", ")", ";", "}", "catch", "(", "exception", "$", "e", ")", "{", "}", "}", "if", "(", "$", "locale", "===", "null", ")", "{", "// Crude fallback if we can't use Locale::acceptFromHttp", "$", "pieces", "=", "explode", "(", "','", ",", "$", "_SERVER", "[", "'HTTP_ACCEPT_LANGUAGE'", "]", ")", ";", "$", "locale", "=", "$", "pieces", "[", "0", "]", ";", "}", "}", "if", "(", "$", "locale", "===", "null", "&&", "isset", "(", "$", "CFG", "->", "fallbacklocale", ")", "&&", "$", "CFG", "->", "fallbacklocale", ")", "{", "$", "locale", "=", "$", "CFG", "->", "fallbacklocale", ";", "}", "if", "(", "$", "locale", "===", "null", ")", "return", ";", "$", "locale", "=", "str_replace", "(", "'-'", ",", "'_'", ",", "$", "locale", ")", ";", "if", "(", "isset", "(", "$", "CFG", "->", "legacytranslation", ")", ")", "{", "putenv", "(", "'LC_ALL='", ".", "$", "locale", ")", ";", "setlocale", "(", "LC_ALL", ",", "$", "locale", ")", ";", "}", "// error_log(\"setLocale=$locale\");", "if", "(", "$", "TSUGI_LOCALE", "!=", "$", "locale", ")", "$", "TSUGI_LOCALE_RELOAD", "=", "true", ";", "$", "TSUGI_LOCALE", "=", "$", "locale", ";", "}" ]
Set the LOCAL for the current user
[ "Set", "the", "LOCAL", "for", "the", "current", "user" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/I18N.php#L87-L128
train
tsugiproject/tsugi-php
src/Core/I18N.php
I18N.setupTextDomain
public static function setupTextDomain() { global $CFG, $TSUGI_LOCALE, $TSUGI_LOCALE_RELOAD, $TSUGI_TRANSLATE; $domain = $CFG->getScriptFolder(); $folder = $CFG->getScriptPathFull()."/locale"; // error_log("setupTextDomain($domain, $folder, $TSUGI_LOCALE, $TSUGI_LOCALE_RELOAD)"); $TSUGI_LOCALE_RELOAD = false; $TSUGI_TRANSLATE = false; if ( isset($CFG->legacytranslation) && $CFG->legacytranslation ) { if (function_exists('bindtextdomain')) { bindtextdomain("master", $CFG->dirroot."/locale"); bindtextdomain($domain, $folder); } if (function_exists('textdomain')) { textdomain($domain); } return; } $lang = substr($TSUGI_LOCALE, 0, 2); // error_log("lang=$lang"); $master_file = $CFG->dirroot."/locale/$lang/LC_MESSAGES/master.mo"; $domain_file = $CFG->getScriptPathFull()."/locale/$lang/LC_MESSAGES/$domain.mo"; $TSUGI_TRANSLATE = new Translator($lang, new MessageSelector()); if ( file_exists($master_file) ) { $TSUGI_TRANSLATE->addLoader('master', new MoFileLoader()); $TSUGI_TRANSLATE->addResource('master', $master_file, $lang); } if ( file_exists($domain_file) ) { $TSUGI_TRANSLATE->addLoader($domain, new MoFileLoader()); $TSUGI_TRANSLATE->addResource($domain, $domain_file, $lang); } }
php
public static function setupTextDomain() { global $CFG, $TSUGI_LOCALE, $TSUGI_LOCALE_RELOAD, $TSUGI_TRANSLATE; $domain = $CFG->getScriptFolder(); $folder = $CFG->getScriptPathFull()."/locale"; // error_log("setupTextDomain($domain, $folder, $TSUGI_LOCALE, $TSUGI_LOCALE_RELOAD)"); $TSUGI_LOCALE_RELOAD = false; $TSUGI_TRANSLATE = false; if ( isset($CFG->legacytranslation) && $CFG->legacytranslation ) { if (function_exists('bindtextdomain')) { bindtextdomain("master", $CFG->dirroot."/locale"); bindtextdomain($domain, $folder); } if (function_exists('textdomain')) { textdomain($domain); } return; } $lang = substr($TSUGI_LOCALE, 0, 2); // error_log("lang=$lang"); $master_file = $CFG->dirroot."/locale/$lang/LC_MESSAGES/master.mo"; $domain_file = $CFG->getScriptPathFull()."/locale/$lang/LC_MESSAGES/$domain.mo"; $TSUGI_TRANSLATE = new Translator($lang, new MessageSelector()); if ( file_exists($master_file) ) { $TSUGI_TRANSLATE->addLoader('master', new MoFileLoader()); $TSUGI_TRANSLATE->addResource('master', $master_file, $lang); } if ( file_exists($domain_file) ) { $TSUGI_TRANSLATE->addLoader($domain, new MoFileLoader()); $TSUGI_TRANSLATE->addResource($domain, $domain_file, $lang); } }
[ "public", "static", "function", "setupTextDomain", "(", ")", "{", "global", "$", "CFG", ",", "$", "TSUGI_LOCALE", ",", "$", "TSUGI_LOCALE_RELOAD", ",", "$", "TSUGI_TRANSLATE", ";", "$", "domain", "=", "$", "CFG", "->", "getScriptFolder", "(", ")", ";", "$", "folder", "=", "$", "CFG", "->", "getScriptPathFull", "(", ")", ".", "\"/locale\"", ";", "// error_log(\"setupTextDomain($domain, $folder, $TSUGI_LOCALE, $TSUGI_LOCALE_RELOAD)\");", "$", "TSUGI_LOCALE_RELOAD", "=", "false", ";", "$", "TSUGI_TRANSLATE", "=", "false", ";", "if", "(", "isset", "(", "$", "CFG", "->", "legacytranslation", ")", "&&", "$", "CFG", "->", "legacytranslation", ")", "{", "if", "(", "function_exists", "(", "'bindtextdomain'", ")", ")", "{", "bindtextdomain", "(", "\"master\"", ",", "$", "CFG", "->", "dirroot", ".", "\"/locale\"", ")", ";", "bindtextdomain", "(", "$", "domain", ",", "$", "folder", ")", ";", "}", "if", "(", "function_exists", "(", "'textdomain'", ")", ")", "{", "textdomain", "(", "$", "domain", ")", ";", "}", "return", ";", "}", "$", "lang", "=", "substr", "(", "$", "TSUGI_LOCALE", ",", "0", ",", "2", ")", ";", "// error_log(\"lang=$lang\");", "$", "master_file", "=", "$", "CFG", "->", "dirroot", ".", "\"/locale/$lang/LC_MESSAGES/master.mo\"", ";", "$", "domain_file", "=", "$", "CFG", "->", "getScriptPathFull", "(", ")", ".", "\"/locale/$lang/LC_MESSAGES/$domain.mo\"", ";", "$", "TSUGI_TRANSLATE", "=", "new", "Translator", "(", "$", "lang", ",", "new", "MessageSelector", "(", ")", ")", ";", "if", "(", "file_exists", "(", "$", "master_file", ")", ")", "{", "$", "TSUGI_TRANSLATE", "->", "addLoader", "(", "'master'", ",", "new", "MoFileLoader", "(", ")", ")", ";", "$", "TSUGI_TRANSLATE", "->", "addResource", "(", "'master'", ",", "$", "master_file", ",", "$", "lang", ")", ";", "}", "if", "(", "file_exists", "(", "$", "domain_file", ")", ")", "{", "$", "TSUGI_TRANSLATE", "->", "addLoader", "(", "$", "domain", ",", "new", "MoFileLoader", "(", ")", ")", ";", "$", "TSUGI_TRANSLATE", "->", "addResource", "(", "$", "domain", ",", "$", "domain_file", ",", "$", "lang", ")", ";", "}", "}" ]
Set up the translation entities
[ "Set", "up", "the", "translation", "entities" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Core/I18N.php#L133-L170
train
tsugiproject/tsugi-php
src/Util/ContentItem.php
ContentItem.addLtiLinkItem
public function addLtiLinkItem($url, $title=false, $text=false, $icon=false, $fa_icon=false, $custom=false, $points=false, $activityId=false, $additionalParams = array()) { global $CFG; $params = array( 'url' => $url, 'title' => $title, 'text' => $text, 'icon' => $icon, 'fa_icon' => $fa_icon, 'custom' => $custom, 'points' => $points, 'activityId' => $activityId, ); // package the parameter list into an array for the helper function if (! empty($additionalParams['placementTarget'])) $params['placementTarget'] = $additionalParams['placementTarget']; if (! empty($additionalParams['placementWidth'])) $params['placementWidth'] = $additionalParams['placementWidth']; if (! empty($additionalParams['placementHeight'])) $params['placementHeight'] = $additionalParams['placementHeight']; $this->addLtiLinkItemExtended($params); }
php
public function addLtiLinkItem($url, $title=false, $text=false, $icon=false, $fa_icon=false, $custom=false, $points=false, $activityId=false, $additionalParams = array()) { global $CFG; $params = array( 'url' => $url, 'title' => $title, 'text' => $text, 'icon' => $icon, 'fa_icon' => $fa_icon, 'custom' => $custom, 'points' => $points, 'activityId' => $activityId, ); // package the parameter list into an array for the helper function if (! empty($additionalParams['placementTarget'])) $params['placementTarget'] = $additionalParams['placementTarget']; if (! empty($additionalParams['placementWidth'])) $params['placementWidth'] = $additionalParams['placementWidth']; if (! empty($additionalParams['placementHeight'])) $params['placementHeight'] = $additionalParams['placementHeight']; $this->addLtiLinkItemExtended($params); }
[ "public", "function", "addLtiLinkItem", "(", "$", "url", ",", "$", "title", "=", "false", ",", "$", "text", "=", "false", ",", "$", "icon", "=", "false", ",", "$", "fa_icon", "=", "false", ",", "$", "custom", "=", "false", ",", "$", "points", "=", "false", ",", "$", "activityId", "=", "false", ",", "$", "additionalParams", "=", "array", "(", ")", ")", "{", "global", "$", "CFG", ";", "$", "params", "=", "array", "(", "'url'", "=>", "$", "url", ",", "'title'", "=>", "$", "title", ",", "'text'", "=>", "$", "text", ",", "'icon'", "=>", "$", "icon", ",", "'fa_icon'", "=>", "$", "fa_icon", ",", "'custom'", "=>", "$", "custom", ",", "'points'", "=>", "$", "points", ",", "'activityId'", "=>", "$", "activityId", ",", ")", ";", "// package the parameter list into an array for the helper function", "if", "(", "!", "empty", "(", "$", "additionalParams", "[", "'placementTarget'", "]", ")", ")", "$", "params", "[", "'placementTarget'", "]", "=", "$", "additionalParams", "[", "'placementTarget'", "]", ";", "if", "(", "!", "empty", "(", "$", "additionalParams", "[", "'placementWidth'", "]", ")", ")", "$", "params", "[", "'placementWidth'", "]", "=", "$", "additionalParams", "[", "'placementWidth'", "]", ";", "if", "(", "!", "empty", "(", "$", "additionalParams", "[", "'placementHeight'", "]", ")", ")", "$", "params", "[", "'placementHeight'", "]", "=", "$", "additionalParams", "[", "'placementHeight'", "]", ";", "$", "this", "->", "addLtiLinkItemExtended", "(", "$", "params", ")", ";", "}" ]
addLtiLinkItem - Add an LTI Link Content Item @param $url The launch URL of the tool that is about to be placed @param $title A plain text title of the content-item. @param $text A plain text description of the content-item. @param $icon An image URL of an icon @param $fa_icon The class name of a FontAwesome icon @param $custom An optional array of custom key / value pairs @param $points The number of points if this is an assignment @param $activityId The activity for the item
[ "addLtiLinkItem", "-", "Add", "an", "LTI", "Link", "Content", "Item" ]
b5397a98540f6cf4dc3981f1802c450b90d1fa44
https://github.com/tsugiproject/tsugi-php/blob/b5397a98540f6cf4dc3981f1802c450b90d1fa44/src/Util/ContentItem.php#L121-L145
train