code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
public function loadConfiguration(): void { $builder = $this->getContainerBuilder(); $config = $this->getConfig($this->defaults); $reader = $builder->addDefinition($this->prefix('delegatedReader')) ->setFactory(AnnotationReader::class) ->setAutowired(false); foreach ((array) $config['ignore'] as $annotationName) { $reader->addSetup('addGlobalIgnoredName', [$annotationName]); AnnotationReader::addGlobalIgnoredName($annotationName); } $this->loadCacheConfiguration(); $builder->addDefinition($this->prefix('reader')) ->setType(Reader::class) ->setFactory(CachedReader::class, [ $this->prefix('@delegatedReader'), $this->prefix('@cache'), $config['debug'], ]); AnnotationRegistry::registerUniqueLoader('class_exists'); }
Register services
public function import(Contact $contact, ImportRecordsDataTable $importRecordsDataTable) { return $importRecordsDataTable->with([ 'resource' => $contact, 'tabs' => 'adminarea.contacts.tabs', 'url' => route('adminarea.contacts.stash'), 'id' => "adminarea-contacts-{$contact->getRouteKey()}-import-table", ])->render('cortex/foundation::adminarea.pages.datatable-dropzone'); }
Import contacts. @TODO: Refactor required! Do we need import for bookings? Yes? refactor then! @param \Cortex\Contacts\Models\Contact $contact @param \Cortex\Foundation\DataTables\ImportRecordsDataTable $importRecordsDataTable @return \Illuminate\View\View
public function stash(ImportFormRequest $request, DefaultImporter $importer, Event $event) { // Handle the import $importer->config['resource'] = $this->resource; $importer->handleImport(); }
Stash events. @param \Cortex\Foundation\Http\Requests\ImportFormRequest $request @param \Cortex\Foundation\Importers\DefaultImporter $importer @param \Cortex\Bookings\Models\Event $event @return void
protected function form(Event $event, EventBooking $eventBooking) { $tickets = $event->tickets->pluck('name', 'id'); $customers = app('rinvex.contacts.contact')->all()->pluck('full_name', 'id'); return view('cortex/bookings::adminarea.pages.event_booking', compact('event', 'eventBooking', 'tickets', 'customers')); }
Show event create/edit form. @param \Cortex\Bookings\Models\Event $event @param \Cortex\Bookings\Models\EventBooking $eventBooking @return \Illuminate\View\View
public function store(EventBookingFormRequest $request, Event $event, EventBooking $eventBooking) { return $this->process($request, $event, $eventBooking); }
Store new event. @param \Cortex\Bookings\Http\Requests\Adminarea\EventBookingFormRequest $request @param \Cortex\Bookings\Models\Event $event @param \Cortex\Bookings\Models\EventBooking $eventBooking @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
protected function process(FormRequest $request, Event $event, EventBooking $eventBooking) { // Prepare required input fields $data = $request->validated(); // Save event $eventBooking->fill($data)->save(); return intend([ 'url' => route('adminarea.events.bookings.index', ['event' => $event]), 'with' => ['success' => trans('cortex/foundation::messages.resource_saved', ['resource' => trans('cortex/bookings::common.event_booking'), 'identifier' => $eventBooking->name])], ]); }
Process stored/updated event. @param \Illuminate\Foundation\Http\FormRequest $request @param \Cortex\Bookings\Models\Event $event @param \Cortex\Bookings\Models\EventBooking $eventBooking @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
public function destroy(Event $event, EventBooking $eventBooking) { $event->bookings()->where($eventBooking->getKeyName(), $eventBooking->getKey())->first()->delete(); return intend([ 'url' => route('adminarea.events.bookings.index', ['event' => $event]), 'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/bookings::common.event_booking'), 'identifier' => $eventBooking->name])], ]); }
Destroy given event. @param \Cortex\Bookings\Models\Event $event @param \Cortex\Bookings\Models\EventBooking $eventBooking @throws \Exception @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
public function authorizeResource($model, $parameter = null, array $options = [], $request = null): void { $middleware = []; $parameter = $parameter ?: snake_case(class_basename($model)); foreach ($this->mapResourceAbilities() as $method => $ability) { $modelName = in_array($method, $this->resourceMethodsWithoutModels()) ? $model : $parameter; $middleware["can:update,{$modelName}"][] = $method; $middleware["can:{$ability},media"][] = $method; } foreach ($middleware as $middlewareName => $methods) { $this->middleware($middlewareName, $options)->only($methods); } }
{@inheritdoc}
public function index(Event $event, MediaDataTable $mediaDataTable) { return $mediaDataTable->with([ 'resource' => $event, 'tabs' => 'adminarea.events.tabs', 'id' => "adminarea-events-{$event->getRouteKey()}-media-table", 'url' => route('adminarea.events.media.store', ['event' => $event]), ])->render('cortex/foundation::adminarea.pages.datatable-dropzone'); }
List event media. @param \Cortex\Bookings\Models\Event $event @param \Cortex\Foundation\DataTables\MediaDataTable $mediaDataTable @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
public function store(ImageFormRequest $request, Event $event): void { $event->addMediaFromRequest('file') ->sanitizingFileName(function ($fileName) { return md5($fileName).'.'.pathinfo($fileName, PATHINFO_EXTENSION); }) ->toMediaCollection('default', config('cortex.bookings.media.disk')); }
Store new event media. @param \Cortex\Foundation\Http\Requests\ImageFormRequest $request @param \Cortex\Bookings\Models\Event $event @return void
public function destroy(Event $event, Media $media) { $event->media()->where($media->getKeyName(), $media->getKey())->first()->delete(); return intend([ 'url' => route('adminarea.events.media.index', ['event' => $event]), 'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/foundation::common.media'), 'identifier' => $media->getRouteKey()])], ]); }
Destroy given event media. @param \Cortex\Bookings\Models\Event $event @param \Spatie\MediaLibrary\Models\Media $media @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
protected function get(string $path, array $query = []) { $response = $this->connection->getHttpClient()->get($path, compact('query')); return json_decode($response->getBody()->getContents(), true); }
Send a GET request with query parameters. @param string $path @param array $query @return array|string
protected function post(string $path, array $parameters = []) { $response = $this->connection->getHttpClient()->post( $path, ['json' => $parameters] ); return json_decode($response->getBody()->getContents(), true); }
Send a POST request with JSON-encoded parameters. @param string $path @param array $parameters @return array|string
protected function prepareForValidation(): void { $data = $this->all(); $duration = explode(' - ', $data['duration']); $data['starts_at'] = (new Carbon($duration[0]))->toDateTimeString(); $data['ends_at'] = (new Carbon($duration[1]))->toDateTimeString(); $this->replace($data); }
Prepare the data for validation. @return void
public function rules(): array { $event = $this->route('event') ?? app('cortex.bookings.event'); $event->updateRulesUniques(); return array_merge($event->getRules(), [ 'duration' => 'required', ]); }
Get the validation rules that apply to the request. @return array
public function getOneFile( string $fieldKey, $fileIndex = 0 ) : ProvidesUploadedFileData { $files = $this->getFiles( $fieldKey ); return $files[ $fileIndex ] ?? new UploadedFile( '', '', '', 0, UPLOAD_ERR_NO_FILE ); }
@param string $fieldKey @param int|string $fileIndex @return ProvidesUploadedFileData
protected function prepareForValidation(): void { $data = $this->all(); $data['base_cost'] = (int) $data['base_cost']; $this->replace($data); }
Prepare the data for validation. @return void
public function rules(): array { $service = $this->route('service') ?? app('cortex.bookings.service'); $service->updateRulesUniques(); $rules = $service->getRules(); $rules['availabilities.*.range'] = ['sometimes', 'required', 'string']; $rules['availabilities.*.from'] = ['sometimes', 'required', 'string']; $rules['availabilities.*.to'] = ['sometimes', 'required', 'string']; $rules['availabilities.*.is_bookable'] = ['sometimes', 'boolean']; $rules['availabilities.*.priority'] = ['sometimes', 'nullable', 'integer']; $rules['rates.*.range'] = ['sometimes', 'required', 'string']; $rules['rates.*.from'] = ['sometimes', 'required', 'string']; $rules['rates.*.to'] = ['sometimes', 'required', 'string']; $rules['rates.*.base_cost'] = ['sometimes', 'nullable', 'numeric']; $rules['rates.*.unit_cost'] = ['sometimes', 'required', 'numeric']; return $rules; }
Get the validation rules that apply to the request. @return array
public function query() { $custoemrs = $this->resource->tickets()->with(['bookings'])->get()->pluck('bookings')->collapse()->pluck('customer_id'); return app('rinvex.contacts.contact')->whereIn('id', $custoemrs); }
Get the query object to be processed by dataTables. @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder|\Illuminate\Support\Collection
protected function getColumns(): array { $link = config('cortex.foundation.route.locale_prefix') ? '"<a href=\""+routes.route(\'adminarea.contacts.edit\', {contact: full.id, locale: \''.$this->request->segment(1).'\'})+"\">"+data+"</a>"' : '"<a href=\""+routes.route(\'adminarea.contacts.edit\', {contact: full.id})+"\">"+data+"</a>"'; return [ 'given_name' => ['title' => trans('cortex/contacts::common.given_name'), 'render' => $link, 'responsivePriority' => 0], 'family_name' => ['title' => trans('cortex/contacts::common.family_name')], 'email' => ['title' => trans('cortex/contacts::common.email')], 'phone' => ['title' => trans('cortex/contacts::common.phone')], 'country_code' => ['title' => trans('cortex/contacts::common.country'), 'render' => 'full.country_emoji+" "+data'], 'language_code' => ['title' => trans('cortex/contacts::common.language'), 'visible' => false], 'source' => ['title' => trans('cortex/contacts::common.source'), 'visible' => false], 'method' => ['title' => trans('cortex/contacts::common.method'), 'visible' => false], 'created_at' => ['title' => trans('cortex/contacts::common.created_at'), 'render' => "moment(data).format('YYYY-MM-DD, hh:mm:ss A')"], 'updated_at' => ['title' => trans('cortex/contacts::common.updated_at'), 'render' => "moment(data).format('YYYY-MM-DD, hh:mm:ss A')"], ]; }
Get columns. @return array
public function connect(array $config, string $name = 'main'): Connection { if (isset($this->connections[$name])) { throw new InvalidArgumentException("Connection [$name] is already configured."); } $this->connections[$name] = new Connection($config); return $this->connections[$name]; }
Connect to the given connection. @param array $config @param string $name @return \ArkEcosystem\Client\Connection
public function connection(string $name = null): Connection { $name = $name ?? $this->getDefaultConnection(); if (! isset($this->connections[$name])) { throw new InvalidArgumentException("Connection [$name] not configured."); } return $this->connections[$name]; }
Get a connection instance. @param string|null $name @return \ArkEcosystem\Client\Connection
public function destroy(Service $service) { $service->delete(); return intend([ 'url' => route('adminarea.services.index'), 'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/bookings::common.service'), 'identifier' => $service->name])], ]); }
Destroy given service. @param \Cortex\Bookings\Models\Service $service @throws \Exception @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
public function api(string $name): API\AbstractAPI { $name = ucfirst($name); $class = "ArkEcosystem\\Client\\API\\{$name}"; if (! class_exists($class)) { throw new RuntimeException("Class [$class] does not exist."); } return new $class($this); }
Make a new resource instance. @param string $name @return \ArkEcosystem\Client\API\AbstractAPI
public function index(Service $service, MediaDataTable $mediaDataTable) { return $mediaDataTable->with([ 'resource' => $service, 'tabs' => 'adminarea.services.tabs', 'id' => "adminarea-services-{$service->getRouteKey()}-media-table", 'url' => route('adminarea.services.media.store', ['service' => $service]), ])->render('cortex/foundation::adminarea.pages.datatable-dropzone'); }
List service media. @param \Cortex\Bookings\Models\Service $service @param \Cortex\Foundation\DataTables\MediaDataTable $mediaDataTable @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
public function store(ImageFormRequest $request, Service $service): void { $service->addMediaFromRequest('file') ->sanitizingFileName(function ($fileName) { return md5($fileName).'.'.pathinfo($fileName, PATHINFO_EXTENSION); }) ->toMediaCollection('default', config('cortex.bookings.media.disk')); }
Store new service media. @param \Cortex\Foundation\Http\Requests\ImageFormRequest $request @param \Cortex\Bookings\Models\Service $service @return void
public function destroy(Service $service, Media $media) { $service->media()->where($media->getKeyName(), $media->getKey())->first()->delete(); return intend([ 'url' => route('adminarea.services.media.index', ['service' => $service]), 'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/foundation::common.media'), 'identifier' => $media->getRouteKey()])], ]); }
Destroy given service media. @param \Cortex\Bookings\Models\Service $service @param \Spatie\MediaLibrary\Models\Media $media @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
public function up(): void { Schema::create(config('cortex.bookings.tables.events'), function (Blueprint $table) { // Columns $table->increments('id'); $table->string('slug'); $table->{$this->jsonable()}('name'); $table->{$this->jsonable()}('description')->nullable(); $table->boolean('is_public')->default(true); $table->dateTime('starts_at')->nullable(); $table->dateTime('ends_at')->nullable(); $table->string('timezone')->nullable(); $table->string('location')->nullable(); $table->auditableAndTimestamps(); $table->softDeletes(); }); }
Run the migrations. @return void
final public function notify( CarriesEventData $event ) { $namespaceComponents = explode( "\\", get_class( $event ) ); $lastComponent = (string)end( $namespaceComponents ); $methodName = sprintf( 'when%s', preg_replace( '#Event$#', '', $lastComponent ) ); if ( is_callable( [$this, $methodName] ) ) { $this->{$methodName}( $event ); } else { throw (new EventSubscriberMethodNotCallable())->withMethodName( $methodName ); } }
@param CarriesEventData $event @throws EventSubscriberMethodNotCallable
protected function prepareForValidation(): void { $data = $this->all(); // Calculate price $endsAt = new Carbon($data['ends_at']); $startsAt = new Carbon($data['starts_at']); $service = app('cortex.bookings.service')->find($data['service_id']); [$price, $formula, $currency] = app('cortex.bookings.service_booking')->calculatePrice($service, $startsAt, $endsAt, $data['quantity']); // Fill missing fields $data['ends_at'] = $endsAt; $data['starts_at'] = $startsAt; $data['customer_type'] = 'member'; $data['bookable_type'] = 'service'; $data['currency'] = $currency; $data['formula'] = $formula; $data['price'] = $price; $this->replace($data); }
Prepare the data for validation. @return void
private function getMatchingRoutes( string $uri, $routes ) : array { $router = new OptionsRouter( $routes ); return $router->findMatchingRoutes( $uri ); }
@param string $uri @param array|\Traversable $routes @return array|RoutesToHandler[] @throws \IceHawk\IceHawk\Routing\Exceptions\RoutesAreNotTraversable
public function handle(): void { parent::handle(); $this->call('vendor:publish', ['--tag' => 'cortex-bookings-lang', '--force' => $this->option('force')]); $this->call('vendor:publish', ['--tag' => 'cortex-bookings-views', '--force' => $this->option('force')]); $this->call('vendor:publish', ['--tag' => 'cortex-bookings-config', '--force' => $this->option('force')]); $this->call('vendor:publish', ['--tag' => 'cortex-bookings-migrations', '--force' => $this->option('force')]); }
Execute the console command. @return void
public function export() { // Check if value is cached and set array to cached version if (Cache::has(config('laravel-localization.caches.key'))) { $this->strings = Cache::get(config('laravel-localization.caches.key')); return $this; } foreach (config('laravel-localization.paths.lang_dirs') as $dir) { try { // Collect language files and build array with translations $files = $this->findLanguageFiles($dir); // Parse translations and create final array array_walk($files['lang'], [$this, 'parseLangFiles'], $dir); array_walk($files['vendor'], [$this, 'parseVendorFiles'], $dir); array_walk($files['json'], [$this, 'parseJsonFiles'], $dir); } catch (\Exception $exception) { \Log::critical('Can\'t read lang directory '.$dir.', error: '.$exception->getMessage()); } } // Trigger event for final translated array event(new LaravelLocalizationExported($this->strings)); // If timeout > 0 save array to cache if (config('laravel-localization.caches.timeout', 0) > 0) { Cache::store(config('laravel-localization.caches.driver', 'file')) ->put( config('laravel-localization.caches.key', 'localization.array'), $this->strings, config('laravel-localization.caches.timeout', 60) ); } return $this; }
Method to return generate array with contents of parsed language files. @return object
protected function findLanguageFiles($path) { // Loop through directories $dirIterator = new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS); $recIterator = new \RecursiveIteratorIterator($dirIterator); // Fetch only php files - skip others $phpFiles = array_values( array_map('current', iterator_to_array( new \RegexIterator($recIterator, $this->phpRegex, \RecursiveRegexIterator::GET_MATCH) ) ) ); $jsonFiles = array_values( array_map('current', iterator_to_array( new \RegexIterator($recIterator, $this->jsonRegex, \RecursiveRegexIterator::GET_MATCH) ) ) ); $files = array_merge($phpFiles, $jsonFiles); // Sort array by filepath sort($files); // Remove full path from items array_walk($files, function (&$item) use ($path) { $item = str_replace($path, '', $item); }); // Fetch non-vendor files from filtered php files $nonVendorFiles = array_filter($files, function ($file) { return strpos($file, $this->excludePath) === false && strpos($file, '.json') === false; }); // Fetch vendor files from filtered php files $vendorFiles = array_filter(array_diff($files, $nonVendorFiles), function ($file) { return strpos($file, 'json') === false; }); // Fetch .json files from filtered files $jsonFiles = array_filter($files, function ($file) { return strpos($file, '.json') !== false; }); return [ 'lang' => array_values($nonVendorFiles), 'vendor' => array_values($vendorFiles), 'json' => array_values($jsonFiles), ]; }
Find available language files and parse them to array. @param string $path @return array
public function toFlat($prefix = '.') { $results = []; $default_locale = config('laravel-localization.js.default_locale'); $default_json_strings = null; foreach ($this->strings as $lang => $strings) { if ($lang !== 'json') { foreach ($strings as $lang_array => $lang_messages) { $key = $lang.$prefix.$lang_array; $results[$key] = $lang_messages; } } else { foreach ($strings as $json_lang => $json_strings) { $key = $json_lang.$prefix.'__JSON__'; if (array_key_exists($key, $results)) { $results[$key] = $json_strings; } else { $results[$key] = $json_strings; } // Pick only the first $json_strings if (! $default_json_strings) { $default_json_strings = $json_strings; } } } } // Create a JSON key value pair for the default language $default_key = $default_locale.$prefix.'__JSON__'; if (! array_key_exists($default_key, $results)) { $buffer = array_keys( $default_json_strings ? get_object_vars($default_json_strings) : [] ); $results[$default_key] = array_combine($buffer, $buffer); } return $results; }
If you need special format of array that's recognised by some npm localization packages as Lang.js https://github.com/rmariuzzo/Lang.js use this method. @param array $array @param string $prefix @return array
protected function parseLangFiles($file, $key, $dir) { // Base package name without file ending $packageName = basename($file, '.php'); // Get package, language and file contents from language file // /<language_code>/(<package/)<filename>.php $language = explode(DIRECTORY_SEPARATOR, $file)[1]; $fileContents = require $dir.DIRECTORY_SEPARATOR.$file; // Check if language already exists in array if (array_key_exists($language, $this->strings)) { if (array_key_exists($packageName, $this->strings[$language])) { $this->strings[$language][$packageName] = array_replace_recursive((array) $this->strings[$language][$packageName], (array) $fileContents); } else { $this->strings[$language][$packageName] = $fileContents; } } else { $this->strings[$language] = [ $packageName => $fileContents, ]; } }
Method to parse language files. @param string $file
protected function parseVendorFiles($file, $key, $dir) { // Base package name without file ending $packageName = basename($file, '.php'); // Get package, language and file contents from language file // /vendor/<package>/<language_code>/<filename>.php $package = explode(DIRECTORY_SEPARATOR, $file)[2]; $language = explode(DIRECTORY_SEPARATOR, $file)[3]; $fileContents = require $dir.DIRECTORY_SEPARATOR.$file; // Check if language already exists in array if (array_key_exists($language, $this->strings)) { // Check if package already exists in language if (array_key_exists($package, $this->strings[$language])) { if (array_key_exists($packageName, $this->strings[$language][$package])) { $this->strings[$language][$package][$packageName] = array_replace_recursive((array) $this->strings[$language][$package][$packageName], (array) $fileContents); } else { $this->strings[$language][$package][$packageName] = $fileContents; } } else { $this->strings[$language][$package] = [$packageName => $fileContents]; } } else { $this->strings[$language] = [ $package => [ $packageName => $fileContents, ], ]; } }
Method to parse language files from vendor folder. @param string $file
public function handle() { $messages = ExportLocalizations::export()->toArray(); $filepath = config('laravel-localization.js.filepath', resource_path('assets/js')); $filename = config('laravel-localization.js.filename', 'll_messages.js'); $adapter = new Local($filepath); $filesystem = new Filesystem($adapter); $contents = 'export default '.json_encode($messages); if ($filesystem->has($filename)) { $filesystem->delete($filename); $filesystem->write($filename, $contents); } else { $filesystem->write($filename, $contents); } $this->info('Messages exported to JavaScript file, you can find them at '.$filepath.DIRECTORY_SEPARATOR .$filename); return true; }
Execute the console command. @return mixed
public static function applyEdits(array $edits, string $text) : string { $prevEditStart = PHP_INT_MAX; for ($i = \count($edits) - 1; $i >= 0; $i--) { $edit = $edits[$i]; if ($prevEditStart < $edit->start || $prevEditStart < $edit->start + $edit->length) { throw new \OutOfBoundsException(sprintf( 'Supplied TextEdit[] "%s" must not overlap and be in increasing start position order.', $edit->content )); } if ($edit->start < 0 || $edit->length < 0 || $edit->start + $edit->length > \strlen($text)) { throw new \OutOfBoundsException("Applied TextEdit range out of bounds."); } $prevEditStart = $edit->start; $head = \substr($text, 0, $edit->start); $tail = \substr($text, $edit->start + $edit->length); $text = $head . $edit->content . $tail; } return $text; }
Applies array of edits to the document, and returns the resulting text. Supplied $edits must not overlap, and be ordered by increasing start position. Note that after applying edits, the original AST should be invalidated. @param array | TextEdit[] $edits @param string $text @return string
public function getFullUrl() { $parts = $this->toArray(); unset($parts['full_url'], $parts['pass']); foreach ($parts as $method => $param) { if ($param) { $method = 'add' . ucfirst($method); $this->$method($param); } } return ltrim(implode($this->fullUrl), '/'); }
Build the final url based on the structure defined @return string
public function addUser($user) { //only add the information if there are username and password if ($user && $this->getPass()) { $this->fullUrl['credentials'] = $user . ':' . $this->getPass() . '@'; } return $this; }
Add the credentials to the final url, both username and password are added in this stage @param string $user @return Url
public function addQuery(array $query) { $queryParts = []; foreach ($query as $key => $value) { $queryParts[] = "{$key}={$value}"; } $this->fullUrl['query'] = '?' . implode('&', $queryParts); return $this; }
Add query string to the final url @param array $query @return Url
public static function buildDynamicMetadata($name, array $metadata) { $metaClass = self::getDynamicMetadataClassName($name); if (class_exists($metaClass)) { /* @var DynamicMetadataInterface $metaClass */ return $metaClass::createFromDecodedJsonResponse($metadata); } return null; }
@param string $name The Metadata name @param array $metadata The Metadata contents, as an array @return DynamicMetadataInterface|null
public static function getDynamicMetadataClassName($name) { // Convert to a CamelCase class name. // See Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter::denormalize() $camelCasedName = preg_replace_callback('/(^|_|\.)+(.)/', function ($match) { return ('.' === $match[1] ? '_' : '').strtoupper($match[2]); }, $name); return 'Rokka\Client\Core\DynamicMetadata\\'.$camelCasedName; }
Returns the Dynamic Metadata class name from the API name. @param string $name The Metadata name from the API @return string The DynamicMetadata class name, as fully qualified class name
public function render(ResourceObject $ro) { $ro->headers['Content-Type'] = 'application/json'; $allows = $this->getAllows((new \ReflectionClass($ro))->getMethods()); $ro->headers['Allow'] = implode(', ', $allows); $body = $this->getEntityBody($ro, $allows); $ro->view = json_encode($body, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . PHP_EOL; return $ro->view; }
{@inheritdoc}
private function getAllows(array $methods) { $allows = []; foreach ($methods as $method) { if (in_array($method->name, ['onGet', 'onPost', 'onPut', 'onPatch', 'onDelete', 'onHead'], true)) { $allows[] = strtoupper(substr($method->name, 2)); } } return $allows; }
Return allowed methods @param \ReflectionMethod[] $methods @return array
private function getEntityBody(ResourceObject $ro, array $allows) : array { $mehtodList = []; foreach ($allows as $method) { $mehtodList[$method] = ($this->optionsMethod)($ro, $method); } return $mehtodList; }
Return OPTIONS entity body
public static function gradeShowAll($stmt, $detail = false) { echo('<table border="1">'); echo("\n<tr><th>Name<th>Email</th><th>Grade</th><th>Date</th></tr>\n"); while ( $row = $stmt->fetch(\PDO::FETCH_ASSOC) ) { echo('<tr><td>'); if ( $detail ) { $detail->link($row); } else { echo(htmlent_utf8($row['displayname'])); } echo("</td>\n<td>".htmlent_utf8($row['email'])."</td> <td>".htmlent_utf8($row['grade'])."</td> <td>".htmlent_utf8($row['updated_at'])."</td> </tr>\n"); } echo("</table>\n"); }
$detail is either false or a class with methods
public static function gradeLoad($user_id=false) { global $CFG, $USER, $LINK, $PDOX; $LAUNCH = LTIX::requireData(array(LTIX::LINK, LTIX::USER)); if ( ! $USER->instructor && $user_id !== false ) die("Requires instructor role"); if ( $user_id == false ) $user_id = $USER->id; $p = $CFG->dbprefix; // Get basic grade data $stmt = $PDOX->queryDie( "SELECT R.result_id AS result_id, R.user_id AS user_id, grade, note, R.json AS json, R.note as note, R.updated_at AS updated_at, displayname, email FROM {$p}lti_result AS R JOIN {$p}lti_user AS U ON R.user_id = U.user_id WHERE R.link_id = :LID AND R.user_id = :UID GROUP BY U.email", array(":LID" => $LINK->id, ":UID" => $user_id) ); $row = $stmt->fetch(\PDO::FETCH_ASSOC); return $row; }
Not cached
public static function gradeUpdateJson($newdata=false) { global $CFG, $PDOX, $LINK, $RESULT; if ( $newdata == false ) return; if ( is_string($newdata) ) $newdata = json_decode($newdata, true); $LAUNCH = LTIX::requireData(array(LTIX::LINK)); if ( ! isset($RESULT) ) return; $row = self::gradeLoad(); $data = array(); if ( $row !== false && isset($row['json'])) { $data = json_decode($row['json'], true); } $changed = false; foreach ($newdata as $k => $v ) { if ( (!isset($data[$k])) || $data[$k] != $v ) { $data[$k] = $v; $changed = true; } } if ( $changed === false ) return; $jstr = json_encode($data); $stmt = $PDOX->queryDie( "UPDATE {$CFG->dbprefix}lti_result SET json = :json, updated_at = NOW() WHERE result_id = :RID", array( ':json' => $jstr, ':RID' => $RESULT->id) ); }
newdata can be a string or array (preferred)
public static function loadGradesForCourse($user_id, $context_id) { global $CFG, $PDOX; $p = $CFG->dbprefix; $sql = "SELECT R.result_id AS result_id, L.title as title, L.link_key AS resource_link_id, R.grade AS grade, R.note AS note FROM {$p}lti_result AS R JOIN {$p}lti_link as L ON R.link_id = L.link_id LEFT JOIN {$p}lti_service AS S ON R.service_id = S.service_id WHERE R.user_id = :UID AND L.context_id = :CID AND R.grade IS NOT NULL"; $rows = $PDOX->allRowsDie($sql,array(':UID' => $user_id, ':CID' => $context_id)); return $rows; }
Load all the grades for the current user / course including resource_link_id
public function getNext($min = null, $max = null) { if (($min === null && $max !== null) || ($min !== null && $max === null)) throw new Exception('Invalid arguments'); if ($this->index === 0) { $this->generateTwister(); } $y = $this->state[$this->index]; $y = ($y ^ ($y >> 11)) & 0xffffffff; $y = ($y ^ (($y << 7) & 0x9d2c5680)) & 0xffffffff; $y = ($y ^ (($y << 15) & 0xefc60000)) & 0xffffffff; $y = ($y ^ ($y >> 18)) & 0xffffffff; $this->index = ($this->index + 1) % 624; if ($min === null && $max === null) return $y; $range = abs($max - $min); return min($min, $max) + ($y % ($range + 1)); }
Get the next pseudo-random number in the sequence Returns the next pseudo-random number in the range specified. The $max and $min are inclusive. If $max and $min are omitted a large integer is returned. @param $min The low end of the range (optional) @param $max The high end of the range (optional)
public function gaussian($max, $lambda = 0.2) { $tau = $max; $u = 1.0 * $this->getNext(0, self::MAX) / self::MAX; $x = - log(1 - (1 - exp(- $lambda * $tau)) * $u) / $lambda; $ran = (int) $x; if ( $ran >= $max ) $ran=$max-1; // If $tao and $lambda are wack return $ran; }
http://stats.stackexchange.com/questions/68274/how-to-sample-from-an-exponential-distribution-using-rejection-sampling-in-php
public function shuffle($arr) { $new = $arr; for ($i = count($new) - 1; $i > 0; $i--) { $j = $this->getNext(0,$i); $tmp = $new[$i]; $new[$i] = $new[$j]; $new[$j] = $tmp; } return $new; }
http://bost.ocks.org/mike/algorithms/#shuffling
public function getHashMaybeUpload(AbstractLocalImage $image) { if ($hash = $image->getRokkaHash()) { return $hash; } if (!$hash = $this->callbacks->getHash($image)) { if (!$this->isImage($image)) { return null; } $sourceImage = $this->imageUpload($image); if (null !== $sourceImage) { $hash = $this->callbacks->saveHash($image, $sourceImage); } } return $hash; }
Returns the hash of an image. If we don't have an image stored locally, it uploads it to rokka. @since 1.3.0 @param AbstractLocalImage $image @throws \GuzzleHttp\Exception\GuzzleException @throws \RuntimeException @return string|null
public function getStackUrl( $image, $stack, $format = 'jpg', $seo = null, $seoLanguage = 'de' ) { if (null == $image) { return ''; } $image = $this->getImageObject($image); if (!$hash = self::getHashMaybeUpload($image)) { return ''; } if (null === $seo) { return $this->generateRokkaUrlWithImage($hash, $stack, $format, $image, $seoLanguage); } return $this->generateRokkaUrl($hash, $stack, $format, $seo, $seoLanguage); }
Gets the rokka URL for an image Uploads it, if we don't have a hash locally. @since 1.3.0 @param AbstractLocalImage|string|\SplFileInfo $image The image @param string $stack The stack name @param string|null $format The image format of the image (jpg, png, webp, ...) @param string|null $seo if you want a different seo string than the default @param string|null $seoLanguage Optional language to be used for slugifying (eg. 'de' slugifies 'ö' to 'oe') @throws \GuzzleHttp\Exception\GuzzleException @throws \RuntimeException @return string
public function getResizeUrl($image, $width, $height = null, $format = 'jpg', $seo = null, $seoLanguage = 'de') { $imageObject = $this->getImageObject($image); if (null !== $height) { $heightString = "-height-$height"; } else { $heightString = ''; } $stack = "dynamic/resize-width-$width$heightString--options-autoformat-true-jpg.transparency.autoformat-true"; return $this->getStackUrl($imageObject, $stack, $format, $seo, $seoLanguage); }
Return the rokka URL for getting a resized image. @since 1.3.0 @param AbstractLocalImage|string|\SplFileInfo $image The image to be resized @param string|int $width The width of the image @param string|int|null $height The height of the image @param string $format The image format of the image (jpg, png, webp, ...) @param string|null $seo @param string $seoLanguage @throws \GuzzleHttp\Exception\GuzzleException @throws \RuntimeException @return string
public function getOriginalSizeUrl($image, $format = 'jpg', $seo = null, $seoLanguage = '') { $imageObject = $this->getImageObject($image); $stack = 'dynamic/noop--options-autoformat-true-jpg.transparency.autoformat-true'; return $this->getStackUrl($imageObject, $stack, $format, $seo, $seoLanguage); }
Return the rokka URL for getting the image in it's original size. @since 1.3.0 @param AbstractLocalImage|string|\SplFileInfo $image The image to be resized @param string $format The image format of the image (jpg, png, webp, ...) @param string|null $seo @param string $seoLanguage @throws \GuzzleHttp\Exception\GuzzleException @throws \RuntimeException @return string
public static function getSrcAttributes($url, $sizes = ['2x'], $setWidthInUrl = true) { $attrs = 'src="'.$url.'"'; $srcSets = []; foreach ($sizes as $size => $custom) { if (\is_int($size)) { if (\is_int($custom)) { $size = $custom.'x'; } else { $size = $custom; } $custom = null; } $urlx2 = UriHelper::getSrcSetUrlString($url, $size, $custom, $setWidthInUrl); if ($urlx2 != $url) { $srcSets[] = "${urlx2} ${size}"; } } if (\count($srcSets) > 0) { $attrs .= ' srcset="'.implode(', ', ($srcSets)).'"'; } return $attrs; }
Returns a src and srcset attibrute (as one string) with the correct rokka render urls for responsive images. To be used directly in your HTML templates. @since 1.3.0 @param string $url The render URL of the "non-retina" image @param array $sizes For which sizes srcset links should be generated, works with 'x' or 'w' style @param bool $setWidthInUrl If false, don't set the width as stack operation option, we provide it in $custom, usually as parameter @throws \RuntimeException @return string
public static function getBackgroundImageStyle($url, array $sizes = ['2x']) { $style = "background-image:url('$url');"; $srcSets = []; foreach ($sizes as $size => $custom) { if (\is_int($size)) { $size = $custom; $custom = null; } $urlx2 = UriHelper::getSrcSetUrlString($url, $size, $custom); if ($urlx2 != $url) { $srcSets[] = "url('${urlx2}') ${size}"; } } if (\count($srcSets) > 0) { $style .= " background-image: -webkit-image-set(url('$url') 1x, ".implode(', ', $srcSets).');'; } return $style; }
Returns a background-image:url defintions (as one string) with the correct rokka render urls for responsive images. To be used directly in your CSS templates or HTML tags. @since 1.3.0 @param string $url The render URL of the "non-retina" image @param array $sizes For which sizes srcset links should be generated, works with 'x' or 'w' style @throws \RuntimeException @return string
public function getImagename(AbstractLocalImage $image = null) { if (null === $image) { return ''; } if (null === $image->getFilename()) { return ''; } return pathinfo($image->getFilename(), PATHINFO_FILENAME); }
Returns the filename of the image without extension. @since 1.3.0 @param AbstractLocalImage|null $image @return string
public function generateRokkaUrl( $hash, $stack, $format = 'jpg', $seo = null, $seoLanguage = 'de' ) { if (null === $format) { $format = 'jpg'; } $slug = null; if (!empty($seo) && null !== $seo) { if (null === $seoLanguage) { $seoLanguage = 'de'; } $slug = self::slugify($seo, $seoLanguage); } $path = UriHelper::composeUri(['stack' => $stack, 'hash' => $hash, 'format' => $format, 'filename' => $slug]); return $this->rokkaDomain.$path->getPath(); }
Gets the rokka URL for an image hash and stack with optional seo filename in the URL. Doesn't upload it, if we don't have a local hash for it. Use getStackUrl for that. @since 1.3.0 @see TemplateHelper::getStackUrl() @param string $hash The rokka hash @param string|StackUri $stack The stack name or a StackUrl object @param string|null $format The image format of the image (jpg, png, webp, ...) @param string|null $seo If you want to use a seo string in the URL @param string|null $seoLanguage Optional language to be used for slugifying (eg. 'de' slugifies 'ö' to 'oe') @throws \RuntimeException @return string
public function getRokkaClient() { if (null === $this->imageClient) { $this->imageClient = Factory::getImageClient($this->rokkaOrg, $this->rokkaApiKey, $this->rokkaClientOptions); } return $this->imageClient; }
Gets the rokka image client used by this class. @since 1.3.0 @throws \RuntimeException @return \Rokka\Client\Image
public static function slugify($text, $language = 'de') { \URLify::$maps['specials'] = [ '.' => '-', ',' => '-', '@' => '-', ]; $slug = \URLify::filter($text, 60, $language, true, false); $slug = str_replace(['_'], '-', $slug); $slug = preg_replace('/[^0-9a-z-]/', '', $slug); if (null === $slug) { throw new \RuntimeException('An error eccored when generating the slug for '.$text); } return $slug; }
Create a URL-safe text from $text. @since 1.3.0 @param string $text Text to slugify @param string $language Optional language to be used for slugifying (eg. 'de' slugifies 'ö' to 'oe') @throws \RuntimeException @return string A string that should work in urls. Empty string is only allowed if $emptyText is ''
public function getImageObject($input, $identifier = null, $context = null) { if ($input instanceof AbstractLocalImage) { if (null !== $identifier) { $input->setIdentifier($identifier); } if (null !== $context) { $input->setContext($context); } return $input; } if ($input instanceof \SplFileInfo) { return new FileInfo($input, $identifier, $context); } elseif (\is_string($input)) { if (preg_match('/^[0-9a-f]{6,40}$/', $input)) { return new RokkaHash($input, $identifier, $context, $this); } return new FileInfo(new \SplFileInfo($input), $identifier, $context); } throw new \RuntimeException('getImageObject: Input could not be converted to a LocalImageAbstract object'); }
Returns a LocalImage object depending on the input. If input is - LocalImageAbstract: returns that, sets $identidier and $context, if set - SplFileInfo: returns \Rokka\Client\LocalImage\FileInfo - string with hash pattern (/^[0-9a-f]{6,40}$/): returns \Rokka\Client\LocalImage\RokkaHash - other strings: returns \Rokka\Client\LocalImage\FileInfo with $input as the path to the image @since 1.3.1 @param AbstractLocalImage|string|\SplFileInfo $input @param string|null $identifier @param mixed $context @throws \RuntimeException @return AbstractLocalImage
private function generateRokkaUrlWithImage( $hash, $stack, $format = 'jpg', AbstractLocalImage $image = null, $seoLanguage = 'de' ) { return $this->generateRokkaUrl($hash, $stack, $format, $this->getImagename($image), $seoLanguage); }
Gets the rokka URL for an image hash and stack and uses the $image info for an seo filename in the URL. Doesn't upload it, if we don't have a local hash for it. Use getStackUrl() for that. If $image is set, uses the filename for seo-ing the URL. @see TemplateHelper::getStackUrl() @param string $hash The rokka hash @param string $stack The stack name @param string|null $format The image format of the image (jpg, png, webp, ...) @param AbstractLocalImage $image The image @param string|null $seoLanguage Optional language to be used for slugifying (eg. 'de' slugifies 'ö' to 'oe') @throws \RuntimeException @return string
private function imageUpload(AbstractLocalImage $image) { $imageClient = $this->getRokkaClient(); $metadata = $this->callbacks->getMetadata($image); if (0 === \count($metadata)) { $metadata = null; } $content = $image->getContent(); if (null !== $content) { $filename = $image->getFilename(); if (null === $filename) { $filename = 'unknown'; } $answer = $imageClient->uploadSourceImage( $content, $filename, '', $metadata ); $sourceImages = $answer->getSourceImages(); if (\count($sourceImages) > 0) { return $sourceImages[0]; } } return null; }
@param AbstractLocalImage $image @throws \GuzzleHttp\Exception\GuzzleException @throws \RuntimeException @return null|SourceImage
private function getMimeType(AbstractLocalImage $image) { $mimeType = 'application/not-supported'; $realpath = $image->getRealpath(); if (\is_string($realpath)) { $mimeType = finfo_file(finfo_open(FILEINFO_MIME_TYPE), $realpath); } else { $content = $image->getContent(); if (null !== $content) { $mimeType = finfo_buffer(finfo_open(FILEINFO_MIME_TYPE), $content); } } if ('text/html' == $mimeType || 'text/plain' == $mimeType) { if ($this->isSvg($image)) { $mimeType = 'image/svg+xml'; } } return $mimeType; }
@param AbstractLocalImage $image @return string
private function isSvg(AbstractLocalImage $image) { $dom = new \DOMDocument(); $content = $image->getContent(); if (null === $content) { return false; } if ($dom->loadXML($content)) { $root = $dom->childNodes->item(0); if (null === $root) { return false; } if ('svg' == $root->localName && 'http://www.w3.org/2000/svg' == $root->namespaceURI) { return true; } } return false; }
Checks, if a file is svg (needed when xml declaration is missing). @param AbstractLocalImage $image @return bool
function queryDie($sql, $arr=FALSE, $error_log=TRUE) { global $CFG; $stmt = self::queryReturnError($sql, $arr, $error_log); if ( ! $stmt->success ) { error_log("Sql Failure:".$stmt->errorImplode." ".$sql); if ( $CFG->DEVELOPER ) { die($stmt->errorImplode); // with error_log } else { die('Internal database error'); } } return $stmt; }
Prepare and execute an SQL query or die() in the attempt. @param $sql The SQL to execute in a string. If the SQL is badly formed this function will die. @param $arr An optional array of the substitition values if needed by the query @param $error_log Indicates whether or not errors are to be logged. Default is TRUE. @return \PDOStatement This is either the real PDOStatement from the prepare() call or a stdClass mocked to have error indications as described above.
function rowDie($sql, $arr=FALSE, $error_log=TRUE) { $stmt = self::queryDie($sql, $arr, $error_log); $row = $stmt->fetch(\PDO::FETCH_ASSOC); return $row; }
Prepare and execute an SQL query and retrieve a single row. @param $sql The SQL to execute in a string. If the SQL is badly formed this function will die. @param $arr An optional array of the substitition values if needed by the query @param $error_log Indicates whether or not errors are to be logged. Default is TRUE. @return array This is either the row that was returned or FALSE if no rows were returned.
function allRowsDie($sql, $arr=FALSE, $error_log=TRUE) { $stmt = self::queryDie($sql, $arr, $error_log); $rows = array(); while ( $row = $stmt->fetch(\PDO::FETCH_ASSOC) ) { array_push($rows, $row); } return $rows; }
Prepare and execute an SQL query and retrieve all the rows as an array While this might seem like a bad idea, the coding style for Tsugi is to make every query a paged query with a limited number of records to be retrieved to in most cases, it is quite reasonable to retrieve 10-30 rows into an array. If code wants to stream the results of a query, they should do their own query and loop through the rows in their own code. @param $sql The SQL to execute in a string. If the SQL is badly formed this function will die. @param $arr An optional array of the substitition values if needed by the query @param $error_log Indicates whether or not errors are to be logged. Default is TRUE. @return array This is either the rows that were retrieved or or an empty array if there were no rows.
function metadata($tablename) { $sql = "SHOW COLUMNS FROM ".$tablename; $q = self::queryReturnError($sql); if ( $q->success ) { return $q->fetchAll(); } else { return false; } }
Retrieve the metadata for a table.
function describeColumn($fieldname, $source) { if ( ! is_array($source) ) { if ( ! is_string($source) ) { throw new \Exception('Source must be an array of metadata or a table name'); } $source = self::describe($source); if ( ! is_array($source) ) return null; } foreach( $source as $column ) { $name = U::get($column, "Field"); if ( $fieldname == $name ) return $column; } return null; }
Retrieve the metadata for a column in a table. For the output format for MySQL, see: https://dev.mysql.com/doc/refman/5.7/en/explain.html @param $fieldname The name of the column @param $source Either an array of the column metadata or the name of the table @return mixed An array of the column metadata or null
function columnIsNull($fieldname, $source) { $column = self::describeColumn($fieldname, $source); if ( ! $column ) throw new \Exception("Could not find $fieldname"); return U::get($column, "Null") == "YES"; }
Check if a column is null @param $fieldname The name of the column @param $source Either an array of the column metadata or the name of the table @return mixed Returns true / false if the columns exists and null if the column does not exist.
function columnExists($fieldname, $source) { if ( is_string($source) ) { // Demand table exists $source = self::describe($source); if ( ! $source ) throw new \Exception("Could not find $source"); } $column = self::describeColumn($fieldname, $source); return is_array($column); }
Check if a column exists @param $fieldname The name of the column @param $source Either an array of the column metadata or the name of the table @return boolean Returns true/false
function columnType($fieldname, $source) { $column = self::describeColumn($fieldname, $source); if ( ! $column ) throw new \Exception("Could not find $fieldname"); $type = U::get($column, "Type"); if ( ! $type ) return null; if ( strpos($type, '(') === false ) return $type; $matches = array(); preg_match('/([a-z]+)\([0-9]+\)/', $type, $matches); if ( count($matches) == 2 ) return $matches[1]; return null; }
Get the column type @param $fieldname The name of the column @param $source Either an array of the column metadata or the name of the table @return mixed Returns a string if the columns exists and null if the column does not exist.
public function invoke(MethodInvocation $invocation) { /** @var ResourceObject $ro */ $ro = $invocation->getThis(); $ro->body = $this->camelCaseKey($ro->body); return $invocation->proceed(); }
{@inheritdoc}
function getContentItemSelection() { $this->json->{self::CONTENT_ITEMS} = $this->items; unset($this->json->{self::DATA_CLAIM}); if ( isset($this->claim->data) ) { $this->json->{self::DATA_CLAIM} = $this->claim->data; } return $this->json; }
Return the claims array to send back to the LMS
public function addContentItem($url, $title=false, $text=false, $icon=false, $fa_icon=false, $additionalParams = array()) { $params = array( 'url' => $url, 'title' => $title, 'text' => $text, 'icon' => $icon, 'fa_icon' => $fa_icon, ); // 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->addContentItemExtended($params); }
addContentItem - Add an 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
public function fileCheck($uri=null) { global $TSUGI_REST_PATH_VALUES; global $TSUGI_REST_PATH; $TSUGI_REST_PATH = false; $TSUGI_REST_PATH_VALUES = false; if ( $uri === null ) $uri = $_SERVER['REQUEST_URI']; $uri = self::trimQuery($uri); // /wa4e/tsugi $cwd = self::cwd(); if ( ! endsWith($cwd, '/') ) $cwd = $cwd .'/'; if ( strpos($uri,$cwd) === 0 ) { $remainder = substr($uri, strlen($cwd)); if ( strlen($remainder) < 1 ) return false; $pieces = explode('/',$remainder,2); $file = $pieces[0] . '.php'; if ( file_exists($file) ) { $TSUGI_REST_PATH = $cwd . '/' . $pieces[0]; if ( count($pieces) > 1 ) $TSUGI_REST_PATH_VALUES = $pieces[1]; return $file; } } return false; }
/wa4e/install returns install.php if the file exists
public function setHome($link, $href) { $this->home = new \Tsugi\UI\MenuEntry($link, $href); return $this; }
Set the Home 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 @return MenuSet The instance to allow for chaining
public function addLeft($link, $href, $push=false) { if ( $this->left == false ) $this->left = new Menu(); $x = new \Tsugi\UI\MenuEntry($link, $href, $push); $this->left->add($x, $push); return $this; }
Add an entty to the Left 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 @param $push Indicates to push down the other menu entries @return MenuSet The instance to allow for chaining
public function addRight($link, $href, $push=true) { if ( $this->right == false ) $this->right = new Menu(); $x = new \Tsugi\UI\MenuEntry($link, $href, $push); $this->right->add($x, $push); return $this; }
Add an entty to the Right 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 @param $push Indicates to push down the other menu entries @return MenuSet The instance to allow for chaining
public function export($pretty=false) { $tmp = new \stdClass(); if ( $this->home != false ) $tmp->home = $this->home; if ( $this->left != false ) $tmp->left = $this->left->menu; if ( $this->right != false ) $tmp->right = $this->right->menu; if ( $pretty ) { return json_encode($tmp, JSON_PRETTY_PRINT); } else { return json_encode($tmp); } }
Export a menu to JSON @param $pretty - True if we want pretty output @return string JSON string for the menu
public static function import($json_str) { try { $json = json_decode($json_str); // print_r($json); $retval = new MenuSet(); $retval->home = new \Tsugi\UI\MenuEntry($json->home->link, $json->home->href); if ( isset($json->left) ) $retval->left = self::importRecurse($json->left, 0); if ( isset($json->right) ) $retval->right = self::importRecurse($json->right, 0); return $retval; } catch (Exception $e) { return false; } }
Import a menu from JSON @param $json_str The menu as exported @return The MenuSet as parsed or false on error
private static function importRecurse($entry, $depth) { if ( isset($entry->menu) ) $entry = $entry->menu; // Skip right past these if ( ! is_array($entry) ) { $link = $entry->link; $href = $entry->href; if ( is_string($href) ) { return new \Tsugi\UI\MenuEntry($link, $href); } $submenu = self::importRecurse($href, $depth+1); return new \Tsugi\UI\MenuEntry($link, $submenu); } $submenu = new \Tsugi\UI\Menu(); foreach($entry as $child) { $submenu->add(self::importRecurse($child, $depth+1)); } return $submenu; }
Walk a JSON tree to import a hierarchy of menus
public function setEvents($var) { $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Rxnet\EventStore\Data\ResolvedIndexedEvent::class); $this->events = $arr; return $this; }
Generated from protobuf field <code>repeated .Rxnet.EventStore.Data.ResolvedIndexedEvent events = 1;</code> @param \Rxnet\EventStore\Data\ResolvedIndexedEvent[]|\Google\Protobuf\Internal\RepeatedField $var @return $this
protected function call($method, $path, array $options = [], $needsCredentials = true) { $options['headers'][self::API_VERSION_HEADER] = $this->apiVersion; if ($needsCredentials) { $options['headers'][self::API_KEY_HEADER] = $this->credentials['key']; } return $this->client->request($method, $path, $options); }
Call the API rokka endpoint. @param string $method HTTP method to use @param string $path Path on the API @param array $options Request options @param bool $needsCredentials True if credentials are needed @throws GuzzleException @return ResponseInterface
protected function getOrganizationName($organization = null) { $org = (empty($organization)) ? $this->defaultOrganization : $organization; if (null === $org) { throw new \RuntimeException('Organization is empty'); } return $org; }
Return the organization or the default if empty. @param string|null $organization Organization @throws \RuntimeException @return string
public static function lookupResultBypass($user_id) { global $CFG, $PDOX, $CONTEXT, $LINK; $stmt = $PDOX->queryDie( "SELECT result_id, R.link_id AS link_id, R.user_id AS user_id, sourcedid, service_id, grade, note, R.json AS json, R.note AS note FROM {$CFG->dbprefix}lti_result AS R JOIN {$CFG->dbprefix}lti_link AS L ON L.link_id = R.link_id AND R.link_id = :LID JOIN {$CFG->dbprefix}lti_user AS U ON U.user_id = R.user_id AND U.user_id = :UID JOIN {$CFG->dbprefix}lti_context AS C ON L.context_id = C.context_id AND C.context_id = :CID WHERE R.user_id = :UID and U.user_id = :UID AND L.link_id = :LID", array(":LID" => $LINK->id, ":CID" => $CONTEXT->id, ":UID" => $user_id) ); $row = $stmt->fetch(\PDO::FETCH_ASSOC); return $row; }
hence the complex query to make sure we don't cross silos
public function getJSON() { global $CFG; $PDOX = $this->launch->pdox; $stmt = $PDOX->queryDie( "SELECT json FROM {$CFG->dbprefix}lti_result WHERE result_id = :RID", array(':RID' => $this->id) ); $row = $stmt->fetch(\PDO::FETCH_ASSOC); return $row['json']; }
Get the JSON for this result
public function setJSON($json) { global $CFG; $PDOX = $this->launch->pdox; $stmt = $PDOX->queryDie( "UPDATE {$CFG->dbprefix}lti_result SET json = :json, updated_at = NOW() WHERE result_id = :RID", array( ':json' => $json, ':RID' => $this->id) ); }
Set the JSON for this result
public function setNote($note) { global $CFG; $PDOX = $this->launch->pdox; $stmt = $PDOX->queryDie( "UPDATE {$CFG->dbprefix}lti_result SET note = :note, updated_at = NOW() WHERE result_id = :RID", array( ':note' => $note, ':RID' => $this->id) ); }
Set the Note for this result
protected function configure() { $this->bind(Reader::class)->to(AnnotationReader::class); $this->bindInterceptor( $this->matcher->any(), $this->matcher->annotatedWith(Embed::class), [EmbedInterceptor::class] ); }
{@inheritdoc}
function bodyStart($checkpost=true) { global $CFG; ob_start(); // If we are in an iframe use different margins ?> </head> <body prefix="oer: http://oerschema.org"> <div id="body_container"> <script> if (window!=window.top) { document.getElementById("body_container").className = "container_iframe"; } else { document.getElementById("body_container").className = "container"; } </script> <?php if ( $checkpost && count($_POST) > 0 ) { $dump = self::safe_var_dump($_POST); echo('<p style="color:red">Error - Unhandled POST request</p>'); echo("\n<pre>\n"); echo($dump); if ( count($_FILES) > 0 ) { $files = self::safe_var_dump($_FILES); echo($files); } echo("\n</pre>\n"); error_log($dump); die_with_error_log("Unhandled POST request"); } // Complain if this is a test key $key_key = $this->ltiParameter('key_key'); if ( $key_key == '12345' && strpos($CFG->wwwroot, '://localhost') === false ) { echo('<div style="background-color: orange; position: absolute; bottom: 5px; left: 5px;">'); echo(_m('Test Key - Do not use for production')); echo('</div>'); } $HEAD_CONTENT_SENT = true; $ob_output = ob_get_contents(); ob_end_clean(); if ( $this->buffer ) return $ob_output; echo($ob_output); }
Finish the head and start the body of a Tsugi HTML page. By default this demands that we are in a GET request. It is a fatal error to call this code if we are responding to a POST request unless this behavior is overidden. @param $checkpost (optional, boolean) This can be set to false to emit the body start even for a POST request.
public static function getUtilUrl($path) { global $CFG; if ( isset($CFG->utilroot) ) { return $CFG->utilroot.$path; } // From wwwroot $path = str_replace('.php','',$path); $retval = $CFG->wwwroot . '/util' . $path; return $retval; // The old way from "vendor" // return $CFG->vendorroot.$path; }
getUtilUrl - Get a URL in the utility script space - does not add session @param $path - The path of the file - should start with a slash.
public static function handleHeartBeat($cookie) { global $CFG; self::headerJson(); session_start(); $session_object = null; // TODO: Make sure to do the right thing with the session eventially // See how long since the last update of the activity time $now = time(); $seconds = $now - LTIX::wrapped_session_get($session_object, 'LAST_ACTIVITY', $now); LTIX::wrapped_session_put($session_object, 'LAST_ACTIVITY', $now); // update last activity time stamp // Count the successive heartbeats without a request/response cycle $count = LTIX::wrapped_session_get($session_object, 'HEARTBEAT_COUNT', 0); $count++; LTIX::wrapped_session_put($session_object, 'HEARTBEAT_COUNT', $count); if ( $count > 10 && ( $count % 100 ) == 0 ) { error_log("Heartbeat.php ".session_id().' '.$count); } $retval = array("success" => true, "seconds" => $seconds, "now" => $now, "count" => $count, "cookie" => $cookie, "id" => session_id()); $lti = LTIX::wrapped_session_get($session_object, 'lti'); $retval['lti'] = is_array($lti) && U::get($lti, 'key_id'); $retval['sessionlifetime'] = $CFG->sessionlifetime; return $retval; }
Handle the heartbeat calls. This is UI code basically. Make sure when you call this, you have handled whether the session is cookie based or not and included config.php appropriately if ( isset($_GET[session_name()]) ) { $cookie = false; } else { define('COOKIE_SESSION', true); $cookie = true; } require_once "../config.php"; \Tsugi\UI\Output::handleHeartBeat($cookie);
function welcomeUserCourse() { global $USER, $CONTEXT; if ( isset($USER->displayname) ) { if ( isset($CONTEXT->title) ) { printf(_m("<p>Welcome %s from %s"), htmlent_utf8($USER->displayname), htmlent_utf8($CONTEXT->title)); } else { printf(_m("<p>Welcome %s"), htmlent_utf8($USER->displayname)); } } else { if ( isset($CONTEXT->title) ) { printf(_m("<p>Welcome from %s"), htmlent_utf8($CONTEXT->title)); } else { printf(_m("<p>Welcome ")); } } if ( $USER->admin ) { echo(" "._m("(Instructor+Administrator)")); } else if ( $USER->instructor ) { echo(" "._m("(Instructor)")); } echo("</p>\n"); }
Welcome the user to the course
function exitButton($text=false) { if ( $text === false ) $text = _m("Exit"); $url = Settings::linkGet('done'); if ( $url == false ) { if ( $this->session_get('lti_post') && isset($this->session_get('lti_post')['custom_done']) ) { $url = $this->session_get('lti_post')['custom_done']; } else if ( isset($_GET["done"]) ) { $url = $_GET['done']; } } // If we have no where to go and nothing to do, if ( $url === false || strlen($url) < 1 ) return; $button = "btn-success"; if ( $text == "Cancel" || $text == _m("Cancel") ) $button = "btn-warning"; if ( $url == "_close" ) { echo("<a href=\"#\" onclick=\"window_close();\" class=\"btn ".$button."\">".$text."</a>\n"); } else { echo("<a href==\"$url\" class=\"btn ".$button."\">".$text."</button>\n"); } }
Emit a properly styled done button for use in the launched frame/window This is a bit tricky because custom settings can control the "Done" behavior. These settings can come from one of three places: (1) in the link settings, (2) from a custom parameter named 'done', or (3) from a GET parameter done= The value for this is a URL, "_close", or "_return". TODO: Implement _return