code
stringlengths 52
7.75k
| docs
stringlengths 1
5.85k
|
---|---|
public function ltiParameter($varname, $default=false) {
$row = $this->session_get('lti', false);
if ( ! $row ) return $default;
if ( ! array_key_exists($varname, $row) ) return $default;
return $row[$varname];
} | Pull a keyed variable from the LTI data in the current session with default |
public function ltiParameterUpdate($varname, $value) {
$lti = $this->session_get('lti', false);
if ( ! $lti ) $lti = array(); // Should never happen
if ( is_array($lti) ) $lti[$varname] = $value;
$lti = $this->session_put('lti', $lti);
} | Update a keyed variable from the LTI data in the current session with default |
public function ltiRawParameter($varname, $default=false) {
$lti_post = $this->ltiRawPostArray('lti_post', false);
if ( $lti_post === false ) return $default;
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 |
public function isSakai() {
$ext_lms = $this->ltiRawParameter('ext_lms', false);
$ext_lms = strtolower($ext_lms);
return strpos($ext_lms, 'sakai') === 0 ;
} | Indicate if this launch came from Sakai |
public function isMoodle() {
$ext_lms = $this->ltiRawParameter('ext_lms', false);
$ext_lms = strtolower($ext_lms);
return strpos($ext_lms, 'moodle') === 0 ;
} | Indicate if this launch came from Moodle |
public function isCoursera() {
$product = $this->ltiRawParameter('tool_consumer_info_product_family_code', false);
$tci_description = $this->ltiRawParameter('tool_consumer_instance_description', false);
return ( $product == 'ims' && $tci_description == 'Coursera');
} | Indicate if this launch came from Coursera |
public function newLaunch($send_name=true, $send_email=true) {
$parms = array(
'lti_message_type' => 'basic-lti-launch-request',
'tool_consumer_info_product_family_code' => 'tsugi',
'tool_consumer_info_version' => '1.1',
);
// Some Tsugi Goodness
$form_id = "tsugi_form_id_".bin2Hex(openssl_random_pseudo_bytes(4));
$parms['ext_lti_form_id'] = $form_id;
if ( $this->user ) {
$parms['user_id'] = $this->user->id;
$parms['roles'] = $this->user->instructor ? 'Instructor' : 'Learner';
if ( $send_name ) $parms['lis_person_name_full'] = $this->user->displayname;
if ( $send_email ) $parms['lis_person_contact_email_primary'] = $this->user->email;
if ( $send_email || $send_email ) $parms['image'] = $this->user->image;
}
if ( $this->context ) {
$parms['context_id'] = $this->context->id;
$parms['context_title'] = $this->context->title;
$parms['context_label'] = $this->context->title;
}
if ( $this->link ) {
$parms['resource_link_id'] = $this->link->id;
$parms['resource_link_title'] = $this->link->title;
}
if ( $this->result ) {
$parms['resource_link_id'] = $this->link->id;
$parms['resource_link_title'] = $this->link->title;
}
foreach ( $parms as $k => $v ) {
if ( $v === false || $v === null ) unset($parms[$k]);
}
return $parms;
} | set up parameters for an outbound launch from this launch |
public function createUser($email)
{
$contents = $this
->call('POST', self::USERS_RESOURCE, ['json' => [
'email' => $email,
]], false)
->getBody()
->getContents()
;
return UserModel::createFromJsonResponse($contents);
} | Create a user.
@param string $email Email
@throws GuzzleException
@throws \RuntimeException
@return UserModel |
public function getCurrentUserId()
{
$contents = $this
->call('GET', self::USER_RESOURCE)
->getBody()
->getContents();
$json = json_decode($contents, true);
return $json['user_id'];
} | Get current user.
@since 1.7.0
@throws GuzzleException
@throws \RuntimeException
@return string |
public function createOrganization($name, $billingMail, $displayName = '')
{
$options = ['json' => [
'billing_email' => $billingMail,
]];
if (!empty($displayName)) {
$options['json']['display_name'] = $displayName;
}
$contents = $this
->call('PUT', self::ORGANIZATION_RESOURCE.'/'.$name, $options)
->getBody()
->getContents()
;
return Organization::createFromJsonResponse($contents);
} | Create an organization.
@param string $name Organization name
@param string $billingMail Billing mail
@param string $displayName Optional display name
@throws GuzzleException
@throws \RuntimeException
@return Organization |
public function getOrganization($organization = '')
{
$contents = $this
->call('GET', self::ORGANIZATION_RESOURCE.'/'.$this->getOrganizationName($organization))
->getBody()
->getContents()
;
return Organization::createFromJsonResponse($contents);
} | Return an organization.
@since 1.7.0
@param string $organization Organization name
@throws GuzzleException
@throws \RuntimeException
@return Organization |
public function createMembership($userId, $roles = [Membership::ROLE_READ], $organization = '')
{
if (\is_string($roles)) {
$roles = [$roles];
}
$roles = array_map(function ($role) {
return strtolower($role);
}, $roles);
$contents = $this
->call('PUT', implode('/', [self::ORGANIZATION_RESOURCE, $this->getOrganizationName($organization), 'memberships', $userId]), ['json' => [
'roles' => $roles,
]])
->getBody()
->getContents();
// get the membership, if it already exists
if (empty($contents)) {
return $this->getMembership($userId, $this->getOrganizationName($organization));
}
return $this->getSingleMemberShipFromJsonResponse($contents);
} | Create a membership.
@since 1.7.0
@param string $organization Organization
@param string $userId User ID
@param string|array $roles Role to add
@throws GuzzleException
@throws \RuntimeException
@return Membership |
public function createUserAndMembership($roles = [Membership::ROLE_READ], $organization = '')
{
if (\is_string($roles)) {
$roles = [$roles];
}
$roles = array_map(function ($role) {
return strtolower($role);
}, $roles);
$contents = $this
->call('POST',
implode('/', [self::ORGANIZATION_RESOURCE, $this->getOrganizationName($organization), 'memberships']),
['json' => [
'roles' => $roles,
]])
->getBody()
->getContents();
return $this->getSingleMemberShipFromJsonResponse($contents);
} | Create a user and membership associated to this organization.
@since 1.7.0
@param string $organization Organization
@param string|array $roles Role to add
@throws GuzzleException
@throws \RuntimeException
@return Membership |
public function getMembership($userId, $organization = '')
{
$contents = $this
->call('GET', implode('/', [self::ORGANIZATION_RESOURCE, $this->getOrganizationName($organization), 'memberships', $userId]))
->getBody()
->getContents();
return $this->getSingleMemberShipFromJsonResponse($contents);
} | Get the membership metadata for the given organization and user's ID.
@since 1.7.0
@param string $organization Organization
@param string $userId User ID
@throws GuzzleException
@throws \RuntimeException
@return Membership |
public function deleteMembership($userId, $organization = '')
{
try {
$response = $this
->call('DELETE', implode('/', [self::ORGANIZATION_RESOURCE, $this->getOrganizationName($organization), 'memberships', $userId]));
} catch (GuzzleException $e) {
if (404 == $e->getCode()) {
return false;
}
throw $e;
}
return '204' == $response->getStatusCode();
} | Deletes a membership for the given organization and user's ID.
@since 1.7.0
@param string $organization Organization
@param string $userId User ID
@throws GuzzleException
@throws \RuntimeException
@return bool |
public function listMemberships($organization = '')
{
$contents = $this
->call('GET', implode('/', [self::ORGANIZATION_RESOURCE, $this->getOrganizationName($organization), 'memberships']))
->getBody()
->getContents()
;
$membership = Membership::createFromJsonResponse($contents);
if (!\is_array($membership)) {
throw new \RuntimeException('Something went wrong, return was not array, but should be');
}
return $membership;
} | List the membership metadata for the given organization.
@since 1.7.0
@param string $organization Organization
@throws GuzzleException
@throws \RuntimeException
@return Membership[] |
private function getSingleMemberShipFromJsonResponse($jsonString)
{
$membership = Membership::createFromJsonResponse($jsonString);
if (\is_array($membership)) {
throw new \RuntimeException("Something went wrong, return was an array, but shouldn't be");
}
return $membership;
} | @param string $jsonString
@throws \RuntimeException
@return Membership |
public function render(ResourceObject $ro)
{
if (! array_key_exists('content-type', $ro->headers)) {
$ro->headers['content-type'] = 'application/json';
}
$ro->view = json_encode($ro);
$e = json_last_error();
if ($e) {
// @codeCoverageIgnoreStart
error_log('json_encode error: ' . json_last_error_msg() . ' in ' . __METHOD__);
return '';
// @codeCoverageIgnoreEnd
}
return $ro->view;
} | {@inheritdoc} |
public function get()
{
$schemeCollection = (new SchemeCollectionProvider($this->appName, $this->injector))->get();
foreach ($this->importAppConfig as $importApp) {
/* @var \BEAR\Resource\ImportApp */
$injector = class_exists(AppInjector::class) ? new AppInjector($importApp->appName, $importApp->context) : $this->injector;
$adapter = new AppAdapter($injector, $importApp->appName);
$schemeCollection
->scheme('page')->host($importApp->host)->toAdapter($adapter)
->scheme('app')->host($importApp->host)->toAdapter($adapter);
}
return $schemeCollection;
} | {@inheritdoc}
@return \BEAR\Resource\SchemeCollection |
public function getJson()
{
global $CFG, $PDOX;
$row = $PDOX->rowDie("SELECT json FROM {$CFG->dbprefix}{$this->TABLE_NAME}
WHERE $this->PRIMARY_KEY = :PK",
array(":PK" => $this->id));
if ( $row === false ) return false;
$json = $row['json'];
if ( $json === null ) return false;
return $json;
} | Load the json field for this entity
@return string This returns the json string - it is not parsed - if there is
nothing to return - this returns "false" |
public function getJsonKey($key,$default=false)
{
global $CFG, $PDOX;
$jsonStr = $this->getJson();
if ( ! $jsonStr ) return $default;
$json = json_decode($jsonStr, true);
if ( ! $json ) return $default;
return U::get($json, $key, $default);
} | Get a JSON key for this entity
@params $key The key to be retrieved from the JSON
@params $default The default value (optional) |
public function setJson($json)
{
global $CFG, $PDOX;
$q = $PDOX->queryDie("UPDATE {$CFG->dbprefix}{$this->TABLE_NAME}
SET json = :SET WHERE $this->PRIMARY_KEY = :PK",
array(":SET" => $json, ":PK" => $this->id)
);
} | Set the JSON entry for this entity
@params $json This is a string - no validation is done |
public function setJsonKey($key,$value)
{
global $CFG, $PDOX;
$old = $this->getJson();
$old_json = json_decode($old);
if ( $old_json == null ) $old_json = new \stdClass();
$old_json->{$key} = $value;
$new = json_encode($old_json);
$this->setJson($new);
} | Set/update a JSON key for this entity
@params $key The key to be inserted/updated in the JSON
@params $value The value to be inserted/updated in the JSON |
public function setJsonKeys($values)
{
global $CFG, $PDOX;
if ( ! is_array($values) ) throw new \Exception('setJsonKeys requires an array as parameter.');
$old = $this->getJson();
$old_json = json_decode($old);
if ( $old_json == null ) $old_json = new \stdClass();
foreach($values as $key => $value) {
$old_json->{$key} = $value;
}
$new = json_encode($old_json);
$this->setJson($new);
} | Set/update an array of JSON keys for this entity
@params $values An array of key/value pairs to be inserted/updated in the JSON |
public function setProcessedEventIds($var)
{
$arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::BYTES);
$this->processed_event_ids = $arr;
return $this;
} | Generated from protobuf field <code>repeated bytes processed_event_ids = 2;</code>
@param string[]|\Google\Protobuf\Internal\RepeatedField $var
@return $this |
public function setAction($var)
{
GPBUtil::checkEnum($var, \Rxnet\EventStore\Data\PersistentSubscriptionNakEvents_NakAction::class);
$this->action = $var;
return $this;
} | Generated from protobuf field <code>.Rxnet.EventStore.Data.PersistentSubscriptionNakEvents.NakAction action = 4;</code>
@param int $var
@return $this |
public function get(AbstractUri $uri) : ResourceObject
{
if (substr($uri->path, -1) === '/') {
$uri->path .= 'index';
}
$path = str_replace('-', '', ucwords($uri->path, '/-'));
$class = sprintf('%s%s\Resource\%s', $this->namespace, $this->path, str_replace('/', '\\', ucwords($uri->scheme) . $path));
try {
$instance = $this->injector->getInstance($class);
} catch (Unbound $e) {
throw $this->getNotFound($uri, $e, $class);
}
return $instance;
} | {@inheritdoc}
@throws ResourceNotFoundException
@throws \Ray\Di\Exception\Unbound |
public static function getImageClient($organization, $apiKey, $options = [])
{
$baseUrl = BaseClient::DEFAULT_API_BASE_URL;
if (!\is_array($options)) { // $options was introduced later, if that is an array, we're on the new sig, nothing to change
if (\func_num_args() > 3) { // if more than 3 args, the 4th is the baseUrl
$baseUrl = func_get_arg(3);
} elseif (3 === \func_num_args()) { // if exactly 3 args
//if $baseUrl doesn't start with http, it may be a secret from the old signature, remove that, it's not used anymore
if ('http' !== substr($options, 0, 4)) {
$baseUrl = BaseClient::DEFAULT_API_BASE_URL;
} else {
$baseUrl = $options;
}
}
$options = [];
} else {
if (isset($options[self::API_BASE_URL])) {
$baseUrl = $options[self::API_BASE_URL];
}
}
$client = self::getGuzzleClient($baseUrl, $options);
return new ImageClient($client, $organization, $apiKey);
} | Return an image client.
@param string $organization Organization name
@param string $apiKey API key
@param array|string $options Options like api_base_url or proxy
@throws \RuntimeException
@return Image |
public static function getUserClient($organization = null, $apiKey = null, $options = [])
{
$baseUrl = BaseClient::DEFAULT_API_BASE_URL;
//bc compability, when first param was $options
if (\is_array($organization)) {
$options = $organization;
$organization = null;
$apiKey = null;
}
if (isset($options[self::API_BASE_URL])) {
$baseUrl = $options[self::API_BASE_URL];
}
$client = self::getGuzzleClient($baseUrl, $options);
return new UserClient($client, $organization, $apiKey);
} | Return a user client.
@param string|null|array $organization
@param string|null $apiKey API key
@param array $options Options like api_base_url or proxy
@throws \RuntimeException
@return UserClient |
private static function getGuzzleClient($baseUrl, $options = [])
{
$guzzleOptions = [];
if (isset($options[self::PROXY])) {
$guzzleOptions[self::PROXY] = $options[self::PROXY];
}
if (isset($options[self::GUZZLE_OPTIONS])) {
$guzzleOptions = array_merge($guzzleOptions, $options[self::GUZZLE_OPTIONS]);
}
$handlerStack = HandlerStack::create();
$handlerStack->unshift(Middleware::retry(self::retryDecider(), self::retryDelay()));
$options = array_merge(['base_uri' => $baseUrl, 'handler' => $handlerStack], $guzzleOptions);
return new GuzzleClient($options);
} | Returns a Guzzle client with a retry middleware.
@param string $baseUrl base url
@param array $options
@throws \RuntimeException
@return GuzzleClient GuzzleClient to connect to the backend |
private static function retryDecider()
{
return function (
$retries,
Request $request,
Response $response = null,
RequestException $exception = null
) {
// Limit the number of retries to 10
if ($retries >= 10) {
return false;
}
// Retry connection exceptions
if ($exception instanceof ConnectException) {
return true;
}
if ($response) {
// Retry on server errors or overload
$statusCode = $response->getStatusCode();
if (429 == $statusCode || 504 == $statusCode || 503 == $statusCode || 502 == $statusCode) {
return true;
}
}
return false;
};
} | Returns a Closure for the Retry Middleware to decide if it should retry the request when it failed.
@return \Closure |
public static function returnUrl($postdata=false) {
if ( ! $postdata ) $postdata = LTIX::ltiRawPostArray();
return parent::returnUrl($postdata);
} | returnUrl - Returns the content_item_return_url
@return string The content_item_return_url or false |
public static function allowLtiLinkItem($postdata=false) {
if ( ! $postdata ) $postdata = LTIX::ltiRawPostArray();
return parent::allowLtiLinkItem($postdata);
} | allowLtiLinkItem - Returns true if we can return LTI Link Items |
public static function allowContentItem($postdata=false) {
if ( ! $postdata ) $postdata = LTIX::ltiRawPostArray();
return parent::allowContentItem($postdata);
} | allowContentItem - Returns true if we can return HTML Items |
public static function allowImportItem($postdata=false) {
if ( ! $postdata ) $postdata = LTIX::ltiRawPostArray();
return parent::allowImportItem($postdata);
} | allowImportItem - Returns true if we can return Common Cartridges |
function getContentItemSelection($data=false)
{
if ( ! $data ) $data = LTIX::ltiRawParameter('data');
return parent::getContentItemSelection($data);
} | Return the parameters to send back to the LMS |
function prepareResponse($endform=false) {
$return_url = $this->returnUrl();
$parms = $this->getContentItemSelection();
$parms = LTIX::signParameters($parms, $return_url, "POST", "Install Content");
$endform = '<a href="index.php" class="btn btn-warning">Back to Store</a>';
$content = LTI::postLaunchHTML($parms, $return_url, true, false, $endform);
return $content;
} | Make up a response
@param $endform Some HTML to be included before the form closing tag
$endform = '<a href="index.php" class="btn btn-warning">Back to Store</a>'; |
public static function button($right = false)
{
global $LINK;
if ( $right ) echo('<span style="position: fixed; right: 10px; top: 5px;">');
echo('<button onclick="showModal(\''.__('Analytics').' '.htmlentities($LINK->title).'\',\'analytics_div\'); return false;" type="button" class="btn btn-default">');
echo('<span class="glyphicon glyphicon-signal"></span></button>'."\n");
if ( $right ) echo('</span>');
} | Emit a properly styled "settings" button
This is just the button, using the pencil icon. Wrap in a
span or div tag if you want to move it around |
public static function templateInclude($name) {
if ( is_array($name) ) {
foreach($name as $n) {
self::templateInclude($n);
}
return;
}
echo('<script id="script-template-'.$name.'" type="text/x-handlebars-template">'."\n");
$template = file_get_contents('templates/'.$name.'.hbs');
echo(self::templateProcess($template));
echo("</script>\n");
} | templateInclude - Include a handlebars template, dealing with i18n
This is a normal handlebars template except we can ask for a translation
of text as follows:
...
{{__ 'Hello world' }}
...
The i18n replacement will be handled in the server in the template. Single
or Double quotes can be used. |
public static function templateProcess($template) {
$new = preg_replace_callback(
'|{{__ *\'([^\']*)\' *}}|',
function ($matches) {
return __(htmlent_utf8(trim($matches[1])));
},
$template
);
$new = preg_replace_callback(
'|{{__ *"([^"]*)" *}}|',
function ($matches) {
return __(htmlent_utf8(trim($matches[1])));
},
$new
);
$new = preg_replace_callback(
'|{{>> *([^ ]*) *}}|',
function ($matches) {
$name = 'templates/'.trim($matches[1]);
if ( file_exists($name) ) {
return file_get_contents($name);
}
return "Unable to open $name";
},
$new
);
return $new;
} | templateProcess - Process a handlebars template, dealing with i18n
This is a normal handlebars template except we can ask for a translation
of text as follows:
...
{{__ 'Hello world' }}
...
The i18n replacement will be handled in the server in the template. Single
or double quotes can be used. |
public static function createFromJsonResponse($jsonString)
{
$data = json_decode($jsonString, true);
if (\is_array($data) && isset($data['items'])) {
return array_map(function ($membership) {
return self::getObjectFromArray($membership);
}, $data['items']);
}
return self::getObjectFromArray($data);
} | Create a user from the JSON data returned by the rokka.io API.
@param string $jsonString JSON as a string
@return Membership|Membership[] |
private static function getObjectFromArray($data): self
{
if (!isset($data['last_access'])) {
$lastAccess = null;
} else {
$lastAccess = new \DateTime($data['last_access']);
}
return new self(
$data['user_id'],
$data['organization_id'],
$data['roles'],
$data['active'],
$lastAccess
);
} | @param array $data
@return Membership |
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);
$object = new self();
$object->x = $data['x'];
$object->y = $data['y'];
$object->width = $data['width'];
$object->height = $data['height'];
return $object;
} | Create a SubjectArea from the decoded JSON data.
@param array $data Decoded JSON data
@return self |
public static function isRequestCheck($request_data=false) {
if ( $request_data === false ) $request_data = $_REQUEST;
if ( !isset($request_data["lti_message_type"]) ) return false;
if ( !isset($request_data["lti_version"]) ) return false;
$good_lti_version = self::isValidVersion($request_data["lti_version"]);
if ( ! $good_lti_version ) return "Invalid LTI version ".$request_data["lti_version"];
$good_message_type = self::isValidMessageType($request_data["lti_message_type"]);
if ( ! $good_message_type ) return "Invalid message type ".$request_data["lti_message_type"];
return true;
} | Determines if this is a valid Basic LTI message
@retval mixed Returns true if this is a Basic LTI message
with minimum values to meet the protocol. Returns false
if this is not even close to an LTI launch. If this is a
broken launch, it returns an error as to why. |
public static function verifyKeyAndSecret($key, $secret, $http_url=NULL, $parameters=null, $http_method=NULL) {
global $LastOAuthBodyBaseString;
if ( ! ($key && $secret) ) return array("Missing key or secret", "");
$store = new TrivialOAuthDataStore();
$store->add_consumer($key, $secret);
$server = new OAuthServer($store);
$method = new OAuthSignatureMethod_HMAC_SHA1();
$server->add_signature_method($method);
$method = new OAuthSignatureMethod_HMAC_SHA256();
$server->add_signature_method($method);
$request = OAuthRequest::from_request($http_method, $http_url, $parameters);
$LastOAuthBodyBaseString = $request->get_signature_base_string();
try {
$server->verify_request($request);
return true;
} catch (\Exception $e) {
return array($e->getMessage(), $LastOAuthBodyBaseString);
}
} | Verify the message signature for this request
@return mixed This returns true if the request verified. If the request did not verify,
this returns an array with the first element as an error string, and the second element
as the base string of the request. |
public static function sendJSONGrade($grade, $comment, $result_url, $key_key, $secret, &$debug_log=false, $signature=false) {
global $LastJSONGradeResponse;
$LastJSONGradeResponse = false;
$content_type = "application/vnd.ims.lis.v2.result+json";
if ( is_array($debug_log) ) $debug_log[] = array('Sending '.$grade.' to result_url='.$result_url);
$addStructureRequest = self::getResultJSON($grade, $comment);
$postBody = self::jsonIndent(json_encode($addStructureRequest));
if ( is_array($debug_log) ) $debug_log[] = array('Grade JSON Request',$postBody);
$more_headers = false;
$response = self::sendOAuthBody("PUT", $result_url, $key_key,
$secret, $content_type, $postBody, $more_headers, $signature);
if ( is_array($debug_log) ) $debug_log[] = array('Grade JSON Response',$response);
global $LastOAuthBodyBaseString;
$lbs = $LastOAuthBodyBaseString;
if ( is_array($debug_log) ) $debug_log[] = array('Our base string',$lbs);
// TODO: Be smarter about this :)
return true;
} | Send a grade using the JSON protocol from IMS LTI 2.x
@param debug_log This can either be false or an empty array. If
this is an array, it is filled with data as the steps progress.
Each step is an array with a string message as the first element
and optional debug detail (i.e. like a post body) as the second
element.
@return mixed If things go well this returns true.
If this goes badly, this returns a string with an error message. |
public static function sendJSONSettings($settings, $settings_url, $key_key, $secret, &$debug_log=false, $signature=false) {
$content_type = "application/vnd.ims.lti.v2.toolsettings.simple+json";
if ( is_array($debug_log) ) $debug_log[] = array('Sending '.count($settings).' settings to settings_url='.$settings_url);
// Make sure everything is a string
$sendsettings = array();
foreach ( $settings as $k => $v ) {
$sendsettings[$k] = "".$v;
}
$postBody = self::jsonIndent(json_encode($sendsettings));
if ( is_array($debug_log) ) $debug_log[] = array('Settings JSON Request',$postBody);
$more_headers = false;
$response = self::sendOAuthBody("PUT", $settings_url, $key_key,
$secret, $content_type, $postBody, $more_headers, $signature);
if ( is_array($debug_log) ) $debug_log[] = array('Settings JSON Response',$response);
global $LastOAuthBodyBaseString;
$lbs = $LastOAuthBodyBaseString;
if ( is_array($debug_log) ) $debug_log[] = array('Our base string',$lbs);
// TODO: Be better at error checking...
return true;
} | Send setings data using the JSON protocol from IMS LTI 2.x
@param debug_log This can either be false or an empty array. If
this is an array, it is filled with data as the steps progress.
Each step is an array with a string message as the first element
and optional debug detail (i.e. like a post body) as the second
element.
@return mixed If things go well this returns true.
If this goes badly, this returns a string with an error message. |
public static function sendJSONBody($method, $postBody, $content_type,
$rest_url, $key_key, $secret, &$debug_log=false, $signature=false)
{
if ( is_array($debug_log) ) $debug_log[] = array('Sending '.strlen($postBody).' bytes to rest_url='.$rest_url);
$more_headers = false;
$response = self::sendOAuthBody($method, $rest_url, $key_key,
$secret, $content_type, $postBody);
if ( is_array($debug_log) ) $debug_log[] = array('Caliper JSON Response',$response);
global $LastOAuthBodyBaseString;
$lbs = $LastOAuthBodyBaseString;
if ( is_array($debug_log) ) $debug_log[] = array('Our base string',$lbs);
return true;
} | Send a JSON body LTI 2.x Style
@param debug_log This can either be false or an empty array. If
this is an array, it is filled with data as the steps progress.
Each step is an array with a string message as the first element
and optional debug detail (i.e. like a post body) as the second
element.
@return mixed If things go well this returns true.
If this goes badly, this returns a string with an error message. |
public static function ltiLinkUrl($postdata=false) {
if ( $postdata === false ) $postData = $_POST;
if ( ! isset($postdata['content_item_return_url']) ) return false;
if ( isset($postdata['accept_media_types']) ) {
$ltilink_mimetype = 'application/vnd.ims.lti.v1.ltilink';
$m = new Mimeparse;
$ltilink_allowed = $m->best_match(array($ltilink_mimetype), $postdata['accept_media_types']);
if ( $ltilink_mimetype != $ltilink_allowed ) return false;
return $postdata['content_item_return_url'];
}
return false;
} | ltiLinkUrl - Returns true if we can return LTI Links for this launch
IMS Public Draft: http://www.imsglobal.org/specs/lticiv1p0
@return string The content_item_return_url or false |
public static function validateUpload($FILE_DESCRIPTOR, $SAFETY_CHECK=true)
{
$retval = true;
$filename = isset($FILE_DESCRIPTOR['name']) ? basename($FILE_DESCRIPTOR['name']) : false;
if ( $FILE_DESCRIPTOR['error'] == 1) {
$retval = _m("General upload failure");
} else if ( $FILE_DESCRIPTOR['error'] == 4) {
$retval = _m('Missing file, make sure to select file(s) before pressing submit');
} else if ( $filename === false ) {
$retval = _m("Uploaded file has no name");
} else if ( $FILE_DESCRIPTOR['size'] < 1 ) {
$retval = _m("File is empty: ").$filename;
} else if ( $FILE_DESCRIPTOR['error'] == 0 ) {
if ( $SAFETY_CHECK && preg_match(self::BAD_FILE_SUFFIXES, $filename) ) $retval = _m("File suffix not allowed");
} else {
$retval = _m("Upload failure=").$FILE_DESCRIPTOR['error'];
}
return $retval;
} | Returns true if this is a good upload, an error string if not |
public static function isPngOrJpeg($FILE_DESCRIPTOR)
{
if ( !isset($FILE_DESCRIPTOR['name']) ) return false;
if ( !isset($FILE_DESCRIPTOR['tmp_name']) ) return false;
$info = getimagesize($FILE_DESCRIPTOR['tmp_name']);
if ( ! is_array($info) ) return false;
$image_type = $info[2];
return $image_type == IMAGETYPE_JPEG || $image_type == IMAGETYPE_PNG;
} | Make sure the contents of this file are a PNG or JPEG |
public static function uploadToBlob($FILE_DESCRIPTOR, $SAFETY_CHECK=true)
{
$retval = self::uploadFileToBlob($FILE_DESCRIPTOR, $SAFETY_CHECK);
if ( is_array($retval) ) $retval = $retval[0];
return $retval;
} | uploadToBlob - returns blob_id or false
Returns false for any number of failures, for better detail, use
validateUpload() before calling this to do the actual upload. |
public static function getAccessUrlForBlob($blob_id, $serv_file=false)
{
global $CFG;
if ( $serv_file !== false ) return $serv_file . '?id='.$blob_id;
$url = Output::getUtilUrl('/blob_serve.php?id='.$blob_id);
return $url;
} | control checks |
public static function maxUpload() {
$maxUpload = (int)(ini_get('upload_max_filesize'));
$max_post = (int)(ini_get('post_max_size'));
$memory_limit = (int)(ini_get('memory_limit'));
$upload_mb = min($maxUpload, $max_post, $memory_limit);
return $upload_mb;
} | /* See also the .htaccess file. Many MySQL servers are configured to have a max size of a
blob as 1MB. if you change the .htaccess you need to change the mysql configuration as well.
this may not be possible on a low-cst provider. |
public static function migrate($file_id, $test_key=false)
{
global $CFG, $PDOX;
$retval = false;
// Check to see where we are moving to...
if ( isset($CFG->dataroot) && strlen($CFG->dataroot) > 0 ) {
if ( ! $test_key ) {
$retval = self::blob2file($file_id);
}
} else {
$retval = self::blob2blob($file_id);
}
return $retval;
} | Check and migrate a blob from an old place to the right new place
@return mixed true if the file was migrated, false if the file
was not migrated, and a string if an error was enountered |
public function handle()
{
$basePath = $this->getMigrationPath();
$migrations = $this->migrator->getMigrationFiles($basePath, false);
$count = count($migrations);
if ($count == 0) {
$this->comment('No migrations to move');
return;
}
foreach ($migrations as $migration_name => $migration_path) {
$datePath = $this->migrator->getDateFolderStructure($migration_name);
// Create folder if it does not already exist
if (! $this->files->exists($basePath.'/'.$datePath)) {
$this->files->makeDirectory($basePath.'/'.$datePath, 0775, true);
}
// Move the migration into its new folder
$this->files->move($basePath.'/'.$migration_name.'.php', $basePath.'/'.$datePath.$migration_name.'.php');
}
$this->info('Migrations organised successfully ('.$count.' migrations moved)');
} | Create date folder structure and move migrations into.
@return void |
public static function pushCaliperEvents($seconds=3, $max=100, $debug=false) {
// Remove broken events
$purged = self::purgeCaliperEvents();
$start = time();
$count = 0;
$now = $start;
$end = $start + $seconds;
$failure = 0;
$failure_code = false;
$retval = array();
if ( U::apcAvailable() ) {
$found = false;
$last_push = apc_fetch('last_event_push_time',$found);
$diff = $start - $last_push;
if ( $found && $diff < self::PUSH_REPEAT_SECONDS ) {
// error_log("Last push was $diff seconds ago");
$retval['count'] = $count;
$retval['fail'] = $failure;
$retval['failcode'] = 999;
$retval['seconds'] = 0;
$retval['purged'] = $purged;
return $retval;
}
apc_store('last_event_push_time',$start);
}
while ($count < $max && $now < $end ) {
$result = self::sendCaliperEvent(!$debug);
if ( $debug ) {
echo("\nResults of sendCaliperEvent:\n");
echo(U::safe_var_dump($result));
}
if ( $result === false ) break;
if ( $result['code'] != 200 ) {
$failure++;
if ( $failure_code === false ) $failure_code = $result['code'];
}
$count++;
$now = time();
$delta = $now - $start;
}
$now = time();
$delta = $now - $start;
$retval['count'] = $count;
$retval['fail'] = $failure;
if ( $failure_code !== false ) $retval['failcode'] = $failure_code;
$retval['seconds'] = $delta;
$retval['purged'] = $purged;
return $retval;
} | Send the backlog of caliper events, but don't overrun |
public static function purgeCaliperEvents() {
global $CFG;
// We really want some quiet time...
if ( U::apcAvailable() ) {
$push_found = false;
$last_push = apc_fetch('last_event_push_time',$push_found);
$push_diff = time() - $last_push;
$purge_found = false;
$last_purge = apc_fetch('last_event_purge_time',$purge_found);
$purge_diff = time() - $last_purge;
if ( ($push_found && $push_diff < self::PUSH_REPEAT_SECONDS) ||
($purge_found && $purge_diff < self::PURGE_REPEAT_SECONDS) ) {
// error_log("Last purge was $purge_diff seconds ago last push was $push_diff seconds ago");
return 0;
}
apc_store('last_event_purge_time', time());
} else { // purge probabilistically
$check = isset($CFG->eventcheck) ? $CFG->eventcheck : 1000;
if ( $check < 1 ) $check = 1000;
if ( time() % $check !== 0 ) return 0;
}
$eventtime = isset($CFG->eventtime) ? $CFG->eventtime : 24*60*60; // one day
$PDOX = LTIX::getConnection();
$stmt = $PDOX->queryDie("DELETE FROM {$CFG->dbprefix}cal_event WHERE
created_at < DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL -{$eventtime} SECOND)");
if ( $stmt->rowCount() > 0 ) {
error_log("Event table cleanup rows=".$stmt->rowCount());
}
return $stmt->rowCount();
} | Periodic cleanup of broken Caliper events
This is needed when an lti_key has Caliper turned on for a while
and then later turns it off - the non-pushed events are stranded
since they no longer have a good caliper_url / caliper_key. So
once in a great while, we clean these up. |
public function startsWith($needle) {
// search backwards starting from haystack length characters from the end
return $needle === "" || strrpos($this->internal, $needle, -strlen($this->internal)) !== FALSE;
} | http://stackoverflow.com/questions/834303/startswith-and-endswith-public static functions-in-php |
public function slice($start=0, $end=-1) {
if ( $end == -1 ) return substr($this->internal, $start);
$len = $end - $start - 1;
return substr($this->internal, $start, $len);
} | TODO: handle negatives other than -1 |
protected function heartbeat(): DisposableInterface
{
return $this->readBuffer
->timeout($this->heartBeatRate)
->filter(
function (SocketMessage $message) {
return $message->getMessageType()->getType() === MessageType::HEARTBEAT_REQUEST_COMMAND;
}
)
->subscribe(
new CallbackObserver(
function (SocketMessage $message) {
$this->writer->composeAndWrite(MessageType::HEARTBEAT_RESPONSE_COMMAND, null, $message->getCorrelationID());
},
[$this->connectionSubject, 'onError']
)
);
} | Intercept heartbeat message and answer automatically |
public function catchUpSubscription(
string $streamId,
int $startFrom = self::POSITION_START,
bool $resolveLink = false
): Observable {
return $this->readEventsForward($streamId, $startFrom, self::DEFAULT_MAX_EVENTS, $resolveLink)
->concat($this->volatileSubscription($streamId, $resolveLink));
} | This kind of subscription specifies a starting point, in the form of an event number
or transaction file position.
The given function will be called for events from the starting point until the end of the stream,
and then for subsequently written events.
For example, if a starting point of 50 is specified when a stream has 100 events in it,
the subscriber can expect to see events 51 through 100, and then any events subsequently
written until such time as the subscription is dropped or closed.
@throws \Exception |
public function volatileSubscription(string $streamId, bool $resolveLink = false): Observable
{
$event = new SubscribeToStream();
$event->setEventStreamId($streamId);
$event->setResolveLinkTos($resolveLink);
return Observable::create(function (ObserverInterface $observer) use ($event) {
$correlationID = $this->writer->createUUIDIfNeeded();
$this->writer
->composeAndWrite(
MessageType::SUBSCRIBE_TO_STREAM,
$event,
$correlationID
)
// When written wait for all responses
->merge(
$this->readBuffer
->filter(
function (SocketMessage $message) use ($correlationID) {
// Use same correlationID to pass by this filter
return $message->getCorrelationID() == $correlationID;
}
)
)
->flatMap(
function (SocketMessage $message) {
$data = $message->getData();
if (!$data) {
throw new \RuntimeException('Data should not be null in volatile subscription');
}
switch (get_class($data)) {
case SubscriptionDropped::class:
return Observable::error(new \Exception("Subscription dropped, for reason : {$data->getReason()}"));
case SubscriptionConfirmation::class:
return Observable::empty();
default:
return Observable::of($data);
}
}
)
->map(
function (StreamEventAppeared $eventAppeared) {
$record = $eventAppeared->getEvent()->getEvent();
/* @var \Rxnet\EventStore\Data\EventRecord $record */
return EventRecordFactory::fromEventRecord($record);
}
)
->subscribe($observer);
return new CallbackDisposable(function () {
$event = new UnsubscribeFromStream();
$this->writer->composeAndWrite(
MessageType::UNSUBSCRIBE_FROM_STREAM,
$event
);
});
});
} | This kind of subscription calls a given function for events written after
the subscription is established.
For example, if a stream has 100 events in it when a subscriber connects,
the subscriber can expect to see event number 101 onwards until the time
the subscription is closed or dropped. |
public function getAreasByName($name)
{
if (!isset($this->areas[$name])) {
return null;
}
return $this->areas[$name];
} | Gets an array of Areas with a specific name.
@param string $name The area name to look up
@return DynamicMetadataInterface[]|null |
public function getFirstAreaByName($name)
{
if (!isset($this->areas[$name])) {
return null;
}
if (!isset($this->areas[$name][0])) {
return null;
}
return $this->areas[$name][0];
} | Gets the first Area with a specific name (all others have no meaning currently).
@param string $name The area name to look up
@return DynamicMetadataInterface|null |
public static function createFromDecodedJsonResponse($data)
{
$areas = [];
foreach ($data as $name => $area) {
$areas[$name] = [];
foreach ($area as $class => $data) {
$metaClass = DynamicMetadataHelper::getDynamicMetadataClassName($class);
/* @var DynamicMetadataInterface $metaClass */
$areas[$name][] = $metaClass::createFromDecodedJsonResponse($data);
}
}
return new self($areas);
} | Create a DynamicMetadata from the decoded JSON data.
@param array $data Decoded JSON data
@return DynamicMetadataInterface |
public static function loadLinkInfo($link_id)
{
global $CFG, $PDOX, $CONTEXT;
$cacheloc = 'lti_link';
$row = Cache::check($cacheloc, $link_id);
if ( $row != false ) return $row;
$stmt = $PDOX->queryDie(
"SELECT title FROM {$CFG->dbprefix}lti_link
WHERE link_id = :LID AND context_id = :CID",
array(":LID" => $link_id, ":CID" => $CONTEXT->id)
);
$row = $stmt->fetch(\PDO::FETCH_ASSOC);
Cache::set($cacheloc, $link_id, $row);
return $row;
} | Load link information for a different link than current
Make sure not to cross Context silos.
Returns a row or false. |
public function getPlacementSecret()
{
global $CFG;
$PDOX = $this->launch->pdox;
$stmt = $PDOX->queryDie(
"SELECT placementsecret FROM {$CFG->dbprefix}lti_link
WHERE link_id = :LID",
array(':LID' => $this->id)
);
$row = $stmt->fetch(\PDO::FETCH_ASSOC);
$placementsecret = $row['placementsecret'];
if ( $placementsecret) return $placementsecret;
// Set the placement secret
$placementsecret = bin2Hex(openssl_random_pseudo_bytes(32));
$stmt = $PDOX->queryDie(
"UPDATE {$CFG->dbprefix}lti_link SET placementsecret=:PC
WHERE link_id = :LID",
array(':LID' => $this->id,
':PC' => $placementsecret
)
);
return $placementsecret;
} | Get the placement secret for this Link |
public function returnUrl() {
if ( ! isset($this->claim) ) return false;
return isset($this->claim->deep_link_return_url) ? $this->claim->deep_link_return_url : false;
} | returnUrl - Returns the deep_link_return_url
@return string The deep_link_return_url or false |
public function allowMimetype($Mimetype) {
if ( ! $this->returnUrl() ) return false;
if ( isset($this->claim->accept_media_types) ) {
$ma = $Mimetype;
if ( ! is_array($ma) ) $ma = array($Mimetype);
$m = new Mimeparse;
$allowed = $m->best_match($ma, $this->claim->accept_media_types);
if ( $Mimetype != $allowed ) return false;
return true;
}
return false;
} | allowMimetype - Returns true if we can return LTI Link Items |
public function acceptType($type) {
if ( ! isset($this->claim->accept_types) ) return false;
if ( ! is_array($this->claim->accept_types) ) return false;
return in_array($type, $this->claim->accept_types);
} | acceptType - Returns true if the string is in the accept_types
"accept_types": ["link", "file", "html", "ltiResourceLink", "image"], |
public function allowImportItem() {
$cc_types = array('application/vnd.ims.imsccv1p1',
'application/vnd.ims.imsccv1p2', 'application/vnd.ims.imsccv1p3');
foreach($cc_types as $cc_mimetype ){
$m = new Mimeparse;
$cc_allowed = $this->allowMimetype($cc_mimetype);
if ( $cc_allowed ) return true;
}
return false;
} | allowImportItem - Returns true if we can return IMS Common Cartridges |
function getScriptFolder() {
$path = self::getScriptPathFull();
if ( $path === false ) return false;
// Don't use DIRECTORY_SEPARATOR, PHP makes these forward slashes on Windows
$pieces = explode('/', $path);
if ( count($pieces) < 1 ) return false;
return $pieces[count($pieces)-1];
} | This function will return "attend" |
function getPwd($file) {
$root = $this->dirroot;
$path = realpath(dirname($file));
$root .= '/'; // Add the trailing slash
if ( strlen($path) < strlen($root) ) return false;
// The root must be the prefix of path
if ( strpos($path, $root) !== 0 ) return false;
$retval = substr($path, strlen($root));
return $retval;
} | Get the current working directory of a file |
public function getCurrentUrl() {
$script = self::getScriptName();
if ( $script === false ) return false;
$pieces = $this->apphome;
if ( $this->apphome ) {
$pieces = parse_url($this->apphome);
}
// We only take scheme, host, and port from wwwroot / apphome
if ( ! isset($pieces['scheme']) ) return false;
$retval = $pieces['scheme'].'://'.$pieces['host'];
if ( isset($pieces['port']) ) $retval .= ':'.$pieces['port'];
return $retval . $script;
} | Get the current URL we are executing - no query parameters
http://localhost:8888/py4e/mod/peer-grade/maint.php |
public function getCurrentUrlFolder() {
$url = self::getCurrentUrl();
$pieces = explode('/', $url);
array_pop($pieces);
$retval = implode('/', $pieces);
return $retval;
} | Get the current folder of the URL we are executing - no trailing slash
input: http://localhost:8888/py4e/mod/peer-grade/maint.php
output: http://localhost:8888/py4e/mod/peer-grade |
public function localhost() {
if ( strpos($this->wwwroot,'://localhost') !== false ) return true;
if ( strpos($this->wwwroot,'://127.0.0.1') !== false ) return true;
return false;
} | Are we on localhost? |
public function to_header_internal($start) {
$out = $start;
$comma = ',';
$total = array();
foreach ($this->parameters as $k => $v) {
if (substr($k, 0, 5) != "oauth") continue;
if (is_array($v)) {
throw new OAuthException('Arrays not supported in headers');
}
$out .= $comma .
OAuthUtil::urlencode_rfc3986($k) .
'="' .
OAuthUtil::urlencode_rfc3986($v) .
'"';
$comma = ',';
}
return $out;
} | builds the Authorization: header |
public static function createFromDecodedJsonResponse($data)
{
if (!isset($data['user_metadata'])) {
$data['user_metadata'] = [];
} else {
foreach ($data['user_metadata'] as $key => $value) {
if (0 === strpos($key, 'date:')) {
$data['user_metadata'][$key] = new \DateTime($value);
}
}
}
if (!isset($data['static_metadata'])) {
$data['static_metadata'] = [];
}
$dynamic_metadata = [];
// Rebuild the DynamicMetadata associated to the current SourceImage
if (isset($data['dynamic_metadata'])) {
foreach ($data['dynamic_metadata'] as $name => $metadata) {
$metadata = DynamicMetadataHelper::buildDynamicMetadata($name, $metadata);
if ($metadata) {
$dynamic_metadata[$name] = $metadata;
}
}
}
return new self(
$data['organization'],
$data['binary_hash'],
$data['hash'],
$data['name'],
$data['format'],
$data['size'],
$data['width'],
$data['height'],
$data['user_metadata'],
$dynamic_metadata,
$data['static_metadata'],
new \DateTime($data['created']),
$data['link'],
$data['short_hash']
);
} | Create a source image from the decoded JSON data.
@param array $data Decoded JSON data
@return SourceImage |
private function getHashFilePath(AbstractLocalImage $image)
{
$path = $image->getRealpath();
if (false !== $path) {
return $path.self::$fileExtension;
}
// put it in the system tmp dir, if file doesn't have a real path.
$identifier = $image->getIdentifier();
if (null === $identifier) {
$identifier = 'unknown_identifier';
}
return sys_get_temp_dir().'/'.str_replace('/', '__', $identifier).self::$fileExtension;
} | @param AbstractLocalImage $image
@return string |
public static function &clone_remote($repo_path, $remote, $reference = null) {
return GitRepo::create_new($repo_path, $remote, true, $reference);
} | Clones a remote repo into a directory and then returns a GitRepo object
for the newly created local repo
Accepts a creation path and a remote to clone from
@access public
@param string repository path
@param string remote source
@param string reference path
@return GitRepo |
public static function buildSearchSortParameter(array $sorts)
{
if (empty($sorts)) {
return '';
}
$sorting = [];
foreach ($sorts as $sortField => $direction) {
if (!self::validateFieldName((string) $sortField)) {
throw new \LogicException(sprintf('Invalid field name "%s" for sorting field', $sortField));
}
if (!\in_array($direction, [true, 'desc', 'asc'], true)) {
throw new \LogicException(sprintf('Wrong sorting direction "%s" for field "%s". Use either "desc", "asc"',
$direction, $sortField
));
}
// Only output the "desc" direction as "asc" is the default sorting
$sorting[] = $sortField.('desc' === $direction ? ' '.$direction : '');
}
if (empty($sorting)) {
return '';
}
return implode(',', $sorting);
} | Builds the "sort" parameter for the source image listing API endpoint.
The sort direction can either be: "asc", "desc" (or the boolean TRUE value, treated as "asc")
@param array $sorts The sorting options, as an associative array "field => sort-direction"
@return string |
function dump_dom_levels($node, $level = 0)
{
$class = get_class($node);
if ($class == "DOMNodeList") {
echo "Level $level ($class): $node->length items\n";
foreach ($node as $child_node) {
echo $level.':'.$child_node->getNodePath() . "\n";
dump_dom_levels($child_node, $level+1);
}
} else {
$nChildren = 0;
foreach ($node->childNodes as $child_node) {
if ($child_node->hasChildNodes()) {
$nChildren++;
}
}
if ($nChildren) {
echo "Level $level ($class): $nChildren children\n";
}
foreach ($node->childNodes as $child_node) {
echo $level.':'.$child_node->getNodePath() . "\n";
if ($child_node->hasChildNodes()) {
dump_dom_levels($child_node, $level+1);
}
}
}
} | http://stackoverflow.com/questions/6475394/php-xpath-query-on-xml-with-default-namespace-binding |
public static function isRequestDetail($request_data=false) {
$raw_jwt = self::raw_jwt($request_data);
if ( ! $raw_jwt ) return false;
$jwt = self::parse_jwt($raw_jwt);
if ( is_string($jwt) ) {
return $jwt;
}
return is_object($jwt);
} | Returns true, false , or a string |
public static function isRequest($request_data=false) {
$retval = self::isRequestDetail($request_data);
if ( is_string($retval) ) {
error_log("Bad launch ".$retval);
return false;
}
return is_object($retval);
} | Returns true or false |
public static function verifyPublicKey($raw_jwt, $public_key, $algs) {
try {
// $decoded = JWT::decode($raw_jwt, $public_key, array('RS256'));
$decoded = JWT::decode($raw_jwt, $public_key, $algs);
// $decoded_array = json_decode(json_encode($decoded), true);
return true;
} catch(\Exception $e) {
return $e;
}
} | Verify the Public Key for this request
@return mixed This returns true if the request verified. If the request did not verify,
this returns the exception that was generated. |
public static function jonPostel($body, &$failures) {
if ( isset($CFG->jon_postel) ) return; // We are on Jon Postel mode
// Sanity checks
$version = false;
if ( isset($body->{self::VERSION_CLAIM}) ) $version = $body->{self::VERSION_CLAIM};
if ( strpos($version, '1.3') !== 0 ) $failures[] = "Bad LTI version: ".$version;
$message_type = false;
if ( isset($body->{self::MESSAGE_TYPE_CLAIM}) ) $message_type = $body->{self::MESSAGE_TYPE_CLAIM};
if ( ! $message_type ) {
$failures[] = "Missing message type";
} else if ( $message_type == self::MESSAGE_TYPE_RESOURCE ) {
// Required
if ( ! isset($body->{self::RESOURCE_LINK_CLAIM}) ) $failures[] = "Missing required resource_link claim";
if ( ! isset($body->{self::RESOURCE_LINK_CLAIM}->id) ) $failures[] = "Missing required resource_link id";
} else if ( $message_type == self::MESSAGE_TYPE_DEEPLINK ) {
// OK
} else {
$failures[] = "Bad message type: ".$message_type;
}
if ( ! isset($body->{self::ROLES_CLAIM}) ) $failures[] = "Missing required role claim";
if ( ! isset($body->{self::DEPLOYMENT_ID}) ) $failures[] = "Missing required deployment_id claim";
} | Apply Jon Postel's Law as appropriate
Postel's Law - https://en.wikipedia.org/wiki/Robustness_principle
"TCP implementations should follow a general principle of robustness:
be conservative in what you do, be liberal in what you accept from others."
By default, Jon Postel mode is off and we are stricter than we need to be.
This works well because it reduces the arguments with the certification
folks. But if you add:
$CFG->jon_postel = true;
Tsugi will follow Jon Postel's law. |
public static function loadLineItems($lineitems_url, $access_token, &$debug_log=false) {
$lineitems_url = trim($lineitems_url);
$ch = curl_init();
$headers = [
'Authorization: Bearer '. $access_token,
'Accept: '.self::MEDIA_TYPE_LINEITEMS,
// 'Content-Type: '.self::MEDIA_TYPE_LINEITEMS // TODO: Remove when certification is fixed
];
curl_setopt($ch, CURLOPT_URL, $lineitems_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if (is_array($debug_log) ) $debug_log[] = 'Line Items URL: '.$lineitems_url;
if (is_array($debug_log) ) $debug_log[] = $headers;
$lineitems = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close ($ch);
if ( is_array($debug_log) ) $debug_log[] = "Sent lineitems request, received status=$httpcode (".strlen($lineitems)." characters)";
$json = json_decode($lineitems, false);
if ( $json === null ) {
$retval = "Unable to parse returned lineitems JSON:". json_last_error_msg();
if ( is_array($debug_log) ) {
if (is_array($debug_log) ) $debug_log[] = $retval;
if (is_array($debug_log) ) $debug_log[] = substr($lineitems, 0, 1000);
}
return $retval;
}
if ( $httpcode == 200 && is_array($json) ) {
if ( is_array($debug_log) ) $debug_log[] = "Loaded ".count($json)." lineitems entries";
return $json;
}
$status = isset($json->error) ? $json->error : "Unable to load results";
if ( is_array($debug_log) ) $debug_log[] = "Error status: $status";
return $status;
} | Load LineItems |
public static function loadLineItem($lineitem_url, $access_token, &$debug_log=false) {
$lineitem_url = trim($lineitem_url);
$ch = curl_init();
$headers = [
'Authorization: Bearer '. $access_token,
'Accept: '.self::MEDIA_TYPE_LINEITEM,
];
curl_setopt($ch, CURLOPT_URL, $lineitem_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if (is_array($debug_log) ) $debug_log[] = 'Line Items URL: '.$lineitem_url;
if (is_array($debug_log) ) $debug_log[] = $headers;
$lineitem = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close ($ch);
if ( is_array($debug_log) ) $debug_log[] = "Sent lineitem request, received status=$httpcode (".strlen($lineitem)." characters)";
$json = json_decode($lineitem, false);
if ( $json === null ) {
$retval = "Unable to parse returned lineitem JSON:". json_last_error_msg();
if ( is_array($debug_log) ) {
if (is_array($debug_log) ) $debug_log[] = $retval;
if (is_array($debug_log) ) $debug_log[] = substr($lineitem, 0, 1000);
}
return $retval;
}
if ( $httpcode == 200 && is_object($json) ) {
if ( is_array($debug_log) ) $debug_log[] = "Loaded lineitem";
return $json;
}
$status = isset($json->error) ? $json->error : "Unable to load results";
if ( is_array($debug_log) ) $debug_log[] = "Error status: $status";
return $status;
} | Load A LineItem |
public static function loadResults($lineitem_url, $access_token, &$debug_log=false) {
$lineitem_url = trim($lineitem_url);
$ch = curl_init();
$headers = [
'Authorization: Bearer '. $access_token,
'Content-Type: '.self::RESULTS_TYPE, // TODO: Convince Claude this is wrong
'Accept: '.self::RESULTS_TYPE
];
$actual_url = $lineitem_url."/results";
curl_setopt($ch, CURLOPT_URL, $actual_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if (is_array($debug_log) ) $debug_log[] = 'Line Items URL: '.$actual_url;
if (is_array($debug_log) ) $debug_log[] = $headers;
$results = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close ($ch);
if ( is_array($debug_log) ) $debug_log[] = "Sent results request, received status=$httpcode (".strlen($results)." characters)";
if ( is_array($debug_log)) $debug_log[] = substr($results, 0, 3000);
$json = json_decode($results, false);
if ( $json === null ) {
$retval = "Unable to parse returned results JSON:". json_last_error_msg();
if ( is_array($debug_log) ) $debug_log[] = $retval;
return $retval;
}
if ( $httpcode == 200 && is_array($json) ) {
if ( is_array($debug_log) ) $debug_log[] = "Loaded results";
return $json;
}
$status = isset($json->error) ? $json->error : "Unable to load results";
if ( is_array($debug_log) ) $debug_log[] = "Error status: $status";
return $status;
} | Load results for a LineItem |
public static function deleteLineItem($lineitem_url, $access_token, &$debug_log=false) {
$lineitem_url = trim($lineitem_url);
$ch = curl_init();
$headers = [
'Authorization: Bearer '. $access_token
];
curl_setopt($ch, CURLOPT_URL, $lineitem_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
if (is_array($debug_log) ) $debug_log[] = 'Line Item URL: '.$lineitem_url;
if (is_array($debug_log) ) $debug_log[] = $headers;
$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close ($ch);
if ( is_array($debug_log) ) $debug_log[] = "Sent lineitem delete, received status=$httpcode (".strlen($response)." characters)";
if ( $httpcode == 200 ) {
if ( is_array($debug_log) ) $debug_log[] = "Deleted lineitem";
return true;
}
if ( strlen($response) < 1 ) {
return "Failed with no response body and code=".$httpcode;
}
$json = json_decode($response, false);
if ( $json === null ) {
$retval = "Unable to parse returned lineitem JSON:". json_last_error_msg();
if ( is_array($debug_log) ) {
if (is_array($debug_log) ) $debug_log[] = $retval;
if (is_array($debug_log) ) $debug_log[] = substr($lineitem, 0, 1000);
}
return $retval;
}
$status = U::get($json, "error", "Unable to delete lineitem");
if ( is_array($debug_log) ) $debug_log[] = "Error status: $status";
return $status;
} | Delete A LineItem |
public static function getISO8601($timestamp=false) {
if ( $timestamp === false ) {
$dt = new \DateTime();
} else {
$format = 'Y-m-d H:i:s';
$dt = \DateTime::createFromFormat($format, $timestamp);
}
// 2017-08-16T16:26:31-1000
$iso8601 = $dt->format(\DateTime::ISO8601);
// 2017-08-20T10:34:05.000Z
$iso8601 = str_replace('-1000','.000Z',$iso8601);
return $iso8601;
} | Get Caliper-style ISO8601 Datetime from unix timestamp |
public static function smallCaliper() {
$json = json_decode('{
"sensor": "https://example.edu/sensor/001",
"sendTime": "2004-01-01T06:00:00.000Z",
"dataVersion": "http://purl.imsglobal.org/ctx/caliper/v1p1",
"data": [
{
"@context": "http://purl.imsglobal.org/ctx/caliper/v1p1",
"type": "SessionEvent",
"actor": {
"id": "https://example.edu/user/554433",
"type": "Person"
},
"action": "LoggedIn",
"eventTime": "2004-01-01T06:00:00.000Z",
"object": "http://localhost/tsugi/mod/michat"
}
]
}');
$json->sendTime = self::getISO8601();
$json->data[0]->id = uniqid();
return $json;
} | Required:
$json->data[0]->actor->id = $user;
$json->data[0]->object->{'@id'} = $path;
$json->eventTime = Caliper::getISO8601($timestamp);
Optional:
$json->data[0]->name = $name;
$json->data[0]->extensions = new \stdClass();
$json->data[0]->extensions->email = $email; |
public function handle()
{
$this->basePath = $this->getMigrationPath();
$migrations = $this->migrator->getMigrationFiles($this->basePath);
$count = count($migrations);
if ($count == 0) {
$this->comment('No migrations to move');
return;
}
foreach ($migrations as $migration_name => $migration_path) {
$datePath = $this->migrator->getDateFolderStructure($migration_name);
// Move the migration into base migration folder
$this->files->move($this->basePath.'/'.$datePath.$migration_name.'.php', $this->basePath.'/'.$migration_name.'.php');
}
$this->info('Migrations disorganised successfully ('.$count.' migrations moved)');
$this->cleanup();
} | Create date folder structure and move migrations into.
@return void |
public function cleanup()
{
if ($this->option('force')) {
$this->deleteDirs();
} elseif ($this->confirm('Delete all subdirectories in migrations folder?', true)) {
$this->deleteDirs();
}
} | Decide whether or not to delete directories.
@return void |
public function deleteDirs()
{
$dirs = $this->files->directories($this->basePath);
foreach ($dirs as $dir) {
$this->files->deleteDirectory($dir);
}
$this->info('Subdirectories deleted');
} | Delete subdirectories in the migrations folder.
@return void |
public function invoke(AbstractRequest $request) : ResourceObject
{
$onMethod = 'on' . ucfirst($request->method);
if (! method_exists($request->resourceObject, $onMethod) === true) {
return $this->methodNoExists($request);
}
$params = $this->params->getParameters([$request->resourceObject, $onMethod], $request->query);
$response = call_user_func_array([$request->resourceObject, $onMethod], $params);
if (! $response instanceof ResourceObject) {
$request->resourceObject->body = $response;
$response = $request->resourceObject;
}
return $response;
} | {@inheritdoc} |
public static function createFromDecodedJsonResponse($data)
{
$stack_operations = [];
if (isset($data['stack_operations']) && \is_array($data['stack_operations'])) {
foreach ($data['stack_operations'] as $operation) {
$stack_operations[] = StackOperation::createFromDecodedJsonResponse($operation);
}
}
$stack = new self(
$data['organization'],
$data['name'],
$stack_operations,
[],
new \DateTime($data['created'])
);
if (isset($data['stack_options']) && \is_array($data['stack_options'])) {
$stack->setStackOptions($data['stack_options']);
}
if (isset($data['stack_variables']) && \is_array($data['stack_variables'])) {
$stack->setStackVariables($data['stack_variables']);
}
if (isset($data['stack_expressions']) && \is_array($data['stack_expressions'])) {
$stack_expressions = [];
foreach ($data['stack_expressions'] as $expression) {
$stack_expressions[] = StackExpression::createFromDecodedJsonResponse($expression);
}
$stack->setStackExpressions($stack_expressions);
}
return $stack;
} | Create a stack from a decoded JSON data returned by the rokka.io API.
@param array $data Decoded JSON data
@return Stack |
public static function createFromConfig($stackName, array $config, $organization = null)
{
$stack = new static($organization, $stackName);
if (isset($config['operations'])) {
$stack->setStackOperations($config['operations']);
}
if (isset($config['options'])) {
$stack->setStackOptions($config['options']);
}
if (isset($config['expressions'])) {
$stack->setStackExpressions($config['expressions']);
}
if (isset($config['variables'])) {
$stack->setStackVariables($config['variables']);
}
return $stack;
} | Creates a Stack object from an array.
$config = ['operations' => StackOperation[]
'options' => $options,
'expressions' => $expressions
]
All are optional, if operations doesn't exist, it will be a noop operation.
@since 1.1.0
@param string $stackName
@param array $config
@param string|null $organization
@return self |
public function setStackExpressions(array $stackExpressions)
{
$this->stackExpressions = [];
foreach ($stackExpressions as $stackExpression) {
$this->addStackExpression($stackExpression);
}
return $this;
} | @since 1.1.0
@param StackExpression[] $stackExpressions
@return self |