Import custom thumbnails from webtres 1.x.

@param ServerRequestInterface $request

@return ResponseInterface
354019
public function webtrees1ThumbnailsAction(ServerRequestInterface $request): ResponseInterface
    {
        $thumbnail = $request->getParsedBody()['thumbnail'];
        $action    = $request->getParsedBody()['action'];
        $xrefs     = $request->getParsedBody()['xref'];
        $geds      = $request->getParsedBody()['ged'];

        $media_objects = [];

        foreach ($xrefs as $key => $xref) {
            $tree            = Tree::findByName($geds[$key]);
            $media_objects[] = Media::getInstance($xref, $tree);
        }

        $thumbnail = WT_DATA_DIR . $thumbnail;

        switch ($action) {
            case 'delete':
                if (file_exists($thumbnail)) {
                    unlink($thumbnail);
                }
                break;

            case 'add':
                $image_size = getimagesize($thumbnail);
                [, $extension] = explode('/', $image_size['mime']);
                $move_to = dirname($thumbnail, 2) . '/' . sha1_file($thumbnail) . '.' . $extension;
                rename($thumbnail, $move_to);

                foreach ($media_objects as $media_object) {
                    $prefix = WT_DATA_DIR . $media_object->tree()->getPreference('MEDIA_DIRECTORY');
                    $gedcom = '1 FILE ' . substr($move_to, strlen($prefix)) . "\n2 FORM " . $extension;

                    if ($media_object->firstImageFile() === null) {
                        // The media object doesn't have an image.  Add this as a secondary file.
                        $media_object->createFact($gedcom, true);
                    } else {
                        // The media object already has an image.  Show this custom one in preference.
                        $gedcom = '0 @' . $media_object->xref() . "@ OBJE\n" . $gedcom;
                        foreach ($media_object->facts() as $fact) {
                            $gedcom .= "\n" . $fact->gedcom();
                        }
                        $media_object->updateRecord($gedcom, true);
                    }

                    // Accept the changes, to keep the filesystem in sync with the GEDCOM data.
                    FunctionsImport::acceptAllChanges($media_object->getxref(), $media_object->tree());
                }
                break;
        }

        return response([]);
    }
130582
public function dispatch(ServerRequestInterface $request): ResponseInterface
    {
        if ($this->currentRoute === null) {
            return $this->generate404($request);
        }

        foreach ($this->hostParameters as $param => $value) {
            $request = $request->withAttribute($param, $value);
        }

        foreach ($this->currentRoute->getHostParameters() as $param => $value) {
            $request = $request->withAttribute($param, $value);
        }

        foreach ($this->routeParameters as $param => $value) {
            $request = $request->withAttribute($param, $value);
        }

        $this->pushMiddlewaresToApplyInPipe();

        return $this->handle($request);
    }
195091
public function uploadImageAction(Request $request): Response
    {
        if ($this->isValidCsrfToken($request)) {
            $data = new ImageAssetUploadData(
                $request->files->get(self::FILE_KEY),
                $request->request->get(self::LANGUAGE_CODE_KEY)
            );

            $errors = $this->validator->validate($data);
            if ($errors->count() === 0) {
                try {
                    $file = $data->getFile();

                    $content = $this->imageAssetMapper->createAsset(
                        $file->getClientOriginalName(),
                        new ImageValue([
                            'path' => $file->getRealPath(),
                            'fileSize' => $file->getSize(),
                            'fileName' => $file->getClientOriginalName(),
                            'alternativeText' => null,
                        ]),
                        $data->getLanguageCode()
                    );

                    return new JsonResponse([
                        'destinationContent' => [
                            'id' => $content->contentInfo->id,
                            'name' => $content->getName(),
                            'locationId' => $content->contentInfo->mainLocationId,
                        ],
                        'value' => $this->imageAssetMapper->getAssetValue($content),
                    ]);
                } catch (Exception $e) {
                    return $this->createGenericErrorResponse($e->getMessage());
                }
            } else {
                return $this->createInvalidInputResponse($errors);
            }
        }

        return $this->createInvalidCsrfResponse();
    }
