Passed
Push — feature/code-analysis ( 4fe35d...c99b5b )
by Jonathan
11:08 queued 07:29
created
app/Module/Certificates/Http/RequestHandlers/AutoCompleteFile.php 1 patch
Indentation   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -31,53 +31,53 @@
 block discarded – undo
31 31
  */
32 32
 class AutoCompleteFile extends AbstractAutocompleteHandler
33 33
 {
34
-    // Tell the browser to cache the results
35
-    protected const CACHE_LIFE = 10;
34
+	// Tell the browser to cache the results
35
+	protected const CACHE_LIFE = 10;
36 36
 
37
-    private ?CertificatesModule $module;
38
-    private CertificateFilesystemService $certif_filesystem;
39
-    private UrlObfuscatorService $url_obfuscator_service;
37
+	private ?CertificatesModule $module;
38
+	private CertificateFilesystemService $certif_filesystem;
39
+	private UrlObfuscatorService $url_obfuscator_service;
40 40
 
41
-    /**
42
-     * Constructor for AutoCompleteFile Request Handler
43
-     *
44
-     * @param ModuleService $module_service
45
-     * @param CertificateFilesystemService $certif_filesystem
46
-     * @param UrlObfuscatorService $url_obfuscator_service
47
-     * @param SearchService $search_service
48
-     */
49
-    public function __construct(
50
-        ModuleService $module_service,
51
-        CertificateFilesystemService $certif_filesystem,
52
-        UrlObfuscatorService $url_obfuscator_service,
53
-        SearchService $search_service
54
-    ) {
55
-        parent::__construct($search_service);
56
-        $this->module = $module_service->findByInterface(CertificatesModule::class)->first();
57
-        $this->certif_filesystem = $certif_filesystem;
58
-        $this->url_obfuscator_service = $url_obfuscator_service;
59
-    }
41
+	/**
42
+	 * Constructor for AutoCompleteFile Request Handler
43
+	 *
44
+	 * @param ModuleService $module_service
45
+	 * @param CertificateFilesystemService $certif_filesystem
46
+	 * @param UrlObfuscatorService $url_obfuscator_service
47
+	 * @param SearchService $search_service
48
+	 */
49
+	public function __construct(
50
+		ModuleService $module_service,
51
+		CertificateFilesystemService $certif_filesystem,
52
+		UrlObfuscatorService $url_obfuscator_service,
53
+		SearchService $search_service
54
+	) {
55
+		parent::__construct($search_service);
56
+		$this->module = $module_service->findByInterface(CertificatesModule::class)->first();
57
+		$this->certif_filesystem = $certif_filesystem;
58
+		$this->url_obfuscator_service = $url_obfuscator_service;
59
+	}
60 60
 
61
-    /**
62
-     * {@inheritDoc}
63
-     * @see \Fisharebest\Webtrees\Http\RequestHandlers\AbstractAutocompleteHandler::search()
64
-     */
65
-    protected function search(ServerRequestInterface $request): Collection
66
-    {
67
-        $tree = Validator::attributes($request)->tree();
68
-        $city = Validator::queryParams($request)->string('cityobf', '');
61
+	/**
62
+	 * {@inheritDoc}
63
+	 * @see \Fisharebest\Webtrees\Http\RequestHandlers\AbstractAutocompleteHandler::search()
64
+	 */
65
+	protected function search(ServerRequestInterface $request): Collection
66
+	{
67
+		$tree = Validator::attributes($request)->tree();
68
+		$city = Validator::queryParams($request)->string('cityobf', '');
69 69
 
70
-        if ($this->module === null || $city === '' || !$this->url_obfuscator_service->tryDeobfuscate($city)) {
71
-            return collect();
72
-        }
70
+		if ($this->module === null || $city === '' || !$this->url_obfuscator_service->tryDeobfuscate($city)) {
71
+			return collect();
72
+		}
73 73
 
74
-        $query  =  Validator::attributes($request)->string('query', '');
74
+		$query  =  Validator::attributes($request)->string('query', '');
75 75
 
76
-        /** @var Collection<int, string> $results */
77
-        $results =  $this->certif_filesystem
78
-            ->certificatesForCityContaining($tree, $city, $query)
79
-            ->map(fn(Certificate $certificate): string => $certificate->filename());
76
+		/** @var Collection<int, string> $results */
77
+		$results =  $this->certif_filesystem
78
+			->certificatesForCityContaining($tree, $city, $query)
79
+			->map(fn(Certificate $certificate): string => $certificate->filename());
80 80
 
81
-        return $results;
82
-    }
81
+		return $results;
82
+	}
83 83
 }
Please login to merge, or discard this patch.
app/Module/Certificates/Http/RequestHandlers/AdminConfigPage.php 1 patch
Indentation   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -35,56 +35,56 @@
 block discarded – undo
35 35
  */
36 36
 class AdminConfigPage implements RequestHandlerInterface
37 37
 {
38
-    use ViewResponseTrait;
38
+	use ViewResponseTrait;
39 39
 
40
-    private ?CertificatesModule $module;
41
-    private TreeService $tree_service;
40
+	private ?CertificatesModule $module;
41
+	private TreeService $tree_service;
42 42
 
43
-    /**
44
-     * Constructor for Admin Config page request handler
45
-     *
46
-     * @param ModuleService $module_service
47
-     */
48
-    public function __construct(ModuleService $module_service, TreeService $tree_service)
49
-    {
50
-        $this->module = $module_service->findByInterface(CertificatesModule::class)->first();
51
-        $this->tree_service = $tree_service;
52
-    }
43
+	/**
44
+	 * Constructor for Admin Config page request handler
45
+	 *
46
+	 * @param ModuleService $module_service
47
+	 */
48
+	public function __construct(ModuleService $module_service, TreeService $tree_service)
49
+	{
50
+		$this->module = $module_service->findByInterface(CertificatesModule::class)->first();
51
+		$this->tree_service = $tree_service;
52
+	}
53 53
 
54
-    /**
55
-     * {@inheritDoc}
56
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
57
-     */
58
-    public function handle(ServerRequestInterface $request): ResponseInterface
59
-    {
60
-        $this->layout = 'layouts/administration';
54
+	/**
55
+	 * {@inheritDoc}
56
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
57
+	 */
58
+	public function handle(ServerRequestInterface $request): ResponseInterface
59
+	{
60
+		$this->layout = 'layouts/administration';
61 61
 
62
-        if ($this->module === null) {
63
-            throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
64
-        }
62
+		if ($this->module === null) {
63
+			throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
64
+		}
65 65
 
66
-        $user = Validator::attributes($request)->user();
66
+		$user = Validator::attributes($request)->user();
67 67
 
68
-        $all_trees = $this->tree_service->all()->filter(fn(Tree $tree) => Auth::isManager($tree, $user));
69
-        if ($all_trees->count() === 0) {
70
-            throw new HttpAccessDeniedException();
71
-        }
68
+		$all_trees = $this->tree_service->all()->filter(fn(Tree $tree) => Auth::isManager($tree, $user));
69
+		if ($all_trees->count() === 0) {
70
+			throw new HttpAccessDeniedException();
71
+		}
72 72
 
73
-        $tree = Validator::attributes($request)->treeOptional('tree') ?? $all_trees->first();
73
+		$tree = Validator::attributes($request)->treeOptional('tree') ?? $all_trees->first();
74 74
 
75
-        $data_folder = Registry::filesystem()->dataName();
75
+		$data_folder = Registry::filesystem()->dataName();
76 76
 
77
-        $same_tree = fn(Tree $tree_collection): bool => $tree->id() === $tree_collection->id();
78
-        if (!$all_trees->contains($same_tree)) {
79
-            throw new HttpAccessDeniedException();
80
-        }
77
+		$same_tree = fn(Tree $tree_collection): bool => $tree->id() === $tree_collection->id();
78
+		if (!$all_trees->contains($same_tree)) {
79
+			throw new HttpAccessDeniedException();
80
+		}
81 81
 
82
-        return $this->viewResponse($this->module->name() . '::admin/config', [
83
-            'module_name'       =>  $this->module->name(),
84
-            'title'             =>  $this->module->title(),
85
-            'tree'              =>  $tree,
86
-            'other_trees'       =>  $all_trees->reject($same_tree),
87
-            'data_folder'       =>  $data_folder
88
-        ]);
89
-    }
82
+		return $this->viewResponse($this->module->name() . '::admin/config', [
83
+			'module_name'       =>  $this->module->name(),
84
+			'title'             =>  $this->module->title(),
85
+			'tree'              =>  $tree,
86
+			'other_trees'       =>  $all_trees->reject($same_tree),
87
+			'data_folder'       =>  $data_folder
88
+		]);
89
+	}
90 90
 }
Please login to merge, or discard this patch.
app/Module/Certificates/Http/RequestHandlers/CertificateImage.php 1 patch
Indentation   +102 added lines, -102 removed lines patch added patch discarded remove patch
@@ -38,106 +38,106 @@
 block discarded – undo
