Passed
Branch feature/2.0 (be78a0)
by Jonathan
11:57
created
src/Webtrees/Module/WelcomeBlock/WelcomeBlockModule.php 1 patch
Indentation   +153 added lines, -153 removed lines patch added patch discarded remove patch
@@ -30,157 +30,157 @@
 block discarded – undo
30 30
  */
31 31
 class WelcomeBlockModule extends AbstractModuleMaj implements ModuleBlockInterface
32 32
 {
33
-    use ModuleBlockTrait;
34
-
35
-    /**
36
-     * {@inheritDoc}
37
-     * @see \Fisharebest\Webtrees\Module\AbstractModule::title()
38
-     */
39
-    public function title(): string
40
-    {
41
-        return /* I18N: Name of the “WelcomeBlock” module */ I18N::translate('MyArtJaub Welcome Block');
42
-    }
43
-
44
-    /**
45
-     * {@inheritDoc}
46
-     * @see \Fisharebest\Webtrees\Module\AbstractModule::description()
47
-     */
48
-    public function description(): string
49
-    {
50
-        //phpcs:ignore Generic.Files.LineLength.TooLong
51
-        return /* I18N: Description of the “WelcomeBlock” module */ I18N::translate('The MyArtJaub Welcome block welcomes the visitor to the site, allows a quick login to the site, and displays statistics on visits.');
52
-    }
53
-
54
-    /**
55
-     * {@inheritDoc}
56
-     * @see \MyArtJaub\Webtrees\Module\AbstractModuleMaj::loadRoutes()
57
-     */
58
-    public function loadRoutes(Map $router): void
59
-    {
60
-        $router->attach('', '', static function (Map $router): void {
61
-
62
-            $router->attach('', '/module-maj/welcomeblock/{block_id}', static function (Map $router): void {
63
-
64
-                $router->get(MatomoStats::class, '/matomostats', MatomoStats::class);
65
-            });
66
-        });
67
-    }
68
-
69
-    /**
70
-     * {@inheritDoc}
71
-     * @see \Fisharebest\Webtrees\Module\ModuleCustomInterface::customModuleVersion()
72
-     */
73
-    public function customModuleVersion(): string
74
-    {
75
-        return '2.0.6-v.1';
76
-    }
77
-
78
-    /**
79
-     * {@inheritDoc}
80
-     * @see \Fisharebest\Webtrees\Module\ModuleBlockInterface::getBlock()
81
-     */
82
-    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
83
-    {
84
-        $fab_welcome_block_view = app(\Fisharebest\Webtrees\Module\WelcomeBlockModule::class)
85
-            ->getBlock($tree, $block_id, ModuleBlockInterface::CONTEXT_EMBED);
86
-
87
-        $fab_login_block_view = app(\Fisharebest\Webtrees\Module\LoginBlockModule::class)
88
-            ->getBlock($tree, $block_id, ModuleBlockInterface::CONTEXT_EMBED);
89
-
90
-        $content = view($this->name() . '::block-embed', [
91
-            'block_id'                  =>  $block_id,
92
-            'fab_welcome_block_view'    =>  $fab_welcome_block_view,
93
-            'fab_login_block_view'      =>  $fab_login_block_view,
94
-            'matomo_enabled'            =>  $this->isMatomoEnabled($block_id)
95
-        ]);
96
-
97
-        if ($context !== self::CONTEXT_EMBED) {
98
-            return view('modules/block-template', [
99
-                'block'      => Str::kebab($this->name()),
100
-                'id'         => $block_id,
101
-                'config_url' => $this->configUrl($tree, $context, $block_id),
102
-                'title'      => $tree->title(),
103
-                'content'    => $content,
104
-            ]);
105
-        }
106
-
107
-        return $content;
108
-    }
109
-
110
-    /**
111
-     * {@inheritDoc}
112
-     * @see \Fisharebest\Webtrees\Module\ModuleBlockInterface::isTreeBlock()
113
-     */
114
-    public function isTreeBlock(): bool
115
-    {
116
-        return true;
117
-    }
118
-
119
-    /**
120
-     * {@inheritDoc}
121
-     * @see \Fisharebest\Webtrees\Module\ModuleBlockInterface::editBlockConfiguration()
122
-     */
123
-    public function editBlockConfiguration(Tree $tree, int $block_id): string
124
-    {
125
-        return view($this->name() . '::config', $this->matomoSettings($block_id));
126
-    }
127
-
128
-    /**
129
-     * {@inheritDoc}
130
-     * @see \Fisharebest\Webtrees\Module\ModuleBlockInterface::saveBlockConfiguration()
131
-     */
132
-    public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
133
-    {
134
-        $params = (array) $request->getParsedBody();
135
-
136
-        $matomo_enabled = $params['matomo_enabled'] == 'yes';
137
-        $this->setBlockSetting($block_id, 'matomo_enabled', $matomo_enabled ? 'yes' : 'no');
138
-        if (!$matomo_enabled) {
139
-            return;
140
-        }
141
-
142
-        if (filter_var($params['matomo_url'], FILTER_VALIDATE_URL) === false) {
143
-            FlashMessages::addMessage(I18N::translate('The Matomo URL provided is not valid.'), 'danger');
144
-            return;
145
-        }
146
-
147
-        if (filter_var($params['matomo_siteid'], FILTER_VALIDATE_INT) === false) {
148
-            FlashMessages::addMessage(I18N::translate('The Matomo Site ID provided is not valid.'), 'danger');
149
-            return;
150
-        }
151
-
152
-        $this
153
-            ->setBlockSetting($block_id, 'matomo_url', trim($params['matomo_url']))
154
-            ->setBlockSetting($block_id, 'matomo_token', trim($params['matomo_token']))
155
-            ->setBlockSetting($block_id, 'matomo_siteid', $params['matomo_siteid']);
156
-
157
-        app('cache.files')->forget($this->name() . '-matomovisits-yearly-' . $block_id);
158
-    }
159
-
160
-    /**
161
-     * Returns whether Matomo statistics is enabled for a specific MyArtJaub WelcomeBlock block
162
-     *
163
-     * @param int $block_id
164
-     * @return bool
165
-     */
166
-    public function isMatomoEnabled(int $block_id): bool
167
-    {
168
-        return $this->getBlockSetting($block_id, 'matomo_enabled', 'no') === 'yes';
169
-    }
170
-
171
-    /**
172
-     * Returns settings for retrieving Matomo statistics for a specific MyArtJaub WelcomeBlock block
173
-     *
174
-     * @param int $block_id
175
-     * @return array<string, mixed>
176
-     */
177
-    public function matomoSettings(int $block_id): array
178
-    {
179
-        return [
180
-            'matomo_enabled' => $this->isMatomoEnabled($block_id),
181
-            'matomo_url' => $this->getBlockSetting($block_id, 'matomo_url'),
182
-            'matomo_token' => $this->getBlockSetting($block_id, 'matomo_token'),
183
-            'matomo_siteid'  => (int) $this->getBlockSetting($block_id, 'matomo_siteid', '0')
184
-        ];
185
-    }
33
+	use ModuleBlockTrait;
34
+
35
+	/**
36
+	 * {@inheritDoc}
37
+	 * @see \Fisharebest\Webtrees\Module\AbstractModule::title()
38
+	 */
39
+	public function title(): string
40
+	{
41
+		return /* I18N: Name of the “WelcomeBlock” module */ I18N::translate('MyArtJaub Welcome Block');
42
+	}
43
+
44
+	/**
45
+	 * {@inheritDoc}
46
+	 * @see \Fisharebest\Webtrees\Module\AbstractModule::description()
47
+	 */
48
+	public function description(): string
49
+	{
50
+		//phpcs:ignore Generic.Files.LineLength.TooLong
51
+		return /* I18N: Description of the “WelcomeBlock” module */ I18N::translate('The MyArtJaub Welcome block welcomes the visitor to the site, allows a quick login to the site, and displays statistics on visits.');
52
+	}
53
+
54
+	/**
55
+	 * {@inheritDoc}
56
+	 * @see \MyArtJaub\Webtrees\Module\AbstractModuleMaj::loadRoutes()
57
+	 */
58
+	public function loadRoutes(Map $router): void
59
+	{
60
+		$router->attach('', '', static function (Map $router): void {
61
+
62
+			$router->attach('', '/module-maj/welcomeblock/{block_id}', static function (Map $router): void {
63
+
64
+				$router->get(MatomoStats::class, '/matomostats', MatomoStats::class);
65
+			});
66
+		});
67
+	}
68
+
69
+	/**
70
+	 * {@inheritDoc}
71
+	 * @see \Fisharebest\Webtrees\Module\ModuleCustomInterface::customModuleVersion()
72
+	 */
73
+	public function customModuleVersion(): string
74
+	{
75
+		return '2.0.6-v.1';
76
+	}
77
+
78
+	/**
79
+	 * {@inheritDoc}
80
+	 * @see \Fisharebest\Webtrees\Module\ModuleBlockInterface::getBlock()
81
+	 */
82
+	public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
83
+	{
84
+		$fab_welcome_block_view = app(\Fisharebest\Webtrees\Module\WelcomeBlockModule::class)
85
+			->getBlock($tree, $block_id, ModuleBlockInterface::CONTEXT_EMBED);
86
+
87
+		$fab_login_block_view = app(\Fisharebest\Webtrees\Module\LoginBlockModule::class)
88
+			->getBlock($tree, $block_id, ModuleBlockInterface::CONTEXT_EMBED);
89
+
90
+		$content = view($this->name() . '::block-embed', [
91
+			'block_id'                  =>  $block_id,
92
+			'fab_welcome_block_view'    =>  $fab_welcome_block_view,
93
+			'fab_login_block_view'      =>  $fab_login_block_view,
94
+			'matomo_enabled'            =>  $this->isMatomoEnabled($block_id)
95
+		]);
96
+
97
+		if ($context !== self::CONTEXT_EMBED) {
98
+			return view('modules/block-template', [
99
+				'block'      => Str::kebab($this->name()),
100
+				'id'         => $block_id,
101
+				'config_url' => $this->configUrl($tree, $context, $block_id),
102
+				'title'      => $tree->title(),
103
+				'content'    => $content,
104
+			]);
105
+		}
106
+
107
+		return $content;
108
+	}
109
+
110
+	/**
111
+	 * {@inheritDoc}
112
+	 * @see \Fisharebest\Webtrees\Module\ModuleBlockInterface::isTreeBlock()
113
+	 */
114
+	public function isTreeBlock(): bool
115
+	{
116
+		return true;
117
+	}
118
+
119
+	/**
120
+	 * {@inheritDoc}
121
+	 * @see \Fisharebest\Webtrees\Module\ModuleBlockInterface::editBlockConfiguration()
122
+	 */
123
+	public function editBlockConfiguration(Tree $tree, int $block_id): string
124
+	{
125
+		return view($this->name() . '::config', $this->matomoSettings($block_id));
126
+	}
127
+
128
+	/**
129
+	 * {@inheritDoc}
130
+	 * @see \Fisharebest\Webtrees\Module\ModuleBlockInterface::saveBlockConfiguration()
131
+	 */
132
+	public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
133
+	{
134
+		$params = (array) $request->getParsedBody();
135
+
136
+		$matomo_enabled = $params['matomo_enabled'] == 'yes';
137
+		$this->setBlockSetting($block_id, 'matomo_enabled', $matomo_enabled ? 'yes' : 'no');
138
+		if (!$matomo_enabled) {
139
+			return;
140
+		}
141
+
142
+		if (filter_var($params['matomo_url'], FILTER_VALIDATE_URL) === false) {
143
+			FlashMessages::addMessage(I18N::translate('The Matomo URL provided is not valid.'), 'danger');
144
+			return;
145
+		}
146
+
147
+		if (filter_var($params['matomo_siteid'], FILTER_VALIDATE_INT) === false) {
148
+			FlashMessages::addMessage(I18N::translate('The Matomo Site ID provided is not valid.'), 'danger');
149
+			return;
150
+		}
151
+
152
+		$this
153
+			->setBlockSetting($block_id, 'matomo_url', trim($params['matomo_url']))
154
+			->setBlockSetting($block_id, 'matomo_token', trim($params['matomo_token']))
155
+			->setBlockSetting($block_id, 'matomo_siteid', $params['matomo_siteid']);
156
+
157
+		app('cache.files')->forget($this->name() . '-matomovisits-yearly-' . $block_id);
158
+	}
159
+
160
+	/**
161
+	 * Returns whether Matomo statistics is enabled for a specific MyArtJaub WelcomeBlock block
162
+	 *
163
+	 * @param int $block_id
164
+	 * @return bool
165
+	 */
166
+	public function isMatomoEnabled(int $block_id): bool
167
+	{
168
+		return $this->getBlockSetting($block_id, 'matomo_enabled', 'no') === 'yes';
169
+	}
170
+
171
+	/**
172
+	 * Returns settings for retrieving Matomo statistics for a specific MyArtJaub WelcomeBlock block
173
+	 *
174
+	 * @param int $block_id
175
+	 * @return array<string, mixed>
176
+	 */
177
+	public function matomoSettings(int $block_id): array
178
+	{
179
+		return [
180
+			'matomo_enabled' => $this->isMatomoEnabled($block_id),
181
+			'matomo_url' => $this->getBlockSetting($block_id, 'matomo_url'),
182
+			'matomo_token' => $this->getBlockSetting($block_id, 'matomo_token'),
183
+			'matomo_siteid'  => (int) $this->getBlockSetting($block_id, 'matomo_siteid', '0')
184
+		];
185
+	}
186 186
 }