805805
public function postAdminAction(ServerRequestInterface $request): ResponseInterface
    {
        $this->setPreference('body', $request->get('body', ''));
        $this->setPreference('head', $request->get('head', ''));

        $message = I18N::translate('The preferences for the module “%s” have been updated.', $this->title());
        FlashMessages::addMessage($message, 'success');

        return redirect($this->getConfigLink());
    }
1221026
public function handle(ServerRequestInterface $request): ResponseInterface{
        $routing        = $this->getRouteCollector()
            ->router($request->getUri()->getHost(), $request->getMethod())
            ->search($request->getUri()->getPath())
        ;
        $handlerBuilder = $kernel->getRequestHandlerBuilder();

        if($routing->found){
            $method = $routing->data["action"]["method"];
            $object = $kernel->getContainer()->getInstance(
                $routing->data["action"]["class"]
            );
            $action = [$object, $method];

            if($object instanceof Bundle\MiddlewareRegisterInterface){
                $object->middlewareRegister($handlerBuilder);
            }
        }else{
            $action = function(){
                throw new \Fratily\Http\Message\Status\NotFound();
            };
        }

        return $handlerBuilder
            ->append(
                new Controller\ActionMiddleware($this->getContainer())
            )
            ->create(
                $kernel->getContainer()->has("kernel.responseFactory")
                    ? $kernel->getContainer()->get("kernel.responseFactory")
                    : new \Fratily\Http\Message\ResponseFactory()
            )
            ->handle(
                $request
                    ->withAttribute("action", $action)
                    ->withAttribute("routing", $routing)
                    ->withAttribute("kernel", $kernel)
                    ->withAttribute(
                        "environment",
                        $kernel->getConfig()->getEnvironment()
                    )
                    ->withAttribute(
                        "debug",
                        $kernel->getConfig()->isDebug()
                    )
            )
        ;
    }
806249
public function importMessage(ImportMessageRequest $request)
    {
        $response = new ImportMessageResponse();
        return $this->client->sendRequest($request, $response);
    }
810766
public function save(ServerRequestInterface $request): ResponseInterface
    {
        $username  = $request->getParsedBody()['username'];
        $real_name = $request->getParsedBody()['real_name'];
        $email     = $request->getParsedBody()['email'];
        $password  = $request->getParsedBody()['password'];

        $errors = false;
        if ($this->user_service->findByUserName($username)) {
            FlashMessages::addMessage(I18N::translate('Duplicate username. A user with that username already exists. Please choose another username.'));
            $errors = true;
        }

        if ($this->user_service->findByEmail($email)) {
            FlashMessages::addMessage(I18N::translate('Duplicate email address. A user with that email already exists.'));
            $errors = true;
        }

        if ($errors) {
            $url = route('admin-users-create', [
                'email'     => $email,
                'real_name' => $real_name,
                'username'  => $username,
            ]);

            return redirect($url);
        }

        $new_user = $this->user_service->create($username, $real_name, $email, $password)
            ->setPreference('verified', '1')
            ->setPreference('language', WT_LOCALE)
            ->setPreference('timezone', Site::getPreference('TIMEZONE'))
            ->setPreference('reg_timestamp', date('U'))
            ->setPreference('sessiontime', '0');

        Log::addAuthenticationLog('User ->' . $username . '<- created');

        $url = route('admin-users-edit', [
            'user_id' => $new_user->id(),
        ]);

        return redirect($url);
    }
689779
public function handleRequest(ServerRequestInterface $request): ResponseInterface
    {
        $this->request = $request;
        $action = $request->getQueryParams()['action'] ?? $request->getParsedBody()['action'] ?? 'overview';
        $this->initializeView($action);

        $result = call_user_func_array([$this, $action . 'Action'], [$request]);
        if ($result instanceof ResponseInterface) {
            return $result;
        }
        $this->moduleTemplate->setContent($this->view->render());
        return new HtmlResponse($this->moduleTemplate->renderContent());
    }