38 38
  */
39 39
 class CertificateImage implements RequestHandlerInterface
40 40
 {
41
-    private ?CertificatesModule $module;
42
-    private CertificateFilesystemService $certif_filesystem;
43
-    private CertificateImageFactory $certif_image_factory;
44
-    private CertificateDataService $certif_data_service;
45
-    private UrlObfuscatorService $url_obfuscator_service;
46
-
47
-    /**
48
-     * Constructor for Certificate Image Request Handler
49
-     *
50
-     * @param ModuleService $module_service
51
-     */
52
-    public function __construct(
53
-        ModuleService $module_service,
54
-        CertificateFilesystemService $certif_filesystem,
55
-        CertificateDataService $certif_data_service,
56
-        UrlObfuscatorService $url_obfuscator_service
57
-    ) {
58
-        $this->module = $module_service->findByInterface(CertificatesModule::class)->first();
59
-        $this->certif_filesystem = $certif_filesystem;
60
-        $this->certif_image_factory = new CertificateImageFactory($this->certif_filesystem);
61
-        $this->certif_data_service = $certif_data_service;
62
-        $this->url_obfuscator_service = $url_obfuscator_service;
63
-    }
64
-
65
-    /**
66
-     * {@inheritDoc}
67
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
68
-     */
69
-    public function handle(ServerRequestInterface $request): ResponseInterface
70
-    {
71
-        if ($this->module === null) {
72
-            throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
73
-        }
74
-
75
-        $tree = Validator::attributes($request)->tree();
76
-        $user = Validator::attributes($request)->user();
77
-
78
-        $certif_path = Validator::attributes($request)->string('cid', '');
79
-        $certificate = null;
80
-        if ($certif_path !== '' && $this->url_obfuscator_service->tryDeobfuscate($certif_path)) {
81
-            $certificate = $this->certif_filesystem->certificate($tree, $certif_path);
82
-        }
83
-
84
-        if ($certificate === null) {
85
-            return $this->certif_image_factory
86
-                ->replacementImageResponse((string) StatusCodeInterface::STATUS_NOT_FOUND)
87
-                ->withHeader('X-Image-Exception', I18N::translate('The certificate was not found in this family tree.'))
88
-            ;
89
-        }
90
-
91
-        $use_watermark = $this->certif_image_factory->certificateNeedsWatermark($certificate, $user);
92
-        $watermark = $use_watermark ? $this->watermark($request, $certificate) : null;
93
-
94
-        return $this->certif_image_factory->certificateFileResponse(
95
-            $certificate,
96
-            $use_watermark,
97
-            $watermark
98
-        );
99
-    }
100
-
101
-    /**
102
-     * Get watermark data for a certificate.
103
-     *
104
-     * @param ServerRequestInterface $request
105
-     * @param Certificate $certificate
106
-     * @return Watermark
107
-     */
108
-    private function watermark(ServerRequestInterface $request, Certificate $certificate): Watermark
109
-    {
110
-        $color = $certificate->tree()->getPreference('MAJ_CERTIF_WM_FONT_COLOR', Watermark::DEFAULT_COLOR);
111
-        $size = $certificate->tree()->getPreference('MAJ_CERTIF_WM_FONT_MAXSIZE');
112
-        $text = $this->watermarkText($request, $certificate);
113
-
114
-        return new Watermark($text, $color, is_numeric($size) ? (int) $size : Watermark::DEFAULT_SIZE);
115
-    }
116
-
117
-    /**
118
-     * Get the text to be watermarked for a certificate.
119
-     *
120
-     * @param ServerRequestInterface $request
121
-     * @param Certificate $certificate
122
-     * @return string
123
-     */
124
-    private function watermarkText(ServerRequestInterface $request, Certificate $certificate): string
125
-    {
126
-        $sid = Validator::queryParams($request)->isXref()->string('sid', '');
127
-        if ($sid !== '') {
128
-            $source = Registry::sourceFactory()->make($sid, $certificate->tree());
129
-        } else {
130
-            $source = $this->certif_data_service->oneLinkedSource($certificate);
131
-        }
132
-
133
-        if ($source !== null && $source->canShowName()) {
134
-            $repo = $source->facts(['REPO'])->first();
135
-            if ($repo !== null && ($repo = $repo->target()) !== null && $repo->canShowName()) {
136
-                return I18N::translate('© %s - %s', strip_tags($repo->fullName()), strip_tags($source->fullName()));
137
-            }
138
-            return strip_tags($source->fullName());
139
-        }
140
-        $default_text = $certificate->tree()->getPreference('MAJ_CERTIF_WM_DEFAULT');
141
-        return $default_text !== '' ? $default_text : I18N::translate('This image is protected under copyright law.');
142
-    }
41
+	private ?CertificatesModule $module;
42
+	private CertificateFilesystemService $certif_filesystem;
43
+	private CertificateImageFactory $certif_image_factory;
44
+	private CertificateDataService $certif_data_service;
45
+	private UrlObfuscatorService $url_obfuscator_service;
46
+
47
+	/**
48
+	 * Constructor for Certificate Image Request Handler
49
+	 *
50
+	 * @param ModuleService $module_service
51
+	 */
52
+	public function __construct(
53
+		ModuleService $module_service,
54
+		CertificateFilesystemService $certif_filesystem,
55
+		CertificateDataService $certif_data_service,
56
+		UrlObfuscatorService $url_obfuscator_service
57
+	) {
58
+		$this->module = $module_service->findByInterface(CertificatesModule::class)->first();
59
+		$this->certif_filesystem = $certif_filesystem;
60
+		$this->certif_image_factory = new CertificateImageFactory($this->certif_filesystem);
61
+		$this->certif_data_service = $certif_data_service;
62
+		$this->url_obfuscator_service = $url_obfuscator_service;
63
+	}
64
+
65
+	/**
66
+	 * {@inheritDoc}
67
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
68
+	 */
69
+	public function handle(ServerRequestInterface $request): ResponseInterface
70
+	{
71
+		if ($this->module === null) {
72
+			throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
73
+		}
74
+
75
+		$tree = Validator::attributes($request)->tree();
76
+		$user = Validator::attributes($request)->user();
77
+
78
+		$certif_path = Validator::attributes($request)->string('cid', '');
79
+		$certificate = null;
80
+		if ($certif_path !== '' && $this->url_obfuscator_service->tryDeobfuscate($certif_path)) {
81
+			$certificate = $this->certif_filesystem->certificate($tree, $certif_path);
82
+		}
83
+
84
+		if ($certificate === null) {
85
+			return $this->certif_image_factory
86
+				->replacementImageResponse((string) StatusCodeInterface::STATUS_NOT_FOUND)
87
+				->withHeader('X-Image-Exception', I18N::translate('The certificate was not found in this family tree.'))
88
+			;
89
+		}
90
+
91
+		$use_watermark = $this->certif_image_factory->certificateNeedsWatermark($certificate, $user);
92
+		$watermark = $use_watermark ? $this->watermark($request, $certificate) : null;
93
+
94
+		return $this->certif_image_factory->certificateFileResponse(
95
+			$certificate,
96
+			$use_watermark,
97
+			$watermark
98
+		);
99
+	}
100
+
101
+	/**
102
+	 * Get watermark data for a certificate.
103
+	 *
104
+	 * @param ServerRequestInterface $request
105
+	 * @param Certificate $certificate
106
+	 * @return Watermark
107
+	 */
108
+	private function watermark(ServerRequestInterface $request, Certificate $certificate): Watermark
109
+	{
110
+		$color = $certificate->tree()->getPreference('MAJ_CERTIF_WM_FONT_COLOR', Watermark::DEFAULT_COLOR);
111
+		$size = $certificate->tree()->getPreference('MAJ_CERTIF_WM_FONT_MAXSIZE');
112
+		$text = $this->watermarkText($request, $certificate);
113
+
114
+		return new Watermark($text, $color, is_numeric($size) ? (int) $size : Watermark::DEFAULT_SIZE);
115
+	}
116
+
117
+	/**
118
+	 * Get the text to be watermarked for a certificate.
119
+	 *
120
+	 * @param ServerRequestInterface $request
121
+	 * @param Certificate $certificate
122
+	 * @return string
123
+	 */
124
+	private function watermarkText(ServerRequestInterface $request, Certificate $certificate): string
125
+	{
126
+		$sid = Validator::queryParams($request)->isXref()->string('sid', '');
127
+		if ($sid !== '') {
128
+			$source = Registry::sourceFactory()->make($sid, $certificate->tree());
129
+		} else {
130
+			$source = $this->certif_data_service->oneLinkedSource($certificate);
131
+		}
132
+
133
+		if ($source !== null && $source->canShowName()) {
134
+			$repo = $source->facts(['REPO'])->first();
135
+			if ($repo !== null && ($repo = $repo->target()) !== null && $repo->canShowName()) {
136
+				return I18N::translate('© %s - %s', strip_tags($repo->fullName()), strip_tags($source->fullName()));
137
+			}
138
+			return strip_tags($source->fullName());
139
+		}
140
+		$default_text = $certificate->tree()->getPreference('MAJ_CERTIF_WM_DEFAULT');
141
+		return $default_text !== '' ? $default_text : I18N::translate('This image is protected under copyright law.');
142
+	}
143 143
 }