Please login to merge, or discard this patch.
src/Webtrees/Module/WelcomeBlock/Services/MatomoStatsService.php 1 patch
Indentation   +83 added lines, -83 removed lines patch added patch discarded remove patch
@@ -30,95 +30,95 @@
 block discarded – undo
30 30
 class MatomoStatsService
31 31
 {
32 32
 
33
-    /**
34
-     * Returns the number of visits for the current year (up to the day before).
35
-     * That statistic is cached for the day, to avoid unecessary calls to Matomo API.
36
-     *
37
-     * @param WelcomeBlockModule $module
38
-     * @param int $block_id
39
-     * @return int|NULL
40
-     */
41
-    public function visitsThisYear(WelcomeBlockModule $module, int $block_id): ?int
42
-    {
43
-        $cache = Registry::cache()->file();
33
+	/**
34
+	 * Returns the number of visits for the current year (up to the day before).
35
+	 * That statistic is cached for the day, to avoid unecessary calls to Matomo API.
36
+	 *
37
+	 * @param WelcomeBlockModule $module
38
+	 * @param int $block_id
39
+	 * @return int|NULL
40
+	 */
41
+	public function visitsThisYear(WelcomeBlockModule $module, int $block_id): ?int
42
+	{
43
+		$cache = Registry::cache()->file();
44 44
 
45
-        return $cache->remember(
46
-            $module->name() . '-matomovisits-yearly-' . $block_id,
47
-            function () use ($module, $block_id): ?int {
48
-                $visits_year = $this->visits($module, $block_id, 'year');
49
-                if ($visits_year === null) {
50
-                    return null;
51
-                }
52
-                $visits_today = (int) $this->visits($module, $block_id, 'day');
45
+		return $cache->remember(
46
+			$module->name() . '-matomovisits-yearly-' . $block_id,
47
+			function () use ($module, $block_id): ?int {
48
+				$visits_year = $this->visits($module, $block_id, 'year');
49
+				if ($visits_year === null) {
50
+					return null;
51
+				}
52
+				$visits_today = (int) $this->visits($module, $block_id, 'day');
53 53
 
54
-                return $visits_year - $visits_today;
55
-            },
56
-            Carbon::now()->addDay()->startOfDay()->diffInSeconds(Carbon::now()) // Valid until midnight
57
-        );
58
-    }
54
+				return $visits_year - $visits_today;
55
+			},
56
+			Carbon::now()->addDay()->startOfDay()->diffInSeconds(Carbon::now()) // Valid until midnight
57
+		);
58
+	}
59 59
 
60
-    /**
61
-     * Returns the number of visits for the current day.
62
-     *
63
-     * @param WelcomeBlockModule $module
64
-     * @param int $block_id
65
-     * @return int|NULL
66
-     */
67
-    public function visitsToday(WelcomeBlockModule $module, int $block_id): ?int
68
-    {
69
-        return app('cache.array')->remember(
70
-            $module->name() . '-matomovisits-daily-' . $block_id,
71
-            function () use ($module, $block_id): ?int {
72
-                return $this->visits($module, $block_id, 'day');
73
-            }
74
-        );
75
-    }
60
+	/**
61
+	 * Returns the number of visits for the current day.
62
+	 *
63
+	 * @param WelcomeBlockModule $module
64
+	 * @param int $block_id
65
+	 * @return int|NULL
66
+	 */
67
+	public function visitsToday(WelcomeBlockModule $module, int $block_id): ?int
68
+	{
69
+		return app('cache.array')->remember(
70
+			$module->name() . '-matomovisits-daily-' . $block_id,
71
+			function () use ($module, $block_id): ?int {
72
+				return $this->visits($module, $block_id, 'day');
73
+			}
74
+		);
75
+	}
76 76
 
77
-    /**
78
-     * Invoke the Matomo API to retrieve the number of visits over a period.
79
-     *
80
-     * @param WelcomeBlockModule $module
81
-     * @param int $block_id
82
-     * @param string $period
83
-     * @return int|NULL
84
-     */
85
-    protected function visits(WelcomeBlockModule $module, int $block_id, string $period): ?int
86
-    {
87
-        $settings = $module->matomoSettings($block_id);
77
+	/**
78
+	 * Invoke the Matomo API to retrieve the number of visits over a period.
79
+	 *
80
+	 * @param WelcomeBlockModule $module
81
+	 * @param int $block_id
82
+	 * @param string $period
83
+	 * @return int|NULL
84
+	 */
85
+	protected function visits(WelcomeBlockModule $module, int $block_id, string $period): ?int
86
+	{
87
+		$settings = $module->matomoSettings($block_id);
88 88
 
89
-        if (
90
-            $settings['matomo_enabled'] === true
91
-            && mb_strlen($settings['matomo_url']) > 0
92
-            && mb_strlen($settings['matomo_token']) > 0
93
-            && $settings['matomo_siteid'] > 0
94
-        ) {
95
-            try {
96
-                $http_client = new Client([
97
-                    RequestOptions::TIMEOUT => 30
98
-                ]);
89
+		if (
90
+			$settings['matomo_enabled'] === true
91
+			&& mb_strlen($settings['matomo_url']) > 0
92
+			&& mb_strlen($settings['matomo_token']) > 0
93
+			&& $settings['matomo_siteid'] > 0
94
+		) {
95
+			try {
96
+				$http_client = new Client([
97
+					RequestOptions::TIMEOUT => 30
98
+				]);
99 99
 
100
-                $response = $http_client->get($settings['matomo_url'], [
101
-                    'query' =>  [
102
-                        'module'    =>  'API',
103
-                        'method'    =>  'VisitsSummary.getVisits',
104
-                        'idSite'    =>  $settings['matomo_siteid'],
105
-                        'period'    =>  $period,
106
-                        'date'      =>  'today',
107
-                        'token_auth' =>  $settings['matomo_token'],
108
-                        'format'    =>  'json'
109
-                    ]
110
-                ]);
100
+				$response = $http_client->get($settings['matomo_url'], [
101
+					'query' =>  [
102
+						'module'    =>  'API',
103
+						'method'    =>  'VisitsSummary.getVisits',
104
+						'idSite'    =>  $settings['matomo_siteid'],
105
+						'period'    =>  $period,
106
+						'date'      =>  'today',
107
+						'token_auth' =>  $settings['matomo_token'],
108
+						'format'    =>  'json'
109
+					]
110
+				]);
111 111
 
112
-                if ($response->getStatusCode() === StatusCodeInterface::STATUS_OK) {
113
-                    $result = json_decode((string) $response->getBody(), true)['value'] ?? null;
114
-                    if ($result !== null) {
115
-                        return (int)$result;
116
-                    }
117
-                }
118
-            } catch (RequestException $ex) {
119
-            }
120
-        }
112
+				if ($response->getStatusCode() === StatusCodeInterface::STATUS_OK) {
113
+					$result = json_decode((string) $response->getBody(), true)['value'] ?? null;
114
+					if ($result !== null) {
115
+						return (int)$result;
116
+					}
117
+				}
118
+			} catch (RequestException $ex) {
119
+			}
120
+		}
121 121
 
122
-        return null;
123
-    }
122
+		return null;
123
+	}
124 124
 }
Please login to merge, or discard this patch.
src/Webtrees/Module/AdminTasks/AdminTasksModule.php 1 patch
Indentation   +118 added lines, -118 removed lines patch added patch discarded remove patch
@@ -40,123 +40,123 @@
 block discarded – undo
40 40
  * Allow for tasks to be run on a (nearly-)regular schedule
41 41
  */
42 42
 class AdminTasksModule extends AbstractModuleMaj implements