780909
public function frameworkImportAction(Request $request)
    {
        $this->checkToolAccess();

        $data = $this->decodeRequest($request);
        $fileData = isset($data['file']) ? $data['file'] : null;
        $this->manager->importFramework($fileData);

        return new JsonResponse();
    }
116041
public function upload(HTTPRequest $request)
    {
        if ($this->isDisabled() || $this->isReadonly()) {
            return $this->httpError(403);
        }

        // CSRF check
        $token = $this->getForm()->getSecurityToken();
        if (!$token->checkRequest($request)) {
            return $this->httpError(400);
        }

        $tmpFile = $request->postVar('Upload');
        /** @var File $file */
        $file = $this->saveTemporaryFile($tmpFile, $error);

        // Prepare result
        if ($error) {
            $result = [
                'message' => [
                    'type' => 'error',
                    'value' => $error,
                ]
            ];
            $this->getUpload()->clearErrors();
            return (new HTTPResponse(json_encode($result), 400))
                ->addHeader('Content-Type', 'application/json');
        }

        // We need an ID for getObjectFromData
        if (!$file->isInDB()) {
            $file->write();
        }

        // Return success response
        $result = [
            AssetAdmin::singleton()->getObjectFromData($file)
        ];

        // Don't discard pre-generated client side canvas thumbnail
        if ($result[0]['category'] === 'image') {
            unset($result[0]['thumbnail']);
        }
        $this->getUpload()->clearErrors();
        return (new HTTPResponse(json_encode($result)))
            ->addHeader('Content-Type', 'application/json');
    }