Please login to merge, or discard this patch.
app/Module/Certificates/Http/RequestHandlers/AdminConfigAction.php 1 patch
Indentation   +59 added lines, -59 removed lines patch added patch discarded remove patch
@@ -30,73 +30,73 @@
 block discarded – undo
30 30
  */
31 31
 class AdminConfigAction implements RequestHandlerInterface
32 32
 {
33
-    private ?CertificatesModule $module;
33
+	private ?CertificatesModule $module;
34 34
 
35
-    /**
36
-     * Constructor for Admin Config Action request handler
37
-     *
38
-     * @param ModuleService $module_service
39
-     */
40
-    public function __construct(ModuleService $module_service)
41
-    {
42
-        $this->module = $module_service->findByInterface(CertificatesModule::class)->first();
43
-    }
35
+	/**
36
+	 * Constructor for Admin Config Action request handler
37
+	 *
38
+	 * @param ModuleService $module_service
39
+	 */
40
+	public function __construct(ModuleService $module_service)
41
+	{
42
+		$this->module = $module_service->findByInterface(CertificatesModule::class)->first();
43
+	}
44 44
 
45
-    /**
46
-     * {@inheritDoc}
47
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
48
-     */
49
-    public function handle(ServerRequestInterface $request): ResponseInterface
50
-    {
51
-        $tree = Validator::attributes($request)->tree();
45
+	/**
46
+	 * {@inheritDoc}
47
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
48
+	 */
49
+	public function handle(ServerRequestInterface $request): ResponseInterface
50
+	{
51
+		$tree = Validator::attributes($request)->tree();
52 52
 
53
-        $admin_config_route = route(AdminConfigPage::class, ['tree' => $tree->name()]);
53
+		$admin_config_route = route(AdminConfigPage::class, ['tree' => $tree->name()]);
54 54
 
55
-        if ($this->module === null) {
56
-            FlashMessages::addMessage(
57
-                I18N::translate('The attached module could not be found.'),
58
-                'danger'
59
-            );
60
-            return redirect($admin_config_route);
61
-        }
55
+		if ($this->module === null) {
56
+			FlashMessages::addMessage(
57
+				I18N::translate('The attached module could not be found.'),
58
+				'danger'
59
+			);
60
+			return redirect($admin_config_route);
61
+		}
62 62
 
63
-        $tree->setPreference(
64
-            'MAJ_CERTIF_SHOW_CERT',
65
-            (string) Validator::parsedBody($request)->integer('MAJ_CERTIF_SHOW_CERT', Auth::PRIV_HIDE)
66
-        );
67
-        $tree->setPreference(
68
-            'MAJ_CERTIF_SHOW_NO_WATERMARK',
69
-            (string) Validator::parsedBody($request)->integer('MAJ_CERTIF_SHOW_NO_WATERMARK', Auth::PRIV_HIDE)
70
-        );
71
-        $tree->setPreference(
72
-            'MAJ_CERTIF_WM_DEFAULT',
73
-            Validator::parsedBody($request)->string('MAJ_CERTIF_WM_DEFAULT', '')
74
-        );
63
+		$tree->setPreference(
64
+			'MAJ_CERTIF_SHOW_CERT',
65
+			(string) Validator::parsedBody($request)->integer('MAJ_CERTIF_SHOW_CERT', Auth::PRIV_HIDE)
66
+		);
67
+		$tree->setPreference(
68
+			'MAJ_CERTIF_SHOW_NO_WATERMARK',
69
+			(string) Validator::parsedBody($request)->integer('MAJ_CERTIF_SHOW_NO_WATERMARK', Auth::PRIV_HIDE)
70
+		);
71
+		$tree->setPreference(
72
+			'MAJ_CERTIF_WM_DEFAULT',
73
+			Validator::parsedBody($request)->string('MAJ_CERTIF_WM_DEFAULT', '')
74
+		);
75 75
 
76
-        $tree->setPreference(
77
-            'MAJ_CERTIF_WM_FONT_MAXSIZE',
78
-            (string) (
79
-                Validator::parsedBody($request)->isBetween(0, PHP_INT_MAX)->integer('MAJ_CERTIF_WM_FONT_MAXSIZE', 18)
80
-            )
81
-        );
76
+		$tree->setPreference(
77
+			'MAJ_CERTIF_WM_FONT_MAXSIZE',
78
+			(string) (
79
+				Validator::parsedBody($request)->isBetween(0, PHP_INT_MAX)->integer('MAJ_CERTIF_WM_FONT_MAXSIZE', 18)
80
+			)
81
+		);
82 82
 
83
-        // Only accept valid color for MAJ_WM_FONT_COLOR
84
-        $watermark_color = Validator::parsedBody($request)->string('MAJ_CERTIF_WM_FONT_COLOR', '');
85
-        if (preg_match('/#([a-fA-F0-9]{3}){1,2}/', $watermark_color) === 1) {
86
-            $tree->setPreference('MAJ_CERTIF_WM_FONT_COLOR', $watermark_color);
87
-        }
83
+		// Only accept valid color for MAJ_WM_FONT_COLOR
84
+		$watermark_color = Validator::parsedBody($request)->string('MAJ_CERTIF_WM_FONT_COLOR', '');
85
+		if (preg_match('/#([a-fA-F0-9]{3}){1,2}/', $watermark_color) === 1) {
86
+			$tree->setPreference('MAJ_CERTIF_WM_FONT_COLOR', $watermark_color);
87
+		}
88 88
 
89
-        // Only accept valid folders for MAJ_CERT_ROOTDIR
90
-        $cert_root_dir = Validator::parsedBody($request)->string('MAJ_CERTIF_ROOTDIR', '');
91
-        $cert_root_dir = preg_replace('/[:\/\\\\]+/', '/', $cert_root_dir) ?? '';
92
-        $cert_root_dir = trim($cert_root_dir, '/') . '/';
93
-        $tree->setPreference('MAJ_CERTIF_ROOTDIR', $cert_root_dir);
89
+		// Only accept valid folders for MAJ_CERT_ROOTDIR
90
+		$cert_root_dir = Validator::parsedBody($request)->string('MAJ_CERTIF_ROOTDIR', '');
91
+		$cert_root_dir = preg_replace('/[:\/\\\\]+/', '/', $cert_root_dir) ?? '';
92
+		$cert_root_dir = trim($cert_root_dir, '/') . '/';
93
+		$tree->setPreference('MAJ_CERTIF_ROOTDIR', $cert_root_dir);
94 94
 
95
-        FlashMessages::addMessage(
96
-            I18N::translate('The preferences for the module “%s” have been updated.', $this->module->title()),
97
-            'success'
98
-        );
95
+		FlashMessages::addMessage(
96
+			I18N::translate('The preferences for the module “%s” have been updated.', $this->module->title()),
97
+			'success'
98
+		);
99 99
 
100
-        return redirect($admin_config_route);
101
-    }
100
+		return redirect($admin_config_route);
101
+	}
102 102
 }
Please login to merge, or discard this patch.
app/Module/Certificates/Http/RequestHandlers/CertificatesList.php 1 patch
Indentation   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -32,63 +32,63 @@
 block discarded – undo
32 32
  */
33 33
 class CertificatesList implements RequestHandlerInterface