43
-    ModuleCustomInterface,
44
-    ModuleConfigInterface,
45
-    ModuleGlobalInterface,
46
-    ModuleTasksProviderInterface
43
+	ModuleCustomInterface,
44
+	ModuleConfigInterface,
45
+	ModuleGlobalInterface,
46
+	ModuleTasksProviderInterface
47 47
 {
48
-    use ModuleConfigTrait;
49
-    use ModuleGlobalTrait;
50
-
51
-    //How to update the database schema for this module
52
-    private const SCHEMA_TARGET_VERSION   = 2;
53
-    private const SCHEMA_SETTING_NAME     = 'MAJ_ADMTASKS_SCHEMA_VERSION';
54
-    private const SCHEMA_MIGRATION_PREFIX = __NAMESPACE__ . '\Schema';
55
-
56
-    /**
57
-     * {@inheritDoc}
58
-     * @see \Fisharebest\Webtrees\Module\AbstractModule::title()
59
-     */
60
-    public function title(): string
61
-    {
62
-        return I18N::translate('Administration Tasks');
63
-    }
64
-
65
-    /**
66
-     * {@inheritDoc}
67
-     * @see \Fisharebest\Webtrees\Module\AbstractModule::description()
68
-     */
69
-    public function description(): string
70
-    {
71
-        return I18N::translate('Manage and run nearly-scheduled administration tasks.');
72
-    }
73
-
74
-    /**
75
-     * {@inheritDoc}
76
-     * @see \MyArtJaub\Webtrees\Module\AbstractModuleMaj::boot()
77
-     */
78
-    public function boot(): void
79
-    {
80
-        parent::boot();
81
-        app(MigrationService::class)->updateSchema(
82
-            self::SCHEMA_MIGRATION_PREFIX,
83
-            self::SCHEMA_SETTING_NAME,
84
-            self::SCHEMA_TARGET_VERSION
85
-        );
86
-    }
87
-
88
-    /**
89
-     * {@inheritDoc}
90
-     * @see \MyArtJaub\Webtrees\Module\AbstractModuleMaj::loadRoutes()
91
-     */
92
-    public function loadRoutes(Map $router): void
93
-    {
94
-        $router->attach('', '', static function (Map $router): void {
95
-
96
-            $router->attach('', '/module-maj/admintasks', static function (Map $router): void {
97
-
98
-                $router->attach('', '/admin', static function (Map $router): void {
99
-
100
-                    $router->extras([
101
-                        'middleware' => [
102
-                            AuthAdministrator::class,
103
-                        ],
104
-                    ]);
105
-                    $router->get(AdminConfigPage::class, '/config', AdminConfigPage::class);
106
-
107
-                    $router->attach('', '/tasks', static function (Map $router): void {
108
-
109
-                        $router->get(TasksList::class, '', TasksList::class);
110
-                        $router->get(TaskEditPage::class, '/{task}', TaskEditPage::class);
111
-                        $router->post(TaskEditAction::class, '/{task}', TaskEditAction::class);
112
-                        $router->get(TaskStatusAction::class, '/{task}/status/{enable}', TaskStatusAction::class);
113
-                    });
114
-                });
115
-
116
-                $router->get(TaskTrigger::class, '/trigger{/task}', TaskTrigger::class)
117
-                    ->allows(RequestMethodInterface::METHOD_POST);
118
-
119
-                $router->post(TokenGenerate::class, '/token', TokenGenerate::class)
120
-                    ->extras(['middleware' => [AuthAdministrator::class]]);
121
-            });
122
-        });
123
-    }
124
-
125
-    /**
126
-     * {@inheritDoc}
127
-     * @see \Fisharebest\Webtrees\Module\ModuleCustomInterface::customModuleLatestVersion()
128
-     */
129
-    public function customModuleVersion(): string
130
-    {
131
-        return '2.0.5-v.1';
132
-    }
133
-
134
-    /**
135
-     * {@inheritDoc}
136
-     * @see \Fisharebest\Webtrees\Module\ModuleConfigInterface::getConfigLink()
137
-     */
138
-    public function getConfigLink(): string
139
-    {
140
-        return route(AdminConfigPage::class);
141
-    }
142
-
143
-    /**
144
-     * {@inheritDoc}
145
-     * @see \Fisharebest\Webtrees\Module\ModuleGlobalInterface::bodyContent()
146
-     */
147
-    public function bodyContent(): string
148
-    {
149
-        return view($this->name() . '::snippet', [ 'url' => route(TaskTrigger::class) ]);
150
-    }
151
-
152
-    /**
153
-     * {@inheritDoc}
154
-     * @see \MyArtJaub\Webtrees\Module\AdminTasks\Contracts\ModuleTasksProviderInterface::listTasks()
155
-     */
156
-    public function listTasks(): array
157
-    {
158
-        return [
159
-            'maj-healthcheck' => HealthCheckEmailTask::class
160
-        ];
161
-    }
48
+	use ModuleConfigTrait;
49
+	use ModuleGlobalTrait;
50
+
51
+	//How to update the database schema for this module
52
+	private const SCHEMA_TARGET_VERSION   = 2;
53
+	private const SCHEMA_SETTING_NAME     = 'MAJ_ADMTASKS_SCHEMA_VERSION';
54
+	private const SCHEMA_MIGRATION_PREFIX = __NAMESPACE__ . '\Schema';
55
+
56
+	/**
57
+	 * {@inheritDoc}
58
+	 * @see \Fisharebest\Webtrees\Module\AbstractModule::title()
59
+	 */
60
+	public function title(): string
61
+	{
62
+		return I18N::translate('Administration Tasks');
63
+	}
64
+
65
+	/**
66
+	 * {@inheritDoc}
67
+	 * @see \Fisharebest\Webtrees\Module\AbstractModule::description()
68
+	 */
69
+	public function description(): string
70
+	{
71
+		return I18N::translate('Manage and run nearly-scheduled administration tasks.');
72
+	}
73
+
74
+	/**
75
+	 * {@inheritDoc}
76
+	 * @see \MyArtJaub\Webtrees\Module\AbstractModuleMaj::boot()
77
+	 */
78
+	public function boot(): void
79
+	{
80
+		parent::boot();
81
+		app(MigrationService::class)->updateSchema(
82
+			self::SCHEMA_MIGRATION_PREFIX,
83
+			self::SCHEMA_SETTING_NAME,
84
+			self::SCHEMA_TARGET_VERSION
85
+		);
86
+	}
87
+
88
+	/**
89
+	 * {@inheritDoc}
90
+	 * @see \MyArtJaub\Webtrees\Module\AbstractModuleMaj::loadRoutes()
91
+	 */
92
+	public function loadRoutes(Map $router): void
93
+	{
94
+		$router->attach('', '', static function (Map $router): void {
95
+
96
+			$router->attach('', '/module-maj/admintasks', static function (Map $router): void {
97
+
98
+				$router->attach('', '/admin', static function (Map $router): void {
99
+
100
+					$router->extras([
101
+						'middleware' => [
102
+							AuthAdministrator::class,
103
+						],
104
+					]);
105
+					$router->get(AdminConfigPage::class, '/config', AdminConfigPage::class);
106
+
107
+					$router->attach('', '/tasks', static function (Map $router): void {
108
+
109
+						$router->get(TasksList::class, '', TasksList::class);
110
+						$router->get(TaskEditPage::class, '/{task}', TaskEditPage::class);
111
+						$router->post(TaskEditAction::class, '/{task}', TaskEditAction::class);
112
+						$router->get(TaskStatusAction::class, '/{task}/status/{enable}', TaskStatusAction::class);
113
+					});
114
+				});
115
+
116
+				$router->get(TaskTrigger::class, '/trigger{/task}', TaskTrigger::class)
117
+					->allows(RequestMethodInterface::METHOD_POST);
118
+
119
+				$router->post(TokenGenerate::class, '/token', TokenGenerate::class)
120
+					->extras(['middleware' => [AuthAdministrator::class]]);
121
+			});
122
+		});
123
+	}
124
+
125
+	/**
126
+	 * {@inheritDoc}
127
+	 * @see \Fisharebest\Webtrees\Module\ModuleCustomInterface::customModuleLatestVersion()
128
+	 */
129
+	public function customModuleVersion(): string
130
+	{
131
+		return '2.0.5-v.1';
132
+	}
133
+
134
+	/**
135
+	 * {@inheritDoc}
136
+	 * @see \Fisharebest\Webtrees\Module\ModuleConfigInterface::getConfigLink()
137
+	 */
138
+	public function getConfigLink(): string
139
+	{
140
+		return route(AdminConfigPage::class);
141
+	}
142
+
143
+	/**
144
+	 * {@inheritDoc}
145
+	 * @see \Fisharebest\Webtrees\Module\ModuleGlobalInterface::bodyContent()
146
+	 */
147
+	public function bodyContent(): string
148
+	{
149
+		return view($this->name() . '::snippet', [ 'url' => route(TaskTrigger::class) ]);
150
+	}
151
+
152
+	/**
153
+	 * {@inheritDoc}
154
+	 * @see \MyArtJaub\Webtrees\Module\AdminTasks\Contracts\ModuleTasksProviderInterface::listTasks()
155
+	 */
156
+	public function listTasks(): array
157
+	{
158
+		return [
159
+			'maj-healthcheck' => HealthCheckEmailTask::class
160
+		];
161
+	}
162 162
 }
Please login to merge, or discard this patch.
src/Webtrees/Module/AdminTasks/Model/TaskSchedule.php 1 patch
Indentation   +286 added lines, -286 removed lines patch added patch discarded remove patch
@@ -25,290 +25,290 @@
 block discarded – undo
25 25
 class TaskSchedule
