code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
function closeButton($text=false) { if ( $text === false ) $text = _m("Exit"); $button = "btn-success"; if ( $text == "Cancel" || $text == _m("Cancel") ) $button = "btn-warning"; echo("<a href=\"#\" onclick=\"window_close();\" class=\"btn ".$button."\">".$text."</a>\n"); }
Emit a properly styled close button for use in own popup
function topNavSession($menuset) { global $CFG; $export = $menuset->export(); $sess_key = 'tsugi_top_nav_'.$CFG->wwwroot; if ( $this->session_get($sess_key) !== $export) { $this->session_put($sess_key, $export); } }
Store the top navigation in the session
function dumpDebugArray($debug_log) { if ( ! is_array($debug_log) ) return; foreach ( $debug_log as $k => $v ) { if ( count($v) > 1 ) { $this->togglePre($v[0], $v[1]); } else if ( is_array($v) ) { line_out($v[0]); } else if ( is_string($v) ) { line_out($v); } } }
Dump a debug array with messages and optional detail This kind of debug array comes back from some of the grade calls. We loop through printing the messages and put the detail into a togglable pre tag is present.
public static function doRedirect($location) { if ( headers_sent() ) { // TODO: Check if this is fixed in PHP 70200 // https://bugs.php.net/bug.php?id=74892 if ( PHP_VERSION_ID >= 70000 ) { $location = U::addSession($location); } echo('<a href="'.$location.'">Continue</a>'."\n"); } else { if ( ini_get('session.use_cookies') == 0 ) { $location = U::addSession($location); } header("Location: $location"); } }
Redirect to a local URL, adding session if necessary Note that this is only needed for AJAX and header() calls as &lt;form> and &lt;a href tags are properly handled already by the PHP built-in "don't use cookies for session" support.
public static function safe_var_cleanup(&$x, $depth) { if ( $depth >= 5 ) return; if ( is_array($x) || is_object($x) ) { foreach($x as $k => $v ) { if ( is_string($v) && strlen($v) > 0 && strpos($k, 'secret') !== false || strpos($k, 'priv') !== false ) { if ( is_array($x) ) { $x[$k] = 'Hidden as MD5: '.MD5($v); } else { $x->{$k} = 'Hidden as MD5: '.MD5($v); } } if ( is_array($v) || is_object($v) ) self::safe_var_cleanup($v,$depth+1); } } }
Clean out the array of 'secret' keys
public function set_title($title) { $xpath = new \DOMXpath($this); $general = $xpath->query(CC::lom_general_xpath)->item(0); $new_title = $this->add_child_ns(CC::LOMIMSCC_NS, $general, 'title'); $new_string = $this->add_child_ns(CC::LOMIMSCC_NS, $new_title, 'string', $title, array("language" => "en-US")); }
/* Set the title This function must be called or the resulting CC will not be compliant. This function must only be called once. @param $title The title
public function set_description($desc) { $xpath = new \DOMXpath($this); $general = $xpath->query(CC::lom_general_xpath)->item(0); $new_description = $this->add_child_ns(CC::LOMIMSCC_NS, $general, 'description'); $new_string = $this->add_child_ns(CC::LOMIMSCC_NS, $new_description, 'string', $desc, array("language" => "en-US")); }
/* Set the description @param $desc The new description This function must be called or the resulting CC will not be compliant This function must only be called once.
public function add_module($title) { $this->resource_count++; $resource_str = str_pad($this->resource_count.'',6,'0',STR_PAD_LEFT); $identifier = 'T_'.$resource_str; $xpath = new \DOMXpath($this); $items = $xpath->query(CC::item_xpath)->item(0); $module = $this->add_child_ns(CC::CC_1_1_CP, $items, 'item', null, array('identifier' => $identifier)); $new_title = $this->add_child_ns(CC::CC_1_1_CP, $module, 'title', $title); return $module; }
Adds a module to the manifest @param $title The title of the module @return the DOMNode of the newly added module
public function add_sub_module($module, $title) { $this->resource_count++; $resource_str = str_pad($this->resource_count.'',6,'0',STR_PAD_LEFT); $identifier = 'T_'.$resource_str; $sub_module = $this->add_child_ns(CC::CC_1_1_CP, $module, 'item', null, array('identifier' => $identifier)); $new_title = $this->add_child_ns(CC::CC_1_1_CP, $sub_module, 'title',$title); return $sub_module; }
Adds a sub module to a module As a note, while some LMS's are happpy with deeply nested sub-module trees, other LMS's prefre a strict two-layer module / submodule structure. @param $sub_module DOMNode The module where we are adding the submodule @param $title The title of the sub module @return the DOMNode of the newly added sub module
public function add_web_link($module, $title=null) { $this->resource_count++; $resource_str = str_pad($this->resource_count.'',6,'0',STR_PAD_LEFT); $file = 'xml/WL_'.$resource_str.'.xml'; $identifier = 'T_'.$resource_str; $type = 'imswl_xmlv1p1'; $this-> add_resource_item($module, $title, $type, $identifier, $file); return $file; }
/* Add a web link resource item This adds the web link to the manifest, to complete this when making a zip file, you must generate and place the web link XML in the returned file name within the ZIP. The `zip_add_url_to_module()` combines these two steps. @param $module DOMNode The module or sub module where we are adding the web link @param $title The title of the link @return The name of a file to contain the web link XML in the ZIP.
public function add_resource_item($module, $title=null, $type, $identifier, $file) { $identifier_ref = $identifier."_R"; $xpath = new \DOMXpath($this); $new_item = $this->add_child_ns(CC::CC_1_1_CP, $module, 'item', null, array('identifier' => $identifier, "identifierref" => $identifier_ref)); if ( $title != null ) { $new_title = $this->add_child_ns(CC::CC_1_1_CP, $new_item, 'title', $title); } $resources = $xpath->query(CC::resource_xpath)->item(0); $identifier_ref = $identifier."_R"; $new_resource = $this->add_child_ns(CC::CC_1_1_CP, $resources, 'resource', null, array('identifier' => $identifier_ref, "type" => $type)); $new_file = $this->add_child_ns(CC::CC_1_1_CP, $new_resource, 'file', null, array("href" => $file)); return $file; }
Add a resource to the manifest.
function zip_add_url_to_module($zip, $module, $title, $url) { $file = $this->add_web_link($module, $title); $web_dom = new CC_WebLink(); $web_dom->set_title($title); $web_dom->set_url($url, array("target" => "_iframe")); $zip->addFromString($file,$web_dom->saveXML()); }
/* Add a web link resource item and create the file within the ZIP @param $zip The zip file handle that we are creating @param $module DOMNode The module or sub module where we are adding the web link @param $title The title of the link @param $url The url for the link @return The name of a file to contain the web link XML in the ZIP.
function zip_add_lti_to_module($zip, $module, $title, $url, $custom=null, $extensions=null) { $file = $this->add_lti_link($module, $title); $lti_dom = new CC_LTI(); $lti_dom->set_title($title); // $lti_dom->set_description('Create a single SQL table and insert some records.'); $lti_dom->set_secure_launch_url($url); if ( $custom != null ) foreach($custom as $key => $value) { $lti_dom->set_custom($key,$value); } if ( $extensions != null ) foreach($extensions as $key => $value) { $lti_dom->set_extension($key,$value); } $zip->addFromString($file,$lti_dom->saveXML()); }
/* Add a LTI link resource item and create the file within the ZIP @param $zip The zip file handle that we are creating @param $module DOMNode The module or sub module where we are adding the LTI link @param $title The title of the link @param $url The url/endpoint for the link @param $custom An optional array of custom parameters for this link @param $extenions An optional array of tsugi extensions for this link @return The name of a file to contain the web link XML in the ZIP.
public static function &create_new($repo_path, $source = null, $remote_source = false, $reference = null) { if (is_dir($repo_path) && file_exists($repo_path."/.git") && is_dir($repo_path."/.git")) { throw new \Exception('"'.$repo_path.'" is already a git repository'); } else { $repo = new self($repo_path, true, false); if (is_string($source)) { if ($remote_source) { if (!is_dir($reference) || !is_dir($reference.'/.git')) { throw new \Exception('"'.$reference.'" is not a git repository. Cannot use as reference.'); } else if (strlen($reference)) { $reference = realpath($reference); $reference = "--reference $reference"; } $repo->clone_remote($source, $reference); } else { $repo->clone_from($source); } } else { $repo->run('init'); } return $repo; } }
Create a new git repository Accepts a creation path, and, optionally, a source path @access public @param string repository path @param string directory to source @param string reference path @return GitRepo
public function set_repo_path($repo_path, $create_new = false, $_init = true) { if (is_string($repo_path)) { if ($new_path = realpath($repo_path)) { $repo_path = $new_path; if (is_dir($repo_path)) { // Is this a work tree? if (file_exists($repo_path."/.git") && is_dir($repo_path."/.git")) { $this->repo_path = $repo_path; $this->bare = false; // Is this a bare repo? } else if (is_file($repo_path."/config")) { $parse_ini = parse_ini_file($repo_path."/config"); if ($parse_ini['bare']) { $this->repo_path = $repo_path; $this->bare = true; } } else { if ($create_new) { $this->repo_path = $repo_path; if ($_init) { $this->run('init'); } } else { throw new \Exception('"'.$repo_path.'" is not a git repository'); } } } else { throw new \Exception('"'.$repo_path.'" is not a directory'); } } else { if ($create_new) { if ($parent = realpath(dirname($repo_path))) { mkdir($repo_path); $this->repo_path = $repo_path; if ($_init) $this->run('init'); } else { throw new \Exception('cannot create repository in non-existent directory'); } } else { throw new \Exception('"'.$repo_path.'" does not exist'); } } } }
Set the repository's path Accepts the repository path @access public @param string repository path @param bool create if not exists? @param bool initialize new Git repo if not exists? @return void
public function status($html = false) { $msg = $this->run("status"); if ($html == true) { $msg = str_replace("\n", "<br />", $msg); } return $msg; }
Runs a 'git status' call Accept a convert to HTML bool @access public @param bool return string with <br /> @return string
public function rm($files = "*", $cached = false) { if (is_array($files)) { $files = '"'.implode('" "', $files).'"'; } return $this->run("rm ".($cached ? '--cached ' : '').$files); }
Runs a `git rm` call Accepts a list of files to remove @access public @param mixed files to remove @param Boolean use the --cached flag? @return string
public function commit($message = "", $commit_all = true) { $flags = $commit_all ? '-av' : '-v'; return $this->run("commit ".$flags." -m ".escapeshellarg($message)); }
Runs a `git commit` call Accepts a commit message string @access public @param string commit message @param boolean should all files be committed automatically (-a flag) @return string
public function list_remote_branches() { $branchArray = explode("\n", $this->run("branch -r")); foreach($branchArray as $i => &$branch) { $branch = trim($branch); if ($branch == "" || strpos($branch, 'HEAD -> ') !== false) { unset($branchArray[$i]); } } return $branchArray; }
Lists remote branches (using `git branch -r`). Also strips out the HEAD reference (e.g. "origin/HEAD -> origin/master"). @access public @return array
public function active_branch($keep_asterisk = false) { $branchArray = $this->list_branches(true); $active_branch = preg_grep("/^\*/", $branchArray); reset($active_branch); if ($keep_asterisk) { return current($active_branch); } else { return str_replace("* ", "", current($active_branch)); } }
Returns name of active branch @access public @param bool keep asterisk mark on branch name @return string
public function add_tag($tag, $message = null) { if ($message === null) { $message = $tag; } return $this->run("tag -a $tag -m " . escapeshellarg($message)); }
Add a new tag on the current position Accepts the name for the tag and the message @param string $tag @param string $message @return string
public function list_tags($pattern = null) { $tagArray = explode("\n", $this->run("tag -l $pattern")); foreach ($tagArray as $i => &$tag) { $tag = trim($tag); if ($tag == '') { unset($tagArray[$i]); } } return $tagArray; }
List all the available repository tags. Optionally, accept a shell wildcard pattern and return only tags matching it. @access public @param string $pattern Shell wildcard pattern to match tags against. @return array Available repository tags.
public function log($format = null) { if ($format === null) return $this->run('log'); else return $this->run('log --pretty=format:"' . $format . '"'); }
List log entries. @param strgin $format @return string
public static function createFromJsonResponse($jsonString) { $data = json_decode($jsonString, true); $operations = []; foreach ($data as $name => $operationData) { // Ensuring that the required fields exist. $operationData = array_merge(['required' => [], 'properties' => []], $operationData); $operations[] = new Operation($name, $operationData['properties'], $operationData['required']); } return new self($operations); }
Create a collection from the JSON data returned by the rokka.io API. @param string $jsonString JSON as a string @return OperationCollection
public static function createFromDecodedJsonResponse($data) { // Make sure to build the SubjectArea with correct defaults in case of missing attributes. $data = array_merge(['x' => 0, 'y' => 0, 'width' => 1, 'height' => 1], $data); return new self( max(0, $data['x']), max(0, $data['y']), max(1, $data['width']), max(1, $data['height']) ); }
Create a SubjectArea from the decoded JSON data. @param array $data Decoded JSON data @return SubjectArea
public function handle(\ReflectionParameter $parameter) { $func = $parameter->getDeclaringFunction(); $method = new \ReflectionMethod($parameter->getDeclaringClass()->name, $func->name); $parameter->getDeclaringFunction()->name; $annotations = $this->reader->getMethodAnnotations($method); foreach ($annotations as $annotation) { if ($annotation instanceof ResourceParam && $annotation->param === $parameter->name) { return $this->getResourceParam($annotation->uri); } } (new VoidParamHandler)->handle($parameter); }
{@inheritdoc} @throws \BEAR\Resource\Exception\ParameterException
private function getResourceParam($uri) { $resource = $this->injector->getInstance(ResourceInterface::class); $resourceResult = $resource->get->uri($uri)->eager->request(); $fragment = parse_url($uri, PHP_URL_FRAGMENT); return $resourceResult[$fragment]; }
@param string $uri @return mixed
public static function addOptionsToUriString($url, $options, $shortNames = true) { return (string) self::addOptionsToUri(new Uri($url), $options, $shortNames); }
Allows you to add stack options to a Rokka URL. Useful eg. if you just want to add "options-dpr-2" to an existing URL. Returns the original URL, if it can't parse it as valid Rokka URL. @see UriHelper::addOptionsToUri @param string $url The rokka image render URL @param array|string $options The options you want to add as string @param bool $shortNames if short names (like o for option or v for variables) should be used @throws \RuntimeException @return string
public static function addOptionsToUri(UriInterface $uri, $options, $shortNames = true) { if (\is_array($options)) { return self::addOptionsToUri($uri, self::getUriStringFromStackConfig($options, $shortNames), $shortNames); } $matches = self::decomposeUri($uri); if (empty($matches)) { //if nothing matches, it's not a proper rokka URL, just return the original uri return $uri; } $stack = $matches->getStack(); $stack->addOverridingOptions($options); return self::composeUri($matches, $uri, $shortNames); }
Allows you to add stack options to a Rokka URL. Useful eg. if you just want to add "options-dpr-2" to an existing URL Returns the original URL, if it can't parse it as valid Rokka URL. Example with string as input ```language-php UriHelper::addOptionsToUri($uri, 'options-dpr-2--resize-upscale-false'); ``` Example with array ```language-php UriHelper::addOptionsToUri($uri, [ 'options' => ['dpr' => 2], 'operations' => [ [ 'name' => 'resize', 'options' => ['upscale' => 'false'] ], ], ]); ``` @param UriInterface $uri The rokka image render URL @param array|string $options The options you want to add as string @param bool $shortNames if short names (like o for option or v for variables) should be used @throws \RuntimeException @return UriInterface
public static function composeUri($components, UriInterface $uri = null, $shortNames = true) { if (\is_array($components)) { $components = UriComponents::createFromArray($components); } $stack = $components->getStack(); $stackName = $stack->getName(); $path = '/'.$stackName; $stackConfig = $stack->getConfigAsArray(); $stackUrl = self::getUriStringFromStackConfig($stackConfig, $shortNames); if (!empty($stackUrl)) { $path .= '/'.$stackUrl; } if (!empty($components->getHash())) { $path .= '/'.$components->getHash(); if (!empty($components->getFilename())) { $path .= '/'.$components->getFilename(); } $path .= '.'.$components->getFormat(); } if (null !== $uri) { return $uri->withPath($path); } return new Uri($path); }
Generate a rokka uri with an array or an UriComponent returned by decomposeUri(). The array looks like ``` ['stack' => 'stackname', #or StackUri object 'hash' => 'hash', 'filename' => 'filename-for-url', 'format' => 'image format', # eg. jpg ] ``` @since 1.2.0 @param array|UriComponents $components @param UriInterface $uri If this is provided, it will change the path for that object and return @param bool $shortNames if short names (like o for option or v for variables) should be used @throws \RuntimeException @return UriInterface
public static function decomposeUri(UriInterface $uri) { $stackPattern = '(?<stack>.*([^-]|--)|-*)'; $hashPattern = '(?<hash>[0-9a-f]{6,40})'; $filenamePattern = '(?<filename>[A-Za-z\-\0-\9]+)'; $formatPattern = '(?<format>.{3,4})'; $pathPattern = '(?<hash>-.+-)'; $path = $uri->getPath(); // hash with seo-filename if (preg_match('#^/'.$stackPattern.'/'.$hashPattern.'/'.$filenamePattern.'\.'.$formatPattern.'$#', $path, $matches) || // hash without seo-filename preg_match('#^/'.$stackPattern.'/'.$hashPattern.'.'.$formatPattern.'$#', $path, $matches) || // remote_path with seo-filename preg_match('#^/'.$stackPattern.'/'.$pathPattern.'/'.$filenamePattern.'\.'.$formatPattern.'$#', $path, $matches) || // remote_path without seo-filename preg_match('#^/'.$stackPattern.'/'.$pathPattern.'.'.$formatPattern.'$#', $path, $matches)) { return UriComponents::createFromArray($matches); } }
Return components of a rokka URL. @since 1.2.0 @param UriInterface $uri @throws \RuntimeException @return UriComponents|null
public static function getSrcSetUrlString($url, $size, $custom = null, $setWidthInUrl = true) { return self::getSrcSetUrl(new Uri($url), $size, $custom, $setWidthInUrl); }
@param string $url The original rokka render URL to be adjusted @param string $size The size of the image, eg '300w' or '2x' @param null|string $custom Any rokka options you'd like to add, or are a dpi identifier like '2x' @param bool $setWidthInUrl If false, don't set the width as stack operation option, we provide it in $custom, usually as parameter @throws \RuntimeException @return UriInterface
public static function getSrcSetUrl(UriInterface $url, $size, $custom = null, $setWidthInUrl = true) { $identifier = substr($size, -1, 1); $size = substr($size, 0, -1); switch ($identifier) { case 'x': $uri = self::addOptionsToUri($url, 'options-dpr-'.$size); break; case 'w': if ($setWidthInUrl) { $uri = self::addOptionsToUri($url, 'resize-width-'.$size); } else { $uri = $url; } break; default: return $url; } if (null !== $custom) { $uri = self::getSrcSetUrlCustom($size, $custom, $setWidthInUrl, $uri); } return $uri; }
Returns a rokka URL to be used in srcset style attributes. $size can be eg. "2x" or "500w" $custom can be any rokka options you want to optionally add, or also a dpi identifier like "2x" This method will then generate the right rokka URLs to get what you want, see `\Rokka\Client\Tests\UriHelperTest::provideGetSrcSetUrl` for some examples and the expected returns. @param UriInterface $url The original rokka render URL to be adjusted @param string $size The size of the image, eg '300w' or '2x' @param null|string $custom Any rokka options you'd like to add, or are a dpi identifier like '2x' @param bool $setWidthInUrl If false, don't set the width as stack operation option, we provide it in $custom, usually as parameter @throws \RuntimeException @return UriInterface
private static function getUriStringFromStackConfig(array $config, $shortNames = true) { $newOptions = []; if (isset($config['operations'])) { foreach ($config['operations'] as $values) { if ($values instanceof StackOperation) { $newOptions[] = self::getStringForOptions($values->name, $values->options, $values->expressions); } else { if (!isset($values['expressions'])) { $values['expressions'] = []; } $newOptions[] = self::getStringForOptions($values['name'], $values['options'], $values['expressions']); } } } $newStackOptions = null; $nameOptions = $shortNames ? 'o' : 'options'; if (isset($config['options'])) { $newStackOptions = self::getStringForOptions($nameOptions, $config['options']); } //don't return this, if it's only "options" as string if (null !== $newStackOptions && $nameOptions !== $newStackOptions) { $newOptions[] = $newStackOptions; } $newStackVariables = null; $nameVariables = $shortNames ? 'v' : 'variables'; if (isset($config['variables'])) { $newStackVariables = self::getStringForOptions($nameVariables, $config['variables']); } //don't return this, if it's only "variables" as string if (null !== $newStackVariables && $nameVariables !== $newStackVariables) { $newOptions[] = $newStackVariables; } $options = implode('--', $newOptions); return $options; }
@param array $config @param bool $shortNames if short names (like o for option or v for variables) should be used @return string
private static function getStringForOptions($name, $options, $expressions = []) { $newOption = $name; foreach ($expressions as $key => $value) { $expressions[$key] = '['.$value.']'; } $options = array_merge($options, $expressions); ksort($options); foreach ($options as $k => $v) { if (false === $v) { $v = 'false'; } elseif (true === $v) { $v = 'true'; } $newOption .= "-$k-$v"; } return $newOption; }
@param string $name @param array $options @param array $expressions @return string
private static function getSrcSetUrlCustom($size, $custom, $setWidthInUrl, UriInterface $uri) { // if custom is eg '2x', add options-dpr- if (preg_match('#^([0-9]+)x$#', $custom, $matches)) { $uri = self::addOptionsToUri($uri, 'options-dpr-'.$matches[1]. ($setWidthInUrl ? '--resize-width-'.(int) ceil($size / $matches[1]) : '')); } else { $stack = new StackUri(); $stack->addOverridingOptions($custom); // if dpr is given in custom option, but not width, calculate correct width $resizeOperations = $stack->getStackOperationsByName('resize'); $widthIsNotSet = true; foreach ($resizeOperations as $resizeOperation) { if (isset($resizeOperation->options['width'])) { $widthIsNotSet = false; } } $options = $stack->getStackOptions(); if (isset($options['dpr']) && $widthIsNotSet && $setWidthInUrl) { $custom .= '--resize-width-'.(int) ceil($size / $options['dpr']); } $uri = self::addOptionsToUri($uri, $custom); } return $uri; }
Adds custom options to the URL. @param string $size @param string $custom @param bool $setWidthInUrl @param UriInterface $uri @throws \RuntimeException if stack configuration can't be parsed @return UriInterface
public static function getConnection() { global $PDOX, $CFG; if ( isset($PDOX) && is_object($PDOX) && get_class($PDOX) == 'Tsugi\Util\PDOX' ) { return $PDOX; } if ( defined('PDO_WILL_CATCH') ) { $PDOX = new \Tsugi\Util\PDOX($CFG->pdo, $CFG->dbuser, $CFG->dbpass); $PDOX->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); } else { try { $PDOX = new \Tsugi\Util\PDOX($CFG->pdo, $CFG->dbuser, $CFG->dbpass); $PDOX->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); } catch(\PDOException $ex){ error_log("DB connection: ".$ex->getMessage()); die('Failure connecting to the database, see error log'); // with error_log } } if ( isset($CFG->slow_query) ) $PDOX->slow_query = $CFG->slow_query; return $PDOX; }
Get a singleton global connection or set it up if not already set up.
public static function launchCheck($needed=self::ALL, $session_object=null,$request_data=false) { global $TSUGI_LAUNCH, $CFG; $needed = self::patchNeeded($needed); // Check if we are an LTI 1.1 or LTI 1.3 launch $LTI11 = false; $LTI13 = false; $detail = LTI13::isRequestDetail($request_data); if ( $detail === true ) { $LTI13 = true; } else { $lti11_request_data = $request_data; if ( $lti11_request_data === false ) $lti11_request_data = self::oauth_parameters(); $LTI11 = LTI::isRequestCheck($lti11_request_data); if ( is_string($LTI11) ) { self::abort_with_error_log($LTI11, $request_data); } } if ( $LTI11 === false && $LTI13 === false ) return $detail; $session_id = self::setupSession($needed,$session_object,$request_data); if ( $session_id === false ) return false; // Redirect back to ourselves... $url = self::curPageUrl(); if ( $session_object !== null ) { $TSUGI_LAUNCH->redirect_url = self::curPageUrl(); return true; } $location = U::addSession($url); session_write_close(); // To avoid any race conditions... if ( headers_sent() ) { echo('<p><a href="'.$url.'">Click to continue</a></p>'); } else { header('Location: '.$location); } exit(); }
Silently check if this is a launch and if so, handle it and redirect back to ourselves
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
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
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
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
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
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
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
public static function ltiParameter($varname, $default=false) { global $TSUGI_LAUNCH; if ( isset($TSUGI_LAUNCH) ) { return $TSUGI_LAUNCH->ltiParameter($varname, $default); } if ( ! isset($_SESSION) ) return $default; if ( ! isset($_SESSION['lti']) ) return $default; $lti = $_SESSION['lti']; if ( ! isset($lti[$varname]) ) return $default; return $lti[$varname]; }
Pull a keyed variable from the LTI data in the current session with default @deprecated Session access should be through the Launch Object
public static function ltiRawPostArray() { global $TSUGI_LAUNCH; if ( isset($TSUGI_LAUNCH) ) { return $TSUGI_LAUNCH->ltiRawPostArray(); } if ( ! isset($_SESSION) ) return array(); if ( ! isset($_SESSION['lti_post']) ) return array(); return($_SESSION['lti_post']); }
Return the original $_POST array @deprecated Session access should be through the Launch Object
public static function ltiRawParameter($varname, $default=false) { global $TSUGI_LAUNCH; if ( isset($TSUGI_LAUNCH) ) { return $TSUGI_LAUNCH->ltiRawParameter($varname, $default); } if ( ! isset($_SESSION) ) return $default; if ( ! isset($_SESSION['lti_post']) ) return $default; $lti_post = $_SESSION['lti_post']; if ( ! isset($lti_post[$varname]) ) return $default; return $lti_post[$varname]; }
Pull a keyed variable from the original LTI post data in the current session with default @deprecated Session access should be through the Launch Object
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
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
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.
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.
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.
public static function gradeGet($row=false, &$debug_log=false) { global $RESULT; if ( isset($RESULT) ) return $RESULT->gradeGet($row,$debug_log); return 'LTIX::gradeGet $RESULT not set'; }
Load the grade for a particular row and update our local copy (Deprecated - moved to Result) Call the right LTI service to retrieve the server's grade and update our local cached copy of the server_grade and the date retrieved. This routine pulls the key and secret from the LTIX session to avoid crossing cross tennant boundaries. TODO: Add LTI 2.x support for the JSON style services to this @param $row An optional array with the data that has the result_id, sourcedid, and service (url) if this is not present, the data is pulled from the LTI session for the current user/link combination. @param $debug_log An (optional) array (by reference) that returns the steps that were taken. Each entry is an array with the [0] element a message and an optional [1] element as some detail (i.e. like a POST body) @return mixed If this work this returns a float. If not you get a string with an error.
public static function gradeSend($grade, $row=false, &$debug_log=false) { global $RESULT; if ( isset($RESULT) ) return $RESULT->gradeSend($grade,$row,$debug_log); return 'LTIX::gradeSend $RESULT not set'; }
Send a grade and update our local copy (Deprecated - moved to Result) Call the right LTI service to send a new grade up to the server. update our local cached copy of the server_grade and the date retrieved. This routine pulls the key and secret from the LTIX session to avoid crossing cross tennant boundaries. @param $grade A new grade - floating point number between 0.0 and 1.0 @param $row An optional array with the data that has the result_id, sourcedid, and service (url) if this is not present, the data is pulled from the LTI session for the current user/link combination. @param $debug_log An (optional) array (by reference) that returns the steps that were taken. Each entry is an array with the [0] element a message and an optional [1] element as some detail (i.e. like a POST body) @return mixed If this works it returns true. If not, you get a string with an error.
public static function gradeSendDueDate($gradetosend, $oldgrade=false, $dueDate=false) { global $RESULT; if ( isset($RESULT) ) return $RESULT->gradeSendDueDate($gradetosend,$oldgrade,$dueDate); return 'LTIX::gradeSendDueDate $RESULT not set'; }
Send a grade applying the due date logic and only increasing grades (Deprecated - moved to Result) Puts messages in the session for a redirect. @param $gradetosend - The grade in the range 0.0 .. 1.0 @param $oldgrade - The previous grade in the range 0.0 .. 1.0 (optional) @param $dueDate - The due date for this assignment
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
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
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.
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
public static function getKeySecretForLaunch($url) { global $CFG, $CONTEXT; $PDOX = self::getConnection(); $host = parse_url($url, PHP_URL_HOST); $port = parse_url($url, PHP_URL_PORT); $key_id = self::ltiParameter('key_id', null); if ( $key_id == null ) return false; $sql = "SELECT consumer_key, secret FROM {$CFG->dbprefix}lti_domain WHERE domain = :DOM AND key_id = :KID"; $values = array(":DOM" => $host, ":KID" => $key_id); if ( isset($CONTEXT->id) ) { $sql .= " AND (context_id IS NULL OR context_id = :CID) ORDER BY context_id DESC"; $values[':CID'] = $CONTEXT->id; } $row = $PDOX->rowDie($sql, $values); if ( $row === false ) { error_log("Unable to key/secret key_id=$key_id url=$url"); return false; } $row['key'] = $row['consumer_key']; return $row; }
getKeySecretForLaunch - Retrieve a Key/Secret for a Launch @param $url - The url to lookup
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
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/
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
private static function checkHeartBeat($session_object=null) { global $CFG; if ( session_id() == "" ) return; // This should not start the session if ( isset($CFG->sessionlifetime) ) { if (self::wrapped_session_get($session_object,'LAST_ACTIVITY') ) { $heartbeat = $CFG->sessionlifetime/4; $ellapsed = time() - self::wrapped_session_get($session_object,'LAST_ACTIVITY'); if ( $ellapsed > $heartbeat ) { self::wrapped_session_put($session_object,'LAST_ACTIVITY', time()); // TODO: Remove this after verification $filename = isset($_SERVER['SCRIPT_FILENAME']) ? $_SERVER['SCRIPT_FILENAME'] : ''; error_log("Heartbeat ".session_id().' '.$ellapsed.' '.$filename); } } else { self::wrapped_session_put($session_object,'LAST_ACTIVITY', time()); } } }
http://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes
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
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
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
public static function getContentItem($contentReturn, $dataProps) { global $CFG, $CONTEXT, $USER, $CONTEXT, $LINK; $ltiProps = self::getCoreLaunchData(); $ltiProps[LTIConstants::LTI_MESSAGE_TYPE] = LTIConstants::CONTENT_ITEM_SELECTION_REQUEST; $ltiProps[LTIConstants::ACCEPT_MEDIA_TYPES] = LTIConstants::MEDIA_LTILINKITEM; $ltiProps[LTIConstants::ACCEPT_PRESENTATION_DOCUMENT_TARGETS] = "iframe,window"; // Nice to add overlay $ltiProps[LTIConstants::ACCEPT_UNSIGNED] = "true"; $ltiProps[LTIConstants::ACCEPT_MULTIPLE] = "false"; $ltiProps[LTIConstants::ACCEPT_COPY_ADVICE] = "false"; // ??? $ltiProps[LTIConstants::AUTO_CREATE] = "true"; $ltiProps[LTIConstants::CAN_CONFIRM] = "false"; $ltiProps[LTIConstants::CONTENT_ITEM_RETURN_URL] = $contentReturn; $ltiProps[LTIConstants::LAUNCH_PRESENTATION_RETURN_URL] = $contentReturn; // This is needed to trigger WarpWire to send us back the link $ltiProps['tool_consumer_info_product_family_code'] = 'canvas'; $ltiProps['custom_canvas_course_id'] = $CONTEXT->id; return $ltiProps; }
getLaunchData - Get the launch data for am LTI ContentItem launch
public static function getLaunchUrl($endpoint, $debug=false) { $launchurl = Output::getUtilUrl('/launch.php?debug='); $launchurl .= ($debug) ? '1':'0'; $launchurl .= '&endpoint='; $launchurl .= urlencode($endpoint); return $launchurl; }
getLaunchData - Get the launch data for am LTI ContentItem launch
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
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
public static function populateRoster($groups=false) { global $ROSTER; if(!is_object($ROSTER)) { return false; } $encryptedSecret = self::ltiParameter('secret'); $key = self::ltiParameter('key_key'); $response = LTI::getContextMemberships($ROSTER->id, $ROSTER->url, $key, self::decrypt_secret($encryptedSecret), $groups); if($response != false) { $ROSTER->data = $response; } return true; }
populateRoster If the LTI Extension: Context Memberships Service is supported in the launch, get the memberships information @param bool $groups, whether or not to get groups in the Memberships @return bool true if successful, false if not possible
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); }
emit the header material
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
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
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
public function render($buffer=false) { if ( $this->isSingle() ) { return $this->renderSingle($buffer); } else { return $this->renderAll($buffer); } }
/* * render
public static function nostyleUrl($title, $url) { echo('<a href="'.$url.'" target="_blank" typeof="oer:SupportingMaterial">'.htmlentities($url)."</a>\n"); if ( isset($_SESSION['gc_count']) ) { echo('<div class="g-sharetoclassroom" data-size="16" data-url="'.$url.'" '); echo(' data-title="'.htmlentities($title).'" '); echo('></div>'); } }
/* A Nostyle URL Link with title
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
public static function getUrlResources($module) { $resources = array(); if ( isset($module->videos) ) { foreach($module->videos as $video ) { $resources[] = self::makeUrlResource('video',$video->title, 'https://www.youtube.com/watch?v='.urlencode($video->youtube)); } } if ( isset($module->slides) ) { $resources[] = self::makeUrlResource('slides','Slides: '.$module->title, $module->slides); } if ( isset($module->assignment) ) { $resources[] = self::makeUrlResource('assignment','Assignment Specification', $module->assignment); } if ( isset($module->solution) ) { $resources[] = self::makeUrlResource('solution','Assignment Solution', $module->solution); } if ( isset($module->references) ) { foreach($module->references as $reference ) { $resources[] = self::makeUrlResource('reference',$reference->title, $reference->href); } } return $resources; }
/* After PHP 5.6 const RESOURCE_ICONS = array( 'video' => 'fa-video-camera', 'slides' => 'fa-file-powerpoint-o', 'assignment' => 'fa-lock', 'solution' => 'fa-unlock', 'reference' => 'fa-external-link' );
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); }
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
public static function getCurl($url, $header=false) { if ( ! function_exists('curl_init') ) return false; global $last_http_response; global $LastHeadersSent; global $LastHeadersReceived; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); // Make sure that the header is an array and pitch white space $LastHeadersSent = trim($header); $header = explode("\n", trim($header)); $htrim = Array(); foreach ( $header as $h ) { $htrim[] = trim($h); } curl_setopt ($ch, CURLOPT_HTTPHEADER, $htrim); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // ask for results to be returned curl_setopt($ch, CURLOPT_HEADER, 1); // Thanks to more and more PHP's not shipping with CA's installed // This becomes necessary if ( self::$VERIFY_PEER ) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); } else { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); } // Send to remote and return data to caller. $result = curl_exec($ch); $info = curl_getinfo($ch); $last_http_response = $info['http_code']; $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $LastHeadersReceived = substr($result, 0, $header_size); $body = substr($result, $header_size); if ( $body === false ) $body = ""; curl_close($ch); return $body; }
Note - handles port numbers in URL automatically
public static function doBody($url, $method, $body, $header) { global $LastBODYURL; global $LastBODYMethod; global $LastBODYImpl; global $LastHeadersSent; global $last_http_response; global $LastHeadersReceived; global $LastBODYContent; $LastBODYURL = $url; $LastBODYMethod = $method; $LastBODYImpl = false; $LastHeadersSent = false; $last_http_response = false; $LastHeadersReceived = false; $LastBODYContent = false; // Prefer curl because it checks if it works before trying $LastBODYContent = NET::bodyCurl($url, $method, $body, $header); $LastBODYImpl = "CURL"; if ( $LastBODYContent !== false ) return $LastBODYContent; $LastBODYContent = NET::bodySocket($url, $method, $body, $header); $LastBODYImpl = "Socket"; if ( $LastBODYContent !== false ) return $LastBODYContent; $LastBODYContent = NET::bodyStream($url, $method, $body, $header); $LastBODYImpl = "Stream"; if ( $LastBODYContent !== false ) return $LastBODYContent; $LastBODYImpl = "Error"; error_log("Unable to $method Url=$url"); error_log("Header: $header"); error_log("Body: $body"); throw new \Exception("Unable to $method $url"); }
configured...
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.
private function getResourceParam(ResourceParam $resourceParam, array $query) { $uri = $resourceParam->templated === true ? uri_template($resourceParam->uri, $query) : $resourceParam->uri; $resource = $this->injector->getInstance(ResourceInterface::class); $resourceResult = $resource->get->uri($uri)->eager->request(); $fragment = parse_url($uri, PHP_URL_FRAGMENT); return $resourceResult[$fragment]; }
@param ResourceParam $resourceParam @param array $query @return mixed
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.
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
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
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
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)
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
public function process(EnvironmentInterface $environment) { $definition = $environment->getDataDefinition(); $basicDefinition = $definition->getBasicDefinition(); $dataProvider = $environment->getDataProvider(); if (!$basicDefinition->isCreatable()) { throw new NotCreatableException('DataContainer ' . $definition->getName() . ' is not creatable'); } // We only support flat tables, sorry. if (BasicDefinitionInterface::MODE_FLAT !== $basicDefinition->getMode()) { return false; } $modelId = ModelId::fromSerialized($environment->getInputProvider()->getParameter('source')); /** @var Driver $dataProvider */ $model = $dataProvider->createVariant($dataProvider->getEmptyConfig()->setId($modelId->getId())); if (null === $model) { throw new DcGeneralRuntimeException( sprintf( 'Could not find model with id %s for creating a variant.', $modelId ) ); } $metaModel = $this->factory->getMetaModel($model->getProviderName()); if (null === $metaModel || false === $metaModel->hasVariants()) { return false; } $preFunction = static function ($environment, $model) { /** @var EnvironmentInterface $environment */ $createModelEvent = new PreCreateModelEvent($environment, $model); $environment->getEventDispatcher()->dispatch($createModelEvent::NAME, $createModelEvent); }; $postFunction = static function ($environment, $model) { /** @var EnvironmentInterface $environment */ $createModelEvent = new PostCreateModelEvent($environment, $model); $environment->getEventDispatcher()->dispatch($createModelEvent::NAME, $createModelEvent); }; $editMask = new EditMask($environment, $model, null, $preFunction, $postFunction); return $editMask->execute(); }
Handle the action. @param EnvironmentInterface $environment The environment. @return string|false @throws NotCreatableException When the DataContainer is not creatable. @throws DcGeneralRuntimeException When the model to create a variant from was not found.
public function invoke(MethodInvocation $invocation) { /** @var ResourceObject $ro */ $ro = $invocation->getThis(); $method = $invocation->getMethod(); $query = $this->getArgsByInvocation($invocation); $embeds = $this->reader->getMethodAnnotations($method); $this->embedResource($embeds, $ro, $query); return $invocation->proceed(); }
{@inheritdoc} @throws \BEAR\Resource\Exception\EmbedException
private function embedResource(array $embeds, ResourceObject $ro, array $query) { foreach ($embeds as $embed) { /* @var $embed Embed */ if (! $embed instanceof Embed) { continue; } try { $templateUri = $this->getFullUri($embed->src, $ro); $uri = uri_template($templateUri, $query); $ro->body[$embed->rel] = clone $this->resource->get->uri($uri); } catch (BadRequestException $e) { // wrap ResourceNotFound or Uri exception throw new EmbedException($embed->src, 500, $e); } } }
@param Embed[] $embeds @throws EmbedException
protected function configure() { $this->bind(ResourceInterface::class)->to(Resource::class)->in(Scope::SINGLETON); $this->bind(InvokerInterface::class)->to(Invoker::class); $this->bind(LinkerInterface::class)->to(Linker::class); $this->bind(FactoryInterface::class)->to(Factory::class); $this->bind(SchemeCollectionInterface::class)->toProvider(SchemeCollectionProvider::class); $this->bind(AnchorInterface::class)->to(Anchor::class); $this->bind(NamedParameterInterface::class)->to(NamedParameter::class); $this->bind(RenderInterface::class)->to(PrettyJsonRenderer::class)->in(Scope::SINGLETON); $this->bind(Cache::class)->to(ArrayCache::class); $this->bind(RenderInterface::class)->annotatedWith('options')->to(OptionsRenderer::class); $this->bind(OptionsMethods::class); $this->bind(NamedParamMetasInterface::class)->to(NamedParamMetas::class); }
{@inheritdoc} @throws \Ray\Di\Exception\NotFound
public function handle(\ReflectionParameter $parameter) { $class = $parameter->getDeclaringClass(); $className = $class->implementsInterface(WeavedInterface::class) ? $class->getParentClass()->getName() : $class->name; $method = $parameter->getDeclaringFunction()->name; $msg = sprintf('$%s in %s::%s()', $parameter->name, $className, $method); throw new ParameterException($msg, Code::BAD_REQUEST); }
{@inheritdoc} @throws ParameterException
private function ignoreAnnotatedPrameter(\ReflectionMethod $method, array $paramMetas) : array { $annotations = $this->reader->getMethodAnnotations($method); foreach ($annotations as $annotation) { if ($annotation instanceof ResourceParam) { unset($paramMetas['parameters'][$annotation->param]); $paramMetas['required'] = array_values(array_diff($paramMetas['required'], [$annotation->param])); } if ($annotation instanceof Assisted) { $paramMetas = $this->ignorreAssisted($paramMetas, $annotation); } } return $paramMetas; }
Ignore @ Assisted @ ResourceParam parameter
private function ignorreAssisted(array $paramMetas, Assisted $annotation) : array { $paramMetas['required'] = array_values(array_diff($paramMetas['required'], $annotation->values)); foreach ($annotation->values as $varName) { unset($paramMetas['parameters'][$varName]); } return $paramMetas; }
Ignore @ Assisted parameter