34 34
 {
35
-    use ViewResponseTrait;
35
+	use ViewResponseTrait;
36 36
 
37
-    private ?CertificatesModule $module;
38
-    private CertificateFilesystemService $certif_filesystem;
39
-    private UrlObfuscatorService $url_obfuscator_service;
37
+	private ?CertificatesModule $module;
38
+	private CertificateFilesystemService $certif_filesystem;
39
+	private UrlObfuscatorService $url_obfuscator_service;
40 40
 
41
-    /**
42
-     * Constructor for CertificatesList Request Handler
43
-     *
44
-     * @param ModuleService $module_service
45
-     */
46
-    public function __construct(
47
-        ModuleService $module_service,
48
-        CertificateFilesystemService $certif_filesystem,
49
-        UrlObfuscatorService $url_obfuscator_service
50
-    ) {
51
-        $this->module = $module_service->findByInterface(CertificatesModule::class)->first();
52
-        $this->certif_filesystem = $certif_filesystem;
53
-        $this->url_obfuscator_service = $url_obfuscator_service;
54
-    }
41
+	/**
42
+	 * Constructor for CertificatesList Request Handler
43
+	 *
44
+	 * @param ModuleService $module_service
45
+	 */
46
+	public function __construct(
47
+		ModuleService $module_service,
48
+		CertificateFilesystemService $certif_filesystem,
49
+		UrlObfuscatorService $url_obfuscator_service
50
+	) {
51
+		$this->module = $module_service->findByInterface(CertificatesModule::class)->first();
52
+		$this->certif_filesystem = $certif_filesystem;
53
+		$this->url_obfuscator_service = $url_obfuscator_service;
54
+	}
55 55
 
56
-    /**
57
-     * {@inheritDoc}
58
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
59
-     */
60
-    public function handle(ServerRequestInterface $request): ResponseInterface
61
-    {
62
-        if ($this->module === null) {
63
-            throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
64
-        }
56
+	/**
57
+	 * {@inheritDoc}
58
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
59
+	 */
60
+	public function handle(ServerRequestInterface $request): ResponseInterface
61
+	{
62
+		if ($this->module === null) {
63
+			throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
64
+		}
65 65
 
66
-        $tree = Validator::attributes($request)->tree();
66
+		$tree = Validator::attributes($request)->tree();
67 67
 
68
-        $title = I18N::translate('Certificates');
68
+		$title = I18N::translate('Certificates');
69 69
 
70
-        $cities = array_map(function (string $item): array {
71
-            return [$this->url_obfuscator_service->obfuscate($item), $item];
72
-        }, $this->certif_filesystem->cities($tree));
70
+		$cities = array_map(function (string $item): array {
71
+			return [$this->url_obfuscator_service->obfuscate($item), $item];
72
+		}, $this->certif_filesystem->cities($tree));
73 73
 
74
-        $city = Validator::queryParams($request)->string(
75
-            'cityobf',
76
-            Validator::attributes($request)->string('cityobf', '')
77
-        );
74
+		$city = Validator::queryParams($request)->string(
75
+			'cityobf',
76
+			Validator::attributes($request)->string('cityobf', '')
77
+		);
78 78
 
79
-        if ($city !== '' && $this->url_obfuscator_service->tryDeobfuscate($city)) {
80
-            $title = I18N::translate('Certificates for %s', $city);
81
-            $certificates = $this->certif_filesystem->certificatesForCity($tree, $city);
82
-        }
79
+		if ($city !== '' && $this->url_obfuscator_service->tryDeobfuscate($city)) {
80
+			$title = I18N::translate('Certificates for %s', $city);
81
+			$certificates = $this->certif_filesystem->certificatesForCity($tree, $city);
82
+		}
83 83
 
84
-        return $this->viewResponse($this->module->name() . '::certificates-list', [
85
-            'title'                     =>  $title,
86
-            'tree'                      =>  $tree,
87
-            'module_name'               =>  $this->module->name(),
88
-            'cities'                    =>  $cities,
89
-            'selected_city'             =>  $city,
90
-            'certificates_list'         =>  $certificates ?? collect(),
91
-            'url_obfuscator_service'    =>  $this->url_obfuscator_service
92
-        ]);
93
-    }
84
+		return $this->viewResponse($this->module->name() . '::certificates-list', [
85
+			'title'                     =>  $title,
86
+			'tree'                      =>  $tree,
87
+			'module_name'               =>  $this->module->name(),
88
+			'cities'                    =>  $cities,
89
+			'selected_city'             =>  $city,
90
+			'certificates_list'         =>  $certificates ?? collect(),
91
+			'url_obfuscator_service'    =>  $this->url_obfuscator_service
92
+		]);
93
+	}
94 94
 }
Please login to merge, or discard this patch.
app/Module/Certificates/Services/CertificateDataService.php 1 patch
Indentation   +132 added lines, -132 removed lines patch added patch discarded remove patch
@@ -28,144 +28,144 @@
 block discarded – undo
28 28
  */
29 29
 class CertificateDataService
