code
stringlengths 52
7.75k
| docs
stringlengths 1
5.85k
|
---|---|
public static function insertForm($fields, $from_location, $titles=false) {
echo('<form method="post">'."\n");
for($i=0; $i < count($fields); $i++ ) {
$field = $fields[$i];
// Don't allow setting of these fields
if ( strpos($field, "_at") > 0 ) continue;
if ( strpos($field, "_sha256") > 0 ) continue;
echo('<div class="form-group">'."\n");
echo('<label for="'.$field.'">'.self::fieldToTitle($field, $titles)."<br/>\n");
if ( strpos($field, "secret") !== false ) {
echo('<input id="'.$field.'" type="password" autocomplete="off" size="80" name="'.$field.'"');
echo("onclick=\"if ( $(this).attr('type') == 'text' ) $(this).attr('type','password'); else $(this).attr('type','text'); return false;\">\n");
} else {
echo('<input type="text" size="80" id="'.$field.'" name="'.$field.'">'."\n");
}
echo("</label>\n</div>");
}
echo('<input type="submit" name="doSave" class="btn btn-normal" value="'._m("Save").'">'."\n");
echo('<a href="'.$from_location.'" class="btn btn-default">Cancel</a>'."\n");
echo('</form>'."\n");
} | Generate the HTML for an insert form.
Here is a sample call:
$from_location = "keys.php";
$fields = array("key_key", "key_sha256", "secret", "created_at", "updated_at");
CrudForm::insertForm($fields, $from_location);
@param $fields An array of fields to prompt for.
@param $from_location A URL to jump to when the user presses 'Cancel'.
@param $titles An array of fields->titles |
public static function fieldToTitle($name, $titles=false) {
if ( is_array($titles) && U::get($titles, $name) ) return U::get($titles, $name);
return ucwords(str_replace('_',' ',$name));
} | Maps a field name to a presentable title.
@todo Make this translatable and pretty |
public static function selectSql($tablename, $fields, $where_clause=false) {
$sql = "SELECT ";
$first = true;
foreach ( $fields as $field ) {
if ( ! $first ) $sql .= ', ';
$sql .= $field;
$first = false;
}
$sql .= "\n FROM ".$tablename;
if ( $where_clause && strlen($where_clause) > 0 ) $sql .= "\nWHERE ".$where_clause;
return $sql;
} | Produce the SELECT statement for a table, set of fields and where clause.
@param $fields An array of field names to select.
@param $where_clause This is the WHERE clause but should not include
the WHERE keyword. |
protected function configure()
{
$this->bind()->annotatedWith('json_schema_dir')->toInstance($this->jsonSchemaDir);
$this->bind()->annotatedWith('json_validate_dir')->toInstance($this->jsonValidateDir);
$this->bind(JsonSchemaExceptionHandlerInterface::class)->to(JsonSchemaExceptionVoidHandler::class);
$this->bindInterceptor(
$this->matcher->subclassesOf(ResourceObject::class),
$this->matcher->annotatedWith(JsonSchema::class),
[JsonSchemaInterceptor::class]
);
} | {@inheritdoc} |
public function getMigrationFiles($paths = [], $recursive = true)
{
if ($recursive) {
$paths = $this->getRecursiveFolders($paths);
}
$files = parent::getMigrationFiles($paths);
return $files;
} | Get all of the migration files in a given path.
@param string $path
@param bool $recursive
@return array |
public function getRecursiveFolders($folders)
{
if (! is_array($folders)) {
$folders = [$folders];
}
$paths = [];
foreach ($folders as $folder) {
$iter = new Iterator(
new DirectoryIterator($folder, DirectoryIterator::SKIP_DOTS),
Iterator::SELF_FIRST,
Iterator::CATCH_GET_CHILD // Ignore "Permission denied"
);
$subPaths = [$folder];
foreach ($iter as $path => $dir) {
if ($dir->isDir()) {
$subPaths[] = $path;
}
}
$paths = array_merge($paths, $subPaths);
}
return $paths;
} | Get all subdirectories located in an array of folders.
@param array $folders
@return array |
private function addNamedParams(array $parameters, array $assistedNames, array $webcontext) : array
{
$names = [];
foreach ($parameters as $parameter) {
if (isset($assistedNames[$parameter->name])) {
$names[$parameter->name] = $assistedNames[$parameter->name];
continue;
}
if (isset($webcontext[$parameter->name])) {
$default = $this->getDefault($parameter);
$names[$parameter->name] = new AssistedWebContextParam($webcontext[$parameter->name], $default);
continue;
}
$names[$parameter->name] = $this->getParam($parameter);
}
return $names;
} | @param \ReflectionParameter[] $parameters
@return ParamInterface[] |
public function getIterator()
{
$isTraversal = (is_array($this->body) || $this->body instanceof \Traversable);
return $isTraversal ? new \ArrayIterator($this->body) : new \ArrayIterator([]);
} | Get array iterator
@return \ArrayIterator |
public function toString()
{
if ($this->view !== null) {
return $this->view;
}
if (! $this->renderer instanceof RenderInterface) {
$this->renderer = new JsonRenderer;
}
return $this->renderer->render($this);
} | {@inheritdoc} |
public static function addOrReplaceTextInPng($png,$key,$text) {
$png = self::removeTextChunks($key, $png);
$chunk = self::phpTextChunk($key,$text);
$png2 = self::addPngChunk($chunk,$png);
return $png2;
} | http://stackoverflow.com/questions/8842387/php-add-itxt-comment-to-a-png-image |
public static function removeTextChunks($key,$png) {
// Read the magic bytes and verify
$retval = substr($png,0,8);
$ipos = 8;
if ($retval != "\x89PNG\x0d\x0a\x1a\x0a")
throw new Exception('Is not a valid PNG image');
// Loop through the chunks. Byte 0-3 is length, Byte 4-7 is type
$chunkHeader = substr($png,$ipos,8);
$ipos = $ipos + 8;
while ($chunkHeader) {
// Extract length and type from binary data
$chunk = @unpack('Nsize/a4type', $chunkHeader);
$skip = false;
if ( $chunk['type'] == 'tEXt' ) {
$data = substr($png,$ipos,$chunk['size']);
$sections = explode("\0", $data);
print_r($sections);
if ( $sections[0] == $key ) $skip = true;
}
// Extract the data and the CRC
$data = substr($png,$ipos,$chunk['size']+4);
$ipos = $ipos + $chunk['size'] + 4;
// Add in the header, data, and CRC
if ( ! $skip ) $retval = $retval . $chunkHeader . $data;
// Read next chunk header
$chunkHeader = substr($png,$ipos,8);
$ipos = $ipos + 8;
}
return $retval;
} | Strip out any existing text chunks with a particular key |
public static function phpTextChunk($key,$text) {
$chunktype = "tEXt";
$chunkdata = $key . "\0" . $text;
$crc = pack("N", crc32($chunktype . $chunkdata));
$len = pack("N",strlen($chunkdata));
return $len . $chunktype . $chunkdata . $crc;
} | ToDo: check that key length is less than 79 and that neither includes null bytes |
public static function addPngChunk($chunk,$png) {
$len = strlen($png);
return substr($png,0,$len-12) . $chunk . substr($png,$len-12,12);
} | inserts chunk before IEND chunk (last 12 bytes) |
public function request()
{
if ($this->in === 'eager') {
$this->result = $this->invoke();
return $this->result;
}
return $this;
} | {@inheritdoc} |
public function offsetGet($offset)
{
$this->invoke();
if (! isset($this->result->body[$offset])) {
throw new OutOfBoundsException("[${offset}] for object[" . get_class($this->result) . ']', 400);
}
return $this->result->body[$offset];
} | {@inheritdoc}
@throws OutOfBoundsException |
public function getIterator()
{
$this->invoke();
$isArray = (is_array($this->result->body) || $this->result->body instanceof \Traversable);
return $isArray ? new \ArrayIterator($this->result->body) : new \ArrayIterator([]);
} | {@inheritdoc} |
public function hash() : string
{
return md5(get_class($this->resourceObject) . $this->method . serialize($this->query) . serialize($this->links));
} | {@inheritdoc} |
public function add($entry, $push=false)
{
if ( $push ) {
array_unshift($this->menu, $entry);
} else {
$this->menu[] = $entry;
}
return $this;
} | Add an entry to the menu
@param $entry a MenuEntry
@param $push true if this is to be put before the rest of the items in the menue
@return Menu The instance is returned to allow chaining syntax |
public function addLink($link, $href, $push=false)
{
$entry = new MenuEntry($link, $href);
return $this->add($entry, $push);
} | Add an link to the menu
@param $link The text of the link - can be text, HTML, or even an img tag
@param $href An optional place to go when the link is clicked. Also can be
a Menu.
@param $push true if this is to be put before the rest of the items in the menue
@return Menu The instance is returned to allow chaining syntax |
public function addSeparator($push=false)
{
$entry = MenuEntry::separator();
return $this->add($entry, $push);
} | Add a separator to the menu
@param $push true if this is to be put before the rest of the items in the menue
@return Menu The instance is returned to allow chaining syntax |
public function getNameAndEmail() {
$display = '';
if ( isset($this->displayname) && strlen($this->displayname) > 0 ) {
$display = $this->displayname;
}
if ( isset($this->email) && strlen($this->email) > 0 ) {
if ( strlen($display) > 0 ) {
$display .= ' ('.$this->email.')';
} else {
$display = $this->email;
}
}
$display = trim($display);
if ( strlen($display) < 1 ) return false;
return $display;
} | Construct the user's name / email combination |
function getFirstName($displayname=null) {
if ( $displayname === null ) $displayname = $this->getNameAndEmail();
if ( $displayname === null ) return null;
$pieces = explode(' ',$displayname);
if ( count($pieces) > 0 ) return $pieces[0];
return null;
} | Get the user's first name, falling back to email |
public static function loadUserInfoBypass($user_id)
{
global $CFG, $PDOX, $CONTEXT;
$cacheloc = 'lti_user';
$row = Cache::check($cacheloc, $user_id);
if ( $row != false ) return $row;
$stmt = $PDOX->queryDie(
"SELECT displayname, email, user_key FROM {$CFG->dbprefix}lti_user AS U
JOIN {$CFG->dbprefix}lti_membership AS M
ON U.user_id = M.user_id AND M.context_id = :CID
WHERE U.user_id = :UID",
array(":UID" => $user_id, ":CID" => $CONTEXT->id)
);
$row = $stmt->fetch(\PDO::FETCH_ASSOC);
if ( strlen($row['displayname']) < 1 && strlen($row['user_key']) > 0 ) {
$row['displayname'] = 'user_key:'.substr($row['user_key'],0,25);
}
Cache::set($cacheloc, $user_id, $row);
return $row;
} | Load a user's info from the user_id
We make sure that the user is a member of the current
context so as not to slide across silos. |
public static function create($id,$guid,$context_id,$debug=false) {
global $CFG;
$pt = $CFG->cookiepad.'::'.$id.'::'.$guid.'::'.$context_id;
if ( $debug ) echo("PT1: $pt\n");
$ct = \Tsugi\Crypt\AesCtr::encrypt($pt, $CFG->cookiesecret, 256) ;
return $ct;
} | Utility code to deal with Secure Cookies. |
public static function set($user_id, $userEmail, $context_id) {
global $CFG;
$ct = self::create($user_id,$userEmail, $context_id);
setcookie($CFG->cookiename,$ct,time() + (86400 * 45), '/'); // 86400 = 1 day
} | We have a user - set their secure cookie |
public function toAdapter(AdapterInterface $adapter) : SchemeCollectionInterface
{
$this->collection[$this->scheme . '://' . $this->app] = $adapter;
return $this;
} | {@inheritdoc} |
public function getAdapter(AbstractUri $uri) : AdapterInterface
{
$schemeIndex = $uri->scheme . '://' . $uri->host;
if (! array_key_exists($schemeIndex, $this->collection)) {
throw new SchemeException($uri->scheme . '://' . $uri->host);
}
return $this->collection[$schemeIndex];
} | {@inheritdoc}
@throws SchemeException |
public function newInstance($uri) : ResourceObject
{
if (is_string($uri)) {
$uri = new Uri($uri);
}
$adapter = $this->scheme->getAdapter($uri);
return $adapter->get($uri);
} | {@inheritdoc}
@throws \BEAR\Resource\Exception\UriException |
public static function createFromJsonResponse($jsonString)
{
$data = json_decode($jsonString, true);
return new self($data['id'], $data['email'], $data['api_key']);
} | Create a user from the JSON data returned by the rokka.io API.
@param string $jsonString JSON as a string
@return User |
public function setReason($var)
{
GPBUtil::checkEnum($var, \Rxnet\EventStore\Data\NotHandled_NotHandledReason::class);
$this->reason = $var;
return $this;
} | Generated from protobuf field <code>.Rxnet.EventStore.Data.NotHandled.NotHandledReason reason = 1;</code>
@param int $var
@return $this |
public function href(string $rel, AbstractRequest $request, array $query)
{
$classMethod = 'on' . ucfirst($request->method);
$annotations = $this->reader->getMethodAnnotations(new \ReflectionMethod(get_class($request->resourceObject), $classMethod));
foreach ($annotations as $annotation) {
if ($this->isValidLinkAnnotation($annotation, $rel)) {
return $this->getMethodUdi($request, $query, $annotation);
}
}
throw new LinkException("rel:{$rel} class:" . get_class($request->resourceObject), 500);
} | {@inheritdoc}
@throws LinkException |
public static function dump() {
global $DEBUG_STRING;
$retval = '';
$sess = (strlen(session_id()) > 0 );
if ( $sess ) {
// echo("<br/>=== DUMP ====<br/>".$_SESSION['__zzz_debug']."<br/>\n");flush();
if (strlen($_SESSION['__zzz_debug']) > 0) {
$retval = $_SESSION['__zzz_debug'];
unset($_SESSION['__zzz_debug']);
}
}
if ( strlen($retval) > 0 && strlen($DEBUG_STRING) > 0) {
$retval .= "\n";
}
if (strlen($DEBUG_STRING) > 0) {
$retval .= $DEBUG_STRING;
$DEBUG_STRING = '';
}
return $retval;
} | Calling this clears debug buffer... |
public static function dumpPost() {
print "<pre>\n";
print "Raw POST Parameters:\n\n";
ksort($_POST);
foreach($_POST as $key => $value ) {
if (get_magic_quotes_gpc()) $value = stripslashes($value);
print "$key=$value (".mb_detect_encoding($value).")\n";
}
print "</pre>";
} | Dump out the contents of the $_POST properly escaped in pre tags. |
public static function set($cacheloc, $cachekey, $cacheval, $expiresec=false)
{
$cacheloc = "cache_" . $cacheloc;
if ( $cacheval === null || $cacheval === false ) {
unset($_SESSION[$cacheloc]);
return;
}
if ( $expiresec !== false ) $expiresec = time() + $expiresec;
$_SESSION[$cacheloc] = array($cachekey, $cacheval, $expiresec);
} | Place an entry in the cache.
We don't cache null or false if that was our value. |
public static function check($cacheloc, $cachekey)
{
$cacheloc = "cache_" . $cacheloc;
if ( isset($_SESSION[$cacheloc]) ) {
$cache_row = $_SESSION[$cacheloc];
if ( time() >= $cache_row[2] ) {
unset($_SESSION[$cacheloc]);
return false;
}
if ( $cache_row[0] == $cachekey ) {
// error_log("Cache hit $cacheloc");
return $cache_row[1];
}
unset($_SESSION[$cacheloc]);
}
return false;
} | Check and return a value from the cache.
Returns false if there is no entry. |
public static function expires($cacheloc, $cachekey)
{
$cacheloc = "cache_" . $cacheloc;
if ( isset($_SESSION[$cacheloc]) ) {
$cache_row = $_SESSION[$cacheloc];
if ( time() >= $cache_row[2] ) {
unset($_SESSION[$cacheloc]);
return false;
}
if ( $cache_row[0] != $cachekey ) return false;
if ( $cache_row[0] === false ) return false;
return $cache_row[2] - time();
}
return false;
} | Check when value in the cache expires
Returns false if there is no entry. |
public static function handleSettingsPost() {
global $USER;
if ( ! $USER ) return false;
if ( isset($_POST['settings_internal_post']) && $USER->instructor ) {
$newsettings = array();
foreach ( $_POST as $k => $v ) {
if ( $k == session_name() ) continue;
if ( $k == 'settings_internal_post' ) continue;
if ( strpos('_ignore',$k) > 0 ) continue;
$newsettings[$k] = $v;
}
// Merge these with the existing settings
Settings::linkUpdate($newsettings);
return true;
}
return false;
} | Handle incoming settings post data
@return boolean Returns true if there were settings to handle and false
if there was nothing done. Generally the calling tool will redirect
when true is returned.
if ( SettingsForm::handleSettingsPost() ) {
header( 'Location: '.U::addSession('index.php?howdysuppress=1') ) ;
return;
} |
public static function select($name, $default=false, $fields)
{
global $USER;
if ( ! $USER ) return;
$oldsettings = Settings::linkGetAll();
if ( ! $USER->instructor ) {
$configured = false;
foreach ( $fields as $k => $v ) {
$index = $k;
$display = $v;
if ( is_int($index) ) $index = $display; // No keys
if ( ! is_string($display) ) $display = $index;
if ( isset($oldsettings[$name]) && $k == $oldsettings[$name] ) {
$configured = $display;
}
}
if ( $configured === false ) {
echo('<p>'._m('Setting').' '.htmlent_utf8($name).' '._m('is not set').'</p>');
} else {
echo('<p>'.htmlent_utf8(ucwords($name)).' '._m('is set to').' '.htmlent_utf8($configured).'</p>');
}
return;
}
// Instructor view
if ( $default === false ) $default = _m('Please Select');
echo('<select name="'.$name.'">');
echo('<option value="0">'.$default.'</option>');
foreach ( $fields as $k => $v ) {
$index = $k;
$display = $v;
if ( is_int($index) ) $index = $display; // No keys
if ( ! is_string($display) ) $display = $index;
echo('<option value="'.$index.'"');
if ( isset($oldsettings[$name]) && $index == $oldsettings[$name] ) {
echo(' selected');
}
echo('>'.$display.'</option>'."\n");
}
echo('</select>');
} | Handle a settings selector box |
public static function text($name, $title=false)
{
global $USER;
if ( ! $USER ) return false;
$oldsettings = Settings::linkGetAll();
$configured = isset($oldsettings[$name]) ? $oldsettings[$name] : false;
if ( $title === false ) $title = $name;
if ( ! $USER->instructor ) {
if ( $configured === false || strlen($configured) < 1 ) {
echo('<p>'._m('Setting').' '.htmlent_utf8($name).' '._m('is not set').'</p>');
} else {
echo('<p>'.htmlent_utf8(ucwords($name)).' '._m('is set to').' '.htmlent_utf8($configured).'</p>');
}
return;
}
// Instructor view
echo('<label style="width:100%;" for="'.$name.'">'.htmlent_utf8($title)."\n");
echo('<input type="text" class="form-control" style="width:100%;" name="'.$name.'"');
echo('value="'.htmlent_utf8($configured).'"></label>'."\n");
} | Handle a settings text box |
public static function getDueDateDelta($time)
{
if ( $time < 600 ) {
$delta = $time . ' seconds';
} else if ($time < 3600) {
$delta = sprintf("%0.0f",($time/60.0)) . ' ' . _m('minutes');
} else if ($time <= 86400 ) {
$delta = sprintf("%0.2f",($time/3600.0)) . ' ' . _m('hours');
} else {
$delta = sprintf("%0.2f",($time/86400.0)) . ' ' . _m('days');
}
return $delta;
} | Show a due date delta in reasonable units |
public function invoke(MethodInvocation $invocation)
{
/** @var ReflectionMethod $method */
$method = $invocation->getMethod();
/** @var JsonSchema $jsonSchema */
$jsonSchema = $method->getAnnotation(JsonSchema::class);
if ($jsonSchema->params) {
$arguments = $this->getNamedArguments($invocation);
$this->validateRequest($jsonSchema, $arguments);
}
/** @var ResourceObject $ro */
$ro = $invocation->proceed();
if ($ro->code === 200 || $ro->code == 201) {
$this->validateResponse($ro, $jsonSchema);
}
return $ro;
} | {@inheritdoc} |
public function uploadSourceImage($contents, $fileName, $organization = '', $options = null)
{
if (empty($contents)) {
throw new \LogicException('You need to provide an image content to be uploaded');
}
$requestOptions = [[
'name' => 'filedata',
'contents' => $contents,
'filename' => $fileName,
]];
return $this->uploadSourceImageInternal($organization, $options, $requestOptions);
} | Upload a source image.
@param string $contents Image contents
@param string $fileName Image file name
@param string $organization Optional organization
@param array|null $options Options for creating the image (like meta_user and meta_dynamic)
@throws GuzzleException
@throws \RuntimeException
@return SourceImageCollection If no image contents are provided to be uploaded |
public function uploadSourceImageByUrl($url, $organization = '', $options = null)
{
if (empty($url)) {
throw new \LogicException('You need to provide an url to an image');
}
$requestOptions = [[
'name' => 'url[0]',
'contents' => $url,
]];
return $this->uploadSourceImageInternal($organization, $options, $requestOptions);
} | Upload a source image.
@param string $url url to a remote image
@param string $organization Optional organization
@param array|null $options Options for creating the image (like meta_user and meta_dynamic)
@throws GuzzleException
@throws \RuntimeException
@return SourceImageCollection If no image contents are provided to be uploaded |
public function deleteSourceImage($hash, $organization = '')
{
try {
$response = $this->call('DELETE', implode('/', [self::SOURCEIMAGE_RESOURCE, $this->getOrganizationName($organization), $hash]));
} catch (GuzzleException $e) {
if (404 == $e->getCode()) {
return false;
}
throw $e;
}
return '204' == $response->getStatusCode();
} | Delete a source image.
@param string $hash Hash of the image
@param string $organization Optional organization name
@throws GuzzleException If the request fails for a different reason than image not found
@throws \Exception
@return bool True if successful, false if image not found |
public function copySourceImage($hash, $destinationOrg, $overwrite = true, $sourceOrg = '')
{
try {
$headers = ['Destination' => $destinationOrg];
if (false === $overwrite) {
$headers['Overwrite'] = 'F';
}
$response = $this->call('COPY',
implode('/', [self::SOURCEIMAGE_RESOURCE, $this->getOrganizationName($sourceOrg), $hash]),
['headers' => $headers]
);
} catch (GuzzleException $e) {
if (404 == $e->getCode()) {
return false;
}
throw $e;
}
$statusCode = $response->getStatusCode();
return $statusCode >= 200 && $statusCode < 300;
} | Copy a source image to another org.
Needs read permissions on the source organization and write permissions on the write organization.
@param string $hash Hash of the image
@param string $destinationOrg The destination organization
@param bool $overwrite If an existing image should be overwritten
@param string $sourceOrg Optional source organization name
@throws GuzzleException If the request fails for a different reason than image not found
@return bool True if successful, false if source image not found |
public function copySourceImages($hashes, $destinationOrg, $overwrite = true, $sourceOrg = '')
{
try {
$headers = ['Destination' => $destinationOrg];
if (false === $overwrite) {
$headers['Overwrite'] = 'F';
}
$response = $this->call('POST',
implode('/', [self::SOURCEIMAGE_RESOURCE, $this->getOrganizationName($sourceOrg), 'copy']),
['headers' => $headers, 'json' => $hashes]
);
} catch (GuzzleException $e) {
if (404 == $e->getCode()) {
return ['existing' => [], 'created' => []];
}
throw $e;
}
return json_decode($response->getBody()->getContents(), true);
} | Copy multiple sources image to another org.
Needs read permissions on the source organization and write permissions on the write organization.
@param array $hashes Hashes of the images as array (max. 100)
@param string $destinationOrg The destination organization
@param bool $overwrite If an existing image should be overwritten
@param string $sourceOrg Optional source organization name
@throws GuzzleException If the request fails for a different reason than image not found
@throws \RuntimeException
@return array An array in the form of ['existing' => [...], 'created' => [..]] with all the hashes in it |
public function deleteSourceImagesWithBinaryHash($binaryHash, $organization = '')
{
try {
$response = $this->call('DELETE', implode('/', [self::SOURCEIMAGE_RESOURCE, $this->getOrganizationName($organization)]), ['query' => ['binaryHash' => $binaryHash]]);
} catch (GuzzleException $e) {
if (404 == $e->getCode()) {
return false;
}
throw $e;
}
return '204' == $response->getStatusCode();
} | Delete source images by binaryhash.
Since the same binaryhash can have different images in rokka, this may delete more than one picture.
@param string $binaryHash Hash of the image
@param string $organization Optional organization name
@throws GuzzleException If the request fails for a different reason than image not found
@throws \Exception
@return bool True if successful, false if image not found |
public function searchSourceImages($search = [], $sorts = [], $limit = null, $offset = null, $organization = '')
{
$options = ['query' => []];
$sort = SearchHelper::buildSearchSortParameter($sorts);
if (!empty($sort)) {
$options['query']['sort'] = $sort;
}
if (\is_array($search) && !empty($search)) {
foreach ($search as $field => $value) {
if (!SearchHelper::validateFieldName((string) $field)) {
throw new \LogicException(sprintf('Invalid field name "%s" as search field', $field));
}
$options['query'][$field] = $value;
}
}
if (isset($limit)) {
$options['query']['limit'] = $limit;
}
if (isset($offset)) {
$options['query']['offset'] = $offset;
}
$contents = $this
->call('GET', self::SOURCEIMAGE_RESOURCE.'/'.$this->getOrganizationName($organization), $options)
->getBody()
->getContents();
return SourceImageCollection::createFromJsonResponse($contents);
} | Search and list source images.
Sort direction can either be: "asc", "desc" (or the boolean TRUE value, treated as "asc")
@param array $search The search query, as an associative array "field => value"
@param array $sorts The sorting parameters, as an associative array "field => sort-direction"
@param int|null $limit Optional limit
@param int|string|null $offset Optional offset, either integer or the "Cursor" value
@param string $organization Optional organization name
@throws GuzzleException
@throws \RuntimeException
@return SourceImageCollection |
public function listSourceImages($limit = null, $offset = null, $organization = '')
{
return $this->searchSourceImages([], [], $limit, $offset, $organization);
} | List source images.
@deprecated 2.0.0 Use Image::searchSourceImages()
@see Image::searchSourceImages()
@param null|int $limit Optional limit
@param null|int|string $offset Optional offset, either integer or the "Cursor" value
@param string $organization Optional organization name
@throws GuzzleException
@throws \RuntimeException
@return SourceImageCollection |
public function getSourceImage($hash, $organization = '')
{
$path = self::SOURCEIMAGE_RESOURCE.'/'.$this->getOrganizationName($organization);
$path .= '/'.$hash;
$contents = $this
->call('GET', $path)
->getBody()
->getContents();
return SourceImage::createFromJsonResponse($contents);
} | Load a source image's metadata from Rokka.
@param string $hash Hash of the image
@param string $organization Optional organization name
@throws GuzzleException
@throws \RuntimeException
@return SourceImage |
public function getSourceImagesWithBinaryHash($binaryHash, $organization = '')
{
$path = self::SOURCEIMAGE_RESOURCE.'/'.$this->getOrganizationName($organization);
$options['query'] = ['binaryHash' => $binaryHash];
$contents = $this
->call('GET', $path, $options)
->getBody()
->getContents();
return SourceImageCollection::createFromJsonResponse($contents);
} | Loads source images metadata from Rokka by binaryhash.
Since the same binaryhash can have different images in rokka, this may return more than one picture.
@param string $binaryHash Hash of the image
@param string $organization Optional organization name
@throws GuzzleException
@throws \RuntimeException
@return SourceImageCollection |
public function getSourceImageContents($hash, $organization = '')
{
$path = implode('/', [
self::SOURCEIMAGE_RESOURCE,
$this->getOrganizationName($organization),
$hash,
'download', ]
);
return $this
->call('GET', $path)
->getBody()
->getContents();
} | Get a source image's binary contents from Rokka.
@param string $hash Hash of the image
@param string $organization Optional organization name
@throws GuzzleException
@throws \RuntimeException
@return string |
public function listOperations()
{
$contents = $this
->call('GET', self::OPERATIONS_RESOURCE)
->getBody()
->getContents();
return OperationCollection::createFromJsonResponse($contents);
} | List operations.
@throws GuzzleException
@throws \RuntimeException
@return OperationCollection |
public function createStack(
$stackName,
array $stackOperations,
$organization = '',
array $stackOptions = [],
$overwrite = false
) {
$stackData = [
'operations' => $stackOperations,
'options' => $stackOptions,
];
$stack = Stack::createFromConfig($stackName, $stackData, $organization);
return $this->saveStack($stack, ['overwrite' => $overwrite]);
} | Create a stack.
@deprecated 2.0.0 Use Image::saveStack() instead
@see Image::saveStack()
@param string $stackName Name of the stack
@param array $stackOperations Stack operations
@param string $organization Optional organization name
@param array $stackOptions Stack options
@param bool $overwrite If an existing stack should be overwritten
@throws GuzzleException
@throws \RuntimeException
@return Stack |
public function saveStack(Stack $stack, array $requestConfig = [])
{
if (empty($stack->getName())) {
throw new \LogicException('Stack has no name, please set one.');
}
if (empty($stack->getOrganization())) {
$stack->setOrganization($this->defaultOrganization);
}
$queryString = [];
if (isset($requestConfig['overwrite']) && true === $requestConfig['overwrite']) {
$queryString['overwrite'] = 'true';
}
$contents = $this
->call(
'PUT',
implode('/', [self::STACK_RESOURCE, $stack->getOrganization(), $stack->getName()]),
['json' => $stack->getConfig(), 'query' => $queryString]
)
->getBody()
->getContents();
return Stack::createFromJsonResponse($contents);
} | Save a stack on rokka.
Example:
```language-php
$stack = new Stack(null, 'teststack');
$stack->addStackOperation(new StackOperation('resize', ['width' => 200, 'height' => 200]));
$stack->addStackOperation(new StackOperation('rotate', ['angle' => 45]));
$stack->setStackOptions(['jpg.quality' => 80]);
$requestConfig = ['overwrite' => true];
$stack = $client->saveStack($stack, $requestConfig);
echo 'Created stack ' . $stack->getName() . PHP_EOL;
```
The only requestConfig option currently can be
['overwrite' => true|false] (false is the default)
@since 1.1.0
@param Stack $stack the Stack object to be saved
@param array $requestConfig options for the request
@throws GuzzleException
@throws \LogicException when stack name is not set
@throws \RuntimeException
@return Stack |
public function listStacks($limit = null, $offset = null, $organization = '')
{
$options = [];
if ($limit || $offset) {
$options = ['query' => ['limit' => $limit, 'offset' => $offset]];
}
$contents = $this
->call('GET', self::STACK_RESOURCE.'/'.$this->getOrganizationName($organization), $options)
->getBody()
->getContents();
return StackCollection::createFromJsonResponse($contents);
} | List stacks.
```language-php
use Rokka\Client\Core\Stack;
$client = \Rokka\Client\Factory::getImageClient('testorganization', 'apiKey');
$stacks = $client->listStacks();
foreach ($stacks as $stack) {
echo 'Stack ' . $stack->getName() . PHP_EOL;
}
```
@param null|int $limit Optional limit
@param null|int $offset Optional offset
@param string $organization Optional organization name
@throws GuzzleException
@throws \RuntimeException
@return StackCollection |
public function getStack($stackName, $organization = '')
{
$contents = $this
->call('GET', implode('/', [self::STACK_RESOURCE, $this->getOrganizationName($organization), $stackName]))
->getBody()
->getContents();
return Stack::createFromJsonResponse($contents);
} | Return a stack.
@param string $stackName Stack name
@param string $organization Optional organization name
@throws GuzzleException
@throws \RuntimeException
@return Stack |
public function deleteStack($stackName, $organization = '')
{
$response = $this->call('DELETE', implode('/', [self::STACK_RESOURCE, $this->getOrganizationName($organization), $stackName]));
return '204' == $response->getStatusCode();
} | Delete a stack.
@param string $stackName Delete the stack
@param string $organization Optional organization name
@throws GuzzleException
@return bool True if successful |
public function deleteDynamicMetadata($dynamicMetadataName, $hash, $organization = '', $options = [])
{
if (empty($hash)) {
throw new \LogicException('Missing image Hash.');
}
if (empty($dynamicMetadataName)) {
throw new \LogicException('Missing DynamicMetadata name.');
}
$path = implode('/', [
self::SOURCEIMAGE_RESOURCE,
$this->getOrganizationName($organization),
$hash,
self::DYNAMIC_META_RESOURCE,
$dynamicMetadataName,
]);
$callOptions = [];
if (isset($options['deletePrevious']) && $options['deletePrevious']) {
$callOptions['query'] = ['deletePrevious' => 'true'];
}
$response = $this->call('DELETE', $path, $callOptions);
if ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300) {
return $this->extractHashFromLocationHeader($response->getHeader('Location'));
}
// Throw an exception to be handled by the caller.
throw new \LogicException($response->getBody()->getContents(), $response->getStatusCode());
} | Delete the given DynamicMetadata from a SourceImage.
Returns the new Hash for the SourceImage, it could be the same as the input one if the operation
did not change it.
The only option currently can be
['deletePrevious' => true]
which deletes the previous image from rokka (but not the binary, since that's still used)
If not set, the original image is kept in rokka.
@param string $dynamicMetadataName The DynamicMetadata name
@param string $hash The Image hash
@param string $organization Optional organization name
@param array $options Optional options
@throws GuzzleException
@throws \RuntimeException
@return string|false |
public function setUserMetadataField($field, $value, $hash, $organization = '')
{
return $this->doUserMetadataRequest([$field => $value], $hash, 'PATCH', $organization);
} | Add (or update) the given user-metadata field to the image.
@param string $field The field name
@param string $value The field value
@param string $hash The image hash
@param string $organization The organization name
@throws GuzzleException
@return bool |
public function deleteUserMetadataField($field, $hash, $organization = '')
{
return $this->doUserMetadataRequest([$field => null], $hash, 'PATCH', $organization);
} | Delete the given field from the user-metadata of the image.
@param string $field The field name
@param string $hash The image hash
@param string $organization The organization name
@throws GuzzleException
@return bool |
public function deleteUserMetadataFields($fields, $hash, $organization = '')
{
$data = [];
foreach ($fields as $value) {
$data[$value] = null;
}
return $this->doUserMetadataRequest($data, $hash, 'PATCH', $organization);
} | Delete the given fields from the user-metadata of the image.
@param array $fields The fields name
@param string $hash The image hash
@param string $organization The organization name
@throws GuzzleException
@return bool |
public function getSourceImageUri($hash, $stack, $format = 'jpg', $name = null, $organization = null)
{
$apiUri = new Uri($this->client->getConfig('base_uri'));
$format = strtolower($format);
// Removing the 'api.' part (third domain level)
$parts = explode('.', $apiUri->getHost(), 2);
$baseHost = array_pop($parts);
$path = UriHelper::composeUri(['stack' => $stack, 'hash' => $hash, 'format' => $format, 'filename' => $name]);
// Building the URI as "{scheme}://{organization}.{baseHost}[:{port}]/{stackName}/{hash}[/{name}].{format}"
$parts = [
'scheme' => $apiUri->getScheme(),
'port' => $apiUri->getPort(),
'host' => $this->getOrganizationName($organization).'.'.$baseHost,
'path' => $path->getPath(),
];
return Uri::fromParts($parts);
} | Returns url for accessing the image.
@param string $hash Identifier Hash
@param string|StackUri $stack Stack to apply (name or StackUri object)
@param string $format Image format for output [jpg|png|gif]
@param string $name Optional image name for SEO purposes
@param string $organization Optional organization name (if different from default in client)
@throws \RuntimeException
@return UriInterface |
protected function extractHashFromLocationHeader(array $headers)
{
$location = reset($headers);
// Check if we got a Location header, otherwise something went wrong here.
if (empty($location)) {
return false;
}
$uri = new Uri($location);
$parts = explode('/', $uri->getPath());
// Returning just the HASH part for "api.rokka.io/organization/sourceimages/{HASH}"
$return = array_pop($parts);
if (null === $return) {
return false;
}
return $return;
} | Helper function to extract from a Location header the image hash, only the first Location is used.
@param array $headers The collection of Location headers
@return string|false |
private function doUserMetadataRequest($fields, $hash, $method, $organization = '')
{
$path = implode('/', [
self::SOURCEIMAGE_RESOURCE,
$this->getOrganizationName($organization),
$hash,
self::USER_META_RESOURCE,
]);
$data = [];
if ($fields) {
$fields = $this->applyValueTransformationsToUserMeta($fields);
$data = ['json' => $fields];
}
$response = $this->call($method, $path, $data);
return true;
} | @param array|null $fields
@param string $hash
@param string $method
@param string $organization
@throws GuzzleException
@throws \RuntimeException
@return bool |
private function uploadSourceImageInternal($organization, $options, $requestOptions)
{
if (isset($options['meta_user'])) {
$options['meta_user'] = $this->applyValueTransformationsToUserMeta($options['meta_user']);
$requestOptions[] = [
'name' => 'meta_user[0]',
'contents' => json_encode($options['meta_user']),
];
}
if (isset($options['meta_dynamic'])) {
foreach ($options['meta_dynamic'] as $key => $value) {
if ($value instanceof DynamicMetadataInterface) {
$key = $value::getName();
$value = $value->getForJson();
}
$requestOptions[] = [
'name' => 'meta_dynamic[0]['.$key.']',
'contents' => json_encode($value),
];
}
}
if (isset($options['optimize_source']) && true === $options['optimize_source']) {
$requestOptions[] = [
'name' => 'optimize_source',
'contents' => 'true',
];
}
$contents = $this
->call('POST', self::SOURCEIMAGE_RESOURCE.'/'.$this->getOrganizationName($organization), ['multipart' => $requestOptions])
->getBody()
->getContents();
return SourceImageCollection::createFromJsonResponse($contents);
} | @param string $organization Optional organization
@param array|null $options Options for creating the image (like meta_user and meta_dynamic)
@param array $requestOptions multipart options for the guzzle client
@throws GuzzleException
@throws \RuntimeException
@return SourceImageCollection |
public function getConfigAsArray()
{
$config = ['operations' => []];
foreach ($this->getStackOperations() as $operation) {
$config['operations'][] = $operation->toArray();
}
$config['options'] = $this->getStackOptions();
$config['variables'] = $this->getStackVariables();
return $config;
} | Gets stack operations / options as "flat" array.
Useful for generating dynamic stacks for example
@since 1.2.0
@return array |
private static function parseOptions(array $options)
{
$optionValues = array_filter($options, function ($key) {
return $key % 2;
}, ARRAY_FILTER_USE_KEY);
$optionKeys = array_filter($options, function ($key) {
return !($key % 2);
}, ARRAY_FILTER_USE_KEY);
if (\count($optionKeys) !== \count($optionValues)) {
throw new \InvalidArgumentException('The options given has to be an even array with key and value.');
}
$combined = array_combine($optionKeys, $optionValues);
if (false === $combined) {
// returns false, if both are empty (or not equal length, but that's handled above)
// phpstan complained
return [];
}
return $combined;
} | @param array $options
@throws \InvalidArgumentException
@return array |
protected function configure()
{
$this->bind(Reader::class)->to(AnnotationReader::class);
$this->bindInterceptor(
$this->matcher->subclassesOf(ResourceObject::class),
$this->matcher->startsWith('toString'),
[CamelCaseKeyInterceptor::class]
);
} | {@inheritdoc} |
public function insert($data) {
$map = $this->extractMap($data);
$sql = "INSERT INTO $this->KVS_TABLE ($this->KVS_FK_NAME, $this->KVS_SK_NAME,
uk1, sk1, tk1, co1, co2, json_body, created_at)
VALUES (:foreign_key, :secondary_key, :uk1, :sk1, :tk1, :co1, :co2, :json_body, $this->NOW)";
$map[':foreign_key'] = $this->KVS_FK;
$map[':secondary_key'] = $this->KVS_SK;
$copy = self::preStoreCleanup($data);
$map[':json_body'] = json_encode($copy);
$stmt = $this->PDOX->queryDie($sql, $map);
if ( $stmt->success) return(intval($this->PDOX->lastInsertId()));
return false;
} | /*
Insert a row
$data array A structured array to be inserted into the KVS.
The array must be completely key-value at its top level. Below
that, anything that can be serialized into JSON is allowed. |
public function insertOrUpdate($data) {
$map = $this->extractMap($data);
$sql = "INSERT INTO $this->KVS_TABLE ($this->KVS_FK_NAME, $this->KVS_SK_NAME,
uk1, sk1, tk1, co1, co2, json_body, created_at)
VALUES (:foreign_key, :uk1, :sk1, :tk1, :co1, :co2, :json_body, $this->NOW)
ON DUPLICATE KEY UPDATE
$this->KVS_FK_NAME=:foreign_key, $this->KVS_SK_NAME=:secondary_key,
sk1=:sk1, tk1=:tk1,
co1=:co1, co2=:co2, json_body=:json_body, updated_at=$this->NOW ";
$map[':foreign_key'] = $this->KVS_FK;
$map[':secondary_key'] = $this->KVS_SK;
$map[':json_body'] = json_encode($data);
$stmt = $this->PDOX->queryDie($sql, $map);
if ( $stmt->success) return($this->PDOX->lastInsertId());
return false;
} | /*
Insert a row, or update it if there is a duplicate key clash
$data array A structured array to be inserted into the KVS.
The array must be completely key-value at its top level. Below
that, anything that can be serialized into JSON is allowed. |
public function selectOne($where) {
$clause = false;
$values = false;
$retval = self::extractWhere($where, $clause, $values);
if ( is_string($retval) ) throw new \Exception($val);
$sql = "SELECT KVS.id AS id, json_body, KVS.created_at, KVS.updated_at
FROM $this->KVS_TABLE AS KVS
WHERE $this->KVS_FK_NAME = :foreign_key AND $this->KVS_SK_NAME = :secondary_key AND ".$clause." LIMIT 1";
$values[':foreign_key'] = $this->KVS_FK;
$values[':secondary_key'] = $this->KVS_SK;
$row = $this->PDOX->rowDie($sql, $values);
if ( $row === false ) return false;
$retval = json_decode($row['json_body'], true);
if ( is_array($retval) ) {
$retval['id'] = intval($row['id']);
$retval['created_at'] = $row['created_at'];
$retval['updated_at'] = $row['updated_at'];
}
return $retval;
} | /*
Note that the JSON is returned as an associative array |
public function selectAll($where=false, $order=false, $limit=false) {
$clause = false;
$values = array();
if ( is_array($where) ) {
$retval = self::extractWhere($where, $clause, $values);
if ( is_string($retval) ) throw new \Exception($val);
}
$orderby = '';
if ( is_string($order) ) {
$orderby = self::extractOrder($order);
if ( $orderby === false ) throw new \Exception('Invalid Order value');
}
$sql = "SELECT KVS.id AS id, json_body, KVS.created_at, KVS.updated_at
FROM $this->KVS_TABLE AS KVS
WHERE $this->KVS_FK_NAME = :foreign_key";
if ( $clause ) $sql .= ' AND '.$clause;
if ( $orderby ) $sql .= ' '.$orderby;
$values[':foreign_key'] = $this->KVS_FK;
$rows = $this->PDOX->allRowsDie($sql, $values);
return $rows;
} | /*
$order array of the fields and the order |
public static function validate($data) {
if ( ! is_array($data) ) return '$data must be an array';
$id = U::get($data, 'id');
if ( $id ) {
if ( ! is_int($id) ) return "id must be an an integer";
}
$uk1 = U::get($data, 'uk1');
if ( $uk1 ) {
if ( ! is_string($uk1) ) return "uk1 must be a string";
if ( strlen($uk1) < 1 || strlen($uk1) > 150 ) return "uk1 must be no more than 150 characters";
}
$sk1 = U::get($data, 'sk1');
if ( $sk1 ) {
if ( ! is_string($sk1) ) return "sk1 must be a string";
if ( strlen($sk1) < 1 || strlen($sk1) > 75 ) return "sk1 must be no more than 75 characters";
}
$tk1 = U::get($data, 'tk1');
if ( $tk1 ) {
if ( ! is_string($tk1) ) return "tk1 must be a string";
if ( strlen($tk1) < 1 ) return "tk1 cannot be empty";
}
$co1 = U::get($data, 'co1');
if ( $co1 ) {
if ( ! is_string($co1) ) return "co1 must be a string";
if ( strlen($co1) < 1 || strlen($co1) > 150 ) return "co1 must be no more than 150 characters";
}
$co2 = U::get($data, 'co2');
if ( $co2 ) {
if ( ! is_string($co2) ) return "co2 must be a string";
if ( strlen($co2) < 1 || strlen($co2) > 150 ) return "co2 must be no more than 150 characters";
}
return true;
} | Validate a kvs record |
public function setEvent($var)
{
GPBUtil::checkMessage($var, \Rxnet\EventStore\Data\EventRecord::class);
$this->event = $var;
return $this;
} | Generated from protobuf field <code>.Rxnet.EventStore.Data.EventRecord event = 1;</code>
@param \Rxnet\EventStore\Data\EventRecord $var
@return $this |
public function setLink($var)
{
GPBUtil::checkMessage($var, \Rxnet\EventStore\Data\EventRecord::class);
$this->link = $var;
return $this;
} | Generated from protobuf field <code>.Rxnet.EventStore.Data.EventRecord link = 2;</code>
@param \Rxnet\EventStore\Data\EventRecord $var
@return $this |
private function getOptions(string $class) : Options
{
$ref = new \ReflectionClass($class);
$allows = $this->getAllows($ref->getMethods());
$params = [];
foreach ($allows as $method) {
$params[] = $this->getParams($class, $method);
}
return new Options($allows, $params);
} | Return available resource request method |
public function object(ResourceObject $ro) : RequestInterface
{
return new Request($this->invoker, $ro, $this->method);
} | {@inheritdoc}
@throws \BEAR\Resource\Exception\MethodException |
public function uri($uri) : RequestInterface
{
if (is_string($uri)) {
$uri = new Uri($uri);
}
$uri->method = $this->method;
$ro = $this->newInstance($uri);
$ro->uri = $uri;
$this->request = new Request($this->invoker, $ro, $uri->method, $uri->query, [], $this->linker);
$this->method = 'get';
return $this->request;
} | {@inheritdoc} |
public function href(string $rel, array $query = []) : ResourceObject
{
list($method, $uri) = $this->anchor->href($rel, $this->request, $query);
return $this->{$method}->uri($uri)->addQuery($query)->eager->request();
} | {@inheritdoc} |
protected function configure()
{
$this->bind()->annotatedWith(ImportAppConfig::class)->toInstance($this->importAppConfig);
$this->bind(SchemeCollectionInterface::class)->toProvider(ImportSchemeCollectionProvider::class);
} | {@inheritdoc}
@throws \Ray\Di\Exception\NotFound |
public function handleFrontendEditingInListRendering(RenderItemListEvent $event): void
{
$caller = $event->getCaller();
if (!($caller instanceof HybridList)) {
return;
}
$page = null;
$enabled = (bool) $caller->metamodel_fe_editing;
if ($enabled) {
$page = $this->getPageDetails($caller->metamodel_fe_editing_page);
$enabled = (null !== $page);
$view = $event->getList()->getView();
$view->set(self::FRONTEND_EDITING_PAGE, $page);
$view->set(self::FRONTEND_EDITING_ENABLED_FLAG, $enabled);
}
if ($enabled) {
$tableName = $this->factory->translateIdToMetaModelName($caller->metamodel);
$definition = $this->frontendEditor->createDcGeneral($tableName)->getDataDefinition();
$enabled = $definition->getBasicDefinition()->isCreatable();
if ($enabled) {
$url = $this->generateAddUrl($page);
$caller->Template->addUrl = $url;
$caller->Template->addNewLabel = $this->translateLabel('metamodel_add_item', $tableName);
$event->getTemplate()->addUrl = $url;
}
}
$event->getTemplate()->editEnable = $caller->Template->editEnable = $enabled;
} | Process the event.
@param RenderItemListEvent $event The event to process.
@return void |
private function generateAddUrl(array $page): string
{
$event = new GenerateFrontendUrlEvent($page, null, $page['language']);
$this->dispatcher->dispatch(ContaoEvents::CONTROLLER_GENERATE_FRONTEND_URL, $event);
$url = UrlBuilder::fromUrl($event->getUrl() . '?')
->setQueryParameter('act', 'create');
return $url->getUrl();
} | Generate the url to add an item.
@param array $page The page details.
@return string |
private function getPageDetails($pageId): ?array
{
if (empty($pageId)) {
return null;
}
$event = new GetPageDetailsEvent($pageId);
$this->dispatcher->dispatch(ContaoEvents::CONTROLLER_GET_PAGE_DETAILS, $event);
return $event->getPageDetails();
} | Retrieve the details for the page with the given id.
@param string $pageId The id of the page to retrieve the details for.
@return array |
private function translateLabel($transString, $definitionName, array $parameters = []): string
{
$translator = $this->translator;
$label = $translator->trans($definitionName . '.' . $transString, $parameters, 'contao_' . $definitionName);
if ($label !== $definitionName . '.' . $transString) {
return $label;
}
$label = $translator->trans('MSC.' . $transString, $parameters, 'contao_default');
if ($label !== $transString) {
return $label;
}
// Fallback, just return the key as is it.
return $transString;
} | Get a translated label from the translator.
The fallback is as follows:
1. Try to translate via the data definition name as translation section.
2. Try to translate with the prefix 'MSC.'.
3. Return the input value as nothing worked out.
@param string $transString The non translated label for the button.
@param string $definitionName The data definition of the current item.
@param array $parameters The parameters to pass to the translator.
@return string |
protected function configure()
{
$this->bind()->annotatedWith(AppName::class)->toInstance($this->appName);
$this->install(new ResourceClientModule);
$this->install(new EmbedResourceModule);
} | {@inheritdoc} |
public function settingsGetAll()
{
global $CFG;
$name = $this->ENTITY_NAME;
$retval = $this->ltiParameter($name."_settings", false);
// Null means in the session - false means not in the session
if ( $retval === null || ( is_string($retval) && strlen($retval) < 1 ) ) {
$retval = array();
} else if ( strlen($retval) > 0 ) {
try {
$retval = json_decode($retval, true);
} catch(Exception $e) {
$retval = array();
}
}
// echo("Session $name: "); var_dump($retval);
if ( is_array($retval) ) return $retval;
$row = $this->launch->pdox->rowDie("SELECT settings FROM {$CFG->dbprefix}{$this->TABLE_NAME}
WHERE {$name}_id = :ID",
array(":ID" => $this->id));
if ( $row === false ) return array();
$json = $row['settings'];
if ( $json === null ) return array();
try {
$retval = json_decode($json, true);
} catch(Exception $e) {
$retval = array();
}
// Put in session for quicker retrieval
$this->ltiParameterUpdate($name."_settings", json_encode($retval));
// echo("<hr>From DB\n");var_dump($retval);
return $retval;
} | Retrieve an array of all of the settings
If there are no settings, return an empty array. |
public function settingsGet($key, $default=false)
{
$allSettings = $this->settingsGetAll();
if ( array_key_exists ($key, $allSettings ) ) {
return $allSettings[$key];
} else {
return $default;
}
} | Retrieve a particular key from the settings.
Returns the value found in settings or false if the key was not found.
@param $key - The key to get from the settings.
@param $default - What to return if the key is not present |
public function settingsSet($key, $value)
{
$allSettings = $this->settingsGetAll();
$allSettings[$key] = $value;
$this->settingsSetAll($allSettings);
} | Update a single key in settings |
public function settingsUpdate($keyvals)
{
$allSettings = $this->settingsGetAll();
$different = false;
foreach ( $keyvals as $k => $v ) {
if ( array_key_exists ($k, $allSettings ) ) {
if ( $v != $allSettings[$k] ) {
$different = true;
break;
}
} else {
$different = true;
break;
}
}
if ( ! $different ) return;
$newSettings = array_merge($allSettings, $keyvals);
return $this->settingsSetAll($newSettings);
} | Set or update a number of keys to new values in link settings.
@params $keyvals An array of key value pairs that are to be placed in the
settings. |
protected function settingsSetAll($new_settings)
{
global $CFG;
$this->settingsDebugArray = array();
if ( ! is_array($new_settings) ) {
$this->settingsDebugArray[] = 'settingsSetAll requires an array';
return false;
}
$name = $this->ENTITY_NAME;
// Update in session for quicker retrieval
$this->ltiParameterUpdate($name."_settings", json_encode($new_settings));
$stmt = $this->launch->pdox->queryDie("UPDATE {$CFG->dbprefix}{$this->TABLE_NAME}
SET settings = :NEW WHERE {$name}_id = :ID",
array(":NEW" => json_encode($new_settings), ":ID" => $this->id));
if ( ! $stmt->success ) {
$this->settingsDebugArray[] = "Failed to update settings {$name}_id=".$this->id;
return false;
}
$this->settingsDebugArray[] = count($new_settings)." settings updated {$name}_id=".$this->id;
$settings_url = $this->ltiParameter($name."_settings_url", null); // NULL is actually empty
if ( $settings_url === null ) return true;
$this->settingsDebugArray[] = array("Sending settings to ".$settings_url);
$retval = LTIX::settingsSend($new_settings, $settings_url, $this->settingsDebugArray);
return $retval;
} | Replace all the settings (Dangerous) |
public static function __($message, $textdomain=false) {
global $CFG, $PDOX, $TSUGI_LOCALE, $TSUGI_LOCALE_RELOAD, $TSUGI_TRANSLATE;
// If we have been asked to do some translation
if ( isset($CFG->checktranslation) && $CFG->checktranslation && isset($PDOX) )
{
$string_sha = U::lti_sha256($message);
$domain = $textdomain;
if ( ! $domain ) $domain = textdomain(NULL);
if ( $domain ) {
$stmt = $PDOX->queryReturnError("INSERT INTO {$CFG->dbprefix}tsugi_string
(domain, string_text, string_sha256) VALUES ( :DOM, :TEXT, :SHA)
ON DUPLICATE KEY UPDATE updated_at = NOW()",
array(
':DOM' => $domain,
':TEXT' => $message,
':SHA' => $string_sha
)
);
}
}
// Setup Text domain late...
if ( $TSUGI_LOCALE_RELOAD ) {
self::setupTextDomain();
}
if ( isset($TSUGI_TRANSLATE) && $TSUGI_TRANSLATE ) {
$retval = $TSUGI_TRANSLATE->trans($message);
// error_log("DOM=$TSUGI_LOCALE msg=$message trans=$retval");
return $retval;
}
if ( ! function_exists('gettext')) return $message;
if ( $textdomain === false ) {
return gettext($message);
} else {
return dgettext($textdomain, $message);
}
} | Translate a messege from the master domain
Pattern borrowed from WordPress |
public static function setLocale($locale=null)
{
global $CFG, $TSUGI_LOCALE, $TSUGI_LOCALE_RELOAD;
// No internationalization support
if ( isset($CFG->legacytranslation) ) {
if ( ! function_exists('bindtextdomain') ) return;
if ( ! function_exists('textdomain') ) return;
}
if ( isset($CFG->legacytranslation) && $locale &&
strpos($locale, 'UTF-8') === false ) $locale = $locale . '.UTF-8';
if ( $locale === null && isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ) {
if ( class_exists('\Locale') ) {
try {
// Symfony may implement a stub for this function that throws an exception
$locale = \Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
} catch (exception $e) { }
}
if ($locale === null) { // Crude fallback if we can't use Locale::acceptFromHttp
$pieces = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
$locale = $pieces[0];
}
}
if ( $locale === null && isset($CFG->fallbacklocale) && $CFG->fallbacklocale ) {
$locale = $CFG->fallbacklocale;
}
if ( $locale === null ) return;
$locale = str_replace('-','_',$locale);
if ( isset($CFG->legacytranslation) ) {
putenv('LC_ALL='.$locale);
setlocale(LC_ALL, $locale);
}
// error_log("setLocale=$locale");
if ( $TSUGI_LOCALE != $locale ) $TSUGI_LOCALE_RELOAD = true;
$TSUGI_LOCALE = $locale;
} | Set the LOCAL for the current user |
public static function setupTextDomain() {
global $CFG, $TSUGI_LOCALE, $TSUGI_LOCALE_RELOAD, $TSUGI_TRANSLATE;
$domain = $CFG->getScriptFolder();
$folder = $CFG->getScriptPathFull()."/locale";
// error_log("setupTextDomain($domain, $folder, $TSUGI_LOCALE, $TSUGI_LOCALE_RELOAD)");
$TSUGI_LOCALE_RELOAD = false;
$TSUGI_TRANSLATE = false;
if ( isset($CFG->legacytranslation) && $CFG->legacytranslation ) {
if (function_exists('bindtextdomain')) {
bindtextdomain("master", $CFG->dirroot."/locale");
bindtextdomain($domain, $folder);
}
if (function_exists('textdomain')) {
textdomain($domain);
}
return;
}
$lang = substr($TSUGI_LOCALE, 0, 2);
// error_log("lang=$lang");
$master_file = $CFG->dirroot."/locale/$lang/LC_MESSAGES/master.mo";
$domain_file = $CFG->getScriptPathFull()."/locale/$lang/LC_MESSAGES/$domain.mo";
$TSUGI_TRANSLATE = new Translator($lang, new MessageSelector());
if ( file_exists($master_file) ) {
$TSUGI_TRANSLATE->addLoader('master', new MoFileLoader());
$TSUGI_TRANSLATE->addResource('master', $master_file, $lang);
}
if ( file_exists($domain_file) ) {
$TSUGI_TRANSLATE->addLoader($domain, new MoFileLoader());
$TSUGI_TRANSLATE->addResource($domain, $domain_file, $lang);
}
} | Set up the translation entities |
public static function allowLtiLinkItem($postdata) {
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 true;
}
return false;
} | allowLtiLinkItem - Returns true if we can return LTI Link Items |
public static function allowContentItem($postdata) {
if ( ! isset($postdata['content_item_return_url']) ) return false;
if ( isset($postdata['accept_media_types']) ) {
$web_mimetype = 'text/html';
$m = new Mimeparse;
$web_allowed = $m->best_match(array($web_mimetype), $postdata['accept_media_types']);
if ( $web_mimetype != $web_allowed ) return false;
return true;
}
return false;
} | allowContentItem - Returns true if we can return HTML Items |
public static function allowImportItem($postdata) {
$cc_types = array('application/vnd.ims.imsccv1p1',
'application/vnd.ims.imsccv1p2', 'application/vnd.ims.imsccv1p3');
if ( ! isset($postdata['content_item_return_url']) ) return false;
if ( isset($postdata['accept_media_types']) ) {
$accept = $postdata['accept_media_types'];
foreach($cc_types as $cc_mimetype ){
$m = new Mimeparse;
$cc_allowed = $m->best_match(array($cc_mimetype), $accept);
if ( $cc_mimetype == $cc_allowed ) return true;
}
}
return false;
} | allowImportItem - Returns true if we can return IMS Common Cartridges |
function getContentItemSelection($data=false)
{
$selection = json_encode($this->json);
$parms = array();
$parms["lti_message_type"] = "ContentItemSelection";
$parms["lti_version"] = "LTI-1p0";
$parms["content_items"] = $selection;
if ( $data ) $parms['data'] = $data;
return $parms;
} | Return the parameters to send back to the LMS |
public function addLtiLinkItem($url, $title=false, $text=false,
$icon=false, $fa_icon=false, $custom=false,
$points=false, $activityId=false, $additionalParams = array())
{
global $CFG;
$params = array(
'url' => $url,
'title' => $title,
'text' => $text,
'icon' => $icon,
'fa_icon' => $fa_icon,
'custom' => $custom,
'points' => $points,
'activityId' => $activityId,
);
// package the parameter list into an array for the helper function
if (! empty($additionalParams['placementTarget']))
$params['placementTarget'] = $additionalParams['placementTarget'];
if (! empty($additionalParams['placementWidth']))
$params['placementWidth'] = $additionalParams['placementWidth'];
if (! empty($additionalParams['placementHeight']))
$params['placementHeight'] = $additionalParams['placementHeight'];
$this->addLtiLinkItemExtended($params);
} | addLtiLinkItem - Add an LTI Link Content Item
@param $url The launch URL of the tool that is about to be placed
@param $title A plain text title of the content-item.
@param $text A plain text description of the content-item.
@param $icon An image URL of an icon
@param $fa_icon The class name of a FontAwesome icon
@param $custom An optional array of custom key / value pairs
@param $points The number of points if this is an assignment
@param $activityId The activity for the item |
public function getContent()
{
if (null === $this->templateHelper) {
throw new \RuntimeException('Rokka TemplateHelper is not set in RokkaHash. Needed for downloading images.');
}
if (null === $this->content) {
$rokkaHash = $this->getRokkaHash();
if (null !== $rokkaHash) {
$this->content = $this->templateHelper->getRokkaClient()->getSourceImageContents($rokkaHash);
}
}
return $this->content;
} | Returns the actual content of an image.
@since 1.3.0
@throws \GuzzleHttp\Exception\GuzzleException
@return null|string |