626471
public function data(ServerRequestInterface $request, DatatablesService $datatables_service): ResponseInterface
    {
        $files  = $request->getQueryParams()['files']; // local|external|unused
        $search = $request->getQueryParams()['search'];
        $search = $search['value'];
        $start  = (int) $request->getQueryParams()['start'];
        $length = (int) $request->getQueryParams()['length'];

        // Files within this folder
        $media_folder = $request->getQueryParams()['media_folder'];

        // subfolders within $media_path
        $subfolders = $request->getQueryParams()['subfolders']; // include|exclude

        $search_columns = ['multimedia_file_refn', 'descriptive_title'];

        $sort_columns = [
            0 => 'multimedia_file_refn',
            2 => DB::raw('descriptive_title || multimedia_file_refn'),
        ];

        switch ($files) {
            case 'local':
                $query = DB::table('media_file')
                    ->join('media', static function (JoinClause $join): void {
                        $join
                            ->on('media.m_file', '=', 'media_file.m_file')
                            ->on('media.m_id', '=', 'media_file.m_id');
                    })
                    ->join('gedcom_setting', 'gedcom_id', '=', 'media.m_file')
                    ->where('setting_name', '=', 'MEDIA_DIRECTORY')
                    ->where('multimedia_file_refn', 'NOT LIKE', 'http://%')
                    ->where('multimedia_file_refn', 'NOT LIKE', 'https://%')
                    ->select(['media.*', 'multimedia_file_refn', 'descriptive_title']);

                $query->where(DB::raw('setting_value || multimedia_file_refn'), 'LIKE', $media_folder . '%');

                if ($subfolders === 'exclude') {
                    $query->where(DB::raw('setting_value || multimedia_file_refn'), 'NOT LIKE', $media_folder . '%/%');
                }

                return $datatables_service->handle($request, $query, $search_columns, $sort_columns, function (stdClass $row): array {
                    /** @var Media $media */
                    $media = Media::rowMapper()($row);

                    $media_files = $media->mediaFiles()
                        ->filter(static function (MediaFile $media_file) use ($row): bool {
                            return $media_file->filename() == $row->multimedia_file_refn;
                        })
                        ->map(static function (MediaFile $media_file): string {
                            return $media_file->displayImage(150, 150, '', []);
                        })
                        ->implode('');

                    return [
                        $row->multimedia_file_refn,
                        $media_files,
                        $this->mediaObjectInfo($media),
                    ];
                });

            case 'external':
                $query = DB::table('media_file')
                    ->join('media', static function (JoinClause $join): void {
                        $join
                            ->on('media.m_file', '=', 'media_file.m_file')
                            ->on('media.m_id', '=', 'media_file.m_id');
                    })
                    ->where(static function (Builder $query): void {
                        $query
                            ->where('multimedia_file_refn', 'LIKE', 'http://%')
                            ->orWhere('multimedia_file_refn', 'LIKE', 'https://%');
                    })
                    ->select(['media.*', 'multimedia_file_refn', 'descriptive_title']);

                return $datatables_service->handle($request, $query, $search_columns, $sort_columns, function (stdClass $row): array {
                    /** @var Media $media */
                    $media = Media::rowMapper()($row);

                    $media_files = $media->mediaFiles()
                        ->filter(static function (MediaFile $media_file) use ($row): bool {
                            return $media_file->filename() === $row->multimedia_file_refn;
                        })
                        ->map(static function (MediaFile $media_file): string {
                            return $media_file->displayImage(150, 150, '', []);
                        })
                        ->implode('');

                    return [
                        $row->multimedia_file_refn,
                        $media_files,
                        $this->mediaObjectInfo($media),
                    ];
                });

            case 'unused':
                // Which trees use which media folder?
                $media_trees = DB::table('gedcom')
                    ->join('gedcom_setting', 'gedcom_setting.gedcom_id', '=', 'gedcom.gedcom_id')
                    ->where('setting_name', '=', 'MEDIA_DIRECTORY')
                    ->where('gedcom.gedcom_id', '>', 0)
                    ->pluck('setting_value', 'gedcom_name');

                $disk_files = $this->allDiskFiles($media_folder, $subfolders);
                $db_files   = $this->allMediaFiles($media_folder, $subfolders);

                // All unused files
                $unused_files = array_diff($disk_files, $db_files);
                $recordsTotal = count($unused_files);

                // Filter unused files
                if ($search) {
                    $unused_files = array_filter($unused_files, static function (string $x) use ($search): bool {
                        return strpos($x, $search) !== false;
                    });
                }
                $recordsFiltered = count($unused_files);

                // Sort files - only option is column 0
                sort($unused_files);
                $order = $request->getQueryParams()['order'];
                if ($order && $order[0]['dir'] === 'desc') {
                    $unused_files = array_reverse($unused_files);
                }

                // Paginate unused files
                $unused_files = array_slice($unused_files, $start, $length);

                $data = [];
                foreach ($unused_files as $unused_file) {
                    $imgsize = getimagesize(WT_DATA_DIR . $media_folder . $unused_file);
                    // We can’t create a URL (not in public_html) or use the media firewall (no such object)
                    if ($imgsize === false) {
                        $img = '-';
                    } else {
                        $url = route('unused-media-thumbnail', [
                            'folder' => $media_folder,
                            'file'   => $unused_file,
                            'w'      => 100,
                            'h'      => 100,
                        ]);
                        $img = '<img src="' . e($url) . '">';
                    }

                    // Form to create new media object in each tree
                    $create_form = '';
                    foreach ($media_trees as $media_tree => $media_directory) {
                        if (Str::startsWith($media_folder . $unused_file, $media_directory)) {
                            $tmp         = substr($media_folder . $unused_file, strlen($media_directory));
                            $create_form .=
                                '<p><a href="#" data-toggle="modal" data-target="#modal-create-media-from-file" data-file="' . e($tmp) . '" data-tree="' . e($media_tree) . '" onclick="document.getElementById(\'file\').value=this.dataset.file; document.getElementById(\'ged\').value=this.dataset.tree;">' . I18N::translate('Create') . '</a> — ' . e($media_tree) . '<p>';
                        }
                    }

                    $delete_link = '<p><a data-confirm="' . I18N::translate('Are you sure you want to delete “%s”?', e($unused_file)) . '" data-url="' . e(route('admin-media-delete', [
                            'file'   => $unused_file,
                            'folder' => $media_folder,
                        ])) . '" onclick="if (confirm(this.dataset.confirm)) jQuery.post(this.dataset.url, function (){document.location.reload();})" href="#">' . I18N::translate('Delete') . '</a></p>';

                    $data[] = [
                        $this->mediaFileInfo($media_folder, $unused_file) . $delete_link,
                        $img,
                        $create_form,
                    ];
                }
                break;

            default:
                throw new BadRequestHttpException();
        }

        // See http://www.datatables.net/usage/server-side
        return response([
            'draw'            => (int) $request->getQueryParams()['draw'],
            'recordsTotal'    => $recordsTotal,
            'recordsFiltered' => $recordsFiltered,
            'data'            => $data,
        ]);
    }