26 26
 {
27 27
 
28
-    /**
29
-     * Task Schedule ID
30
-     * @var int $id
31
-     */
32
-    private $id;
33
-
34
-    /**
35
-     * Task schedule status
36
-     * @var bool $enabled
37
-     */
38
-    private $enabled;
39
-
40
-    /**
41
-     * ID of the task attached to schedule
42
-     * @var string $task_id
43
-     */
44
-    private $task_id;
45
-
46
-    /**
47
-     * Last updated date
48
-     * @var Carbon $last_run
49
-     */
50
-    private $last_run;
51
-
52
-    /**
53
-     * Last run result
54
-     * @var bool $last_result
55
-     */
56
-    private $last_result;
57
-
58
-    /**
59
-     * Task run frequency
60
-     * @var CarbonInterval $frequency
61
-     */
62
-    private $frequency;
63
-
64
-    /**
65
-     * Task remaining runs
66
-     * @var int $nb_occurrences
67
-     */
68
-    private $nb_occurrences;
69
-
70
-    /**
71
-     * Current running status of the task
72
-     * @var bool $is_running
73
-     */
74
-    private $is_running;
75
-
76
-    /**
77
-     * Constructor for TaskSchedule
78
-     *
79
-     * @param int $id Schedule ID
80
-     * @param string $task_id Task ID
81
-     * @param bool $enabled Is the schedule enabled
82
-     * @param Carbon $last_run Last successful run date/time
83
-     * @param bool $last_result Result of the last run
84
-     * @param CarbonInterval $frequency Schedule frequency
85
-     * @param int $nb_occurrences Number of remaining occurrences to be run
86
-     * @param bool $is_running Is the task currently running
87
-     */
88
-    public function __construct(
89
-        int $id,
90
-        string $task_id,
91
-        bool $enabled,
92
-        Carbon $last_run,
93
-        bool $last_result,
94
-        CarbonInterval $frequency,
95
-        int $nb_occurrences,
96
-        bool $is_running
97
-    ) {
98
-        $this->id = $id;
99
-        $this->task_id = $task_id;
100
-        $this->enabled = $enabled;
101
-        $this->last_run = $last_run;
102
-        $this->last_result = $last_result;
103
-        $this->frequency = $frequency;
104
-        $this->nb_occurrences = $nb_occurrences;
105
-        $this->is_running = $is_running;
106
-    }
107
-
108
-    /**
109
-     * Get the schedule ID.
110
-     *
111
-     * @return int
112
-     */
113
-    public function id(): int
114
-    {
115
-        return $this->id;
116
-    }
117
-
118
-    /**
119
-     * Get the task ID.
120
-     *
121
-     * @return string
122
-     */
123
-    public function taskId(): string
124
-    {
125
-        return $this->task_id;
126
-    }
127
-
128
-    /**
129
-     * Returns whether the schedule is enabled
130
-     *
131
-     * @return bool
132
-     */
133
-    public function isEnabled(): bool
134
-    {
135
-        return $this->enabled;
136
-    }
137
-
138
-    /**
139
-     * Enable the schedule
140
-     *
141
-     * @return self
142
-     */
143
-    public function enable(): self
144
-    {
145
-        $this->enabled = true;
146
-        return $this;
147
-    }
148
-
149
-    /**
150
-     * Disable the schedule
151
-     *
152
-     * @return self
153
-     */
154
-    public function disable(): self
155
-    {
156
-        $this->enabled = false;
157
-        return $this;
158
-    }
159
-
160
-    /**
161
-     * Get the frequency of the schedule
162
-     *
163
-     * @return CarbonInterval
164
-     */
165
-    public function frequency(): CarbonInterval
166
-    {
167
-        return $this->frequency;
168
-    }
169
-
170
-    /**
171
-     * Set the frequency of the schedule
172
-     *
173
-     * @param CarbonInterval $frequency
174
-     * @return self
175
-     */
176
-    public function setFrequency(CarbonInterval $frequency): self
177
-    {
178
-        $this->frequency = $frequency;
179
-        return $this;
180
-    }
181
-
182
-    /**
183
-     * Get the date/time of the last successful run.
184
-     *
185
-     * @return Carbon
186
-     */
187
-    public function lastRunTime(): Carbon
188
-    {
189
-        return $this->last_run;
190
-    }
191
-
192
-    /**
193
-     * Set the last successful run date/time
194
-     *
195
-     * @param Carbon $last_run
196
-     * @return self
197
-     */
198
-    public function setLastRunTime(Carbon $last_run): self
199
-    {
200
-        $this->last_run = $last_run;
201
-        return $this;
202
-    }
203
-
204
-    /**
205
-     * Returns whether the last run was successful
206
-     *
207
-     * @return bool
208
-     */
209
-    public function wasLastRunSuccess(): bool
210
-    {
211
-        return $this->last_result;
212
-    }
213
-
214
-    /**
215
-     * Set the last run result
216
-     *
217
-     * @param bool $last_result
218
-     * @return self
219
-     */
220
-    public function setLastResult(bool $last_result): self
221
-    {
222
-        $this->last_result = $last_result;
223
-        return $this;
224
-    }
225
-
226
-    /**
227
-     * Get the number of remaining of occurrences of task runs.
228
-     * Returns 0 if the tasks must be run indefinitely.
229
-     *
230
-     * @return int
231
-     */
232
-    public function remainingOccurences(): int
233
-    {
234
-        return $this->nb_occurrences;
235
-    }
236
-
237
-    /**
238
-     * Decrements the number of remaining occurences by 1.
239
-     * The task will be disabled when the number reaches 0.
240
-     *
241
-     * @return self
242
-     */
243
-    public function decrementRemainingOccurences(): self
244
-    {
245
-        if ($this->nb_occurrences > 0) {
246
-            $this->nb_occurrences--;
247
-            if ($this->nb_occurrences == 0) {
248
-                $this->disable();
249
-            }
250
-        }
251
-        return $this;
252
-    }
253
-
254
-    /**
255
-     * Set the number of remaining occurences of task runs.
256
-     *
257
-     * @param int $nb_occurrences
258
-     * @return self
259
-     */
260
-    public function setRemainingOccurences(int $nb_occurrences): self
261
-    {
262
-        $this->nb_occurrences = $nb_occurrences;
263
-        return $this;
264
-    }
265
-
266
-    /**
267
-     * Returns whether the task is running
268
-     * @return bool
269
-     */
270
-    public function isRunning(): bool
271
-    {
272
-        return $this->is_running;
273
-    }
274
-
275
-    /**
276
-     * Informs the schedule that the task is going to run
277
-     *
278
-     * @return self
279
-     */
280
-    public function startRunning(): self
281
-    {
282
-        $this->is_running = true;
283
-        return $this;
284
-    }
285
-
286
-    /**
287
-     * Informs the schedule that the task has stopped running.
288
-     * @return self
289
-     */
290
-    public function stopRunning(): self
291
-    {
292
-        $this->is_running = false;
293
-        return $this;
294
-    }
295
-
296
-    /**
297
-     * Returns the schedule details as an associate array
298
-     *
299
-     * @return array
300
-     */
301
-    public function toArray(): array
302
-    {
303
-        return [
304
-            'id'            =>  $this->id,
305
-            'task_id'       =>  $this->task_id,
306
-            'enabled'       =>  $this->enabled,
307
-            'last_run'      =>  $this->last_run,
308
-            'last_result'   =>  $this->last_result,
309
-            'frequency'     =>  $this->frequency,
310
-            'nb_occurrences' =>  $this->nb_occurrences,
311
-            'is_running'    =>  $this->is_running
312
-        ];
313
-    }
28
+	/**
29
+	 * Task Schedule ID
30
+	 * @var int $id
31
+	 */
32
+	private $id;
33
+
34
+	/**
35
+	 * Task schedule status
36
+	 * @var bool $enabled
37
+	 */
38
+	private $enabled;
39
+
40
+	/**
41
+	 * ID of the task attached to schedule
42
+	 * @var string $task_id
43
+	 */
44
+	private $task_id;
45
+
46
+	/**
47
+	 * Last updated date
48
+	 * @var Carbon $last_run
49
+	 */
50
+	private $last_run;
51
+
52
+	/**
53
+	 * Last run result
54
+	 * @var bool $last_result
55
+	 */
56
+	private $last_result;
57
+
58
+	/**
59
+	 * Task run frequency
60
+	 * @var CarbonInterval $frequency
61
+	 */
62
+	private $frequency;
63
+
64
+	/**
65
+	 * Task remaining runs
66
+	 * @var int $nb_occurrences
67
+	 */
68
+	private $nb_occurrences;
69
+
70
+	/**
71
+	 * Current running status of the task
72
+	 * @var bool $is_running
73
+	 */
74
+	private $is_running;
75
+
76
+	/**
77
+	 * Constructor for TaskSchedule
78
+	 *
79
+	 * @param int $id Schedule ID
80
+	 * @param string $task_id Task ID
81
+	 * @param bool $enabled Is the schedule enabled
82
+	 * @param Carbon $last_run Last successful run date/time
83
+	 * @param bool $last_result Result of the last run
84
+	 * @param CarbonInterval $frequency Schedule frequency
85
+	 * @param int $nb_occurrences Number of remaining occurrences to be run
86
+	 * @param bool $is_running Is the task currently running
87
+	 */
88
+	public function __construct(
89
+		int $id,
90
+		string $task_id,
91
+		bool $enabled,
92
+		Carbon $last_run,
93
+		bool $last_result,
94
+		CarbonInterval $frequency,
95
+		int $nb_occurrences,
96
+		bool $is_running
97
+	) {
98
+		$this->id = $id;
99
+		$this->task_id = $task_id;
100
+		$this->enabled = $enabled;
101
+		$this->last_run = $last_run;
102
+		$this->last_result = $last_result;
103
+		$this->frequency = $frequency;
104
+		$this->nb_occurrences = $nb_occurrences;
105
+		$this->is_running = $is_running;
106
+	}
107
+
108
+	/**
109
+	 * Get the schedule ID.
110
+	 *
111
+	 * @return int
112
+	 */
113
+	public function id(): int
114
+	{
115
+		return $this->id;
116
+	}
117
+
118
+	/**
119
+	 * Get the task ID.
120
+	 *
121
+	 * @return string
122
+	 */
123
+	public function taskId(): string
124
+	{
125
+		return $this->task_id;
126
+	}
127
+
128
+	/**
129
+	 * Returns whether the schedule is enabled
130
+	 *
131
+	 * @return bool
132
+	 */
133
+	public function isEnabled(): bool
134
+	{
135
+		return $this->enabled;
136
+	}
137
+
138
+	/**
139
+	 * Enable the schedule
140
+	 *
141
+	 * @return self
142
+	 */
143
+	public function enable(): self
144
+	{
145
+		$this->enabled = true;
146
+		return $this;
147
+	}
148
+
149
+	/**
150
+	 * Disable the schedule
151
+	 *
152
+	 * @return self
153
+	 */
154
+	public function disable(): self
155
+	{
156
+		$this->enabled = false;
157
+		return $this;
158
+	}
159
+
160
+	/**
161
+	 * Get the frequency of the schedule
162
+	 *
163
+	 * @return CarbonInterval
164
+	 */
165
+	public function frequency(): CarbonInterval
166
+	{
167
+		return $this->frequency;
168
+	}
169
+
170
+	/**
171
+	 * Set the frequency of the schedule
172
+	 *
173
+	 * @param CarbonInterval $frequency
174
+	 * @return self
175
+	 */
176
+	public function setFrequency(CarbonInterval $frequency): self
177
+	{
178
+		$this->frequency = $frequency;
179
+		return $this;
180
+	}
181
+
182
+	/**
183
+	 * Get the date/time of the last successful run.
184
+	 *
185
+	 * @return Carbon
186
+	 */
187
+	public function lastRunTime(): Carbon
188
+	{
189
+		return $this->last_run;
190
+	}
191
+
192
+	/**
193
+	 * Set the last successful run date/time
194
+	 *
195
+	 * @param Carbon $last_run
196
+	 * @return self
197
+	 */
198
+	public function setLastRunTime(Carbon $last_run): self
199
+	{
200
+		$this->last_run = $last_run;
201
+		return $this;
202
+	}
203
+
204
+	/**
205
+	 * Returns whether the last run was successful
206
+	 *
207
+	 * @return bool
208
+	 */
209
+	public function wasLastRunSuccess(): bool
210
+	{
211
+		return $this->last_result;
212
+	}
213
+
214
+	/**
215
+	 * Set the last run result
216
+	 *
217
+	 * @param bool $last_result
218
+	 * @return self
219
+	 */
220
+	public function setLastResult(bool $last_result): self
221
+	{
222
+		$this->last_result = $last_result;
223
+		return $this;
224
+	}
225
+
226
+	/**
227
+	 * Get the number of remaining of occurrences of task runs.
228
+	 * Returns 0 if the tasks must be run indefinitely.
229
+	 *
230
+	 * @return int
231
+	 */
232
+	public function remainingOccurences(): int
233
+	{
234
+		return $this->nb_occurrences;
235
+	}
236
+
237
+	/**
238
+	 * Decrements the number of remaining occurences by 1.
239
+	 * The task will be disabled when the number reaches 0.
240
+	 *
241
+	 * @return self
242
+	 */
243
+	public function decrementRemainingOccurences(): self
244
+	{
245
+		if ($this->nb_occurrences > 0) {
246
+			$this->nb_occurrences--;
247
+			if ($this->nb_occurrences == 0) {
248
+				$this->disable();
249
+			}
250
+		}
251
+		return $this;
252
+	}
253
+
254
+	/**
255
+	 * Set the number of remaining occurences of task runs.
256
+	 *
257
+	 * @param int $nb_occurrences
258
+	 * @return self
259
+	 */
260
+	public function setRemainingOccurences(int $nb_occurrences): self
261
+	{
262
+		$this->nb_occurrences = $nb_occurrences;
263
+		return $this;
264
+	}
265
+
266
+	/**
267
+	 * Returns whether the task is running
268
+	 * @return bool
269
+	 */
270
+	public function isRunning(): bool
271
+	{
272
+		return $this->is_running;
273
+	}
274
+
275
+	/**
276
+	 * Informs the schedule that the task is going to run
277
+	 *
278
+	 * @return self
279
+	 */
280
+	public function startRunning(): self
281
+	{
282
+		$this->is_running = true;
283
+		return $this;
284
+	}
285
+
286
+	/**
287
+	 * Informs the schedule that the task has stopped running.
288
+	 * @return self
289
+	 */
290
+	public function stopRunning(): self
291
+	{
292
+		$this->is_running = false;
293
+		return $this;
294
+	}
295
+
296
+	/**
297
+	 * Returns the schedule details as an associate array
298
+	 *
299
+	 * @return array
300
+	 */
301
+	public function toArray(): array
302
+	{
303
+		return [
304
+			'id'            =>  $this->id,
305
+			'task_id'       =>  $this->task_id,
306
+			'enabled'       =>  $this->enabled,
307
+			'last_run'      =>  $this->last_run,
308
+			'last_result'   =>  $this->last_result,
309
+			'frequency'     =>  $this->frequency,
310
+			'nb_occurrences' =>  $this->nb_occurrences,
311
+			'is_running'    =>  $this->is_running
312
+		];
313
+	}
314 314
 }