30 30
 {
31
-    /**
32
-     * Find individuals linked to a certificate.
33
-     *
34
-     * {@internal Ideally, the underscore should be escaped in the WHERE clause,
35
-     * but does not work with Sqlite if no default escape has been defined}
36
-     *
37
-     * @param Certificate $certificate
38
-     * @return Collection<\Fisharebest\Webtrees\Individual>
39
-     */
40
-    public function linkedIndividuals(Certificate $certificate): Collection
41
-    {
42
-        $tree = $certificate->tree();
43
-        return DB::table('individuals')
44
-            ->where('i_file', '=', $tree->id())
45
-            ->where('i_gedcom', 'like', '% _ACT ' . $this->escapedSqlPath($certificate) . '%')
46
-            ->select(['individuals.*'])
47
-            ->get()
48
-            ->map(Registry::individualFactory()->mapper($tree))
49
-            ->filter(GedcomRecord::accessFilter());
50
-    }
31
+	/**
32
+	 * Find individuals linked to a certificate.
33
+	 *
34
+	 * {@internal Ideally, the underscore should be escaped in the WHERE clause,
35
+	 * but does not work with Sqlite if no default escape has been defined}
36
+	 *
37
+	 * @param Certificate $certificate
38
+	 * @return Collection<\Fisharebest\Webtrees\Individual>
39
+	 */
40
+	public function linkedIndividuals(Certificate $certificate): Collection
41
+	{
42
+		$tree = $certificate->tree();
43
+		return DB::table('individuals')
44
+			->where('i_file', '=', $tree->id())
45
+			->where('i_gedcom', 'like', '% _ACT ' . $this->escapedSqlPath($certificate) . '%')
46
+			->select(['individuals.*'])
47
+			->get()
48
+			->map(Registry::individualFactory()->mapper($tree))
49
+			->filter(GedcomRecord::accessFilter());
50
+	}
51 51
 
52
-    /**
53
-     * Find families linked to a certificate.
54
-     *
55
-     * {@internal Ideally, the underscore should be escaped in the WHERE clause,
56
-     * but does not work with Sqlite if no default escape has been defined}
57
-     *
58
-     * @param Certificate $certificate
59
-     * @return Collection<\Fisharebest\Webtrees\Family>
60
-     */
61
-    public function linkedFamilies(Certificate $certificate): Collection
62
-    {
63
-        $tree = $certificate->tree();
64
-        return DB::table('families')
65
-            ->where('f_file', '=', $tree->id())
66
-            ->where('f_gedcom', 'like', '% _ACT ' . $this->escapedSqlPath($certificate) . '%')
67
-            ->select(['families.*'])
68
-            ->get()
69
-            ->map(Registry::familyFactory()->mapper($tree))
70
-            ->filter(GedcomRecord::accessFilter());
71
-    }
52
+	/**
53
+	 * Find families linked to a certificate.
54
+	 *
55
+	 * {@internal Ideally, the underscore should be escaped in the WHERE clause,
56
+	 * but does not work with Sqlite if no default escape has been defined}
57
+	 *
58
+	 * @param Certificate $certificate
59
+	 * @return Collection<\Fisharebest\Webtrees\Family>
60
+	 */
61
+	public function linkedFamilies(Certificate $certificate): Collection
62
+	{
63
+		$tree = $certificate->tree();
64
+		return DB::table('families')
65
+			->where('f_file', '=', $tree->id())
66
+			->where('f_gedcom', 'like', '% _ACT ' . $this->escapedSqlPath($certificate) . '%')
67
+			->select(['families.*'])
68
+			->get()
69
+			->map(Registry::familyFactory()->mapper($tree))
70
+			->filter(GedcomRecord::accessFilter());
71
+	}
72 72
 
73
-    /**
74
-     * Find media objects linked to a certificate.
75
-     *
76
-     * {@internal Ideally, the underscore should be escaped in the WHERE clause,
77
-     * but does not work with Sqlite if no default escape has been defined}
78
-     *
79
-     * @param Certificate $certificate
80
-     * @return Collection<\Fisharebest\Webtrees\Media>
81
-     */
82
-    public function linkedMedias(Certificate $certificate): Collection
83
-    {
84
-        $tree = $certificate->tree();
85
-        return DB::table('media')
86
-            ->where('m_file', '=', $tree->id())
87
-            ->where('m_gedcom', 'like', '% _ACT ' . $this->escapedSqlPath($certificate) . '%')
88
-            ->select(['media.*'])
89
-            ->get()
90
-            ->map(Registry::mediaFactory()->mapper($tree))
91
-            ->filter(GedcomRecord::accessFilter());
92
-    }
73
+	/**
74
+	 * Find media objects linked to a certificate.
75
+	 *
76
+	 * {@internal Ideally, the underscore should be escaped in the WHERE clause,
77
+	 * but does not work with Sqlite if no default escape has been defined}
78
+	 *
79
+	 * @param Certificate $certificate
80
+	 * @return Collection<\Fisharebest\Webtrees\Media>
81
+	 */
82
+	public function linkedMedias(Certificate $certificate): Collection
83
+	{
84
+		$tree = $certificate->tree();
85
+		return DB::table('media')
86
+			->where('m_file', '=', $tree->id())
87
+			->where('m_gedcom', 'like', '% _ACT ' . $this->escapedSqlPath($certificate) . '%')
88
+			->select(['media.*'])
89
+			->get()
90
+			->map(Registry::mediaFactory()->mapper($tree))
91
+			->filter(GedcomRecord::accessFilter());
92
+	}
93 93
 
94
-    /**
95
-     * Find notes linked to a certificate.
96
-     *
97
-     * {@internal Ideally, the underscore should be escaped in the WHERE clause,
98
-     * but does not work with Sqlite if no default escape has been defined}
99
-     *
100
-     * @param Certificate $certificate
101
-     * @return Collection<\Fisharebest\Webtrees\Note>
102
-     */
103
-    public function linkedNotes(Certificate $certificate): Collection
104
-    {
105
-        $tree = $certificate->tree();
106
-        return DB::table('other')
107
-            ->where('o_file', '=', $tree->id())
108
-            ->where('o_type', '=', 'NOTE')
109
-            ->where('o_gedcom', 'like', '% _ACT ' . $this->escapedSqlPath($certificate) . '%')
110
-            ->select(['other.*'])
111
-            ->get()
112
-            ->map(Registry::noteFactory()->mapper($tree))
113
-            ->filter(GedcomRecord::accessFilter());
114
-    }
94
+	/**
95
+	 * Find notes linked to a certificate.
96
+	 *
97
+	 * {@internal Ideally, the underscore should be escaped in the WHERE clause,
98
+	 * but does not work with Sqlite if no default escape has been defined}
99
+	 *
100
+	 * @param Certificate $certificate
101
+	 * @return Collection<\Fisharebest\Webtrees\Note>
102
+	 */
103
+	public function linkedNotes(Certificate $certificate): Collection
104
+	{
105
+		$tree = $certificate->tree();
106
+		return DB::table('other')
107
+			->where('o_file', '=', $tree->id())
108
+			->where('o_type', '=', 'NOTE')
109
+			->where('o_gedcom', 'like', '% _ACT ' . $this->escapedSqlPath($certificate) . '%')
110
+			->select(['other.*'])
111
+			->get()
112
+			->map(Registry::noteFactory()->mapper($tree))
113
+			->filter(GedcomRecord::accessFilter());
114
+	}
115 115
 
116
-    /**
117
-     * Return an escaped string to be used in SQL LIKE comparisons.
118
-     * This would not work well for Sqlite, if the escape character is not defined.
119
-     *
120
-     * @param Certificate $certificate
121
-     * @return string
122
-     */
123
-    protected function escapedSqlPath(Certificate $certificate): string
124
-    {
125
-        return str_replace(array('\\', '%', '_'), array('\\\\', '\\%', '\\_'), $certificate->gedcomPath());
126
-    }
116
+	/**
117
+	 * Return an escaped string to be used in SQL LIKE comparisons.
118
+	 * This would not work well for Sqlite, if the escape character is not defined.
119
+	 *
120
+	 * @param Certificate $certificate
121
+	 * @return string
122
+	 */
123
+	protected function escapedSqlPath(Certificate $certificate): string
124
+	{
125
+		return str_replace(array('\\', '%', '_'), array('\\\\', '\\%', '\\_'), $certificate->gedcomPath());
126
+	}
127 127
 
128
-    /**
129
-     * Find a source linked to a citation where a certificate file is referenced.
130
-     *
131
-     * @param Certificate $certificate
132
-     * @return Source|NULL
133
-     */
134
-    public function oneLinkedSource(Certificate $certificate): ?Source
135
-    {
136
-        $regex_query = preg_quote($certificate->gedcomPath(), '/');
137
-        $regex_pattern = '/[1-9] SOUR @(' . Gedcom::REGEX_XREF . ')@(?:\n[2-9]\s(?:(?!SOUR)\w+)\s.*)*\n[2-9] _ACT ' . $regex_query . '/i'; //phpcs:ignore Generic.Files.LineLength.TooLong
128
+	/**
129
+	 * Find a source linked to a citation where a certificate file is referenced.
130
+	 *
131
+	 * @param Certificate $certificate
132
+	 * @return Source|NULL
133
+	 */
134
+	public function oneLinkedSource(Certificate $certificate): ?Source
135
+	{
136
+		$regex_query = preg_quote($certificate->gedcomPath(), '/');
137
+		$regex_pattern = '/[1-9] SOUR @(' . Gedcom::REGEX_XREF . ')@(?:\n[2-9]\s(?:(?!SOUR)\w+)\s.*)*\n[2-9] _ACT ' . $regex_query . '/i'; //phpcs:ignore Generic.Files.LineLength.TooLong
138 138
 
139
-        foreach ($this->linkedRecordsLists($certificate) as $linked_records) {
140
-            foreach ($linked_records as $gedcom_record) {
141
-                foreach ($gedcom_record->facts() as $fact) {
142
-                    if (preg_match_all($regex_pattern, $fact->gedcom(), $matches, PREG_SET_ORDER) >= 1) {
143
-                        foreach ($matches as $match) {
144
-                            $source = Registry::sourceFactory()->make($match[1], $certificate->tree());
145
-                            if ($source !== null && $source->canShowName()) {
146
-                                return $source;
147
-                            }
148
-                        }
149
-                    }
150
-                }
151
-            }
152
-        }
139
+		foreach ($this->linkedRecordsLists($certificate) as $linked_records) {
140
+			foreach ($linked_records as $gedcom_record) {
141
+				foreach ($gedcom_record->facts() as $fact) {
142
+					if (preg_match_all($regex_pattern, $fact->gedcom(), $matches, PREG_SET_ORDER) >= 1) {
143
+						foreach ($matches as $match) {
144
+							$source = Registry::sourceFactory()->make($match[1], $certificate->tree());
145
+							if ($source !== null && $source->canShowName()) {
146
+								return $source;
147
+							}
148
+						}
149
+					}
150
+				}
151
+			}
152
+		}
153 153
 
154
-        return null;
155
-    }
154
+		return null;
155
+	}
156 156
 
157
-    /**
158
-     * Yield lists of gedcom records linked to a certificate.
159
-     *
160
-     * @param Certificate $certificate
161
-     * @return Generator<int, Collection<GedcomRecord>, mixed, void>
162
-     * @psalm-suppress InvalidReturnType
163
-     */
164
-    protected function linkedRecordsLists(Certificate $certificate): Generator
165
-    {
166
-        yield $this->linkedIndividuals($certificate);
167
-        yield $this->linkedFamilies($certificate);
168
-        yield $this->linkedMedias($certificate);
169
-        yield $this->linkedNotes($certificate);
170
-    }
157
+	/**
158
+	 * Yield lists of gedcom records linked to a certificate.
159
+	 *
160
+	 * @param Certificate $certificate
161
+	 * @return Generator<int, Collection<GedcomRecord>, mixed, void>
162
+	 * @psalm-suppress InvalidReturnType
163
+	 */
164
+	protected function linkedRecordsLists(Certificate $certificate): Generator
165
+	{
166
+		yield $this->linkedIndividuals($certificate);
167
+		yield $this->linkedFamilies($certificate);
168
+		yield $this->linkedMedias($certificate);
169
+		yield $this->linkedNotes($certificate);
170
+	}
171 171
 }
Please login to merge, or discard this patch.
app/Module/Certificates/Services/UrlObfuscatorService.php 1 patch
Indentation   +116 added lines, -116 removed lines patch added patch discarded remove patch
@@ -23,120 +23,120 @@
 block discarded – undo
23 23
  */
24 24
 class UrlObfuscatorService
