sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public static function camelize($string, $separator = null, $preserveWhiteSpace = false, $isKey = false)
{
empty($separator) && $separator = ['_', '-'];
$_newString = ucwords(str_replace($separator, ' ', $string));
if (false !== $isKey) {
$_newString = lcfirst($_newString);
}
return (false === $preserveWhiteSpace ? str_replace(' ', null, $_newString) : $_newString);
} | Converts a separator delimited string to camel case
@param string $string
@param string $separator
@param boolean $preserveWhiteSpace
@param bool $isKey If true, first word is lower-cased
@return string | entailment |
public function handle()
{
$this->laravel['events']->fire('cache:clearing', ['file']);
$this->removeDirectory($this->cacheRoot);
$this->laravel['events']->fire('cache:cleared', ['file']);
$this->info('Cleared DreamFactory cache for all instances!');
} | Execute the console command.
@return mixed | entailment |
protected function removeDirectory($path)
{
$files = glob($path . '/*');
foreach ($files as $file) {
if (is_dir($file)) {
static::removeDirectory($file);
} else if (basename($file) !== '.gitignore') {
unlink($file);
}
}
if ($path !== $this->cacheRoot) {
rmdir($path);
}
return;
} | Removes directories recursively.
@param $path | entailment |
public static function alert($type, $transKey, $transCount = 1, $transParameters = [])
{
$alerts = [];
if (Session::has('alerts')) {
$alerts = Session::get('alerts');
}
$message = trans_choice("forum::{$transKey}", $transCount, $transParameters);
array_push($alerts, compact('type', 'message'));
Session::flash('alerts', $alerts);
} | Process an alert message to display to the user.
@param string $type
@param string $transKey
@param string $transCount
@return void | entailment |
public static function route($route, $model = null)
{
if (!starts_with($route, config('forum.routing.as'))) {
$route = config('forum.routing.as') . $route;
}
$params = [];
$append = '';
if ($model) {
switch (true) {
case $model instanceof Category:
$params = [
'category' => $model->id,
'category_slug' => static::slugify($model->title)
];
break;
case $model instanceof Thread:
$params = [
'category' => $model->category->id,
'category_slug' => static::slugify($model->category->title),
'thread' => $model->id,
'thread_slug' => static::slugify($model->title)
];
break;
case $model instanceof Post:
$params = [
'category' => $model->thread->category->id,
'category_slug' => static::slugify($model->thread->category->title),
'thread' => $model->thread->id,
'thread_slug' => static::slugify($model->thread->title)
];
if ($route == config('forum.routing.as') . 'thread.show') {
// The requested route is for a thread; we need to specify the page number and append a hash for
// the post
$params['page'] = ceil($model->sequence / $model->getPerPage());
$append = "#post-{$model->sequence}";
} else {
// Other post routes require the post parameter
$params['post'] = $model->id;
}
break;
}
}
return route($route, $params) . $append;
} | Generate a URL to a named forum route.
@param string $route
@param null|\Illuminate\Database\Eloquent\Model $model
@return string | entailment |
public static function routes(Router $router)
{
$controllers = config('forum.frontend.controllers');
// Forum index
$router->get('/', ['as' => 'index', 'uses' => "{$controllers['category']}@index"]);
// New/updated threads
$router->get('new', ['as' => 'index-new', 'uses' => "{$controllers['thread']}@indexNew"]);
$router->patch('new', ['as' => 'mark-new', 'uses' => "{$controllers['thread']}@markNew"]);
// Categories
$router->post('category/create', ['as' => 'category.store', 'uses' => "{$controllers['category']}@store"]);
$router->group(['prefix' => '{category}-{category_slug}'], function ($router) use ($controllers) {
$router->get('/', ['as' => 'category.show', 'uses' => "{$controllers['category']}@show"]);
$router->patch('/', ['as' => 'category.update', 'uses' => "{$controllers['category']}@update"]);
$router->delete('/', ['as' => 'category.delete', 'uses' => "{$controllers['category']}@destroy"]);
// Threads
$router->get('{thread}-{thread_slug}', ['as' => 'thread.show', 'uses' => "{$controllers['thread']}@show"]);
$router->get('thread/create', ['as' => 'thread.create', 'uses' => "{$controllers['thread']}@create"]);
$router->post('thread/create', ['as' => 'thread.store', 'uses' => "{$controllers['thread']}@store"]);
$router->patch('{thread}-{thread_slug}', ['as' => 'thread.update', 'uses' => "{$controllers['thread']}@update"]);
$router->delete('{thread}-{thread_slug}', ['as' => 'thread.delete', 'uses' => "{$controllers['thread']}@destroy"]);
// Posts
$router->get('{thread}-{thread_slug}/post/{post}', ['as' => 'post.show', 'uses' => "{$controllers['post']}@show"]);
$router->get('{thread}-{thread_slug}/reply', ['as' => 'post.create', 'uses' => "{$controllers['post']}@create"]);
$router->post('{thread}-{thread_slug}/reply', ['as' => 'post.store', 'uses' => "{$controllers['post']}@store"]);
$router->get('{thread}-{thread_slug}/post/{post}/edit', ['as' => 'post.edit', 'uses' => "{$controllers['post']}@edit"]);
$router->patch('{thread}-{thread_slug}/{post}', ['as' => 'post.update', 'uses' => "{$controllers['post']}@update"]);
$router->delete('{thread}-{thread_slug}/{post}', ['as' => 'post.delete', 'uses' => "{$controllers['post']}@destroy"]);
});
// Bulk actions
$router->group(['prefix' => 'bulk', 'as' => 'bulk.'], function ($router) use ($controllers) {
$router->patch('thread', ['as' => 'thread.update', 'uses' => "{$controllers['thread']}@bulkUpdate"]);
$router->delete('thread', ['as' => 'thread.delete', 'uses' => "{$controllers['thread']}@bulkDestroy"]);
$router->patch('post', ['as' => 'post.update', 'uses' => "{$controllers['post']}@bulkUpdate"]);
$router->delete('post', ['as' => 'post.delete', 'uses' => "{$controllers['post']}@bulkDestroy"]);
});
} | Register the standard forum routes.
@param Router $router
@return void | entailment |
public function handle()
{
/** @var RestHandler $service */
$service = ServiceManager::getService($this->service);
/** @var \DreamFactory\Core\Contracts\ServiceResponseInterface $rs */
$rs = ServiceManager::handleRequest(
$service->getName(),
Verbs::POST, '_table/' . $this->table,
[],
[],
ResourcesWrapper::wrapResources($this->records),
null,
false
);
if (in_array($rs->getStatusCode(), [HttpStatusCodes::HTTP_OK, HttpStatusCodes::HTTP_CREATED])) {
//$data = [];
} else {
$content = $rs->getContent();
Log::error('Failed to insert data into table: ' .
(is_array($content) ? print_r($content, true) : $content));
throw new InternalServerErrorException('Failed to insert data into table. See log for details.');
}
} | Execute the job. | entailment |
public function index($version = null)
{
try {
$request = new ServiceRequest();
if (!empty($version)) {
$request->setApiVersion($version);
}
Log::info('[REQUEST]', [
'API Version' => $request->getApiVersion(),
'Method' => $request->getMethod(),
'Service' => null,
'Resource' => null
]);
Log::debug('[REQUEST]', [
'Parameters' => json_encode($request->getParameters(), JSON_UNESCAPED_SLASHES),
'API Key' => $request->getHeader('X_DREAMFACTORY_API_KEY'),
'JWT' => $request->getHeader('X_DREAMFACTORY_SESSION_TOKEN')
]);
$limitedFields = ['id', 'name', 'label', 'description', 'type'];
$fields = \Request::query(ApiOptions::FIELDS);
if (!empty($fields) && !is_array($fields)) {
$fields = array_map('trim', explode(',', trim($fields, ',')));
} elseif (empty($fields)) {
$fields = $limitedFields;
}
$fields = array_intersect($fields, $limitedFields);
$group = \Request::query('group');
$type = \Request::query('type');
if (!empty($group)) {
$results = ServiceManager::getServiceListByGroup($group, $fields, true);
} elseif (!empty($type)) {
$results = ServiceManager::getServiceListByType($type, $fields, true);
} else {
$results = ServiceManager::getServiceList($fields, true);
}
$services = [];
foreach ($results as $info) {
// only allowed services by role here
if (Session::allowsServiceAccess(array_get($info, 'name'))) {
$services[] = $info;
}
}
if (!empty($group)) {
$results = ServiceManager::getServiceTypes($group);
} elseif (!empty($type)) {
$results = [ServiceManager::getServiceType($type)];
} else {
$results = ServiceManager::getServiceTypes();
}
$types = [];
foreach ($results as $type) {
$types[] = [
'name' => $type->getName(),
'label' => $type->getLabel(),
'group' => $type->getGroup(),
'description' => $type->getDescription()
];
}
$response = ResponseFactory::create(['services' => $services, 'service_types' => $types]);
Log::info('[RESPONSE]', ['Status Code' => $response->getStatusCode(), 'Content-Type' => $response->getContentType()]);
return ResponseFactory::sendResponse($response, $request);
} catch (\Exception $e) {
return ResponseFactory::sendException($e, (isset($request) ? $request : null));
}
} | Handles the root (/) path
@param null|string $version
@return null|ServiceResponseInterface|Response
@throws \DreamFactory\Core\Exceptions\NotImplementedException | entailment |
public function handleVersionedService($version, $service, $resource = null)
{
$request = new ServiceRequest();
$request->setApiVersion($version);
return $this->handleServiceRequest($request, $service, $resource);
} | Handles all service requests
@param null|string $version
@param string $service
@param null|string $resource
@return ServiceResponseInterface|Response|null
@throws \DreamFactory\Core\Exceptions\NotImplementedException | entailment |
public function handleService($service, $resource = null)
{
$request = new ServiceRequest();
return $this->handleServiceRequest($request, $service, $resource);
} | Handles all service requests
@param string $service
@param null|string $resource
@return ServiceResponseInterface|Response|null
@throws \DreamFactory\Core\Exceptions\NotImplementedException | entailment |
public function up()
{
if (Schema::hasTable('service_type')) {
$output = new \Symfony\Component\Console\Output\ConsoleOutput();
$output->writeln('Scanning database for old sql_db service type...');
$ids = DB::table('service')->where('type', 'sql_db')->pluck('id');
if (!empty($ids)) {
$configs = DB::table('sql_db_config')->whereIn('service_id', $ids)->get();
$output->writeln('|--------------------------------------------------------------------');
foreach ($configs as $entry) {
/** @type array $entry */
$entry = (array)$entry;
$newType = '';
$config = static::adaptConfig($entry, $newType);
$config = json_encode($config);
$id = array_get($entry, 'service_id');
$output->writeln('| Service ID: ' . $id . ' New Config: ' . $config);
DB::table('service')->where('id', $id)->update(['type' => $newType]);
DB::table('sql_db_config')->where('service_id', $id)->update(['connection' => $config]);
}
$output->writeln('|--------------------------------------------------------------------');
}
$output->writeln('Scanning database for old script service type...');
$ids = DB::table('service')->where('type', 'script')->pluck('id');
if (!empty($ids)) {
$configs = DB::table('script_config')->whereIn('service_id', $ids)->pluck('type', 'service_id');
$output->writeln('|--------------------------------------------------------------------');
foreach ($configs as $id => $driver) {
$newType = $driver;
$output->writeln('| ID: ' . $id . ' New Type: ' . $newType);
DB::table('service')->where('id', $id)->update(['type' => $newType]);
}
$output->writeln('|--------------------------------------------------------------------');
}
}
} | Run the migrations.
@return void | entailment |
public function getService()
{
if (!empty($this->service)) {
return $this->service;
}
$service = '';
$uri = trim($this->getRequestUri(), '/');
if (!empty($uri)) {
$uriParts = explode('/', $uri);
// Need to get the 3rd element of the array as
// a URI looks like api/v2/<service>/...
$service = array_get($uriParts, 2);
}
return $service;
} | {@inheritdoc} | entailment |
public function getResource()
{
if (!empty($this->service)) {
return $this->service;
}
$resource = '';
$uri = trim($this->getRequestUri(), '/');
if (!empty($uri)) {
$uriParts = explode('/', $uri);
// Need to get all elements after the 3rd of the array as
// a URI looks like api/v2/<service>/<resource>/<resource>...
array_shift($uriParts);
array_shift($uriParts);
array_shift($uriParts);
$resource = implode('/', $uriParts);
}
return $resource;
} | {@inheritdoc} | entailment |
public function getParameter($key = null, $default = null)
{
if ($this->parameters) {
if (null === $key) {
return $this->parameters;
} else {
return array_get($this->parameters, $key, $default);
}
}
return Request::query($key, $default);
} | {@inheritdoc} | entailment |
public function getPayloadData($key = null, $default = null)
{
if (!empty($this->contentAsArray)) {
if (null === $key) {
return $this->contentAsArray;
} else {
return array_get($this->contentAsArray, $key, $default);
}
}
//This just checks the Request Header Content-Type.
if (Request::isJson()) {
// Decoded json data is cached internally using parameterBag.
return $this->json($key, $default);
}
if (Str::contains(Request::header('CONTENT_TYPE'), 'x-www-form-urlencoded')) {
// Formatted xml data is stored in $this->contentAsArray
return $this->input($key, $default);
}
if (Str::contains(Request::header('CONTENT_TYPE'), 'xml')) {
// Formatted xml data is stored in $this->contentAsArray
return $this->xml($key, $default);
}
if (Str::contains(Request::header('CONTENT_TYPE'), 'csv')) {
// Formatted csv data is stored in $this->contentAsArray
return $this->csv($key, $default);
}
if (Str::contains(Request::header('CONTENT_TYPE'), 'text/plain')) {
// Plain text content, return as is.
return $this->getContent();
}
//Check the actual content. If it is blank return blank array.
$content = $this->getContent();
if (empty($content)) {
if (null === $key) {
return [];
} else {
return $default;
}
}
//Checking this last to be more efficient.
if (json_decode($content) !== null) {
$this->contentType = DataFormats::toMimeType(DataFormats::JSON);
//Decoded json data is cached internally using parameterBag.
return $this->json($key, $default);
} else {
if (DataFormatter::xmlToArray($content) !== null) {
$this->contentType = DataFormats::toMimeType(DataFormats::XML);
return $this->xml($key, $default);
} else {
if (!empty(DataFormatter::csvToArray($content))) {
$this->contentType = DataFormats::toMimeType(DataFormats::CSV);
return $this->csv($key, $default);
}
}
}
throw new BadRequestException('Unrecognized payload type');
} | @param null $key
@param null $default
@return array
@throws BadRequestException
@throws \DreamFactory\Core\Exceptions\NotImplementedException | entailment |
protected function csv($key = null, $default = null)
{
if (empty($this->contentAsArray)) {
$content = $this->getContent();
$data = DataFormatter::csvToArray($content);
if (!empty($data)) {
$this->contentAsArray = ResourcesWrapper::wrapResources($data);
}
}
if (null === $key) {
return $this->contentAsArray;
} else {
return array_get($this->contentAsArray, $key, $default);
}
} | Returns CSV payload data
@param null $key
@param null $default
@return array|mixed|null | entailment |
protected function xml($key = null, $default = null)
{
if (empty($this->contentAsArray)) {
$content = $this->getContent();
$data = DataFormatter::xmlToArray($content);
if (!empty($data)) {
if ((1 === count($data)) && !array_key_exists(ResourcesWrapper::getWrapper(), $data)) {
// All XML comes wrapped in a single wrapper, if not resource wrapper, remove it
$data = reset($data);
}
$this->contentAsArray = $data;
}
}
if (null === $key) {
return $this->contentAsArray;
} else {
return array_get($this->contentAsArray, $key, $default);
}
} | Returns XML payload data.
@param null $key
@param null $default
@return array|mixed|null | entailment |
protected function json($key = null, $default = null)
{
if (null === $key) {
return Request::json()->all();
} else {
return Request::json($key, $default);
}
} | @param null $key
@param null $default
@return mixed | entailment |
public function getHeader($key = null, $default = null)
{
if (null === $key) {
return $this->getHeaders();
}
if ($this->headers) {
return array_get($this->headers, $key, $default);
}
return Request::header($key, $default);
} | {@inheritdoc} | entailment |
public function getHeaders()
{
if ($this->headers) {
return $this->headers;
}
return array_map(
function ($value){
return (is_array($value)) ? implode(',', $value) : $value;
},
Request::header()
);
} | {@inheritdoc} | entailment |
public function getFile($key = null, $default = null)
{
if (null === $key) {
$files = [];
foreach ($_FILES as $key => $FILE){
$files[$key] = $this->formatFileInfo($FILE);
}
return $files;
} else {
$file = array_get($_FILES, $key, $default);
$file = $this->formatFileInfo($file);
return $file;
}
} | @param null $key
@param null $default
@return array|mixed | entailment |
protected function formatFileInfo($fileInfo)
{
if(empty($fileInfo) || !is_array($fileInfo) || isset($fileInfo[0])){
return $fileInfo;
}
$file = [];
foreach ($fileInfo as $key => $value){
if(is_array($value)){
foreach ($value as $k => $v){
$file[$k][$key] = $v;
}
} else {
$file[$key] = $value;
}
}
return $file;
} | Format file data for ease of use
@param array|null $fileInfo
@return array | entailment |
public function getApiKey()
{
if (!empty($this->parameters) && !empty($this->headers)) {
$apiKey = $this->getParameter('api_key');
if (empty($apiKey)) {
$apiKey = $this->getHeader('X_DREAMFACTORY_API_KEY');
}
} else {
$apiKey = Request::input('api_key');
if (empty($apiKey)) {
$apiKey = Request::header('X_DREAMFACTORY_API_KEY');
}
}
if (empty($apiKey)) {
$apiKey = null;
}
return $apiKey;
} | {@inheritdoc} | entailment |
public function setBounds($from, $length = null, $stopOutOfBounds = false) {
$this->from = $from;
$this->length = $length;
$this->outOfBounds = (bool) $stopOutOfBounds;
return $this;
} | Set valid bounds (rows which will be printer)
@param int $from from row index...
@param int $length number of rows to print
@return Debug | entailment |
public function configure(TcTable $table) {
$table
->on(TcTable::EV_COLUMN_ADDED, [$this, 'columnAdded'])
->on(TcTable::EV_BODY_ADD, [$this, 'bodyAdd'])
->on(TcTable::EV_BODY_ADDED, [$this, 'bodyAdded'])
->on(TcTable::EV_BODY_SKIPPED, [$this, 'bodySkipped'])
->on(TcTable::EV_HEADER_ADD, [$this, 'headerAdd'])
->on(TcTable::EV_HEADER_ADDED, [$this, 'headerAdded'])
->on(TcTable::EV_PAGE_ADD, [$this, 'pageAdd'])
->on(TcTable::EV_PAGE_ADDED, [$this, 'pageAdded'])
->on(TcTable::EV_ROW_ADD, [$this, 'rowAdd'])
->on(TcTable::EV_ROW_ADDED, [$this, 'rowAdded'])
->on(TcTable::EV_ROW_SKIPPED, [$this, 'rowSkipped'])
->on(TcTable::EV_ROW_HEIGHT_GET, [$this, 'rowHeightGet'])
->on(TcTable::EV_CELL_ADD, [$this, 'cellAdd'])
->on(TcTable::EV_CELL_ADDED, [$this, 'cellAdded'])
->on(TcTable::EV_CELL_HEIGHT_GET, [$this, 'cellHeightGet']);
} | {@inheritDocs} | entailment |
private function inBounds() {
$in = true;
if ($this->from !== null) {
$in = $this->current >= $this->from;
if ($in && $this->length !== null) {
$in = $this->current < $this->from + $this->length;
if (!$in && $this->outOfBounds) {
die("Process stopped in TcTable Debug Plugin, because " .
"\$outOfBounds is set to TRUE in setBounds().");
}
}
}
if ($in && is_callable($this->boundsFn)) {
return $this->boundsFn($this, $this->current);
}
return $in;
} | Check if the current row is in debug bounds
@return bool | entailment |
private function listenTo($event = null) {
if ($event === null && $this->getEventInvoker()) {
$event = $this->getEventInvoker()['id'];
}
return !$this->listen || in_array($event, $this->listen);
} | Check if the given event is listenable
@param int $event event id, current event if null
@return bool | entailment |
public function getModel($table)
{
if (isset($this->map[$table])) {
return $this->map[$table];
}
return null;
} | Return the model for the given table.
@param string $table
@return string | entailment |
public function getTable($model)
{
if (false !== $pos = array_search($model, $this->map)) {
return $pos;
}
return null;
} | Return the table for the given model.
@param string $model
@return string | entailment |
public static function getConfig($id, $local_config = null, $protect = true)
{
$config = parent::getConfig($id, $local_config, $protect);
if ($cacheConfig = ServiceCacheConfig::whereServiceId($id)->first()) {
$config = array_merge($config, $cacheConfig->toArray());
}
return $config;
} | {@inheritdoc} | entailment |
public static function setConfig($id, $config, $local_config = null)
{
ServiceCacheConfig::setConfig($id, $config, $local_config);
return parent::setConfig($id, $config, $local_config);
} | {@inheritdoc} | entailment |
public static function storeConfig($id, $config)
{
ServiceCacheConfig::storeConfig($id, $config);
return parent::storeConfig($id, $config);
} | {@inheritdoc} | entailment |
public function indexNew()
{
$threads = $this->api('thread.index-new')->get();
event(new UserViewingNew($threads));
return view('forum::thread.index-new', compact('threads'));
} | GET: Return a new/updated threads view.
@return \Illuminate\Http\Response | entailment |
public function markNew(Request $request)
{
$threads = $this->api('thread.mark-new')->parameters($request->only('category_id'))->patch();
event(new UserMarkingNew);
if ($request->has('category_id')) {
$category = $this->api('category.fetch', $request->input('category_id'))->get();
if ($category) {
Forum::alert('success', 'categories.marked_read', 0, ['category' => $category->title]);
return redirect(Forum::route('category.show', $category));
}
}
Forum::alert('success', 'threads.marked_read');
return redirect(config('forum.routing.prefix'));
} | PATCH: Mark new/updated threads as read for the current user.
@param Request $request
@return \Illuminate\Http\Response | entailment |
public function show(Request $request)
{
$thread = $this->api('thread.fetch', $request->route('thread'))
->parameters(['include_deleted' => auth()->check()])
->get();
event(new UserViewingThread($thread));
$category = $thread->category;
$categories = [];
if (Gate::allows('moveThreadsFrom', $category)) {
$categories = $this->api('category.index')->parameters(['where' => ['category_id' => 0]], ['where' => ['enable_threads' => 1]])->get();
}
$posts = $thread->postsPaginated;
return view('forum::thread.show', compact('categories', 'category', 'thread', 'posts'));
} | GET: Return a thread view.
@param Request $request
@return \Illuminate\Http\Response | entailment |
public function create(Request $request)
{
$category = $this->api('category.fetch', $request->route('category'))->get();
if (!$category->threadsEnabled) {
Forum::alert('warning', 'categories.threads_disabled');
return redirect(Forum::route('category.show', $category));
}
event(new UserCreatingThread($category));
return view('forum::thread.create', compact('category'));
} | GET: Return a 'create thread' view.
@param Request $request
@return \Illuminate\Http\Response | entailment |
public function store(Request $request)
{
$category = $this->api('category.fetch', $request->route('category'))->get();
if (!$category->threadsEnabled) {
Forum::alert('warning', 'categories.threads_disabled');
return redirect(Forum::route('category.show', $category));
}
$thread = [
'author_id' => auth()->user()->getKey(),
'category_id' => $category->id,
'title' => $request->input('title'),
'content' => $request->input('content')
];
$thread = $this->api('thread.store')->parameters($thread)->post();
Forum::alert('success', 'threads.created');
return redirect(Forum::route('thread.show', $thread));
} | POST: Store a new thread.
@param Request $request
@return \Illuminate\Http\RedirectResponse | entailment |
public function update(Request $request)
{
$action = $request->input('action');
$thread = $this->api("thread.{$action}", $request->route('thread'))->parameters($request->all())->patch();
Forum::alert('success', 'threads.updated', 1);
return redirect(Forum::route('thread.show', $thread));
} | PATCH: Update a thread.
@param Request $request
@return \Illuminate\Http\RedirectResponse | entailment |
public function destroy(Request $request)
{
$this->validate($request, ['action' => 'in:delete,permadelete']);
$permanent = !config('forum.preferences.soft_deletes') || ($request->input('action') == 'permadelete');
$parameters = $request->all();
$parameters['force'] = $permanent ? 1 : 0;
$thread = $this->api('thread.delete', $request->route('thread'))->parameters($parameters)->delete();
Forum::alert('success', 'threads.deleted', 1);
return redirect($permanent ? Forum::route('category.show', $thread->category) : Forum::route('thread.show', $thread));
} | DELETE: Delete a thread.
@param Request $request
@return \Illuminate\Http\RedirectResponse | entailment |
public function configure(array $settings = [])
{
if (empty($this->commandName = array_get($settings, 'command_name'))) {
throw new \Exception("Invalid configuration: missing command name.");
}
// Various ways to figure out how to run this thing
// check settings, then global config, then use the OS to find it
$this->commandPath = array_get($settings, 'command_path');
if (empty($this->commandPath)) {
$this->commandPath = $this->findCommandPath();
if (empty($this->commandPath = $this->commandName)) {
throw new \Exception("Failed to find a valid path to command for scripting.");
}
}
$this->arguments = array_get($settings, 'arguments');
$this->supportsInlineExecution = boolval(array_get($settings, 'supports_inline_execution', false));
$this->inlineArguments = array_get($settings, 'inline_arguments');
$this->fileExtension = array_get($settings, 'file_extension');
} | @param array $settings
@throws \Exception | entailment |
public static function getApiKey($request)
{
// Check for API key in request parameters.
$apiKey = $request->query('api_key');
if (empty($apiKey)) {
// Check for API key in request HEADER.
$apiKey = $request->header('X_DREAMFACTORY_API_KEY');
}
if (empty($apiKey)) {
// Check for API key in request payload.
// Skip if this is a call for system/app
$route = $request->getPathInfo();
if (strpos($route, 'system/app') === false) {
$apiKey = $request->input('api_key');
}
}
return $apiKey;
} | @param Request $request
@return mixed | entailment |
public static function getJwt($request)
{
$token = static::getJWTFromAuthHeader();
if (empty($token)) {
$token = $request->header('X_DREAMFACTORY_SESSION_TOKEN');
}
if (empty($token)) {
$token = $request->input('session_token');
}
return $token;
} | @param Request $request
@return mixed | entailment |
protected static function getJWTFromAuthHeader()
{
if ('testing' === env('APP_ENV')) {
// getallheaders method is not available in unit test mode.
return [];
}
if (!function_exists('getallheaders')) {
function getallheaders()
{
if (!is_array($_SERVER)) {
return [];
}
$headers = [];
foreach ($_SERVER as $name => $value) {
if (substr($name, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] =
$value;
}
}
return $headers;
}
}
$token = null;
$headers = getallheaders();
$authHeader = array_get($headers, 'Authorization');
if (strpos($authHeader, 'Bearer') !== false) {
$token = substr($authHeader, 7);
}
return $token;
} | Gets the token from Authorization header.
@return string | entailment |
public static function getScriptToken($request)
{
// Check for script authorizing token in request parameters.
$token = $request->query('script_token');
if (empty($token)) {
// Check for script token in request HEADER.
$token = $request->header('X_DREAMFACTORY_SCRIPT_TOKEN');
}
if (empty($token)) {
// Check for script token in request payload.
$token = $request->input('script_token');
}
return $token;
} | @param Request $request
@return mixed | entailment |
public function handle(Request $request, \Closure $next)
{
// Not using any stateful session. Therefore, no need to track session
// using cookies. Disabling tracking session by browser cookies.
ini_set('session.use_cookies', 0);
if (!in_array($route = $request->getPathInfo(), ['/setup', '/setup_db',])) {
try {
// Get the API key
$apiKey = static::getApiKey($request);
Session::setApiKey($apiKey);
$appId = App::getAppIdByApiKey($apiKey);
// Get the session token (JWT)
$token = static::getJwt($request);
if (in_array(trim($route, '/'), static::$authApis) && $request->getMethod() === Verbs::POST) {
// If this is a request for login ignore any token provided.
$token = null;
}
Session::setSessionToken($token);
// Get the script token
if (!empty($scriptToken = static::getScriptToken($request))) {
Session::setRequestor(ServiceRequestorTypes::SCRIPT);
}
// Check for basic auth attempt and valid JWT
if (!empty($token)) {
/**
* Note: All caught exceptions from JWT are stored in session variables.
* These are later checked and handled appropriately in the AccessCheck middleware.
*
* This is to allow processing API calls that do not require any valid
* authenticated session. For example POST user/session to login,
* PUT user/session to refresh old JWT, GET system/environment etc.
*
* This also allows for auditing API calls that are called by not permitted/processed.
* It also allows counting unauthorized API calls against API limits.
*/
try {
JWTAuth::setToken($token);
/** @type Payload $payload */
$payload = JWTAuth::getPayload();
JWTUtilities::verifyUser($payload);
$userId = $payload->get('user_id');
Session::setSessionData($appId, $userId);
} catch (TokenExpiredException $e) {
JWTUtilities::clearAllExpiredTokenMaps();
Session::put('token_expired', true);
Session::put(
'token_expired_msg', $e->getMessage() .
': Session expired. Please refresh your token (if still within refresh window) or re-login.'
);
} catch (TokenBlacklistedException $e) {
Session::put('token_blacklisted', true);
Session::put(
'token_blacklisted_msg',
$e->getMessage() . ': Session terminated. Please re-login.'
);
} catch (TokenInvalidException $e) {
Session::put('token_invalid', true);
Session::put('token_invalid_msg', 'Invalid token: ' . $e->getMessage());
}
} elseif (!empty($basicAuthUser = $request->getUser()) ||
!empty($basicAuthPassword = $request->getPassword())) {
// Attempting to login using basic auth.
Auth::onceBasic();
/** @var User $authenticatedUser */
$authenticatedUser = Auth::user();
if (!empty($authenticatedUser)) {
$userId = $authenticatedUser->id;
Session::setSessionData($appId, $userId);
} else {
throw new UnauthorizedException('Unauthorized. User credentials did not match.');
}
} elseif (!empty($scriptToken)) {
// keep this separate from basic auth and jwt handling,
// as this is the fall back when those are not provided from scripting (see node.js and python)
if ($temp = Cache::get('script-token:' . $scriptToken)) {
\Log::debug('script token: ' . $scriptToken);
\Log::debug('script token cache: ' . print_r($temp, true));
Session::setSessionData(array_get($temp, 'app_id'), array_get($temp, 'user_id'));
}
} elseif (!empty($appId)) {
//Just Api Key is supplied. No authenticated session
Session::setSessionData($appId);
}
return $next($request);
} catch (\Exception $e) {
return ResponseFactory::sendException($e);
}
}
return $next($request);
} | @param Request $request
@param \Closure $next
@return array|mixed|string | entailment |
public function boot()
{
// add our df config
$configPath = __DIR__ . '/../config/df.php';
if (function_exists('config_path')) {
$publishPath = config_path('df.php');
} else {
$publishPath = base_path('config/df.php');
}
$this->publishes([$configPath => $publishPath], 'config');
$this->addAliases();
$this->addMiddleware();
$this->registerOtherProviders();
// add routes
/** @noinspection PhpUndefinedMethodInspection */
if (!$this->app->routesAreCached()) {
include __DIR__ . '/../routes/routes.php';
}
// add commands, https://laravel.com/docs/5.4/packages#commands
$this->addCommands();
// add migrations, https://laravel.com/docs/5.4/packages#resources
$this->loadMigrationsFrom(__DIR__ . '/../database/migrations');
// subscribe to all listened to events
Event::subscribe(new ServiceEventHandler());
} | Bootstrap the application events. | entailment |
protected function addMiddleware()
{
// the method name was changed in Laravel 5.4
if (method_exists(\Illuminate\Routing\Router::class, 'aliasMiddleware')) {
Route::aliasMiddleware('df.auth_check', AuthCheck::class);
Route::aliasMiddleware('df.access_check', AccessCheck::class);
Route::aliasMiddleware('df.verb_override', VerbOverrides::class);
} else {
/** @noinspection PhpUndefinedMethodInspection */
Route::middleware('df.auth_check', AuthCheck::class);
/** @noinspection PhpUndefinedMethodInspection */
Route::middleware('df.access_check', AccessCheck::class);
/** @noinspection PhpUndefinedMethodInspection */
Route::middleware('df.verb_override', VerbOverrides::class);
}
/** Add the first user check to the web group */
Route::prependMiddlewareToGroup('web', FirstUserCheck::class);
Route::middlewareGroup('df.api', [
'df.verb_override',
'df.auth_check',
'df.access_check'
]);
} | Register any middleware aliases.
@return void | entailment |
protected function encryptAttribute($key, &$value)
{
if (!is_null($value) && in_array($key, $this->getEncryptable())) {
$value = Crypt::encrypt($value);
return true;
}
return false;
} | Check if the attribute is marked encrypted, if so return the decrypted value.
@param string $key Attribute name
@param mixed $value Value of the attribute $key, decrypt if encrypted
@return bool Whether or not the attribute is being decrypted | entailment |
protected function decryptAttribute($key, &$value)
{
if (!is_null($value) && !$this->encryptedView && in_array($key, $this->getEncryptable())) {
$value = Crypt::decrypt($value);
return true;
}
return false;
} | Check if the attribute is marked encrypted, if so return the decrypted value.
@param string $key Attribute name
@param mixed $value Value of the attribute $key, decrypt if encrypted
@return bool Whether or not the attribute is being decrypted | entailment |
protected function addDecryptedAttributesToArray(array $attributes)
{
if (!$this->encryptedView) {
foreach ($this->getEncryptable() as $key) {
if (!array_key_exists($key, $attributes)) {
continue;
}
if (!empty($attributes[$key])) {
$attributes[$key] = Crypt::decrypt($attributes[$key]);
}
}
}
return $attributes;
} | Decrypt encryptable attributes found in outgoing array
@param array $attributes
@return array | entailment |
public static function toNumeric($contentType)
{
if (!is_string($contentType)) {
throw new \InvalidArgumentException('The content type "' . $contentType . '" is not a string.');
}
return static::defines(strtoupper($contentType), true);
} | @param string $contentType
@throws NotImplementedException
@return string | entailment |
public static function toString($numericLevel = self::TEXT)
{
if (!is_numeric($numericLevel)) {
throw new \InvalidArgumentException('The content type "' . $numericLevel . '" is not numeric.');
}
return static::nameOf($numericLevel, true, false);
} | @param int $numericLevel
@throws NotImplementedException
@return string | entailment |
public function configure(TcTable $table) {
$table
->on(TcTable::EV_BODY_ADD, [$this, 'resetFill'])
->on(TcTable::EV_ROW_ADD, [$this, 'setFill']);
} | {@inheritDocs} | entailment |
public function setFill(TcTable $table) {
if ($this->disabled) {
$fill = false;
} else {
$fill = $this->rowCurrentStripe = !$this->rowCurrentStripe;
}
foreach ($table->getRowDefinition() as $column => $row) {
$table->setRowDefinition($column, 'fill', $row['fill'] ?: $fill);
}
$this->moveY($table);
} | Set the background of the row
@param TcTable $table
@return void | entailment |
public function moveY(TcTable $table) {
$y = 0.6 / $table->getPdf()->getScaleFactor();
$table->getPdf()->SetY($table->getPdf()->GetY() + $y);
} | Adjust Y because cell background passes over the previous cell's border,
hiding it.
@param TcTable $table | entailment |
public static function getParentFolder($path)
{
$path = rtrim($path, '/'); // may be a folder
$marker = strrpos($path, '/');
if (false === $marker) {
return '';
}
return substr($path, 0, $marker);
} | @param $path
@return string | entailment |
public static function getNameFromPath($path)
{
$path = rtrim($path, '/'); // may be a folder
if (empty($path)) {
return '.';
} // self directory
$marker = strrpos($path, '/');
if (false === $marker) {
return $path;
}
return substr($path, $marker + 1);
} | @param $path
@return string | entailment |
public static function url_exist($url)
{
$headers = @get_headers($url);
if (empty($headers) || 'HTTP/1.1 404 Not Found' == $headers[0]) {
return false;
}
return true;
} | @param string $url
@return bool | entailment |
public static function importUrlFileToTemp($url, $name = '')
{
if (static::url_exist($url)) {
$readFrom = @fopen($url, 'rb');
if ($readFrom) {
$directory = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
// $ext = FileUtilities::getFileExtension( basename( $url ) );
// $validTypes = array( 'zip', 'dfpkg' ); // default zip and package extensions
// if ( !in_array( $ext, $validTypes ) )
// {
// throw new Exception( 'Invalid file type. Currently only URLs to repository zip files are accepted.' );
// }
if (empty($name)) {
$name = basename($url);
}
$newFile = $directory . $name;
$writeTo = fopen($newFile, 'wb'); // creating new file on local server
if ($writeTo) {
while (!feof($readFrom)) {
// Write the url file to the directory.
fwrite(
$writeTo,
fread($readFrom, 1024 * 8),
1024 * 8
); // write the file to the new directory at a rate of 8kb/sec. until we reach the end.
}
fclose($readFrom);
fclose($writeTo);
return $newFile;
} else {
throw new \Exception("Could not establish new file ($directory$name) on local server.");
}
} else {
throw new \Exception("Could not read the file: $url");
}
} else {
throw new NotFoundException('Invalid URL entered. File not found.');
}
} | @param string $url
@param string $name name of the temporary file to create
@throws NotFoundException
@throws \Exception
@return string temporary file path | entailment |
public static function determineContentType($ext = '', $content = '', $local_file = '', $default = '')
{
/**
* @var array of file extensions to mime types
*/
static $mimeTypes = array(
'123' => 'application/vnd.lotus-1-2-3',
'3dml' => 'text/vnd.in3d.3dml',
'3ds' => 'image/x-3ds',
'3g2' => 'video/3gpp2',
'3gp' => 'video/3gpp',
'7z' => 'application/x-7z-compressed',
'aab' => 'application/x-authorware-bin',
'aac' => 'audio/x-aac',
'aam' => 'application/x-authorware-map',
'aas' => 'application/x-authorware-seg',
'abw' => 'application/x-abiword',
'ac' => 'application/pkix-attr-cert',
'acc' => 'application/vnd.americandynamics.acc',
'ace' => 'application/x-ace-compressed',
'acu' => 'application/vnd.acucobol',
'acutc' => 'application/vnd.acucorp',
'adp' => 'audio/adpcm',
'aep' => 'application/vnd.audiograph',
'afm' => 'application/x-font-type1',
'afp' => 'application/vnd.ibm.modcap',
'ahead' => 'application/vnd.ahead.space',
'ai' => 'application/postscript',
'aif' => 'audio/x-aiff',
'aifc' => 'audio/x-aiff',
'aiff' => 'audio/x-aiff',
'air' => 'application/vnd.adobe.air-application-installer-package+zip',
'ait' => 'application/vnd.dvb.ait',
'ami' => 'application/vnd.amiga.ami',
'apk' => 'application/vnd.android.package-archive',
'appcache' => 'text/cache-manifest',
'application' => 'application/x-ms-application',
'apr' => 'application/vnd.lotus-approach',
'arc' => 'application/x-freearc',
'asc' => 'application/pgp-signature',
'asf' => 'video/x-ms-asf',
'asm' => 'text/x-asm',
'aso' => 'application/vnd.accpac.simply.aso',
'asx' => 'video/x-ms-asf',
'atc' => 'application/vnd.acucorp',
'atom' => 'application/atom+xml',
'atomcat' => 'application/atomcat+xml',
'atomsvc' => 'application/atomsvc+xml',
'atx' => 'application/vnd.antix.game-component',
'au' => 'audio/basic',
'avi' => 'video/x-msvideo',
'aw' => 'application/applixware',
'azf' => 'application/vnd.airzip.filesecure.azf',
'azs' => 'application/vnd.airzip.filesecure.azs',
'azw' => 'application/vnd.amazon.ebook',
'bat' => 'application/x-msdownload',
'bcpio' => 'application/x-bcpio',
'bdf' => 'application/x-font-bdf',
'bdm' => 'application/vnd.syncml.dm+wbxml',
'bed' => 'application/vnd.realvnc.bed',
'bh2' => 'application/vnd.fujitsu.oasysprs',
'bin' => 'application/octet-stream',
'blb' => 'application/x-blorb',
'blorb' => 'application/x-blorb',
'bmi' => 'application/vnd.bmi',
'bmp' => 'image/bmp',
'book' => 'application/vnd.framemaker',
'box' => 'application/vnd.previewsystems.box',
'boz' => 'application/x-bzip2',
'bpk' => 'application/octet-stream',
'btif' => 'image/prs.btif',
'bz' => 'application/x-bzip',
'bz2' => 'application/x-bzip2',
'c' => 'text/x-c',
'c11amc' => 'application/vnd.cluetrust.cartomobile-config',
'c11amz' => 'application/vnd.cluetrust.cartomobile-config-pkg',
'c4d' => 'application/vnd.clonk.c4group',
'c4f' => 'application/vnd.clonk.c4group',
'c4g' => 'application/vnd.clonk.c4group',
'c4p' => 'application/vnd.clonk.c4group',
'c4u' => 'application/vnd.clonk.c4group',
'cab' => 'application/vnd.ms-cab-compressed',
'caf' => 'audio/x-caf',
'cap' => 'application/vnd.tcpdump.pcap',
'car' => 'application/vnd.curl.car',
'cat' => 'application/vnd.ms-pki.seccat',
'cb7' => 'application/x-cbr',
'cba' => 'application/x-cbr',
'cbr' => 'application/x-cbr',
'cbt' => 'application/x-cbr',
'cbz' => 'application/x-cbr',
'cc' => 'text/x-c',
'cct' => 'application/x-director',
'ccxml' => 'application/ccxml+xml',
'cdbcmsg' => 'application/vnd.contact.cmsg',
'cdf' => 'application/x-netcdf',
'cdkey' => 'application/vnd.mediastation.cdkey',
'cdmia' => 'application/cdmi-capability',
'cdmic' => 'application/cdmi-container',
'cdmid' => 'application/cdmi-domain',
'cdmio' => 'application/cdmi-object',
'cdmiq' => 'application/cdmi-queue',
'cdx' => 'chemical/x-cdx',
'cdxml' => 'application/vnd.chemdraw+xml',
'cdy' => 'application/vnd.cinderella',
'cer' => 'application/pkix-cert',
'cfs' => 'application/x-cfs-compressed',
'cgm' => 'image/cgm',
'chat' => 'application/x-chat',
'chm' => 'application/vnd.ms-htmlhelp',
'chrt' => 'application/vnd.kde.kchart',
'cif' => 'chemical/x-cif',
'cii' => 'application/vnd.anser-web-certificate-issue-initiation',
'cil' => 'application/vnd.ms-artgalry',
'cla' => 'application/vnd.claymore',
'class' => 'application/java-vm',
'clkk' => 'application/vnd.crick.clicker.keyboard',
'clkp' => 'application/vnd.crick.clicker.palette',
'clkt' => 'application/vnd.crick.clicker.template',
'clkw' => 'application/vnd.crick.clicker.wordbank',
'clkx' => 'application/vnd.crick.clicker',
'clp' => 'application/x-msclip',
'cmc' => 'application/vnd.cosmocaller',
'cmdf' => 'chemical/x-cmdf',
'cml' => 'chemical/x-cml',
'cmp' => 'application/vnd.yellowriver-custom-menu',
'cmx' => 'image/x-cmx',
'cod' => 'application/vnd.rim.cod',
'com' => 'application/x-msdownload',
'conf' => 'text/plain',
'cpio' => 'application/x-cpio',
'cpp' => 'text/x-c',
'cpt' => 'application/mac-compactpro',
'crd' => 'application/x-mscardfile',
'crl' => 'application/pkix-crl',
'crt' => 'application/x-x509-ca-cert',
'cryptonote' => 'application/vnd.rig.cryptonote',
'csh' => 'application/x-csh',
'csml' => 'chemical/x-csml',
'csp' => 'application/vnd.commonspace',
'css' => 'text/css',
'cst' => 'application/x-director',
'csv' => 'text/csv',
'cu' => 'application/cu-seeme',
'curl' => 'text/vnd.curl',
'cww' => 'application/prs.cww',
'cxt' => 'application/x-director',
'cxx' => 'text/x-c',
'dae' => 'model/vnd.collada+xml',
'daf' => 'application/vnd.mobius.daf',
'dart' => 'application/vnd.dart',
'dataless' => 'application/vnd.fdsn.seed',
'davmount' => 'application/davmount+xml',
'dbk' => 'application/docbook+xml',
'dcr' => 'application/x-director',
'dcurl' => 'text/vnd.curl.dcurl',
'dd2' => 'application/vnd.oma.dd2+xml',
'ddd' => 'application/vnd.fujixerox.ddd',
'deb' => 'application/x-debian-package',
'def' => 'text/plain',
'deploy' => 'application/octet-stream',
'der' => 'application/x-x509-ca-cert',
'dfac' => 'application/vnd.dreamfactory',
'dgc' => 'application/x-dgc-compressed',
'dic' => 'text/x-c',
'dir' => 'application/x-director',
'dis' => 'application/vnd.mobius.dis',
'dist' => 'application/octet-stream',
'distz' => 'application/octet-stream',
'djv' => 'image/vnd.djvu',
'djvu' => 'image/vnd.djvu',
'dll' => 'application/x-msdownload',
'dmg' => 'application/x-apple-diskimage',
'dmp' => 'application/vnd.tcpdump.pcap',
'dms' => 'application/octet-stream',
'dna' => 'application/vnd.dna',
'doc' => 'application/msword',
'docm' => 'application/vnd.ms-word.document.macroenabled.12',
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'dot' => 'application/msword',
'dotm' => 'application/vnd.ms-word.template.macroenabled.12',
'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
'dp' => 'application/vnd.osgi.dp',
'dpg' => 'application/vnd.dpgraph',
'dra' => 'audio/vnd.dra',
'dsc' => 'text/prs.lines.tag',
'dssc' => 'application/dssc+der',
'dtb' => 'application/x-dtbook+xml',
'dtd' => 'application/xml-dtd',
'dts' => 'audio/vnd.dts',
'dtshd' => 'audio/vnd.dts.hd',
'dump' => 'application/octet-stream',
'dvb' => 'video/vnd.dvb.file',
'dvi' => 'application/x-dvi',
'dwf' => 'model/vnd.dwf',
'dwg' => 'image/vnd.dwg',
'dxf' => 'image/vnd.dxf',
'dxp' => 'application/vnd.spotfire.dxp',
'dxr' => 'application/x-director',
'ecelp4800' => 'audio/vnd.nuera.ecelp4800',
'ecelp7470' => 'audio/vnd.nuera.ecelp7470',
'ecelp9600' => 'audio/vnd.nuera.ecelp9600',
'ecma' => 'application/ecmascript',
'edm' => 'application/vnd.novadigm.edm',
'edx' => 'application/vnd.novadigm.edx',
'efif' => 'application/vnd.picsel',
'ei6' => 'application/vnd.pg.osasli',
'elc' => 'application/octet-stream',
'emf' => 'application/x-msmetafile',
'eml' => 'message/rfc822',
'emma' => 'application/emma+xml',
'emz' => 'application/x-msmetafile',
'eol' => 'audio/vnd.digital-winds',
'eot' => 'application/vnd.ms-fontobject',
'eps' => 'application/postscript',
'epub' => 'application/epub+zip',
'es3' => 'application/vnd.eszigno3+xml',
'esa' => 'application/vnd.osgi.subsystem',
'esf' => 'application/vnd.epson.esf',
'et3' => 'application/vnd.eszigno3+xml',
'etx' => 'text/x-setext',
'eva' => 'application/x-eva',
'evy' => 'application/x-envoy',
'exe' => 'application/x-msdownload',
'exi' => 'application/exi',
'ext' => 'application/vnd.novadigm.ext',
'ez' => 'application/andrew-inset',
'ez2' => 'application/vnd.ezpix-album',
'ez3' => 'application/vnd.ezpix-package',
'f' => 'text/x-fortran',
'f4v' => 'video/x-f4v',
'f77' => 'text/x-fortran',
'f90' => 'text/x-fortran',
'fbs' => 'image/vnd.fastbidsheet',
'fcdt' => 'application/vnd.adobe.formscentral.fcdt',
'fcs' => 'application/vnd.isac.fcs',
'fdf' => 'application/vnd.fdf',
'fe_launch' => 'application/vnd.denovo.fcselayout-link',
'fg5' => 'application/vnd.fujitsu.oasysgp',
'fgd' => 'application/x-director',
'fh' => 'image/x-freehand',
'fh4' => 'image/x-freehand',
'fh5' => 'image/x-freehand',
'fh7' => 'image/x-freehand',
'fhc' => 'image/x-freehand',
'fig' => 'application/x-xfig',
'flac' => 'audio/x-flac',
'fli' => 'video/x-fli',
'flo' => 'application/vnd.micrografx.flo',
'flv' => 'video/x-flv',
'flw' => 'application/vnd.kde.kivio',
'flx' => 'text/vnd.fmi.flexstor',
'fly' => 'text/vnd.fly',
'fm' => 'application/vnd.framemaker',
'fnc' => 'application/vnd.frogans.fnc',
'for' => 'text/x-fortran',
'fpx' => 'image/vnd.fpx',
'frame' => 'application/vnd.framemaker',
'fsc' => 'application/vnd.fsc.weblaunch',
'fst' => 'image/vnd.fst',
'ftc' => 'application/vnd.fluxtime.clip',
'fti' => 'application/vnd.anser-web-funds-transfer-initiation',
'fvt' => 'video/vnd.fvt',
'fxp' => 'application/vnd.adobe.fxp',
'fxpl' => 'application/vnd.adobe.fxp',
'fzs' => 'application/vnd.fuzzysheet',
'g2w' => 'application/vnd.geoplan',
'g3' => 'image/g3fax',
'g3w' => 'application/vnd.geospace',
'gac' => 'application/vnd.groove-account',
'gam' => 'application/x-tads',
'gbr' => 'application/rpki-ghostbusters',
'gca' => 'application/x-gca-compressed',
'gdl' => 'model/vnd.gdl',
'geo' => 'application/vnd.dynageo',
'gex' => 'application/vnd.geometry-explorer',
'ggb' => 'application/vnd.geogebra.file',
'ggt' => 'application/vnd.geogebra.tool',
'ghf' => 'application/vnd.groove-help',
'gif' => 'image/gif',
'gim' => 'application/vnd.groove-identity-message',
'gml' => 'application/gml+xml',
'gmx' => 'application/vnd.gmx',
'gnumeric' => 'application/x-gnumeric',
'gph' => 'application/vnd.flographit',
'gpx' => 'application/gpx+xml',
'gqf' => 'application/vnd.grafeq',
'gqs' => 'application/vnd.grafeq',
'gram' => 'application/srgs',
'gramps' => 'application/x-gramps-xml',
'gre' => 'application/vnd.geometry-explorer',
'grv' => 'application/vnd.groove-injector',
'grxml' => 'application/srgs+xml',
'gsf' => 'application/x-font-ghostscript',
'gtar' => 'application/x-gtar',
'gtm' => 'application/vnd.groove-tool-message',
'gtw' => 'model/vnd.gtw',
'gv' => 'text/vnd.graphviz',
'gxf' => 'application/gxf',
'gxt' => 'application/vnd.geonext',
'h' => 'text/x-c',
'h261' => 'video/h261',
'h263' => 'video/h263',
'h264' => 'video/h264',
'hal' => 'application/vnd.hal+xml',
'hbci' => 'application/vnd.hbci',
'hdf' => 'application/x-hdf',
'hh' => 'text/x-c',
'hlp' => 'application/winhlp',
'hpgl' => 'application/vnd.hp-hpgl',
'hpid' => 'application/vnd.hp-hpid',
'hps' => 'application/vnd.hp-hps',
'hqx' => 'application/mac-binhex40',
'htke' => 'application/vnd.kenameaapp',
'htm' => 'text/html',
'html' => 'text/html',
'hvd' => 'application/vnd.yamaha.hv-dic',
'hvp' => 'application/vnd.yamaha.hv-voice',
'hvs' => 'application/vnd.yamaha.hv-script',
'i2g' => 'application/vnd.intergeo',
'icc' => 'application/vnd.iccprofile',
'ice' => 'x-conference/x-cooltalk',
'icm' => 'application/vnd.iccprofile',
'ico' => 'image/x-icon',
'ics' => 'text/calendar',
'ief' => 'image/ief',
'ifb' => 'text/calendar',
'ifm' => 'application/vnd.shana.informed.formdata',
'iges' => 'model/iges',
'igl' => 'application/vnd.igloader',
'igm' => 'application/vnd.insors.igm',
'igs' => 'model/iges',
'igx' => 'application/vnd.micrografx.igx',
'iif' => 'application/vnd.shana.informed.interchange',
'imp' => 'application/vnd.accpac.simply.imp',
'ims' => 'application/vnd.ms-ims',
'in' => 'text/plain',
'ink' => 'application/inkml+xml',
'inkml' => 'application/inkml+xml',
'install' => 'application/x-install-instructions',
'iota' => 'application/vnd.astraea-software.iota',
'ipfix' => 'application/ipfix',
'ipk' => 'application/vnd.shana.informed.package',
'irm' => 'application/vnd.ibm.rights-management',
'irp' => 'application/vnd.irepository.package+xml',
'iso' => 'application/x-iso9660-image',
'itp' => 'application/vnd.shana.informed.formtemplate',
'ivp' => 'application/vnd.immervision-ivp',
'ivu' => 'application/vnd.immervision-ivu',
'jad' => 'text/vnd.sun.j2me.app-descriptor',
'jam' => 'application/vnd.jam',
'jar' => 'application/java-archive',
'java' => 'text/x-java-source',
'jisp' => 'application/vnd.jisp',
'jlt' => 'application/vnd.hp-jlyt',
'jnlp' => 'application/x-java-jnlp-file',
'joda' => 'application/vnd.joost.joda-archive',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'jpgm' => 'video/jpm',
'jpgv' => 'video/jpeg',
'jpm' => 'video/jpm',
'js' => 'application/javascript',
'json' => 'application/json',
'jsonml' => 'application/jsonml+json',
'kar' => 'audio/midi',
'karbon' => 'application/vnd.kde.karbon',
'kfo' => 'application/vnd.kde.kformula',
'kia' => 'application/vnd.kidspiration',
'kml' => 'application/vnd.google-earth.kml+xml',
'kmz' => 'application/vnd.google-earth.kmz',
'kne' => 'application/vnd.kinar',
'knp' => 'application/vnd.kinar',
'kon' => 'application/vnd.kde.kontour',
'kpr' => 'application/vnd.kde.kpresenter',
'kpt' => 'application/vnd.kde.kpresenter',
'kpxx' => 'application/vnd.ds-keypoint',
'ksp' => 'application/vnd.kde.kspread',
'ktr' => 'application/vnd.kahootz',
'ktx' => 'image/ktx',
'ktz' => 'application/vnd.kahootz',
'kwd' => 'application/vnd.kde.kword',
'kwt' => 'application/vnd.kde.kword',
'lasxml' => 'application/vnd.las.las+xml',
'latex' => 'application/x-latex',
'lbd' => 'application/vnd.llamagraphics.life-balance.desktop',
'lbe' => 'application/vnd.llamagraphics.life-balance.exchange+xml',
'les' => 'application/vnd.hhe.lesson-player',
'lha' => 'application/x-lzh-compressed',
'link66' => 'application/vnd.route66.link66+xml',
'list' => 'text/plain',
'list3820' => 'application/vnd.ibm.modcap',
'listafp' => 'application/vnd.ibm.modcap',
'lnk' => 'application/x-ms-shortcut',
'log' => 'text/plain',
'lostxml' => 'application/lost+xml',
'lrf' => 'application/octet-stream',
'lrm' => 'application/vnd.ms-lrm',
'ltf' => 'application/vnd.frogans.ltf',
'lvp' => 'audio/vnd.lucent.voice',
'lwp' => 'application/vnd.lotus-wordpro',
'lzh' => 'application/x-lzh-compressed',
'm13' => 'application/x-msmediaview',
'm14' => 'application/x-msmediaview',
'm1v' => 'video/mpeg',
'm21' => 'application/mp21',
'm2a' => 'audio/mpeg',
'm2v' => 'video/mpeg',
'm3a' => 'audio/mpeg',
'm3u' => 'audio/x-mpegurl',
'm3u8' => 'application/vnd.apple.mpegurl',
'm4u' => 'video/vnd.mpegurl',
'm4v' => 'video/x-m4v',
'ma' => 'application/mathematica',
'mads' => 'application/mads+xml',
'mag' => 'application/vnd.ecowin.chart',
'maker' => 'application/vnd.framemaker',
'man' => 'text/troff',
'mar' => 'application/octet-stream',
'mathml' => 'application/mathml+xml',
'mb' => 'application/mathematica',
'mbk' => 'application/vnd.mobius.mbk',
'mbox' => 'application/mbox',
'mc1' => 'application/vnd.medcalcdata',
'mcd' => 'application/vnd.mcd',
'mcurl' => 'text/vnd.curl.mcurl',
'mdb' => 'application/x-msaccess',
'mdi' => 'image/vnd.ms-modi',
'me' => 'text/troff',
'mesh' => 'model/mesh',
'meta4' => 'application/metalink4+xml',
'metalink' => 'application/metalink+xml',
'mets' => 'application/mets+xml',
'mfm' => 'application/vnd.mfmp',
'mft' => 'application/rpki-manifest',
'mgp' => 'application/vnd.osgeo.mapguide.package',
'mgz' => 'application/vnd.proteus.magazine',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mie' => 'application/x-mie',
'mif' => 'application/vnd.mif',
'mime' => 'message/rfc822',
'mj2' => 'video/mj2',
'mjp2' => 'video/mj2',
'mk3d' => 'video/x-matroska',
'mka' => 'audio/x-matroska',
'mks' => 'video/x-matroska',
'mkv' => 'video/x-matroska',
'mlp' => 'application/vnd.dolby.mlp',
'mmd' => 'application/vnd.chipnuts.karaoke-mmd',
'mmf' => 'application/vnd.smaf',
'mmr' => 'image/vnd.fujixerox.edmics-mmr',
'mng' => 'video/x-mng',
'mny' => 'application/x-msmoney',
'mobi' => 'application/x-mobipocket-ebook',
'mods' => 'application/mods+xml',
'mov' => 'video/quicktime',
'movie' => 'video/x-sgi-movie',
'mp2' => 'audio/mpeg',
'mp21' => 'application/mp21',
'mp2a' => 'audio/mpeg',
'mp3' => 'audio/mpeg',
'mp4' => 'video/mp4',
'mp4a' => 'audio/mp4',
'mp4s' => 'application/mp4',
'mp4v' => 'video/mp4',
'mpc' => 'application/vnd.mophun.certificate',
'mpe' => 'video/mpeg',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpg4' => 'video/mp4',
'mpga' => 'audio/mpeg',
'mpkg' => 'application/vnd.apple.installer+xml',
'mpm' => 'application/vnd.blueice.multipass',
'mpn' => 'application/vnd.mophun.application',
'mpp' => 'application/vnd.ms-project',
'mpt' => 'application/vnd.ms-project',
'mpy' => 'application/vnd.ibm.minipay',
'mqy' => 'application/vnd.mobius.mqy',
'mrc' => 'application/marc',
'mrcx' => 'application/marcxml+xml',
'ms' => 'text/troff',
'mscml' => 'application/mediaservercontrol+xml',
'mseed' => 'application/vnd.fdsn.mseed',
'mseq' => 'application/vnd.mseq',
'msf' => 'application/vnd.epson.msf',
'msh' => 'model/mesh',
'msi' => 'application/x-msdownload',
'msl' => 'application/vnd.mobius.msl',
'msty' => 'application/vnd.muvee.style',
'mts' => 'model/vnd.mts',
'mus' => 'application/vnd.musician',
'musicxml' => 'application/vnd.recordare.musicxml+xml',
'mvb' => 'application/x-msmediaview',
'mwf' => 'application/vnd.mfer',
'mxf' => 'application/mxf',
'mxl' => 'application/vnd.recordare.musicxml',
'mxml' => 'application/xv+xml',
'mxs' => 'application/vnd.triscape.mxs',
'mxu' => 'video/vnd.mpegurl',
'n-gage' => 'application/vnd.nokia.n-gage.symbian.install',
'n3' => 'text/n3',
'nb' => 'application/mathematica',
'nbp' => 'application/vnd.wolfram.player',
'nc' => 'application/x-netcdf',
'ncx' => 'application/x-dtbncx+xml',
'nfo' => 'text/x-nfo',
'ngdat' => 'application/vnd.nokia.n-gage.data',
'nitf' => 'application/vnd.nitf',
'nlu' => 'application/vnd.neurolanguage.nlu',
'nml' => 'application/vnd.enliven',
'nnd' => 'application/vnd.noblenet-directory',
'nns' => 'application/vnd.noblenet-sealer',
'nnw' => 'application/vnd.noblenet-web',
'npx' => 'image/vnd.net-fpx',
'nsc' => 'application/x-conference',
'nsf' => 'application/vnd.lotus-notes',
'ntf' => 'application/vnd.nitf',
'nzb' => 'application/x-nzb',
'oa2' => 'application/vnd.fujitsu.oasys2',
'oa3' => 'application/vnd.fujitsu.oasys3',
'oas' => 'application/vnd.fujitsu.oasys',
'obd' => 'application/x-msbinder',
'obj' => 'application/x-tgif',
'oda' => 'application/oda',
'odb' => 'application/vnd.oasis.opendocument.database',
'odc' => 'application/vnd.oasis.opendocument.chart',
'odf' => 'application/vnd.oasis.opendocument.formula',
'odft' => 'application/vnd.oasis.opendocument.formula-template',
'odg' => 'application/vnd.oasis.opendocument.graphics',
'odi' => 'application/vnd.oasis.opendocument.image',
'odm' => 'application/vnd.oasis.opendocument.text-master',
'odp' => 'application/vnd.oasis.opendocument.presentation',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
'odt' => 'application/vnd.oasis.opendocument.text',
'oga' => 'audio/ogg',
'ogg' => 'audio/ogg',
'ogv' => 'video/ogg',
'ogx' => 'application/ogg',
'omdoc' => 'application/omdoc+xml',
'onepkg' => 'application/onenote',
'onetmp' => 'application/onenote',
'onetoc' => 'application/onenote',
'onetoc2' => 'application/onenote',
'opf' => 'application/oebps-package+xml',
'opml' => 'text/x-opml',
'oprc' => 'application/vnd.palm',
'org' => 'application/vnd.lotus-organizer',
'osf' => 'application/vnd.yamaha.openscoreformat',
'osfpvg' => 'application/vnd.yamaha.openscoreformat.osfpvg+xml',
'otc' => 'application/vnd.oasis.opendocument.chart-template',
'otf' => 'application/x-font-otf',
'otg' => 'application/vnd.oasis.opendocument.graphics-template',
'oth' => 'application/vnd.oasis.opendocument.text-web',
'oti' => 'application/vnd.oasis.opendocument.image-template',
'otp' => 'application/vnd.oasis.opendocument.presentation-template',
'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template',
'ott' => 'application/vnd.oasis.opendocument.text-template',
'oxps' => 'application/oxps',
'oxt' => 'application/vnd.openofficeorg.extension',
'p' => 'text/x-pascal',
'p10' => 'application/pkcs10',
'p12' => 'application/x-pkcs12',
'p7b' => 'application/x-pkcs7-certificates',
'p7c' => 'application/pkcs7-mime',
'p7m' => 'application/pkcs7-mime',
'p7r' => 'application/x-pkcs7-certreqresp',
'p7s' => 'application/pkcs7-signature',
'p8' => 'application/pkcs8',
'pas' => 'text/x-pascal',
'paw' => 'application/vnd.pawaafile',
'pbd' => 'application/vnd.powerbuilder6',
'pbm' => 'image/x-portable-bitmap',
'pcap' => 'application/vnd.tcpdump.pcap',
'pcf' => 'application/x-font-pcf',
'pcl' => 'application/vnd.hp-pcl',
'pclxl' => 'application/vnd.hp-pclxl',
'pct' => 'image/x-pict',
'pcurl' => 'application/vnd.curl.pcurl',
'pcx' => 'image/x-pcx',
'pdb' => 'application/vnd.palm',
'pdf' => 'application/pdf',
'pfa' => 'application/x-font-type1',
'pfb' => 'application/x-font-type1',
'pfm' => 'application/x-font-type1',
'pfr' => 'application/font-tdpfr',
'pfx' => 'application/x-pkcs12',
'pgm' => 'image/x-portable-graymap',
'pgn' => 'application/x-chess-pgn',
'pgp' => 'application/pgp-encrypted',
'pic' => 'image/x-pict',
'pkg' => 'application/octet-stream',
'pki' => 'application/pkixcmp',
'pkipath' => 'application/pkix-pkipath',
'plb' => 'application/vnd.3gpp.pic-bw-large',
'plc' => 'application/vnd.mobius.plc',
'plf' => 'application/vnd.pocketlearn',
'pls' => 'application/pls+xml',
'pml' => 'application/vnd.ctc-posml',
'png' => 'image/png',
'pnm' => 'image/x-portable-anymap',
'portpkg' => 'application/vnd.macports.portpkg',
'pot' => 'application/vnd.ms-powerpoint',
'potm' => 'application/vnd.ms-powerpoint.template.macroenabled.12',
'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
'ppam' => 'application/vnd.ms-powerpoint.addin.macroenabled.12',
'ppd' => 'application/vnd.cups-ppd',
'ppm' => 'image/x-portable-pixmap',
'pps' => 'application/vnd.ms-powerpoint',
'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroenabled.12',
'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
'ppt' => 'application/vnd.ms-powerpoint',
'pptm' => 'application/vnd.ms-powerpoint.presentation.macroenabled.12',
'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'pqa' => 'application/vnd.palm',
'prc' => 'application/x-mobipocket-ebook',
'pre' => 'application/vnd.lotus-freelance',
'prf' => 'application/pics-rules',
'ps' => 'application/postscript',
'psb' => 'application/vnd.3gpp.pic-bw-small',
'psd' => 'image/vnd.adobe.photoshop',
'psf' => 'application/x-font-linux-psf',
'pskcxml' => 'application/pskc+xml',
'ptid' => 'application/vnd.pvi.ptid1',
'pub' => 'application/x-mspublisher',
'pvb' => 'application/vnd.3gpp.pic-bw-var',
'pwn' => 'application/vnd.3m.post-it-notes',
'pya' => 'audio/vnd.ms-playready.media.pya',
'pyv' => 'video/vnd.ms-playready.media.pyv',
'qam' => 'application/vnd.epson.quickanime',
'qbo' => 'application/vnd.intu.qbo',
'qfx' => 'application/vnd.intu.qfx',
'qps' => 'application/vnd.publishare-delta-tree',
'qt' => 'video/quicktime',
'qwd' => 'application/vnd.quark.quarkxpress',
'qwt' => 'application/vnd.quark.quarkxpress',
'qxb' => 'application/vnd.quark.quarkxpress',
'qxd' => 'application/vnd.quark.quarkxpress',
'qxl' => 'application/vnd.quark.quarkxpress',
'qxt' => 'application/vnd.quark.quarkxpress',
'ra' => 'audio/x-pn-realaudio',
'ram' => 'audio/x-pn-realaudio',
'rar' => 'application/x-rar-compressed',
'ras' => 'image/x-cmu-raster',
'rcprofile' => 'application/vnd.ipunplugged.rcprofile',
'rdf' => 'application/rdf+xml',
'rdz' => 'application/vnd.data-vision.rdz',
'rep' => 'application/vnd.businessobjects',
'res' => 'application/x-dtbresource+xml',
'rgb' => 'image/x-rgb',
'rif' => 'application/reginfo+xml',
'rip' => 'audio/vnd.rip',
'ris' => 'application/x-research-info-systems',
'rl' => 'application/resource-lists+xml',
'rlc' => 'image/vnd.fujixerox.edmics-rlc',
'rld' => 'application/resource-lists-diff+xml',
'rm' => 'application/vnd.rn-realmedia',
'rmi' => 'audio/midi',
'rmp' => 'audio/x-pn-realaudio-plugin',
'rms' => 'application/vnd.jcp.javame.midlet-rms',
'rmvb' => 'application/vnd.rn-realmedia-vbr',
'rnc' => 'application/relax-ng-compact-syntax',
'roa' => 'application/rpki-roa',
'roff' => 'text/troff',
'rp9' => 'application/vnd.cloanto.rp9',
'rpss' => 'application/vnd.nokia.radio-presets',
'rpst' => 'application/vnd.nokia.radio-preset',
'rq' => 'application/sparql-query',
'rs' => 'application/rls-services+xml',
'rsd' => 'application/rsd+xml',
'rss' => 'application/rss+xml',
'rtf' => 'application/rtf',
'rtx' => 'text/richtext',
's' => 'text/x-asm',
's3m' => 'audio/s3m',
'saf' => 'application/vnd.yamaha.smaf-audio',
'sbml' => 'application/sbml+xml',
'sc' => 'application/vnd.ibm.secure-container',
'scd' => 'application/x-msschedule',
'scm' => 'application/vnd.lotus-screencam',
'scq' => 'application/scvp-cv-request',
'scs' => 'application/scvp-cv-response',
'scurl' => 'text/vnd.curl.scurl',
'sda' => 'application/vnd.stardivision.draw',
'sdc' => 'application/vnd.stardivision.calc',
'sdd' => 'application/vnd.stardivision.impress',
'sdkd' => 'application/vnd.solent.sdkm+xml',
'sdkm' => 'application/vnd.solent.sdkm+xml',
'sdp' => 'application/sdp',
'sdw' => 'application/vnd.stardivision.writer',
'see' => 'application/vnd.seemail',
'seed' => 'application/vnd.fdsn.seed',
'sema' => 'application/vnd.sema',
'semd' => 'application/vnd.semd',
'semf' => 'application/vnd.semf',
'ser' => 'application/java-serialized-object',
'setpay' => 'application/set-payment-initiation',
'setreg' => 'application/set-registration-initiation',
'sfd-hdstx' => 'application/vnd.hydrostatix.sof-data',
'sfs' => 'application/vnd.spotfire.sfs',
'sfv' => 'text/x-sfv',
'sgi' => 'image/sgi',
'sgl' => 'application/vnd.stardivision.writer-global',
'sgm' => 'text/sgml',
'sgml' => 'text/sgml',
'sh' => 'application/x-sh',
'shar' => 'application/x-shar',
'shf' => 'application/shf+xml',
'sid' => 'image/x-mrsid-image',
'sig' => 'application/pgp-signature',
'sil' => 'audio/silk',
'silo' => 'model/mesh',
'sis' => 'application/vnd.symbian.install',
'sisx' => 'application/vnd.symbian.install',
'sit' => 'application/x-stuffit',
'sitx' => 'application/x-stuffitx',
'skd' => 'application/vnd.koan',
'skm' => 'application/vnd.koan',
'skp' => 'application/vnd.koan',
'skt' => 'application/vnd.koan',
'sldm' => 'application/vnd.ms-powerpoint.slide.macroenabled.12',
'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
'slt' => 'application/vnd.epson.salt',
'sm' => 'application/vnd.stepmania.stepchart',
'smf' => 'application/vnd.stardivision.math',
'smi' => 'application/smil+xml',
'smil' => 'application/smil+xml',
'smv' => 'video/x-smv',
'smzip' => 'application/vnd.stepmania.package',
'snd' => 'audio/basic',
'snf' => 'application/x-font-snf',
'so' => 'application/octet-stream',
'spc' => 'application/x-pkcs7-certificates',
'spf' => 'application/vnd.yamaha.smaf-phrase',
'spl' => 'application/x-futuresplash',
'spot' => 'text/vnd.in3d.spot',
'spp' => 'application/scvp-vp-response',
'spq' => 'application/scvp-vp-request',
'spx' => 'audio/ogg',
'sql' => 'application/x-sql',
'src' => 'application/x-wais-source',
'srt' => 'application/x-subrip',
'sru' => 'application/sru+xml',
'srx' => 'application/sparql-results+xml',
'ssdl' => 'application/ssdl+xml',
'sse' => 'application/vnd.kodak-descriptor',
'ssf' => 'application/vnd.epson.ssf',
'ssml' => 'application/ssml+xml',
'st' => 'application/vnd.sailingtracker.track',
'stc' => 'application/vnd.sun.xml.calc.template',
'std' => 'application/vnd.sun.xml.draw.template',
'stf' => 'application/vnd.wt.stf',
'sti' => 'application/vnd.sun.xml.impress.template',
'stk' => 'application/hyperstudio',
'stl' => 'application/vnd.ms-pki.stl',
'str' => 'application/vnd.pg.format',
'stw' => 'application/vnd.sun.xml.writer.template',
'sub' => 'image/vnd.dvb.subtitle',
// 'sub' => 'text/vnd.dvb.subtitle',
'sus' => 'application/vnd.sus-calendar',
'susp' => 'application/vnd.sus-calendar',
'sv4cpio' => 'application/x-sv4cpio',
'sv4crc' => 'application/x-sv4crc',
'svc' => 'application/vnd.dvb.service',
'svd' => 'application/vnd.svd',
'svg' => 'image/svg+xml',
'svgz' => 'image/svg+xml',
'swa' => 'application/x-director',
'swf' => 'application/x-shockwave-flash',
'swi' => 'application/vnd.aristanetworks.swi',
'sxc' => 'application/vnd.sun.xml.calc',
'sxd' => 'application/vnd.sun.xml.draw',
'sxg' => 'application/vnd.sun.xml.writer.global',
'sxi' => 'application/vnd.sun.xml.impress',
'sxm' => 'application/vnd.sun.xml.math',
'sxw' => 'application/vnd.sun.xml.writer',
't' => 'text/troff',
't3' => 'application/x-t3vm-image',
'taglet' => 'application/vnd.mynfc',
'tao' => 'application/vnd.tao.intent-module-archive',
'tar' => 'application/x-tar',
'tcap' => 'application/vnd.3gpp2.tcap',
'tcl' => 'application/x-tcl',
'teacher' => 'application/vnd.smart.teacher',
'tei' => 'application/tei+xml',
'teicorpus' => 'application/tei+xml',
'tex' => 'application/x-tex',
'texi' => 'application/x-texinfo',
'texinfo' => 'application/x-texinfo',
'text' => 'text/plain',
'tfi' => 'application/thraud+xml',
'tfm' => 'application/x-tex-tfm',
'tga' => 'image/x-tga',
'thmx' => 'application/vnd.ms-officetheme',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'tmo' => 'application/vnd.tmobile-livetv',
'torrent' => 'application/x-bittorrent',
'tpl' => 'application/vnd.groove-tool-template',
'tpt' => 'application/vnd.trid.tpt',
'tr' => 'text/troff',
'tra' => 'application/vnd.trueapp',
'trm' => 'application/x-msterminal',
'tsd' => 'application/timestamped-data',
'tsv' => 'text/tab-separated-values',
'ttc' => 'application/x-font-ttf',
'ttf' => 'application/x-font-ttf',
'ttl' => 'text/turtle',
'twd' => 'application/vnd.simtech-mindmapper',
'twds' => 'application/vnd.simtech-mindmapper',
'txd' => 'application/vnd.genomatix.tuxedo',
'txf' => 'application/vnd.mobius.txf',
'txt' => 'text/plain',
'u32' => 'application/x-authorware-bin',
'udeb' => 'application/x-debian-package',
'ufd' => 'application/vnd.ufdl',
'ufdl' => 'application/vnd.ufdl',
'ulx' => 'application/x-glulx',
'umj' => 'application/vnd.umajin',
'unityweb' => 'application/vnd.unity',
'uoml' => 'application/vnd.uoml+xml',
'uri' => 'text/uri-list',
'uris' => 'text/uri-list',
'urls' => 'text/uri-list',
'ustar' => 'application/x-ustar',
'utz' => 'application/vnd.uiq.theme',
'uu' => 'text/x-uuencode',
'uva' => 'audio/vnd.dece.audio',
'uvd' => 'application/vnd.dece.data',
'uvf' => 'application/vnd.dece.data',
'uvg' => 'image/vnd.dece.graphic',
'uvh' => 'video/vnd.dece.hd',
'uvi' => 'image/vnd.dece.graphic',
'uvm' => 'video/vnd.dece.mobile',
'uvp' => 'video/vnd.dece.pd',
'uvs' => 'video/vnd.dece.sd',
'uvt' => 'application/vnd.dece.ttml+xml',
'uvu' => 'video/vnd.uvvu.mp4',
'uvv' => 'video/vnd.dece.video',
'uvva' => 'audio/vnd.dece.audio',
'uvvd' => 'application/vnd.dece.data',
'uvvf' => 'application/vnd.dece.data',
'uvvg' => 'image/vnd.dece.graphic',
'uvvh' => 'video/vnd.dece.hd',
'uvvi' => 'image/vnd.dece.graphic',
'uvvm' => 'video/vnd.dece.mobile',
'uvvp' => 'video/vnd.dece.pd',
'uvvs' => 'video/vnd.dece.sd',
'uvvt' => 'application/vnd.dece.ttml+xml',
'uvvu' => 'video/vnd.uvvu.mp4',
'uvvv' => 'video/vnd.dece.video',
'uvvx' => 'application/vnd.dece.unspecified',
'uvvz' => 'application/vnd.dece.zip',
'uvx' => 'application/vnd.dece.unspecified',
'uvz' => 'application/vnd.dece.zip',
'vcard' => 'text/vcard',
'vcd' => 'application/x-cdlink',
'vcf' => 'text/x-vcard',
'vcg' => 'application/vnd.groove-vcard',
'vcs' => 'text/x-vcalendar',
'vcx' => 'application/vnd.vcx',
'vis' => 'application/vnd.visionary',
'viv' => 'video/vnd.vivo',
'vob' => 'video/x-ms-vob',
'vor' => 'application/vnd.stardivision.writer',
'vox' => 'application/x-authorware-bin',
'vrml' => 'model/vrml',
'vsd' => 'application/vnd.visio',
'vsf' => 'application/vnd.vsf',
'vss' => 'application/vnd.visio',
'vst' => 'application/vnd.visio',
'vsw' => 'application/vnd.visio',
'vtu' => 'model/vnd.vtu',
'vxml' => 'application/voicexml+xml',
'w3d' => 'application/x-director',
'wad' => 'application/x-doom',
'wav' => 'audio/x-wav',
'wax' => 'audio/x-ms-wax',
'wbmp' => 'image/vnd.wap.wbmp',
'wbs' => 'application/vnd.criticaltools.wbs+xml',
'wbxml' => 'application/vnd.wap.wbxml',
'wcm' => 'application/vnd.ms-works',
'wdb' => 'application/vnd.ms-works',
'wdp' => 'image/vnd.ms-photo',
'weba' => 'audio/webm',
'webm' => 'video/webm',
'webp' => 'image/webp',
'wg' => 'application/vnd.pmi.widget',
'wgt' => 'application/widget',
'wks' => 'application/vnd.ms-works',
'wm' => 'video/x-ms-wm',
'wma' => 'audio/x-ms-wma',
'wmd' => 'application/x-ms-wmd',
'wmf' => 'application/x-msmetafile',
'wml' => 'text/vnd.wap.wml',
'wmlc' => 'application/vnd.wap.wmlc',
'wmls' => 'text/vnd.wap.wmlscript',
'wmlsc' => 'application/vnd.wap.wmlscriptc',
'wmv' => 'video/x-ms-wmv',
'wmx' => 'video/x-ms-wmx',
'wmz' => 'application/x-ms-wmz',
// 'wmz' => 'application/x-msmetafile',
'woff' => 'application/x-font-woff',
'wpd' => 'application/vnd.wordperfect',
'wpl' => 'application/vnd.ms-wpl',
'wps' => 'application/vnd.ms-works',
'wqd' => 'application/vnd.wqd',
'wri' => 'application/x-mswrite',
'wrl' => 'model/vrml',
'wsdl' => 'application/wsdl+xml',
'wspolicy' => 'application/wspolicy+xml',
'wtb' => 'application/vnd.webturbo',
'wvx' => 'video/x-ms-wvx',
'x32' => 'application/x-authorware-bin',
'x3d' => 'model/x3d+xml',
'x3db' => 'model/x3d+binary',
'x3dbz' => 'model/x3d+binary',
'x3dv' => 'model/x3d+vrml',
'x3dvz' => 'model/x3d+vrml',
'x3dz' => 'model/x3d+xml',
'xaml' => 'application/xaml+xml',
'xap' => 'application/x-silverlight-app',
'xar' => 'application/vnd.xara',
'xbap' => 'application/x-ms-xbap',
'xbd' => 'application/vnd.fujixerox.docuworks.binder',
'xbm' => 'image/x-xbitmap',
'xdf' => 'application/xcap-diff+xml',
'xdm' => 'application/vnd.syncml.dm+xml',
'xdp' => 'application/vnd.adobe.xdp+xml',
'xdssc' => 'application/dssc+xml',
'xdw' => 'application/vnd.fujixerox.docuworks',
'xenc' => 'application/xenc+xml',
'xer' => 'application/patch-ops-error+xml',
'xfdf' => 'application/vnd.adobe.xfdf',
'xfdl' => 'application/vnd.xfdl',
'xht' => 'application/xhtml+xml',
'xhtml' => 'application/xhtml+xml',
'xhvml' => 'application/xv+xml',
'xif' => 'image/vnd.xiff',
'xla' => 'application/vnd.ms-excel',
'xlam' => 'application/vnd.ms-excel.addin.macroenabled.12',
'xlc' => 'application/vnd.ms-excel',
'xlf' => 'application/x-xliff+xml',
'xlm' => 'application/vnd.ms-excel',
'xls' => 'application/vnd.ms-excel',
'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroenabled.12',
'xlsm' => 'application/vnd.ms-excel.sheet.macroenabled.12',
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'xlt' => 'application/vnd.ms-excel',
'xltm' => 'application/vnd.ms-excel.template.macroenabled.12',
'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
'xlw' => 'application/vnd.ms-excel',
'xm' => 'audio/xm',
'xml' => 'application/xml',
'xo' => 'application/vnd.olpc-sugar',
'xop' => 'application/xop+xml',
'xpi' => 'application/x-xpinstall',
'xpl' => 'application/xproc+xml',
'xpm' => 'image/x-xpixmap',
'xpr' => 'application/vnd.is-xpr',
'xps' => 'application/vnd.ms-xpsdocument',
'xpw' => 'application/vnd.intercon.formnet',
'xpx' => 'application/vnd.intercon.formnet',
'xsl' => 'application/xml',
'xslt' => 'application/xslt+xml',
'xsm' => 'application/vnd.syncml+xml',
'xspf' => 'application/xspf+xml',
'xul' => 'application/vnd.mozilla.xul+xml',
'xvm' => 'application/xv+xml',
'xvml' => 'application/xv+xml',
'xwd' => 'image/x-xwindowdump',
'xyz' => 'chemical/x-xyz',
'xz' => 'application/x-xz',
'yang' => 'application/yang',
'yin' => 'application/yin+xml',
'z1' => 'application/x-zmachine',
'z2' => 'application/x-zmachine',
'z3' => 'application/x-zmachine',
'z4' => 'application/x-zmachine',
'z5' => 'application/x-zmachine',
'z6' => 'application/x-zmachine',
'z7' => 'application/x-zmachine',
'z8' => 'application/x-zmachine',
'zaz' => 'application/vnd.zzazz.deck+xml',
'zip' => 'application/zip',
'zir' => 'application/vnd.zul',
'zirz' => 'application/vnd.zul',
'zmm' => 'application/vnd.handheld-entertainment+xml'
);
$defaultMime = 'application/octet-stream';
if (!empty($default)) {
$defaultMime = $default;
}
$mime = '';
if (class_exists('finfo')) {
$file_info = new \finfo(FILEINFO_MIME_TYPE);
if (!empty($content)) {
$mime = $file_info->buffer($content);
} elseif (!empty($local_file)) {
$mime = $file_info->file($local_file);
}
}
if (empty($mime) ||
(0 === strcasecmp($mime, $defaultMime)) ||
(0 === strcasecmp('text/plain', $mime)) ||
(0 === strcasecmp('text/x-asm', $mime)) ||
(0 === strcasecmp('text/x-c', $mime)) ||
(0 === strcasecmp('text/x-c++', $mime)) ||
(0 === strcasecmp('text/x-java', $mime))
) {
// need further guidance on these, as they are sometimes incorrect
if (0 === strcasecmp('dfpkg', $ext)) {
$mime = 'application/zip';
} else {
$mime = array_get($mimeTypes, $ext);
}
}
if (empty($mime)) {
return $defaultMime;
}
return $mime;
} | @param string $ext
@param string $content
@param string $local_file
@param string $default
@return string | entailment |
public static function deleteTree($dir, $force = false, $delete_self = true)
{
if (is_dir($dir)) {
$files = array_diff(scandir($dir), array('.', '..'));
if (!empty($files) && !$force) {
throw new \Exception("Directory not empty, can not delete without force option.");
}
foreach ($files as $file) {
$delPath = $dir . DIRECTORY_SEPARATOR . $file;
if (is_dir($delPath)) {
static::deleteTree($delPath, $force, true);
} elseif (is_file($delPath)) {
unlink($delPath);
} else {
// bad path?
}
}
if ($delete_self) {
rmdir($dir);
}
}
} | @param $dir
@param bool $force
@param bool $delete_self
@throws \Exception | entailment |
public static function copyTree($src, $dst, $clean = false, $skip = array('.', '..'))
{
if (file_exists($dst) && $clean) {
static::deleteTree($dst);
}
if (is_dir($src)) {
@mkdir($dst);
$files = array_diff(scandir($src), $skip);
foreach ($files as $file) {
$srcFile = static::fixFolderPath($src) . $file;
$dstFile = static::fixFolderPath($dst) . $file;
static::copyTree($srcFile, $dstFile, $clean, $skip);
}
} else if (file_exists($src)) {
copy($src, $dst);
}
} | @param string $src
@param string $dst
@param bool $clean
@param array $skip
@return void | entailment |
public static function addTreeToZip($zip, $root, $path = '', $skip = array('.', '..'))
{
$dirPath = rtrim($root, '/') . DIRECTORY_SEPARATOR;
if (!empty($path)) {
$dirPath .= $path . DIRECTORY_SEPARATOR;
}
if (is_dir($dirPath)) {
$files = array_diff(scandir($dirPath), $skip);
if (empty($files)) {
$newPath = str_replace(DIRECTORY_SEPARATOR, '/', $path);
if (!$zip->addEmptyDir($newPath)) {
throw new \Exception("Can not include folder '$newPath' in zip file.");
}
return;
}
foreach ($files as $file) {
$newPath = (empty($path) ? $file : $path . DIRECTORY_SEPARATOR . $file);
if (is_dir($dirPath . $file)) {
static::addTreeToZip($zip, $root, $newPath, $skip);
} else if (file_exists($dirPath . $file)) {
$newPath = str_replace(DIRECTORY_SEPARATOR, '/', $newPath);
if (!$zip->addFile($dirPath . $file, $newPath)) {
throw new \Exception("Can not include file '$newPath' in zip file.");
}
}
}
}
} | @param \ZipArchive $zip
@param string $root
@param string $path
@param array $skip
@throws \Exception | entailment |
public static function rearrangePostedFiles($arr)
{
$new = array();
foreach ($arr as $key => $all) {
if (is_array($all)) {
foreach ($all as $i => $val) {
$new[$i][$key] = $val;
}
} else {
$new[0][$key] = $all;
}
}
return $new;
} | @param $arr
@return array | entailment |
public static function updateEnvSetting(array $settings, $path = null)
{
if (empty($path)) {
$path = base_path('.env');
}
if (file_exists($path)) {
$subject = file_get_contents($path);
foreach ($settings as $key => $value) {
// Uncomment if any of keys are commented out by default.
$subject = str_replace(['#' . $key, '##$key'], $key, $subject);
}
// Update uncommented keys.
file_put_contents($path, $subject);
foreach ($settings as $key => $value) {
/**
* Using a new instance of dotenv to get the
* most update to .env file content for reading.
*/
$dotenv = new Dotenv(base_path());
$dotenv->load();
$search = $key . '=' . getenv($key);
$replace = $key . '=' . $value;
$subject = str_replace($search, $replace, $subject);
}
file_put_contents($path, $subject);
}
} | Updates .env file setting.
@param array $settings
@param null $path | entailment |
public function addColumn(ColumnSchema $schema)
{
$key = strtolower($schema->name);
$this->columns[$key] = $schema;
} | Sets the named column metadata.
@param ColumnSchema $schema | entailment |
public function getColumn($name, $use_alias = false)
{
if ($use_alias) {
foreach ($this->columns as $column) {
if (0 === strcasecmp($name, $column->getName($use_alias))) {
return $column;
}
}
} else {
$key = strtolower($name);
if (isset($this->columns[$key])) {
return $this->columns[$key];
}
}
return null;
} | Gets the named column metadata.
@param string $name column name
@param bool $use_alias
@return ColumnSchema metadata of the named column. Null if the named column does not exist. | entailment |
public function getColumnNames($use_alias = false)
{
$columns = [];
/** @var ColumnSchema $column */
foreach ($this->columns as $column) {
$columns[] = $column->getName($use_alias);
}
return $columns;
} | @param bool $use_alias
@return array list of column names | entailment |
public function getColumns($use_alias = false)
{
if ($use_alias) {
// re-index for alias usage, easier to find requested fields from client
$columns = [];
/** @var ColumnSchema $column */
foreach ($this->columns as $column) {
$columns[strtolower($column->getName(true))] = $column;
}
return $columns;
}
return $this->columns;
} | @param bool $use_alias
@return ColumnSchema[] | entailment |
public function getRelation($name, $use_alias = false)
{
if ($use_alias) {
foreach ($this->relations as $relation) {
if (0 === strcasecmp($name, $relation->getName($use_alias))) {
return $relation;
}
}
} else {
$key = strtolower($name);
if (isset($this->relations[$key])) {
return $this->relations[$key];
}
}
return null;
} | Gets the named relation metadata.
@param string $name relation name
@param bool $use_alias
@return RelationSchema metadata of the named relation. Null if the named relation does not exist. | entailment |
public function getRelationNames($use_alias = false)
{
$relations = [];
foreach ($this->relations as $relation) {
$relations[] = $relation->getName($use_alias);
}
return $relations;
} | @param bool $use_alias
@return array list of column names | entailment |
public function getRelations($use_alias = false)
{
if ($use_alias) {
// re-index for alias usage, easier to find requested fields from client
$relations = [];
/** @var RelationSchema $column */
foreach ($this->relations as $column) {
$relations[strtolower($column->getName(true))] = $column;
}
return $relations;
}
return $this->relations;
} | @param bool $use_alias
@return RelationSchema[] | entailment |
protected function isProtectedAttribute($key, $value)
{
return (in_array($key, $this->getProtectable()) && ($value === $this->protectionMask));
} | Check if the attribute coming from client is set to mask. If so, skip writing to database.
@param string $key Attribute name
@param mixed $value Value of the attribute $key
@return bool | entailment |
protected function protectAttribute($key, &$value)
{
if (!is_null($value) && $this->protectedView && in_array($key, $this->getProtectable())) {
$value = $this->protectionMask;
return true;
}
return false;
} | Check if the attribute is marked protected, if so return the mask, not the value.
@param string $key Attribute name
@param mixed $value Value of the attribute $key, updated to mask if protected
@return bool Whether or not the attribute is being protected | entailment |
protected function addProtectedAttributesToArray(array $attributes)
{
if ($this->protectedView) {
foreach ($this->getProtectable() as $key) {
if (isset($attributes[$key])) {
$attributes[$key] = $this->protectionMask;
}
}
}
return $attributes;
} | Replace all protected attributes in the given array with the mask
@param array $attributes
@return array | entailment |
public function handleRequest(ServiceRequestInterface $request, $resource = null)
{
Log::info('[REQUEST]', [
'API Version' => $request->getApiVersion(),
'Method' => $request->getMethod(),
'Service' => $this->name,
'Resource' => $resource,
'Requestor' => $request->getRequestorType(),
]);
Log::debug('[REQUEST]', [
'Parameters' => json_encode($request->getParameters(), JSON_UNESCAPED_SLASHES),
'API Key' => $request->getHeader('X_DREAMFACTORY_API_KEY'),
'JWT' => $request->getHeader('X_DREAMFACTORY_SESSION_TOKEN')
]);
if (!$this->isActive) {
throw new ForbiddenException("Service {$this->name} is deactivated.");
}
$response = parent::handleRequest($request, $resource);
if ($response instanceof RedirectResponse) {
Log::info('[RESPONSE] Redirect', ['Status Code' => $response->getStatusCode()]);
Log::debug('[RESPONSE]', ['Target URL' => $response->getTargetUrl()]);
} elseif ($response instanceof StreamedResponse) {
Log::info('[RESPONSE] Stream', ['Status Code' => $response->getStatusCode()]);
} else {
Log::info('[RESPONSE]', ['Status Code' => $response->getStatusCode(), 'Content-Type' => $response->getContentType()]);
}
return $response;
} | {@inheritdoc} | entailment |
public function checkPermission($operation, $resource = null)
{
$requestType = ($this->request) ? $this->request->getRequestorType() : ServiceRequestorTypes::API;
Session::checkServicePermission($operation, $this->name, $resource, $requestType);
} | {@inheritdoc} | entailment |
public function getPermissions($resource = null)
{
$requestType = ($this->request) ? $this->request->getRequestorType() : ServiceRequestorTypes::API;
return Session::getServicePermissions($this->name, $resource, $requestType);
} | {@inheritdoc} | entailment |
protected function handleGET()
{
if ($this->request->getParameterAsBool(ApiOptions::AS_ACCESS_LIST)) {
return ResourcesWrapper::wrapResources($this->getAccessList());
}
return parent::handleGET();
} | {@inheritdoc} | entailment |
protected function parseSwaggerEvents(array $content, array $access = [])
{
$events = [];
$eventCount = 0;
foreach (array_get($content, 'paths', []) as $path => $api) {
$apiEvents = [];
$apiParameters = [];
$pathParameters = [];
$path = trim($path, '/');
$eventPath = $this->name;
if (!empty($path)) {
$eventPath .= '.' . str_replace('/', '.', $path);
}
$replacePos = strpos($path, '{');
foreach ($api as $ixOps => $operation) {
if ('parameters' === $ixOps) {
$pathParameters = $operation;
continue;
}
$method = strtolower($ixOps);
if (!array_search("$eventPath.$method", $apiEvents)) {
$apiEvents[] = "$eventPath.$method";
$eventCount++;
$parameters = array_get($operation, 'parameters', []);
if (!empty($pathParameters)) {
$parameters = array_merge($pathParameters, $parameters);
}
foreach ($parameters as $parameter) {
$type = array_get($parameter, 'in', '');
if ('path' === $type) {
$name = array_get($parameter, 'name', '');
$options = array_get($parameter, 'enum', array_get($parameter, 'options'));
if (empty($options) && !empty($access) && (false !== $replacePos)) {
$checkFirstOption = strstr(substr($path, $replacePos + 1), '}', true);
if ($name !== $checkFirstOption) {
continue;
}
$options = [];
// try to match any access path
foreach ($access as $accessPath) {
$accessPath = rtrim($accessPath, '/*');
if (!empty($accessPath) && (strlen($accessPath) > $replacePos)) {
if (0 === substr_compare($accessPath, $path, 0, $replacePos)) {
$option = substr($accessPath, $replacePos);
if (false !== strpos($option, '/')) {
$option = strstr($option, '/', true);
}
$options[] = $option;
}
}
}
}
if (!empty($options)) {
$apiParameters[$name] = array_values(array_unique($options));
}
}
}
}
unset($operation);
}
$events[$eventPath]['type'] = 'api';
$events[$eventPath]['endpoints'] = $apiEvents;
$events[$eventPath]['parameter'] = (empty($apiParameters)) ? null : $apiParameters;
unset($apiEvents, $apiParameters, $api);
}
\Log::debug(" * Discovered $eventCount event(s) for service {$this->name}.");
return $events;
} | @param array $content
@param array $access
@return array | entailment |
public function getAttributeValue($key)
{
$value = $this->getAttributeValueBase($key);
$this->protectAttribute($key, $value);
return $value;
} | {@inheritdoc} | entailment |
protected function getAttributeFromArray($key)
{
$value = $this->getAttributeFromArrayBase($key);
$this->decryptAttribute($key, $value);
return $value;
} | {@inheritdoc} | entailment |
public function setAttribute($key, $value)
{
// if protected, and trying to set the mask, throw it away
if ($this->isProtectedAttribute($key, $value)) {
return $this;
}
$return = $this->setAttributeBase($key, $value);
$value = $this->attributes[$key];
$this->encryptAttribute($key, $value);
$this->attributes[$key] = $value;
return $return;
} | {@inheritdoc} | entailment |
public function attributesToArray()
{
$attributes = $this->attributesToArrayBase();
$attributes = $this->addDecryptedAttributesToArray($attributes);
$attributes = $this->addProtectedAttributesToArray($attributes);
return $attributes;
} | {@inheritdoc} | entailment |
public static function validateAsArray($data, $str_delimiter = null, $check_single = false, $on_fail = null)
{
if (is_string($data) && ('' !== $data) && (is_string($str_delimiter) && !empty($str_delimiter))) {
$data = array_map('trim', explode($str_delimiter, trim($data, $str_delimiter)));
}
if (is_int($data)) {
$data = [$data]; // make an array of it
}
if (!is_array($data) || empty($data)) {
if (!is_string($on_fail) || empty($on_fail)) {
return false;
}
throw new BadRequestException($on_fail);
}
if ($check_single) {
if (!isset($data[0])) {
// single record possibly passed in without wrapper array
$data = [$data];
}
}
return $data;
} | @param array | string $data Array to check or comma-delimited string to convert
@param string | null $str_delimiter Delimiter to check for string to array mapping, no op if null
@param boolean $check_single Check if single (associative) needs to be made multiple (numeric)
@param string | null $on_fail Error string to deliver in thrown exception
@throws BadRequestException
@return array | boolean If requirements not met then throws exception if
$on_fail string given, or returns false. Otherwise returns valid array | entailment |
public function validator(array $data)
{
$validationRules = [
'name' => 'required|max:255',
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|max:255|unique:user',
'username' => 'min:6|unique:user,username|regex:/^\S*$/u|nullable'
];
$loginAttribute = strtolower(config('df.login_attribute', 'email'));
if ($loginAttribute === 'username') {
$validationRules['username'] = str_replace('|nullable', '|required', $validationRules['username']);
}
/** @var \DreamFactory\Core\User\Services\User $userService */
$userService = ServiceManager::getService('user');
if (empty($userService->openRegEmailServiceId)) {
$validationRules['password'] = 'required|confirmed|min:6';
}
return Validator::make($data, $validationRules);
} | Get a validator for an incoming registration request.
@param array $data
@return \Illuminate\Contracts\Validation\Validator | entailment |
public function create(array $data, $serviceId = null)
{
/** @var \DreamFactory\Core\User\Services\User $userService */
$userService = ServiceManager::getService('user');
if (!$userService->allowOpenRegistration) {
throw new ForbiddenException('Open Registration is not enabled.');
}
/** @type User $user */
$user = User::create($data);
if (!empty($userService->openRegEmailServiceId)) {
$this->sendConfirmation($user, $userService->openRegEmailServiceId, $userService->openRegEmailTemplateId);
} else if (!empty($data['password'])) {
$user->password = $data['password'];
$user->save();
}
if (!empty($userService->openRegRoleId)) {
User::applyDefaultUserAppRole($user, $userService->openRegRoleId);
}
if (!empty($serviceId)) {
User::applyAppRoleMapByService($user, $serviceId);
}
return $user;
} | Creates a non-admin user.
@param array $data
@param integer $serviceId
@return \DreamFactory\Core\Models\User
@throws \DreamFactory\Core\Exceptions\ForbiddenException
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException
@throws \Exception | entailment |
protected static function sendConfirmation($user, $emailServiceId, $emailTemplateId, $deleteOnError = true)
{
try {
if (empty($emailServiceId)) {
throw new InternalServerErrorException('No email service configured for user invite. See system configuration.');
}
if (empty($emailTemplateId)) {
throw new InternalServerErrorException("No default email template for user invite.");
}
/** @var EmailServiceInterface $emailService */
$emailService = ServiceManager::getServiceById($emailServiceId);
/** @var EmailTemplate $emailTemplate */
/** @noinspection PhpUndefinedMethodInspection */
$emailTemplate = EmailTemplate::find($emailTemplateId);
if (empty($emailTemplate)) {
throw new InternalServerErrorException("No data found in default email template for user invite.");
}
try {
$email = $user->email;
$user->confirm_code = static::generateConfirmationCode(\Config::get('df.confirm_code_length', 32));
$user->save();
$templateData = $emailTemplate->toArray();
$data = array_merge($templateData, [
'to' => $email,
'confirm_code' => $user->confirm_code,
'link' => url(\Config::get('df.confirm_register_url')) .
'?code=' . $user->confirm_code .
'&email=' . $email .
'&username=' . $user->username,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'name' => $user->name,
'email' => $user->email,
'phone' => $user->phone,
'content_header' => array_get($templateData, 'subject', 'Confirm your DreamFactory account.'),
'app_name' => \Config::get('app.name'),
'instance_name' => \Config::get('app.name'), // older templates
]);
} catch (\Exception $e) {
throw new InternalServerErrorException("Error creating user confirmation.\n{$e->getMessage()}",
$e->getCode());
}
$bodyText = $emailTemplate->body_text;
if (empty($bodyText)) {
//Strip all html tags.
$bodyText = strip_tags($emailTemplate->body_html);
//Change any multi spaces to a single space for clarity.
$bodyText = preg_replace('/ +/', ' ', $bodyText);
}
$emailService->sendEmail($data, $bodyText, $emailTemplate->body_html);
} catch (\Exception $e) {
if ($deleteOnError) {
$user->delete();
}
throw new InternalServerErrorException("Error processing user confirmation.\n{$e->getMessage()}",
$e->getCode());
}
} | @param $user User
@param $emailServiceId
@param $emailTemplateId
@param bool|true $deleteOnError
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException | entailment |
public static function generateConfirmationCode($length = 32)
{
$length = ($length < 5) ? 5 : (($length > 32) ? 32 : $length);
$range = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$code = '';
for ($i = 0; $i < $length; $i++) {
$code .= $range[rand(0, strlen($range) - 1)];
}
return $code;
} | Generates a user confirmation code. (min 5 char)
@param int $length
@return string | entailment |
public function getLink($rel)
{
$link = self::findByRel($this->links, $rel);
if (!$link) {
throw new RelNotFoundException($rel, array_keys($this->links));
}
if (is_array($link)) {
throw new LinkNotUniqueException();
}
return $link;
} | {@inheritDoc} | entailment |
public function getLinks($rel)
{
$links = self::findByRel($this->links, $rel);
if (!$links) {
throw new RelNotFoundException($rel, array_keys($this->links));
}
if (!is_array($links)) {
throw new LinkUniqueException();
}
return $links;
} | {@inheritDoc} | entailment |
public function getEmbeddedResource($rel)
{
$resource = self::findByRel($this->embeddedResources, $rel);
if (!$resource) {
throw new RelNotFoundException($rel, array_keys($this->embeddedResources));
}
if (is_array($resource)) {
throw new EmbeddedResourceNotUniqueException();
}
return $resource;
} | {@inheritDoc} | entailment |
public function getEmbeddedResources($rel)
{
$resources = self::findByRel($this->embeddedResources, $rel);
if (!$resources) {
throw new RelNotFoundException($rel, array_keys($this->embeddedResources));
}
if (!is_array($resources)) {
throw new EmbeddedResourceUniqueException();
}
return $resources;
} | {@inheritDoc} | entailment |
private static function findByRel(array $a, $rel)
{
$relName = mb_strtolower($rel, 'UTF-8');
foreach ($a as $name => $value) {
if (mb_strtolower($name, 'UTF-8') === $relName) {
return $value;
}
}
return null;
} | Looks for the given relation name in a case-insensitive
fashion and returns the corresponding value.
@return mixed The value in $a matching the relation name
or null if not found. | entailment |
public static function fromJson($json)
{
if (!$json) {
$json = [];
}
if (!is_array($json)) {
if (is_object($json)) {
$json = (array) $json;
} elseif (is_string($json)) {
$json = json_decode(trim($json) ? $json : '{}', true);
} else {
throw new \Exception("JSON must be a string, an array or an object ('" . gettype($json) . "' provided).");
}
}
return new Resource(
self::extractState($json),
self::extractByRel($json, '_links'),
self::extractByRel($json, '_embedded')
);
} | {@inheritDoc} | entailment |
public static function registerUser($user, array $payload = [])
{
$source = 'Product Install DreamFactory';
if (env('DF_MANAGED', false)) {
$serverName = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '';
if (false === strpos($serverName, '.enterprise.dreamfactory.com')) {
return true; // bail, not tracking
}
$source = 'Website Free Hosted';
}
$partner = env('DF_INSTALL', '');
if (empty($partner) && (false !== stripos(env('DB_DATABASE', ''), 'bitnami'))) {
$partner = 'Bitnami';
}
$payload = array_merge(
[
'email' => $user->email,
'name' => $user->name,
'firstname' => $user->first_name,
'lastname' => $user->last_name,
'phone' => $user->phone,
'lead_event' => $source,
'lead_source' => $source,
'partner' => $partner,
'product' => 'DreamFactory',
'version' => config('app.version', 'unknown'),
'host_os' => PHP_OS,
],
$payload
);
$payload = json_encode($payload);
$options = [CURLOPT_HTTPHEADER => ['Content-Type: application/json']];
if (false !== ($_response = Curl::post(static::ENDPOINT, $payload, $options))) {
return true;
}
return false;
} | @param User $user
@param array $payload
@return bool | entailment |
protected static function cleanResult(
$response,
/** @noinspection PhpUnusedParameterInspection */
$fields
) {
// for collections and models
if (is_object($response) && method_exists($response, 'toArray')) {
return $response->toArray();
}
return $response;
} | If fields is not '*' (all) then clean out any unwanted properties.
@param mixed $response
@param mixed $fields
@return array | entailment |
public static function bulkCreate(array $records, array $params = [])
{
if (empty($records)) {
throw new BadRequestException('There are no record sets in the request.');
}
$response = [];
$errors = false;
$rollback = array_get_bool($params, ApiOptions::ROLLBACK);
$continue = array_get_bool($params, ApiOptions::CONTINUES);
if ($rollback) {
// Start a transaction
DB::beginTransaction();
}
foreach ($records as $key => $record) {
try {
$response[$key] = static::createInternal($record, $params);
} catch (\Exception $ex) {
$errors = true;
$response[$key] = $ex;
// track the index of the error and copy error to results
if ($rollback || !$continue) {
break;
}
}
}
if ($errors) {
$msg = "Batch Error: Not all requested records could be created.";
if ($rollback) {
DB::rollBack();
$msg .= " All changes rolled back.";
}
throw new BatchException($response, $msg);
}
if ($rollback) {
DB::commit();
}
return $response;
} | @param $records
@param array $params
@return array|mixed
@throws BadRequestException
@throws \Exception | entailment |
public static function createById($id, $record, $params = [])
{
$m = new static;
$pk = $m->getPrimaryKey();
$record[$pk] = $id;
try {
$response = static::bulkCreate([$record], $params);
return current($response);
} catch (BatchException $ex) {
$response = $ex->pickResponse(0);
if ($response instanceof \Exception) {
throw $response;
}
return $response;
} catch (\Exception $ex) {
throw new InternalServerErrorException($ex->getMessage());
}
} | @param $id
@param $record
@param array $params
@return array|mixed
@throws \DreamFactory\Core\Exceptions\BadRequestException
@throws \Exception | entailment |
public function update(array $attributes = [], array $options = [])
{
$relations = [];
$transaction = false;
foreach ($attributes as $key => $value) {
if ($this->isRelationMapped($key)) {
$relations[$key] = $value;
unset($attributes[$key]);
}
}
if (count($relations) > 0) {
DB::beginTransaction();
$transaction = true;
}
try {
$userId = SessionUtility::getCurrentUserId();
if ($userId && static::isField('last_modified_by_id')) {
$this->last_modified_by_id = $userId;
}
$updated = parent::update($attributes);
if ($updated && $this->exists && count($relations) > 0) {
foreach ($relations as $name => $value) {
$relatedModel = $this->getReferencingModel($name);
if (RelationSchema::HAS_ONE === $this->getReferencingType($name)) {
$hasOne = $this->getHasOneByRelationName($name);
$this->saveHasOneData($relatedModel, $hasOne, $value, $name);
} elseif (RelationSchema::HAS_MANY === $this->getReferencingType($name)) {
$hasMany = $this->getHasManyByRelationName($name);
$this->saveHasManyData($relatedModel, $hasMany, $value, $name);
}
}
}
if ($transaction) {
DB::commit();
}
} catch (\Exception $e) {
if ($transaction) {
DB::rollBack();
}
throw $e;
}
return $updated;
} | Update the model in the database.
@param array $attributes
@param array $options
@return bool|int
@throws \Exception | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.