Please login to merge, or discard this patch.
src/Webtrees/Module/AdminTasks/Http/RequestHandlers/TokenGenerate.php 1 patch
Indentation   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -29,35 +29,35 @@
 block discarded – undo
29 29
  */
30 30
 class TokenGenerate implements RequestHandlerInterface
31 31
 {
32
-    /**
33
-     * @var AdminTasksModule $module
34
-     */
35
-    private $module;
36
-
37
-    /**
38
-     * Constructor for TokenGenerate request handler
39
-     *
40
-     * @param ModuleService $module_service
41
-     */
42
-    public function __construct(ModuleService $module_service)
43
-    {
44
-        $this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
45
-    }
46
-
47
-    /**
48
-     * {@inheritDoc}
49
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
50
-     */
51
-    public function handle(ServerRequestInterface $request): ResponseInterface
52
-    {
53
-        if ($this->module === null) {
54
-            throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
55
-        }
56
-
57
-        $token = Functions::generateRandomToken();
58
-        $this->module->setPreference('MAJ_AT_FORCE_EXEC_TOKEN', $token);
59
-        Log::addConfigurationLog($this->module->title() . ' : New token generated.');
60
-
61
-        return response(['token' => $token]);
62
-    }
32
+	/**
33
+	 * @var AdminTasksModule $module
34
+	 */
35
+	private $module;
36
+
37
+	/**
38
+	 * Constructor for TokenGenerate request handler
39
+	 *
40
+	 * @param ModuleService $module_service
41
+	 */
42
+	public function __construct(ModuleService $module_service)
43
+	{
44
+		$this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
45
+	}
46
+
47
+	/**
48
+	 * {@inheritDoc}
49
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
50
+	 */
51
+	public function handle(ServerRequestInterface $request): ResponseInterface
52
+	{
53
+		if ($this->module === null) {
54
+			throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
55
+		}
56
+
57
+		$token = Functions::generateRandomToken();
58
+		$this->module->setPreference('MAJ_AT_FORCE_EXEC_TOKEN', $token);
59
+		Log::addConfigurationLog($this->module->title() . ' : New token generated.');
60
+
61
+		return response(['token' => $token]);
62
+	}
63 63
 }
Please login to merge, or discard this patch.
src/Webtrees/Module/AdminTasks/Http/RequestHandlers/TasksList.php 1 patch
Indentation   +106 added lines, -106 removed lines patch added patch discarded remove patch
@@ -31,110 +31,110 @@
 block discarded – undo
31 31
  */
32 32
 class TasksList implements RequestHandlerInterface
33 33
 {
34
-    /**
35
-     * @var AdminTasksModule $module
36
-     */
37
-    private $module;
38
-
39
-    /**
40
-     * @var TaskScheduleService $taskschedules_service
41
-     */
42
-    private $taskschedules_service;
43
-
44
-    /**
45
-     * @var DatatablesService $datatables_service
46
-     */
47
-    private $datatables_service;
48
-
49
-    /**
50
-     * Constructor for TasksList Request Handler
51
-     *
52
-     * @param ModuleService $module_service
53
-     * @param TaskScheduleService $taskschedules_service
54
-     * @param DatatablesService $datatables_service
55
-     */
56
-    public function __construct(
57
-        ModuleService $module_service,
58
-        TaskScheduleService $taskschedules_service,
59
-        DatatablesService $datatables_service
60
-    ) {
61
-        $this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
62
-        $this->taskschedules_service = $taskschedules_service;
63
-        $this->datatables_service = $datatables_service;
64
-    }
65
-
66
-    /**
67
-     * {@inheritDoc}
68
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
69
-     */
70
-    public function handle(ServerRequestInterface $request): ResponseInterface
71
-    {
72
-        if ($this->module === null) {
73
-            throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
74
-        }
75
-
76
-        $task_schedules = $this->taskschedules_service->all(true, true)
77
-            ->map(function (TaskSchedule $value): array {
78
-
79
-                $row = $value->toArray();
80
-                $task = $this->taskschedules_service->findTask($row['task_id']);
81
-                $row['task_name'] = $task !== null ? $task->name() : I18N::translate('Task not found');
82
-                return $row;
83
-            });
84
-
85
-        $search_columns = ['task_name'];
86
-        $sort_columns   = ['task_name', 'enabled', 'last_run'];
87
-        $module_name = $this->module->name();
88
-
89
-        $callback = function (array $row) use ($module_name): array {
90
-
91
-            $row['frequency']->setLocale(I18N::locale()->code());
92
-
93
-            $task_options_params = [
94
-                'task_sched_id' => $row['id'],
95
-                'task_sched_enabled' => $row['enabled'],
96
-                'task_edit_route' => route(TaskEditPage::class, ['task' => $row['id']]),
97
-                'task_status_route' => route(TaskStatusAction::class, [
98
-                    'task' => $row['id'],
99
-                    'enable' => $row['enabled'] ? 0 : 1
100
-                ])
101
-            ];
102
-
103
-            $task_run_params = [
104
-                'task_sched_id' => $row['id'],
105
-                'run_route' => route(TaskTrigger::class, [
106
-                    'task'  =>  $row['task_id'],
107
-                    'force' =>  $this->module->getPreference('MAJ_AT_FORCE_EXEC_TOKEN')
108
-                ])
109
-            ];
110
-
111
-            $datum = [
112
-                view($module_name . '::admin/tasks-table-options', $task_options_params),
113
-                view($module_name . '::components/yes-no-icons', ['yes' => $row['enabled']]),
114
-                '<span dir="auto">' . e($row['task_name']) . '</span>',
115
-                $row['last_run']->unix() === 0 ?
116
-                view('components/datetime', ['timestamp' => $row['last_run']]) :
117
-                view('components/datetime-diff', ['timestamp' => $row['last_run']]),
118
-                view($module_name . '::components/yes-no-icons', ['yes' => $row['last_result']]),
119
-                '<span dir="auto">' . e($row['frequency']->cascade()->forHumans()) . '</span>',
120
-                $row['nb_occurrences'] > 0 ? I18N::number($row['nb_occurrences']) : I18N::translate('Unlimited'),
121
-                view($module_name . '::components/yes-no-icons', [
122
-                    'yes' => $row['is_running'],
123
-                    'text_yes' => I18N::translate('Running'),
124
-                    'text_no' => I18N::translate('Not running')
125
-                ]),
126
-                view($module_name . '::admin/tasks-table-run', $task_run_params)
127
-            ];
128
-
129
-            return $datum;
130
-        };
131
-
132
-        return $this->datatables_service->handleCollection(
133
-            $request,
134
-            $task_schedules,
135
-            $search_columns,
136
-            $sort_columns,
137
-            $callback
138
-        );
139
-    }
34
+	/**
35
+	 * @var AdminTasksModule $module
36
+	 */
37
+	private $module;
38
+
39
+	/**
40
+	 * @var TaskScheduleService $taskschedules_service
41
+	 */
42
+	private $taskschedules_service;
43
+
44
+	/**
45
+	 * @var DatatablesService $datatables_service
46
+	 */
47
+	private $datatables_service;
48
+
49
+	/**
50
+	 * Constructor for TasksList Request Handler
51
+	 *
52
+	 * @param ModuleService $module_service
53
+	 * @param TaskScheduleService $taskschedules_service
54
+	 * @param DatatablesService $datatables_service
55
+	 */
56
+	public function __construct(
57
+		ModuleService $module_service,
58
+		TaskScheduleService $taskschedules_service,
59
+		DatatablesService $datatables_service
60
+	) {
61
+		$this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
62
+		$this->taskschedules_service = $taskschedules_service;
63
+		$this->datatables_service = $datatables_service;
64
+	}
65
+
66
+	/**
67
+	 * {@inheritDoc}
68
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
69
+	 */
70
+	public function handle(ServerRequestInterface $request): ResponseInterface
71
+	{
72
+		if ($this->module === null) {
73
+			throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
74
+		}
75
+
76
+		$task_schedules = $this->taskschedules_service->all(true, true)
77
+			->map(function (TaskSchedule $value): array {
78
+
79
+				$row = $value->toArray();
80
+				$task = $this->taskschedules_service->findTask($row['task_id']);
81
+				$row['task_name'] = $task !== null ? $task->name() : I18N::translate('Task not found');
82
+				return $row;
83
+			});
84
+
85
+		$search_columns = ['task_name'];
86
+		$sort_columns   = ['task_name', 'enabled', 'last_run'];
87
+		$module_name = $this->module->name();
88
+
89
+		$callback = function (array $row) use ($module_name): array {
90
+
91
+			$row['frequency']->setLocale(I18N::locale()->code());
92
+
93
+			$task_options_params = [
94
+				'task_sched_id' => $row['id'],
95
+				'task_sched_enabled' => $row['enabled'],
96
+				'task_edit_route' => route(TaskEditPage::class, ['task' => $row['id']]),
97
+				'task_status_route' => route(TaskStatusAction::class, [
98
+					'task' => $row['id'],
99
+					'enable' => $row['enabled'] ? 0 : 1
100
+				])
101
+			];
102
+
103
+			$task_run_params = [
104
+				'task_sched_id' => $row['id'],
105
+				'run_route' => route(TaskTrigger::class, [
106
+					'task'  =>  $row['task_id'],
107
+					'force' =>  $this->module->getPreference('MAJ_AT_FORCE_EXEC_TOKEN')
108
+				])
109
+			];
110
+
111
+			$datum = [
112
+				view($module_name . '::admin/tasks-table-options', $task_options_params),
113
+				view($module_name . '::components/yes-no-icons', ['yes' => $row['enabled']]),
114
+				'<span dir="auto">' . e($row['task_name']) . '</span>',
115
+				$row['last_run']->unix() === 0 ?
116
+				view('components/datetime', ['timestamp' => $row['last_run']]) :
117
+				view('components/datetime-diff', ['timestamp' => $row['last_run']]),
118
+				view($module_name . '::components/yes-no-icons', ['yes' => $row['last_result']]),
119
+				'<span dir="auto">' . e($row['frequency']->cascade()->forHumans()) . '</span>',
120
+				$row['nb_occurrences'] > 0 ? I18N::number($row['nb_occurrences']) : I18N::translate('Unlimited'),
121
+				view($module_name . '::components/yes-no-icons', [
122
+					'yes' => $row['is_running'],
123
+					'text_yes' => I18N::translate('Running'),
124
+					'text_no' => I18N::translate('Not running')
125
+				]),
126
+				view($module_name . '::admin/tasks-table-run', $task_run_params)
127
+			];
128
+
129
+			return $datum;
130
+		};
131
+
132
+		return $this->datatables_service->handleCollection(
133
+			$request,
134
+			$task_schedules,
135
+			$search_columns,
136
+			$sort_columns,
137
+			$callback
138
+		);
139
+	}
140 140
 }