25 25
 {
26
-    /**
27
-     * @var string|null $encryption_key
28
-     */
29
-    private $encryption_key;
30
-
31
-
32
-    /**
33
-     * Return (and generate) the key to be used for the encryption step
34
-     *
35
-     * @return string Encryption key
36
-     */
37
-    protected function encryptionKey(): string
38
-    {
39
-        if ($this->encryption_key === null) {
40
-            /** @var ServerRequestInterface $request **/
41
-            $request = app(ServerRequestInterface::class);
42
-            $server_name = $request->getServerParams()['SERVER_NAME'] ?? '';
43
-            $server_software = $request->getServerParams()['SERVER_SOFTWARE'] ?? '';
44
-            $this->encryption_key = str_pad(md5(
45
-                $server_name !== '' && $server_software !== '' ?
46
-                $server_name . $server_software :
47
-                'STANDARDKEYIFNOSERVER'
48
-            ), SODIUM_CRYPTO_SECRETBOX_KEYBYTES, "1234567890ABCDEF");
49
-        }
50
-        return $this->encryption_key;
51
-    }
52
-
53
-    /**
54
-     * Obfuscate a clear text, with a combination of encryption and base64 encoding.
55
-     * The return string is URL-safe.
56
-     *
57
-     * @param string $cleartext Text to obfuscate
58
-     * @param string $key
59
-     * @param string $nonce
60
-     * @return string
61
-     */
62
-    public function obfuscate(string $cleartext, string $key = '', string $nonce = ''): string
63
-    {
64
-        if ($nonce === '') {
65
-            $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
66
-        }
67
-        if ($key === '') {
68
-            $key = $this->encryptionKey();
69
-        }
70
-
71
-        if (strlen($nonce) !== SODIUM_CRYPTO_SECRETBOX_NONCEBYTES) {
72
-            throw new InvalidArgumentException('The nonce needs to be SODIUM_CRYPTO_SECRETBOX_NONCEBYTES long');
73
-        }
74
-
75
-        if (strlen($key) !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
76
-            throw new InvalidArgumentException('The key needs to be SODIUM_CRYPTO_SECRETBOX_KEYBYTES long');
77
-        }
78
-
79
-        $encryted = sodium_crypto_secretbox($cleartext, $nonce, $key);
80
-        return strtr(base64_encode($nonce . $encryted), '+/=', '._-');
81
-    }
82
-
83
-    /**
84
-     * Deobfuscate a string from an URL to a clear text.
85
-     *
86
-     * @param string $obfuscated Text to deobfuscate
87
-     * @param string $key
88
-     * @throws InvalidArgumentException
89
-     * @return string
90
-     */
91
-    public function deobfuscate(string $obfuscated, string $key = ''): string
92
-    {
93
-        $obfuscated = strtr($obfuscated, '._-', '+/=');
94
-        if ($key === '') {
95
-            $key = $this->encryptionKey();
96
-        }
97
-
98
-        if (strlen($key) !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
99
-            throw new InvalidArgumentException('The key needs to be SODIUM_CRYPTO_SECRETBOX_KEYBYTES long');
100
-        }
101
-
102
-        $encrypted = base64_decode($obfuscated, true);
103
-        if ($encrypted === false) {
104
-            throw new InvalidArgumentException('The encrypted value is not in correct base64 format.');
105
-        }
106
-
107
-        if (mb_strlen($encrypted, '8bit') < (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES)) {
108
-            throw new InvalidArgumentException('The encrypted value does not contain enough characters for the key.');
109
-        }
110
-
111
-        $nonce = mb_substr($encrypted, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
112
-        $ciphertext = mb_substr($encrypted, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');
113
-
114
-        $decrypted = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
115
-
116
-        if ($decrypted === false) {
117
-            throw new InvalidArgumentException('The message has been tampered with in transit.');
118
-        }
119
-
120
-        //sodium_memzero($ciphertext);    // sodium_compat cannot handle it, only through libsodium
121
-
122
-        /** @var string $decrypted - Psalm detect as string|true otherwise */
123
-        return $decrypted;
124
-    }
125
-
126
-    /**
127
-     * Try to deobfuscate a string from an URL to a clear text, returning whether the operation is a success.
128
-     *
129
-     * @param string $obfuscated Text to deobfuscate
130
-     * @param string $key
131
-     * @return bool
132
-     */
133
-    public function tryDeobfuscate(string &$obfuscated, string $key = ''): bool
134
-    {
135
-        try {
136
-            $obfuscated = $this->deobfuscate($obfuscated, $key);
137
-            return true;
138
-        } catch (InvalidArgumentException $ex) {
139
-        }
140
-        return false;
141
-    }
26
+	/**
27
+	 * @var string|null $encryption_key
28
+	 */
29
+	private $encryption_key;
30
+
31
+
32
+	/**
33
+	 * Return (and generate) the key to be used for the encryption step
34
+	 *
35
+	 * @return string Encryption key
36
+	 */
37
+	protected function encryptionKey(): string
38
+	{
39
+		if ($this->encryption_key === null) {
40
+			/** @var ServerRequestInterface $request **/
41
+			$request = app(ServerRequestInterface::class);
42
+			$server_name = $request->getServerParams()['SERVER_NAME'] ?? '';
43
+			$server_software = $request->getServerParams()['SERVER_SOFTWARE'] ?? '';
44
+			$this->encryption_key = str_pad(md5(
45
+				$server_name !== '' && $server_software !== '' ?
46
+				$server_name . $server_software :
47
+				'STANDARDKEYIFNOSERVER'
48
+			), SODIUM_CRYPTO_SECRETBOX_KEYBYTES, "1234567890ABCDEF");
49
+		}
50
+		return $this->encryption_key;
51
+	}
52
+
53
+	/**
54
+	 * Obfuscate a clear text, with a combination of encryption and base64 encoding.
55
+	 * The return string is URL-safe.
56
+	 *
57
+	 * @param string $cleartext Text to obfuscate
58
+	 * @param string $key
59
+	 * @param string $nonce
60
+	 * @return string
61
+	 */
62
+	public function obfuscate(string $cleartext, string $key = '', string $nonce = ''): string
63
+	{
64
+		if ($nonce === '') {
65
+			$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
66
+		}
67
+		if ($key === '') {
68
+			$key = $this->encryptionKey();
69
+		}
70
+
71
+		if (strlen($nonce) !== SODIUM_CRYPTO_SECRETBOX_NONCEBYTES) {
72
+			throw new InvalidArgumentException('The nonce needs to be SODIUM_CRYPTO_SECRETBOX_NONCEBYTES long');
73
+		}
74
+
75
+		if (strlen($key) !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
76
+			throw new InvalidArgumentException('The key needs to be SODIUM_CRYPTO_SECRETBOX_KEYBYTES long');
77
+		}
78
+
79
+		$encryted = sodium_crypto_secretbox($cleartext, $nonce, $key);
80
+		return strtr(base64_encode($nonce . $encryted), '+/=', '._-');
81
+	}
82
+
83
+	/**
84
+	 * Deobfuscate a string from an URL to a clear text.
85
+	 *
86
+	 * @param string $obfuscated Text to deobfuscate
87
+	 * @param string $key
88
+	 * @throws InvalidArgumentException
89
+	 * @return string
90
+	 */
91
+	public function deobfuscate(string $obfuscated, string $key = ''): string
92
+	{
93
+		$obfuscated = strtr($obfuscated, '._-', '+/=');
94
+		if ($key === '') {
95
+			$key = $this->encryptionKey();
96
+		}
97
+
98
+		if (strlen($key) !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
99
+			throw new InvalidArgumentException('The key needs to be SODIUM_CRYPTO_SECRETBOX_KEYBYTES long');
100
+		}
101
+
102
+		$encrypted = base64_decode($obfuscated, true);
103
+		if ($encrypted === false) {
104
+			throw new InvalidArgumentException('The encrypted value is not in correct base64 format.');
105
+		}
106
+
107
+		if (mb_strlen($encrypted, '8bit') < (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES)) {
108
+			throw new InvalidArgumentException('The encrypted value does not contain enough characters for the key.');
109
+		}
110
+
111
+		$nonce = mb_substr($encrypted, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
112
+		$ciphertext = mb_substr($encrypted, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');
113
+
114
+		$decrypted = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
115
+
116
+		if ($decrypted === false) {
117
+			throw new InvalidArgumentException('The message has been tampered with in transit.');
118
+		}
119
+
120
+		//sodium_memzero($ciphertext);    // sodium_compat cannot handle it, only through libsodium
121
+
122
+		/** @var string $decrypted - Psalm detect as string|true otherwise */
123
+		return $decrypted;
124
+	}
125
+
126
+	/**
127
+	 * Try to deobfuscate a string from an URL to a clear text, returning whether the operation is a success.
128
+	 *
129
+	 * @param string $obfuscated Text to deobfuscate
130
+	 * @param string $key
131
+	 * @return bool
132
+	 */
133
+	public function tryDeobfuscate(string &$obfuscated, string $key = ''): bool
134
+	{
135
+		try {
136
+			$obfuscated = $this->deobfuscate($obfuscated, $key);
137
+			return true;
138
+		} catch (InvalidArgumentException $ex) {
139
+		}
140
+		return false;
141
+	}
142 142
 }
Please login to merge, or discard this patch.
app/Module/Certificates/Model/Certificate.php 1 patch
Indentation   +189 added lines, -189 removed lines patch added patch discarded remove patch
@@ -25,193 +25,193 @@
 block discarded – undo
25 25
  */
26 26
 class Certificate
27 27
 {
28
-    /**
29
-     * Pattern to extract information from a file name.
30
-     * Specific to the author's workflow.
31
-     * @var string
32
-     */
33
-    private const FILENAME_PATTERN = '/^(?<year>\d{1,4})(\.(?<month>\d{1,2}))?(\.(?<day>\d{1,2}))?( (?<type>[A-Z]{1,2}))?\s(?<descr>.*)/'; //phpcs:ignore Generic.Files.LineLength.TooLong
34
-
35
-    private Tree $tree;
36
-    private string $path;
37
-    private ?string $city = null;
38
-    private ?string $basename = null;
39
-    private ?string $filename = null;
40
-    private ?string $extension = null;
41
-    private ?string $type = null;
42
-    private ?string $description = null;
43
-    private ?Date $date = null;
44
-
45
-    /**
46
-     * Contructor for Certificate
47
-     *
48
-     * @param Tree $tree
49
-     * @param string $path
50
-     */
51
-    public function __construct(Tree $tree, string $path)
52
-    {
53
-        $this->tree = $tree;
54
-        $this->path = $path;
55
-        $this->extractDataFromPath($path);
56
-    }
57
-
58
-    /**
59
-     * Populate fields from the filename, based on a predeterminate pattern.
60
-     * Logic specific to the author.
61
-     *
62
-     * @param string $path
63
-     */
64
-    protected function extractDataFromPath(string $path): void
65
-    {
66
-        $path_parts = pathinfo($this->gedcomPath());
67
-        $this->city = $path_parts['dirname'];
68
-        $this->basename = $path_parts['basename'];
69
-        $this->filename = $path_parts['filename'];
70
-        $this->extension = strtoupper($path_parts['extension'] ?? '');
71
-
72
-        if (preg_match(self::FILENAME_PATTERN, $this->filename, $match) === 1) {
73
-            $this->type = $match['type'];
74
-            $this->description = $match['descr'];
75
-
76
-            $day = $match['day'] ?? '';
77
-            $month_date = DateTime::createFromFormat('m', $match['month'] ?? '');
78
-            $month = $month_date !== false ? strtoupper($month_date->format('M')) : '';
79
-            $year = $match['year'] ?? '';
80
-
81
-            $this->date = new Date(sprintf('%s %s %s', $day, $month, $year));
82
-        } else {
83
-            $this->description = $this->filename;
84
-        }
85
-    }
86
-
87
-    /**
88
-     * Get the family tree of the certificate
89
-     *
90
-     * @return Tree
91
-     */
92
-    public function tree(): Tree
93
-    {
94
-        return $this->tree;
95
-    }
96
-
97
-    /**
98
-     * Get the path of the certificate in the file system.
99
-     *
100
-     * @return string
101
-     */
102
-    public function path(): string
103
-    {
104
-        return $this->path;
105
-    }
106
-
107
-    /**
108
-     * The the path of the certificate, in a Gedcom canonical form.
109
-     *
110
-     * @return string
111
-     */
112
-    public function gedcomPath(): string
113
-    {
114
-        return str_replace('\\', '/', $this->path);
115
-    }
116
-
117
-    /**
118
-     * Get the certificate name.
119
-     *
120
-     * @return string
121
-     */
122
-    public function name(): string
123
-    {
124
-        return $this->filename ?? '';
125
-    }
126
-
127
-    /**
128
-     * Get the certificate file name.
129
-     *
130
-     * @return string
131
-     */
132
-    public function filename(): string
133
-    {
134
-        return $this->basename ?? '';
135
-    }
136
-
137
-    /**
138
-     * Get the certificate's city (the first level folder).
139
-     *
140
-     * @return string
141
-     */
142
-    public function city(): string
143
-    {
144
-        return $this->city ?? '';
145
-    }
146
-
147
-    /**
148
-     * Get the certificate's date. Extracted from the file name.
149
-     *
150
-     * @return Date
151
-     */
152
-    public function date(): Date
153
-    {
154
-        return $this->date ?? new Date('');
155
-    }
156
-
157
-    /**
158
-     * Get the certificate's type. Extracted from the file name.
159
-     *
160
-     * @return string
161
-     */
162
-    public function type(): string
163
-    {
164
-        return $this->type ?? '';
165
-    }
166
-
167
-    /**
168
-     * Get the certificate's description.  Extracted from the file name.
169
-     * @return string
170
-     */
171
-    public function description(): string
172
-    {
173
-        return $this->description ?? '';
174
-    }
175
-
176
-    /**
177
-     * Get the certificate's description to be used for sorting.
178
-     * This is based on surnames (at least 3 letters) found in the file name.
179
-     *
180
-     * @return string
181
-     */
182
-    public function sortDescription(): string
183
-    {
184
-        $sort_prefix = '';
185
-        if (preg_match_all('/\b([A-Z]{3,})\b/', $this->description(), $matches, PREG_SET_ORDER) >= 1) {
186
-            $sort_prefix = implode('_', array_map(function ($match) {
187
-                return $match[1];
188
-            }, $matches)) . '_';
189
-        }
190
-        return $sort_prefix . $this->description();
191
-    }
192
-
193
-    /**
194
-     * Get the certificate's MIME type.
195
-     *
196
-     * @return string
197
-     */
198
-    public function mimeType(): string
199
-    {
200
-        return Mime::TYPES[$this->extension] ?? Mime::DEFAULT_TYPE;
201
-    }
202
-
203
-    /**
204
-     * Get the base parameters to be used in url referencing the certificate.
205
-     *
206
-     * @param UrlObfuscatorService $url_obfuscator_service
207
-     * @return array{tree: string, cid: mixed}
208
-     */
209
-    public function urlParameters(UrlObfuscatorService $url_obfuscator_service = null): array
210
-    {
211
-        $url_obfuscator_service = $url_obfuscator_service ?? app(UrlObfuscatorService::class);
212
-        return [
213
-            'tree' => $this->tree->name(),
214
-            'cid' => $url_obfuscator_service->obfuscate($this->path)
215
-        ];
216
-    }
28
+	/**
29
+	 * Pattern to extract information from a file name.
30
+	 * Specific to the author's workflow.
31
+	 * @var string
32
+	 */
33
+	private const FILENAME_PATTERN = '/^(?<year>\d{1,4})(\.(?<month>\d{1,2}))?(\.(?<day>\d{1,2}))?( (?<type>[A-Z]{1,2}))?\s(?<descr>.*)/'; //phpcs:ignore Generic.Files.LineLength.TooLong
34
+
35
+	private Tree $tree;
36
+	private string $path;
37
+	private ?string $city = null;
38
+	private ?string $basename = null;
39
+	private ?string $filename = null;
40
+	private ?string $extension = null;
41
+	private ?string $type = null;
42
+	private ?string $description = null;
43
+	private ?Date $date = null;
44
+
45
+	/**
46
+	 * Contructor for Certificate
47
+	 *
48
+	 * @param Tree $tree
49
+	 * @param string $path
50
+	 */
51
+	public function __construct(Tree $tree, string $path)
52
+	{
53
+		$this->tree = $tree;
54
+		$this->path = $path;
55
+		$this->extractDataFromPath($path);
56
+	}
57
+
58
+	/**
59
+	 * Populate fields from the filename, based on a predeterminate pattern.
60
+	 * Logic specific to the author.
61
+	 *
62
+	 * @param string $path
63
+	 */
64
+	protected function extractDataFromPath(string $path): void
65
+	{
66
+		$path_parts = pathinfo($this->gedcomPath());
67
+		$this->city = $path_parts['dirname'];
68
+		$this->basename = $path_parts['basename'];
69
+		$this->filename = $path_parts['filename'];
70
+		$this->extension = strtoupper($path_parts['extension'] ?? '');
71
+
72
+		if (preg_match(self::FILENAME_PATTERN, $this->filename, $match) === 1) {
73
+			$this->type = $match['type'];
74
+			$this->description = $match['descr'];
75
+
76
+			$day = $match['day'] ?? '';
77
+			$month_date = DateTime::createFromFormat('m', $match['month'] ?? '');
78
+			$month = $month_date !== false ? strtoupper($month_date->format('M')) : '';
79
+			$year = $match['year'] ?? '';
80
+
81
+			$this->date = new Date(sprintf('%s %s %s', $day, $month, $year));
82
+		} else {
83
+			$this->description = $this->filename;
84
+		}
85
+	}
86
+
87
+	/**
88
+	 * Get the family tree of the certificate
89
+	 *
90
+	 * @return Tree
91
+	 */
92
+	public function tree(): Tree
93
+	{
94
+		return $this->tree;
95
+	}
96
+
97
+	/**
98
+	 * Get the path of the certificate in the file system.
99
+	 *
100
+	 * @return string
101
+	 */
102
+	public function path(): string
103
+	{
104
+		return $this->path;
105
+	}
106
+
107
+	/**
108
+	 * The the path of the certificate, in a Gedcom canonical form.
109
+	 *
110
+	 * @return string
111
+	 */
112
+	public function gedcomPath(): string
113
+	{
114
+		return str_replace('\\', '/', $this->path);
115
+	}
116
+
117
+	/**
118
+	 * Get the certificate name.
119
+	 *
120
+	 * @return string
121
+	 */
122
+	public function name(): string
123
+	{
124
+		return $this->filename ?? '';
125
+	}
126
+
127
+	/**
128
+	 * Get the certificate file name.
129
+	 *
130
+	 * @return string
131
+	 */
132
+	public function filename(): string
133
+	{
134
+		return $this->basename ?? '';
135
+	}
136
+
137
+	/**
138
+	 * Get the certificate's city (the first level folder).
139
+	 *
140
+	 * @return string
141
+	 */
142
+	public function city(): string
143
+	{
144
+		return $this->city ?? '';
145
+	}
146
+
147
+	/**
148
+	 * Get the certificate's date. Extracted from the file name.
149
+	 *
150
+	 * @return Date
151
+	 */
152
+	public function date(): Date
153
+	{
154
+		return $this->date ?? new Date('');
155
+	}
156
+
157
+	/**
158
+	 * Get the certificate's type. Extracted from the file name.
159
+	 *
160
+	 * @return string
161
+	 */
162
+	public function type(): string
163
+	{
164
+		return $this->type ?? '';
165
+	}
166
+
167
+	/**
168
+	 * Get the certificate's description.  Extracted from the file name.
169
+	 * @return string
170
+	 */
171
+	public function description(): string
172
+	{
173
+		return $this->description ?? '';
174
+	}
175
+
176
+	/**
177
+	 * Get the certificate's description to be used for sorting.
178
+	 * This is based on surnames (at least 3 letters) found in the file name.
179
+	 *
180
+	 * @return string
181
+	 */
182
+	public function sortDescription(): string
183
+	{
184
+		$sort_prefix = '';
185
+		if (preg_match_all('/\b([A-Z]{3,})\b/', $this->description(), $matches, PREG_SET_ORDER) >= 1) {
186
+			$sort_prefix = implode('_', array_map(function ($match) {
187
+				return $match[1];
188
+			}, $matches)) . '_';
189
+		}
190
+		return $sort_prefix . $this->description();
191
+	}
192
+
193
+	/**
194
+	 * Get the certificate's MIME type.
195
+	 *
196
+	 * @return string
197
+	 */
198
+	public function mimeType(): string
199
+	{
200
+		return Mime::TYPES[$this->extension] ?? Mime::DEFAULT_TYPE;
201
+	}
202
+
203
+	/**
204
+	 * Get the base parameters to be used in url referencing the certificate.
205
+	 *
206
+	 * @param UrlObfuscatorService $url_obfuscator_service
207
+	 * @return array{tree: string, cid: mixed}
208
+	 */
209
+	public function urlParameters(UrlObfuscatorService $url_obfuscator_service = null): array
210
+	{
211
+		$url_obfuscator_service = $url_obfuscator_service ?? app(UrlObfuscatorService::class);
212
+		return [
213
+			'tree' => $this->tree->name(),
214
+			'cid' => $url_obfuscator_service->obfuscate($this->path)
215
+		];
216
+	}
217 217
 }
Please login to merge, or discard this patch.
app/Module/Certificates/Model/Watermark.php 1 patch
Indentation   +108 added lines, -108 removed lines patch added patch discarded remove patch
@@ -19,112 +19,112 @@
 block discarded – undo
19 19
  */
20 20
 class Watermark
21 21
 {
22
-    /**
23
-     * Default font color for watermarks
24
-     * @var string DEFAULT_COLOR
25
-     * */
26
-    public const DEFAULT_COLOR = '#4D6DF3';
27
-
28
-    /**
29
-     * Default maximum font size for watermarks
30
-     * @var int DEFAULT_SIZE
31
-     * */
32
-    public const DEFAULT_SIZE = 18;
33
-
34
-    /**
35
-     * @var string $text
36
-     */
37
-    private $text;
38
-
39
-    /**
40
-     * @var string $color;
41
-     */
42
-    private $color;
43
-
44
-
45
-    /**
46
-     * @var int $size
47
-     */
48
-    private $size;
49
-
50
-    /**
51
-     * Constructor for Watermark data class
52
-     *
53
-     * @param string $text
54
-     * @param string $color
55
-     * @param int $size
56
-     */
57
-    public function __construct(string $text, string $color, int $size)
58
-    {
59
-        $this->text = $text;
60
-        $this->color = $color;
61
-        $this->size = $size;
62
-    }
63
-
64
-    /**
65
-     * Get the watermark text.
66
-     *
67
-     * @return string
68
-     */
69
-    public function text(): string
70
-    {
71
-        return $this->text;
72
-    }
73
-
74
-    /**
75
-     * Get the watermark font color.
76
-     *
77
-     * @return string
78
-     */
79
-    public function color(): string
80
-    {
81
-        return $this->color;
82
-    }
83
-
84
-    /**
85
-     * Get the watermark maximum font size.
86
-     * @return int
87
-     */
88
-    public function size(): int
89
-    {
90
-        return $this->size;
91
-    }
92
-
93
-    /**
94
-     * Return an estimate of the size in pixels of the watermark text length.
95
-     *
96
-     * @return int
97
-     */
98
-    public function textLengthEstimate(): int
99
-    {
100
-        return $this->stringLengthEstimate(mb_strlen($this->text), $this->size);
101
-    }
102
-
103
-    /**
104
-     * Decrease the font size if necessary, based on the image width.
105
-     *
106
-     * @param int $width
107
-     */
108
-    public function adjustSize(int $width): void
109
-    {
110
-        $len = mb_strlen($this->text);
111
-        while ($this->stringLengthEstimate($len, $this->size) > 0.9 * $width) {
112
-            $this->size--;
113
-            if ($this->size == 2) {
114
-                return;
115
-            }
116
-        }
117
-    }
118
-
119
-    /**
120
-     * Return an estimate of the size in pixels of a text in a specified font size.
121
-     *
122
-     * @param int $text_length
123
-     * @param int $font_size
124
-     * @return int
125
-     */
126
-    private function stringLengthEstimate(int $text_length, int $font_size): int
127
-    {
128
-        return $text_length * (int) ceil(($font_size + 2) * 0.5);
129
-    }
22
+	/**
23
+	 * Default font color for watermarks
24
+	 * @var string DEFAULT_COLOR
25
+	 * */
26
+	public const DEFAULT_COLOR = '#4D6DF3';
27
+
28
+	/**
29
+	 * Default maximum font size for watermarks
30
+	 * @var int DEFAULT_SIZE
31
+	 * */
32
+	public const DEFAULT_SIZE = 18;
33
+
34
+	/**
35
+	 * @var string $text
36
+	 */
37
+	private $text;
38
+
39
+	/**
40
+	 * @var string $color;
41
+	 */
42
+	private $color;
43
+
44
+
45
+	/**
46
+	 * @var int $size
47
+	 */
48
+	private $size;
49
+
50
+	/**
51
+	 * Constructor for Watermark data class
52
+	 *
53
+	 * @param string $text
54
+	 * @param string $color
55
+	 * @param int $size
56
+	 */
57
+	public function __construct(string $text, string $color, int $size)
58
+	{
59
+		$this->text = $text;
60
+		$this->color = $color;
61
+		$this->size = $size;
62
+	}
63
+
64
+	/**
65
+	 * Get the watermark text.
66
+	 *
67
+	 * @return string
68
+	 */
69
+	public function text(): string
70
+	{
71
+		return $this->text;
72
+	}
73
+
74
+	/**
75
+	 * Get the watermark font color.
76
+	 *
77
+	 * @return string
78
+	 */
79
+	public function color(): string
80
+	{
81
+		return $this->color;
82
+	}
83
+
84
+	/**
85
+	 * Get the watermark maximum font size.
86
+	 * @return int
87
+	 */
88
+	public function size(): int
89
+	{
90
+		return $this->size;
91
+	}
92
+
93
+	/**
94
+	 * Return an estimate of the size in pixels of the watermark text length.
95
+	 *
96
+	 * @return int
97
+	 */
98
+	public function textLengthEstimate(): int
99
+	{
100
+		return $this->stringLengthEstimate(mb_strlen($this->text), $this->size);
101
+	}
102
+
103
+	/**
104
+	 * Decrease the font size if necessary, based on the image width.
105
+	 *
106
+	 * @param int $width
107
+	 */
108
+	public function adjustSize(int $width): void
109
+	{
110
+		$len = mb_strlen($this->text);
111
+		while ($this->stringLengthEstimate($len, $this->size) > 0.9 * $width) {
112
+			$this->size--;
113
+			if ($this->size == 2) {
114
+				return;
115
+			}
116
+		}
117
+	}
118
+
119
+	/**
120
+	 * Return an estimate of the size in pixels of a text in a specified font size.
121
+	 *
122
+	 * @param int $text_length
123
+	 * @param int $font_size
124
+	 * @return int
125
+	 */
126
+	private function stringLengthEstimate(int $text_length, int $font_size): int
127
+	{
128
+		return $text_length * (int) ceil(($font_size + 2) * 0.5);
129
+	}
130 130
 }
Please login to merge, or discard this patch.