1207049
public function preferencesSave(ServerRequestInterface $request): ResponseInterface
    {
        $INDEX_DIRECTORY = $request->get('INDEX_DIRECTORY');
        if (substr($INDEX_DIRECTORY, -1) !== '/') {
            $INDEX_DIRECTORY .= '/';
        }
        if (File::mkdir($INDEX_DIRECTORY)) {
            Site::setPreference('INDEX_DIRECTORY', $INDEX_DIRECTORY);
        } else {
            FlashMessages::addMessage(I18N::translate('The folder %s does not exist, and it could not be created.', e($INDEX_DIRECTORY)), 'danger');
        }

        Site::setPreference('THEME_DIR', $request->get('THEME_DIR'));
        Site::setPreference('ALLOW_CHANGE_GEDCOM', (string) (bool) $request->get('ALLOW_CHANGE_GEDCOM'));
        Site::setPreference('TIMEZONE', $request->get('TIMEZONE'));

        FlashMessages::addMessage(I18N::translate('The website preferences have been updated.'), 'success');
        $url = route('admin-control-panel');

        return redirect($url);
    }
959265
public function replace(ServerRequestInterface $request): ResponseInterface
    {
        $search  = $request->get('search', '');
        $replace = $request->get('replace', '');
        $context = $request->get('context', '');

        if ($context !== 'name' && $context !== 'place') {
            $context = 'all';
        }

        $title = I18N::translate('Search and replace');

        return $this->viewResponse('search-replace-page', [
            'context' => $context,
            'replace' => $replace,
            'search'  => $search,
            'title'   => $title,
        ]);
    }
1007360
private function createContent(ServerRequestInterface $request)
    {
        $route = $request->getAttribute('route');
        $template = $this->viewInflector->inflect($route);
        $this->templateEngine->parse($template);
        return $this->templateEngine->process($request->getAttribute('viewData', []));
    }
961204
private function decorateRequest(ServerRequestInterface $request)
    {
        if ($request instanceof Http\Request) {
            return $request;
        }

        return new Http\Request($this, $request);
    }
318021
public function importFromRequest($request)
    {
        $reflect = new ReflectionClass(get_called_class());
        $properties = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED);
        foreach ($properties as $property) {
            $property->setValue($this, $request->get($property->getName()));
        }
    }
154492
private function input(ServerRequestInterface $request): array
    {
        if (! is_null($this->parser)) {

            $input = ($this->parser)($request);

            if (is_array($input)) {

                return $input;

            }

            throw new InputTypeException($input);

        }

        return array_merge(
            $request->getAttributes(),
            $request->getQueryParams(),
            $request->getParsedBody(),
            $request->getUploadedFiles()
        );
    }