Please login to merge, or discard this patch.
src/Webtrees/Module/AdminTasks/Http/RequestHandlers/TaskEditAction.php 1 patch
Indentation   +138 added lines, -138 removed lines patch added patch discarded remove patch
@@ -34,142 +34,142 @@
 block discarded – undo
34 34
  */
35 35
 class TaskEditAction implements RequestHandlerInterface
36 36
 {
37
-    /**
38
-     * @var AdminTasksModule $module
39
-     */
40
-    private $module;
41
-
42
-    /**
43
-     * @var TaskScheduleService $taskschedules_service
44
-     */
45
-    private $taskschedules_service;
46
-
47
-    /**
48
-     * Constructor for TaskEditAction Request Handler
49
-     *
50
-     * @param ModuleService $module_service
51
-     * @param TaskScheduleService $taskschedules_service
52
-     */
53
-    public function __construct(ModuleService $module_service, TaskScheduleService $taskschedules_service)
54
-    {
55
-            $this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
56
-        $this->taskschedules_service = $taskschedules_service;
57
-    }
58
-
59
-    /**
60
-     * {@inheritDoc}
61
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
62
-     */
63
-    public function handle(ServerRequestInterface $request): ResponseInterface
64
-    {
65
-        $task_sched_id = (int) $request->getAttribute('task');
66
-        $task_schedule = $this->taskschedules_service->find($task_sched_id);
67
-
68
-        $admin_config_route = route(AdminConfigPage::class);
69
-
70
-        if ($task_schedule === null) {
71
-            FlashMessages::addMessage(
72
-                I18N::translate('The task shedule with ID “%d” does not exist.', I18N::number($task_sched_id)),
73
-                'danger'
74
-            );
75
-            return redirect($admin_config_route);
76
-        }
77
-
78
-        $success = $this->updateGeneralSettings($task_schedule, $request);
79
-        $success = $success && $this->updateSpecificSettings($task_schedule, $request);
80
-
81
-        if ($success) {
82
-            FlashMessages::addMessage(
83
-                I18N::translate('The scheduled task has been successfully updated'),
84
-                'success'
85
-            );
86
-            //phpcs:ignore Generic.Files.LineLength.TooLong
87
-            Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” has been updated.');
88
-        }
89
-
90
-        return redirect($admin_config_route);
91
-    }
92
-
93
-    /**
94
-     * Update general settings for the task, based on the request parameters
95
-     *
96
-     * @param TaskSchedule $task_schedule
97
-     * @param ServerRequestInterface $request
98
-     * @return bool
99
-     */
100
-    private function updateGeneralSettings(TaskSchedule $task_schedule, ServerRequestInterface $request): bool
101
-    {
102
-        $params = (array) $request->getParsedBody();
103
-
104
-        $frequency = (int) $params['frequency'];
105
-        if ($frequency > 0) {
106
-            $task_schedule->setFrequency(CarbonInterval::minutes($frequency));
107
-        } else {
108
-            FlashMessages::addMessage(I18N::translate('The frequency is not in a valid format'), 'danger');
109
-        }
110
-
111
-        $is_limited = (bool) $params['is_limited'];
112
-        $nb_occur = (int) $params['nb_occur'];
113
-
114
-        if ($is_limited) {
115
-            if ($nb_occur > 0) {
116
-                $task_schedule->setRemainingOccurences($nb_occur);
117
-            } else {
118
-                FlashMessages::addMessage(
119
-                    I18N::translate('The number of remaining occurences is not in a valid format'),
120
-                    'danger'
121
-                );
122
-            }
123
-        } else {
124
-            $task_schedule->setRemainingOccurences(0);
125
-        }
126
-
127
-        try {
128
-            $this->taskschedules_service->update($task_schedule);
129
-            return true;
130
-        } catch (Exception $ex) {
131
-            Log::addErrorLog(
132
-                sprintf(
133
-                    'Error while updating the Task Schedule "%s". Exception: %s',
134
-                    $task_schedule->id(),
135
-                    $ex->getMessage()
136
-                )
137
-            );
138
-        }
139
-
140
-        FlashMessages::addMessage(I18N::translate('An error occured while updating the scheduled task'), 'danger');
141
-        //@phpcs:ignore Generic.Files.LineLength.TooLong
142
-        Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” could not be updated. See error log.');
143
-        return false;
144
-    }
145
-
146
-    /**
147
-     * Update general settings for the task, based on the request parameters
148
-     *
149
-     * @param TaskSchedule $task_schedule
150
-     * @param ServerRequestInterface $request
151
-     * @return bool
152
-     */
153
-    private function updateSpecificSettings(TaskSchedule $task_schedule, ServerRequestInterface $request): bool
154
-    {
155
-        $task = $this->taskschedules_service->findTask($task_schedule->taskId());
156
-        if ($task === null || !($task instanceof ConfigurableTaskInterface)) {
157
-            return true;
158
-        }
159
-
160
-        /** @var TaskInterface&ConfigurableTaskInterface $task */
161
-        if (!$task->updateConfig($request, $task_schedule)) {
162
-            FlashMessages::addMessage(
163
-                I18N::translate(
164
-                    'An error occured while updating the specific settings of administrative task “%s”',
165
-                    $task->name()
166
-                ),
167
-                'danger'
168
-            );
169
-            //phpcs:ignore Generic.Files.LineLength.TooLong
170
-            Log::addConfigurationLog('Module ' . $this->module->title() . ' : AdminTask “' . $task->name() . '” specific settings could not be updated. See error log.');
171
-        }
172
-
173
-        return true;
174
-    }
37
+	/**
38
+	 * @var AdminTasksModule $module
39
+	 */
40
+	private $module;
41
+
42
+	/**
43
+	 * @var TaskScheduleService $taskschedules_service
44
+	 */
45
+	private $taskschedules_service;
46
+
47
+	/**
48
+	 * Constructor for TaskEditAction Request Handler
49
+	 *
50
+	 * @param ModuleService $module_service
51
+	 * @param TaskScheduleService $taskschedules_service
52
+	 */
53
+	public function __construct(ModuleService $module_service, TaskScheduleService $taskschedules_service)
54
+	{
55
+			$this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
56
+		$this->taskschedules_service = $taskschedules_service;
57
+	}
58
+
59
+	/**
60
+	 * {@inheritDoc}
61
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
62
+	 */
63
+	public function handle(ServerRequestInterface $request): ResponseInterface
64
+	{
65
+		$task_sched_id = (int) $request->getAttribute('task');
66
+		$task_schedule = $this->taskschedules_service->find($task_sched_id);
67
+
68
+		$admin_config_route = route(AdminConfigPage::class);
69
+
70
+		if ($task_schedule === null) {
71
+			FlashMessages::addMessage(
72
+				I18N::translate('The task shedule with ID “%d” does not exist.', I18N::number($task_sched_id)),
73
+				'danger'
74
+			);
75
+			return redirect($admin_config_route);
76
+		}
77
+
78
+		$success = $this->updateGeneralSettings($task_schedule, $request);
79
+		$success = $success && $this->updateSpecificSettings($task_schedule, $request);
80
+
81
+		if ($success) {
82
+			FlashMessages::addMessage(
83
+				I18N::translate('The scheduled task has been successfully updated'),
84
+				'success'
85
+			);
86
+			//phpcs:ignore Generic.Files.LineLength.TooLong
87
+			Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” has been updated.');
88
+		}
89
+
90
+		return redirect($admin_config_route);
91
+	}
92
+
93
+	/**
94
+	 * Update general settings for the task, based on the request parameters
95
+	 *
96
+	 * @param TaskSchedule $task_schedule
97
+	 * @param ServerRequestInterface $request
98
+	 * @return bool
99
+	 */
100
+	private function updateGeneralSettings(TaskSchedule $task_schedule, ServerRequestInterface $request): bool
101
+	{
102
+		$params = (array) $request->getParsedBody();
103
+
104
+		$frequency = (int) $params['frequency'];
105
+		if ($frequency > 0) {
106
+			$task_schedule->setFrequency(CarbonInterval::minutes($frequency));
107
+		} else {
108
+			FlashMessages::addMessage(I18N::translate('The frequency is not in a valid format'), 'danger');
109
+		}
110
+
111
+		$is_limited = (bool) $params['is_limited'];
112
+		$nb_occur = (int) $params['nb_occur'];
113
+
114
+		if ($is_limited) {
115
+			if ($nb_occur > 0) {
116
+				$task_schedule->setRemainingOccurences($nb_occur);
117
+			} else {
118
+				FlashMessages::addMessage(
119
+					I18N::translate('The number of remaining occurences is not in a valid format'),
120
+					'danger'
121
+				);
122
+			}
123
+		} else {
124
+			$task_schedule->setRemainingOccurences(0);
125
+		}
126
+
127
+		try {
128
+			$this->taskschedules_service->update($task_schedule);
129
+			return true;
130
+		} catch (Exception $ex) {
131
+			Log::addErrorLog(
132
+				sprintf(
133
+					'Error while updating the Task Schedule "%s". Exception: %s',
134
+					$task_schedule->id(),
135
+					$ex->getMessage()
136
+				)
137
+			);
138
+		}
139
+
140
+		FlashMessages::addMessage(I18N::translate('An error occured while updating the scheduled task'), 'danger');
141
+		//@phpcs:ignore Generic.Files.LineLength.TooLong
142
+		Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” could not be updated. See error log.');
143
+		return false;
144
+	}
145
+
146
+	/**
147
+	 * Update general settings for the task, based on the request parameters
148
+	 *
149
+	 * @param TaskSchedule $task_schedule
150
+	 * @param ServerRequestInterface $request
151
+	 * @return bool
152
+	 */
153
+	private function updateSpecificSettings(TaskSchedule $task_schedule, ServerRequestInterface $request): bool
154
+	{
155
+		$task = $this->taskschedules_service->findTask($task_schedule->taskId());
156
+		if ($task === null || !($task instanceof ConfigurableTaskInterface)) {
157
+			return true;
158
+		}
159
+
160
+		/** @var TaskInterface&ConfigurableTaskInterface $task */
161
+		if (!$task->updateConfig($request, $task_schedule)) {
162
+			FlashMessages::addMessage(
163
+				I18N::translate(
164
+					'An error occured while updating the specific settings of administrative task “%s”',
165
+					$task->name()
166
+				),
167
+				'danger'
168
+			);
169
+			//phpcs:ignore Generic.Files.LineLength.TooLong
170
+			Log::addConfigurationLog('Module ' . $this->module->title() . ' : AdminTask “' . $task->name() . '” specific settings could not be updated. See error log.');
171
+		}
172
+
173
+		return true;
174
+	}
175 175
 }
Please login to merge, or discard this patch.
src/Webtrees/Module/AdminTasks/Tasks/HealthCheckEmailTask.php 1 patch
Indentation   +184 added lines, -184 removed lines patch added patch discarded remove patch
@@ -39,188 +39,188 @@
 block discarded – undo
39 39
  */
40 40
 class HealthCheckEmailTask implements TaskInterface, ConfigurableTaskInterface
41 41
 {
42
-    /**
43
-     * Name of the Tree preference to check if the task is enabled for that tree
44
-     * @var string
45
-     */
46
-    public const TREE_PREFERENCE_NAME = 'MAJ_AT_HEALTHCHECK_ENABLED';
47
-
48
-    /**
49
-     * @var AdminTasksModule $module
50
-     */
51
-    private $module;
52
-
53
-    /**
54
-     * @var HealthCheckService $healthcheck_service;
55
-     */
56
-    private $healthcheck_service;
57
-
58
-    /**
59
-     * @var EmailService $email_service;
60
-     */
61
-    private $email_service;
62
-
63
-    /**
64
-     * @var UserService $user_service
65
-     */
66
-    private $user_service;
67
-
68
-    /**
69
-     * @var TreeService $tree_service
70
-     */
71
-    private $tree_service;
72
-
73
-    /**
74
-     * @var UpgradeService $upgrade_service
75
-     */
76
-    private $upgrade_service;
77
-
78
-    /**
79
-     * Constructor for HealthCheckTask
80
-     *
81
-     * @param ModuleService $module_service
82
-     * @param HealthCheckService $healthcheck_service
83
-     * @param EmailService $email_service
84
-     * @param UserService $user_service
85
-     * @param TreeService $tree_service
86
-     * @param UpgradeService $upgrade_service
87
-     */
88
-    public function __construct(
89
-        ModuleService $module_service,
90
-        HealthCheckService $healthcheck_service,
91
-        EmailService $email_service,
92
-        UserService $user_service,
93
-        TreeService $tree_service,
94
-        UpgradeService $upgrade_service
95
-    ) {
96
-        $this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
97
-        $this->healthcheck_service = $healthcheck_service;
98
-        $this->email_service = $email_service;
99
-        $this->user_service = $user_service;
100
-        $this->tree_service = $tree_service;
101
-        $this->upgrade_service = $upgrade_service;
102
-    }
103
-
104
-
105
-    /**
106
-     * {@inheritDoc}
107
-     * @see \MyArtJaub\Webtrees\Module\AdminTasks\Model\TaskInterface::name()
108
-     */
109
-    public function name(): string
110
-    {
111
-        return I18N::translate('Healthcheck Email');
112
-    }
113
-
114
-    /**
115
-     * {@inheritDoc}
116
-     * @see \MyArtJaub\Webtrees\Module\AdminTasks\Model\TaskInterface::defaultFrequency()
117
-     */
118
-    public function defaultFrequency(): int
119
-    {
120
-        return 10080; // = 1 week = 7 * 24 * 60 min
121
-    }
122
-
123
-    /**
124
-     * {@inheritDoc}
125
-     * @see \MyArtJaub\Webtrees\Module\AdminTasks\Model\TaskInterface::run()
126
-     */
127
-    public function run(TaskSchedule $task_schedule): bool
128
-    {
129
-        if ($this->module === null) {
130
-            return false;
131
-        }
132
-
133
-        $res = true;
134
-
135
-        // Compute the number of days to compute
136
-        $interval_lastrun = $task_schedule->lastRunTime()->diffAsCarbonInterval(Carbon::now());
137
-        //@phpcs:ignore Generic.Files.LineLength.TooLong
138
-        $interval = $interval_lastrun->greaterThan($task_schedule->frequency()) ? $interval_lastrun : $task_schedule->frequency();
139
-        $nb_days = (int) $interval->ceilDay()->totalDays;
140
-
141
-        $view_params_site = [
142
-            'nb_days'               =>  $nb_days,
143
-            'upgrade_available'     =>  $this->upgrade_service->isUpgradeAvailable(),
144
-            'latest_version'        =>  $this->upgrade_service->latestVersion(),
145
-            'download_url'          =>  $this->upgrade_service->downloadUrl(),
146
-            'all_users'             =>  $this->user_service->all(),
147
-            'unapproved'            =>  $this->user_service->unapproved(),
148
-            'unverified'            =>  $this->user_service->unverified(),
149
-        ];
150
-
151
-        foreach ($this->tree_service->all() as $tree) {
152
-        /** @var Tree $tree */
153
-
154
-            if ($tree->getPreference(self::TREE_PREFERENCE_NAME) !== '1') {
155
-                continue;
156
-            }
157
-
158
-            $webmaster = $this->user_service->find((int) $tree->getPreference('WEBMASTER_USER_ID'));
159
-            if ($webmaster === null) {
160
-                continue;
161
-            }
162
-            I18N::init($webmaster->getPreference('language'));
163
-
164
-            $error_logs = $this->healthcheck_service->errorLogs($tree, $nb_days);
165
-            $nb_errors = $error_logs->sum('nblogs');
166
-
167
-            $view_params = array_merge($view_params_site, [
168
-                'tree'              =>  $tree,
169
-                'total_by_type'     =>  $this->healthcheck_service->countByRecordType($tree),
170
-                'change_by_type'    =>  $this->healthcheck_service->changesByRecordType($tree, $nb_days),
171
-                'error_logs'        =>  $error_logs,
172
-                'nb_errors'         =>  $nb_errors
173
-            ]);
174
-
175
-            $res = $res && $this->email_service->send(
176
-                new TreeUser($tree),
177
-                $webmaster,
178
-                new NoReplyUser(),
179
-                I18N::translate('Health Check Report') . ' - ' . I18N::translate('Tree %s', $tree->name()),
180
-                view($this->module->name() . '::tasks/healthcheck/email-healthcheck-text', $view_params),
181
-                view($this->module->name() . '::tasks/healthcheck/email-healthcheck-html', $view_params)
182
-            );
183
-        }
184
-
185
-        return $res;
186
-    }
187
-
188
-    /**
189
-     * {@inheritDoc}
190
-     * @see \MyArtJaub\Webtrees\Module\AdminTasks\Model\ConfigurableTaskInterface::configView()
191
-     */
192
-    public function configView(ServerRequestInterface $request): string
193
-    {
194
-        return view($this->module->name() . '::tasks/healthcheck/config', [
195
-            'all_trees'     =>  $this->tree_service->all()
196
-        ]);
197
-    }
198
-
199
-    /**
200
-     * {@inheritDoc}
201
-     * @see \MyArtJaub\Webtrees\Module\AdminTasks\Model\ConfigurableTaskInterface::updateConfig()
202
-     */
203
-    public function updateConfig(ServerRequestInterface $request, TaskSchedule $task_schedule): bool
204
-    {
205
-        try {
206
-            $params = (array) $request->getParsedBody();
207
-
208
-            foreach ($this->tree_service->all() as $tree) {
209
-                if (Auth::isManager($tree)) {
210
-                    $tree_enabled = (bool) ($params['HEALTHCHECK_ENABLED_' . $tree->id()] ?? false);
211
-                    $tree->setPreference(self::TREE_PREFERENCE_NAME, $tree_enabled ? '1' : '0');
212
-                }
213
-            }
214
-            return true;
215
-        } catch (Exception $ex) {
216
-            Log::addErrorLog(
217
-                sprintf(
218
-                    'Error while updating the Task schedule "%s". Exception: %s',
219
-                    $task_schedule->id(),
220
-                    $ex->getMessage()
221
-                )
222
-            );
223
-        }
224
-        return false;
225
-    }
42
+	/**
43
+	 * Name of the Tree preference to check if the task is enabled for that tree
44
+	 * @var string
45
+	 */
46
+	public const TREE_PREFERENCE_NAME = 'MAJ_AT_HEALTHCHECK_ENABLED';
47
+
48
+	/**
49
+	 * @var AdminTasksModule $module
50
+	 */
51
+	private $module;
52
+
53
+	/**
54
+	 * @var HealthCheckService $healthcheck_service;
55
+	 */
56
+	private $healthcheck_service;
57
+
58
+	/**
59
+	 * @var EmailService $email_service;
60
+	 */
61
+	private $email_service;
62
+
63
+	/**
64
+	 * @var UserService $user_service
65
+	 */
66
+	private $user_service;
67
+
68
+	/**
69
+	 * @var TreeService $tree_service
70
+	 */
71
+	private $tree_service;
72
+
73
+	/**
74
+	 * @var UpgradeService $upgrade_service
75
+	 */
76
+	private $upgrade_service;
77
+
78
+	/**
79
+	 * Constructor for HealthCheckTask
80
+	 *
81
+	 * @param ModuleService $module_service
82
+	 * @param HealthCheckService $healthcheck_service
83
+	 * @param EmailService $email_service
84
+	 * @param UserService $user_service
85
+	 * @param TreeService $tree_service
86
+	 * @param UpgradeService $upgrade_service
87
+	 */
88
+	public function __construct(
89
+		ModuleService $module_service,
90
+		HealthCheckService $healthcheck_service,
91
+		EmailService $email_service,
92
+		UserService $user_service,
93
+		TreeService $tree_service,
94
+		UpgradeService $upgrade_service
95
+	) {
96
+		$this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
97
+		$this->healthcheck_service = $healthcheck_service;
98
+		$this->email_service = $email_service;
99
+		$this->user_service = $user_service;
100
+		$this->tree_service = $tree_service;
101
+		$this->upgrade_service = $upgrade_service;
102
+	}
103
+
104
+
105
+	/**
106
+	 * {@inheritDoc}
107
+	 * @see \MyArtJaub\Webtrees\Module\AdminTasks\Model\TaskInterface::name()
108
+	 */
109
+	public function name(): string
110
+	{
111
+		return I18N::translate('Healthcheck Email');
112
+	}
113
+
114
+	/**
115
+	 * {@inheritDoc}
116
+	 * @see \MyArtJaub\Webtrees\Module\AdminTasks\Model\TaskInterface::defaultFrequency()
117
+	 */
118
+	public function defaultFrequency(): int
119
+	{
120
+		return 10080; // = 1 week = 7 * 24 * 60 min
121
+	}
122
+
123
+	/**
124
+	 * {@inheritDoc}
125
+	 * @see \MyArtJaub\Webtrees\Module\AdminTasks\Model\TaskInterface::run()
126
+	 */
127
+	public function run(TaskSchedule $task_schedule): bool
128
+	{
129
+		if ($this->module === null) {
130
+			return false;
131
+		}
132
+
133
+		$res = true;
134
+
135
+		// Compute the number of days to compute
136
+		$interval_lastrun = $task_schedule->lastRunTime()->diffAsCarbonInterval(Carbon::now());
137
+		//@phpcs:ignore Generic.Files.LineLength.TooLong
138
+		$interval = $interval_lastrun->greaterThan($task_schedule->frequency()) ? $interval_lastrun : $task_schedule->frequency();
139
+		$nb_days = (int) $interval->ceilDay()->totalDays;
140
+
141
+		$view_params_site = [
142
+			'nb_days'               =>  $nb_days,
143
+			'upgrade_available'     =>  $this->upgrade_service->isUpgradeAvailable(),
144
+			'latest_version'        =>  $this->upgrade_service->latestVersion(),
145
+			'download_url'          =>  $this->upgrade_service->downloadUrl(),
146
+			'all_users'             =>  $this->user_service->all(),
147
+			'unapproved'            =>  $this->user_service->unapproved(),
148
+			'unverified'            =>  $this->user_service->unverified(),
149
+		];
150
+
151
+		foreach ($this->tree_service->all() as $tree) {
152
+		/** @var Tree $tree */
153
+
154
+			if ($tree->getPreference(self::TREE_PREFERENCE_NAME) !== '1') {
155
+				continue;
156
+			}
157
+
158
+			$webmaster = $this->user_service->find((int) $tree->getPreference('WEBMASTER_USER_ID'));
159
+			if ($webmaster === null) {
160
+				continue;
161
+			}
162
+			I18N::init($webmaster->getPreference('language'));
163
+
164
+			$error_logs = $this->healthcheck_service->errorLogs($tree, $nb_days);
165
+			$nb_errors = $error_logs->sum('nblogs');
166
+
167
+			$view_params = array_merge($view_params_site, [
168
+				'tree'              =>  $tree,
169
+				'total_by_type'     =>  $this->healthcheck_service->countByRecordType($tree),
170
+				'change_by_type'    =>  $this->healthcheck_service->changesByRecordType($tree, $nb_days),
171
+				'error_logs'        =>  $error_logs,
172
+				'nb_errors'         =>  $nb_errors
173
+			]);
174
+
175
+			$res = $res && $this->email_service->send(
176
+				new TreeUser($tree),
177
+				$webmaster,
178
+				new NoReplyUser(),
179
+				I18N::translate('Health Check Report') . ' - ' . I18N::translate('Tree %s', $tree->name()),
180
+				view($this->module->name() . '::tasks/healthcheck/email-healthcheck-text', $view_params),
181
+				view($this->module->name() . '::tasks/healthcheck/email-healthcheck-html', $view_params)
182
+			);
183
+		}
184
+
185
+		return $res;
186
+	}
187
+
188
+	/**
189
+	 * {@inheritDoc}
190
+	 * @see \MyArtJaub\Webtrees\Module\AdminTasks\Model\ConfigurableTaskInterface::configView()
191
+	 */
192
+	public function configView(ServerRequestInterface $request): string
193
+	{
194
+		return view($this->module->name() . '::tasks/healthcheck/config', [
195
+			'all_trees'     =>  $this->tree_service->all()
196
+		]);
197
+	}
198
+
199
+	/**
200
+	 * {@inheritDoc}
201
+	 * @see \MyArtJaub\Webtrees\Module\AdminTasks\Model\ConfigurableTaskInterface::updateConfig()
202
+	 */
203
+	public function updateConfig(ServerRequestInterface $request, TaskSchedule $task_schedule): bool
204
+	{
205
+		try {
206
+			$params = (array) $request->getParsedBody();
207
+
208
+			foreach ($this->tree_service->all() as $tree) {
209
+				if (Auth::isManager($tree)) {
210
+					$tree_enabled = (bool) ($params['HEALTHCHECK_ENABLED_' . $tree->id()] ?? false);
211
+					$tree->setPreference(self::TREE_PREFERENCE_NAME, $tree_enabled ? '1' : '0');
212
+				}
213
+			}
214
+			return true;
215
+		} catch (Exception $ex) {
216
+			Log::addErrorLog(
217
+				sprintf(
218
+					'Error while updating the Task schedule "%s". Exception: %s',
219
+					$task_schedule->id(),
220
+					$ex->getMessage()
221
+				)
222
+			);
223
+		}
224
+		return false;
225
+	}
226 226
 }
Please login to merge, or discard this patch.
src/Webtrees/Module/AdminTasks/Schema/Migration1.php 1 patch
Indentation   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -25,25 +25,25 @@
 block discarded – undo
25 25
 class Migration1 implements MigrationInterface
26 26
 {
27 27
 
28
-    /**
29
-     * {@inheritDoc}
30
-     * @see \Fisharebest\Webtrees\Schema\MigrationInterface::upgrade()
31
-     */
32
-    public function upgrade(): void
33
-    {
34
-        // Clean up previous admin tasks table if it exists
35
-        DB::schema()->dropIfExists('maj_admintasks');
36
-
37
-        DB::schema()->create('maj_admintasks', static function (Blueprint $table): void {
38
-
39
-            $table->increments('majat_id');
40
-            $table->string('majat_task_id', 32)->unique();
41
-            $table->enum('majat_status', ['enabled', 'disabled'])->default('disabled');
42
-            $table->dateTime('majat_last_run')->default(Carbon::createFromTimestampUTC(0));
43
-            $table->boolean('majat_last_result')->default(true);
44
-            $table->integer('majat_frequency')->default(10080);
45
-            $table->smallInteger('majat_nb_occur')->default(0);
46
-            $table->boolean('majat_running')->default(false);
47
-        });
48
-    }
28
+	/**
29
+	 * {@inheritDoc}
30
+	 * @see \Fisharebest\Webtrees\Schema\MigrationInterface::upgrade()
31
+	 */
32
+	public function upgrade(): void
33
+	{
34
+		// Clean up previous admin tasks table if it exists
35
+		DB::schema()->dropIfExists('maj_admintasks');
36
+
37
+		DB::schema()->create('maj_admintasks', static function (Blueprint $table): void {
38
+
39
+			$table->increments('majat_id');
40
+			$table->string('majat_task_id', 32)->unique();
41
+			$table->enum('majat_status', ['enabled', 'disabled'])->default('disabled');
42
+			$table->dateTime('majat_last_run')->default(Carbon::createFromTimestampUTC(0));
43
+			$table->boolean('majat_last_result')->default(true);
44
+			$table->integer('majat_frequency')->default(10080);
45
+			$table->smallInteger('majat_nb_occur')->default(0);
46
+			$table->boolean('majat_running')->default(false);
47
+		});
48
+	}
49 49
 }
Please login to merge, or discard this patch.