summaryrefslogtreecommitdiff
path: root/app/Module/BatchUpdateModule.php
blob: 2a832604ddb471a9867042d696519d4ecc3e6c49 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
<?php
/**
 * webtrees: online genealogy
 * Copyright (C) 2018 webtrees development team
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
namespace Fisharebest\Webtrees\Module;

use Fisharebest\Webtrees\Auth;
use Fisharebest\Webtrees\Database;
use Fisharebest\Webtrees\Family;
use Fisharebest\Webtrees\GedcomRecord;
use Fisharebest\Webtrees\I18N;
use Fisharebest\Webtrees\Individual;
use Fisharebest\Webtrees\Media;
use Fisharebest\Webtrees\Module\BatchUpdate\BatchUpdateBasePlugin;
use Fisharebest\Webtrees\Note;
use Fisharebest\Webtrees\Repository;
use Fisharebest\Webtrees\Source;
use Fisharebest\Webtrees\Tree;
use Fisharebest\Webtrees\User;
use stdClass;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Class BatchUpdateModule
 */
class BatchUpdateModule extends AbstractModule implements ModuleConfigInterface {
	protected $layout = 'layouts/administration';

	/**
	 * How should this module be labelled on tabs, menus, etc.?
	 *
	 * @return string
	 */
	public function getTitle() {
		return /* I18N: Name of a module */
			I18N::translate('Batch update');
	}

	/**
	 * A sentence describing what this module does.
	 *
	 * @return string
	 */
	public function getDescription() {
		return /* I18N: Description of the “Batch update” module */
			I18N::translate('Apply automatic corrections to your genealogy data.');
	}

	/**
	 * Main entry point
	 *
	 * @param Request $request
	 *
	 * @return Response
	 */
	public function getAdminAction(Request $request): Response {
		/** @var Tree $tree */
		$tree = $request->attributes->get('tree');

		/** @var User $user */
		$user = $request->attributes->get('user');

		// We need a tree to work with.
		if ($tree === null) {
			throw new NotFoundHttpException;
		}

		// Admins only.
		if (!Auth::isAdmin($user)) {
			throw new AccessDeniedHttpException;
		}

		$plugin = $request->get('plugin', '');
		$xref   = $request->get('xref', '');

		$plugins = $this->getPluginList();
		$plugin  = $plugins[$plugin] ?? null;

		$curr_xref = '';
		$prev_xref = '';
		$next_xref = '';

		// Don't do any processing until a plugin is chosen.
		if ($plugin !== null) {
			$plugin->getOptions($request);

			$all_data = $this->allData($plugin, $tree);

			// Make sure that our requested record really does need updating.
			// It may have been updated in another session, or may not have
			// been specified at all.
			if (array_key_exists($xref, $all_data) && $plugin->doesRecordNeedUpdate($this->getRecord($all_data[$xref], $tree))) {
				$curr_xref = $xref;
			}

			// The requested record doesn't need updating - find one that does
			if ($curr_xref === '') {
				$curr_xref = $this->findNextXref($plugin, $xref, $all_data, $tree);
			}
			if ($curr_xref === '') {
				$curr_xref = $this->findPrevXref($plugin, $xref, $all_data, $tree);
			}

			// If we've found a record to update, get details and look for the next/prev
			if ($curr_xref !== '') {
				$prev_xref = $this->findPrevXref($plugin, $xref, $all_data, $tree);
				$next_xref = $this->findNextXref($plugin, $xref, $all_data, $tree);
			}
		}

		return $this->viewResponse('modules/batch_update/admin', [
			'auto_accept' => (bool) $user->getPreference('auto_accept'),
			'plugins'     => $plugins,
			'curr_xref'   => $curr_xref,
			'next_xref'   => $next_xref,
			'plugin'      => $plugin,
			'record'      => GedcomRecord::getInstance($curr_xref, $tree),
			'prev_xref'   => $prev_xref,
			'title'       => I18N::translate('Batch update'),
			'tree'        => $tree,
			'trees'       => Tree::getNameList(),
		]);
	}

	/**
	 * Perform an update
	 *
	 * @param Request $request
	 *
	 * @return RedirectResponse
	 */
	public function postAdminAction(Request $request): RedirectResponse {
		/** @var Tree $tree */
		$tree = $request->attributes->get('tree');

		/** @var User $user */
		$user = $request->attributes->get('user');

		// We need a tree to work with.
		if ($tree === null) {
			throw new NotFoundHttpException;
		}

		// Admins only.
		if (!Auth::isAdmin($user)) {
			throw new AccessDeniedHttpException;
		}

		$plugin = $request->get('plugin', '');
		$update = $request->get('update', '');
		$xref   = $request->request->get('xref', '');

		$plugins = $this->getPluginList();
		$plugin  = $plugins[$plugin] ?? null;

		if ($plugin === null) {
			throw new NotFoundHttpException;
		}
		$plugin->getOptions($request);

		$all_data = $this->allData($plugin, $tree);

		$parameters = $request->request->all();
		unset($parameters['csrf']);
		unset($parameters['update']);

		switch ($update) {
			case 'one':
				$record = $this->getRecord($all_data[$xref], $tree);
				if ($plugin->doesRecordNeedUpdate($record)) {
					$new_gedcom = $plugin->updateRecord($record);
					$record->updateRecord($new_gedcom, !$plugin->chan);
				}

				$parameters['xref'] = $this->findNextXref($plugin, $xref, $all_data, $tree);
				break;

			case 'all':
				foreach ($all_data as $xref => $value) {
					$record = $this->getRecord($value, $tree);
					if ($plugin->doesRecordNeedUpdate($record)) {
						$new_gedcom = $plugin->updateRecord($record);
						$record->updateRecord($new_gedcom, !$plugin->chan);
					}
				}
				$parameters['xref'] = '';
				break;
		}

		$url = route('module', $parameters);

		return new RedirectResponse($url);
	}


	/**
	 * Find the next record that needs to be updated.
	 *
	 * @param BatchUpdateBasePlugin $plugin
	 * @param string                $xref
	 * @param array                 $all_data
	 * @param Tree                  $tree
	 *
	 * @return string
	 */
	private function findNextXref(BatchUpdateBasePlugin $plugin, string $xref, array $all_data, Tree $tree): string {
		foreach (array_keys($all_data) as $key) {
			if ($key > $xref) {
				$record = $this->getRecord($all_data[$key], $tree);
				if ($plugin->doesRecordNeedUpdate($record)) {
					return $key;
				}
			}
		}

		return '';
	}

	/**
	 * Find the previous record that needs to be updated.
	 *
	 * @param BatchUpdateBasePlugin $plugin
	 * @param string                $xref
	 * @param array                 $all_data
	 * @param Tree                  $tree
	 *
	 * @return string
	 */
	private function findPrevXref(BatchUpdateBasePlugin $plugin, string $xref, array $all_data, Tree $tree): string {
		foreach (array_reverse($all_data) as $key => $value) {
			if ($key > $xref) {
				$record = $this->getRecord($all_data[$key], $tree);
				if ($plugin->doesRecordNeedUpdate($record)) {
					return $key;
				}
			}
		}

		return '';
	}

	/**
	 * Fetch all records that might need updating.
	 *
	 * @param BatchUpdateBasePlugin $plugin
	 * @param Tree                  $tree
	 *
	 * @return object[]
	 */
	private function allData(BatchUpdateBasePlugin $plugin, Tree $tree): array {
		$tmp = [];

		foreach ($plugin->getRecordTypesToUpdate() as $type) {
			switch ($type) {
				case 'INDI':
					$tmp += Database::prepare(
						"SELECT i_id AS xref, 'INDI' AS type, i_gedcom AS gedcom  FROM `##individuals` WHERE i_file = :tree_id"
					)->execute([
						'tree_id' => $tree->getTreeId(),
					])->fetchAll();
					break;

				case 'FAM':
					$tmp += Database::prepare(
						"SELECT f_id AS xref, 'FAM' AS type, f_gedcom AS gedcom  FROM `##families` WHERE f_file = :tree_id"
					)->execute([
						'tree_id' => $tree->getTreeId(),
					])->fetchAll();
					break;

				case 'SOUR':
					$tmp += Database::prepare(
						"SELECT s_id AS xref, 'SOUR' AS type, s_gedcom AS gedcom  FROM `##sources` WHERE s_file = :tree_id"
					)->execute([
						'tree_id' => $tree->getTreeId(),
					])->fetchAll();
					break;

				case 'OBJE':
					$tmp += Database::prepare(
						"SELECT m_id AS xref, 'OBJE' AS type, m_gedcom AS gedcom  FROM `##media` WHERE m_file = :tree_id"
					)->execute([
						'tree_id' => $tree->getTreeId(),
					])->fetchAll();
					break;

				default:
					$tmp += Database::prepare(
						"SELECT o_id AS xref, 'OBJE' AS type, o_gedcom AS gedcom  FROM `##other` WHERE o_file = :tree_id AND o_type = :type"
					)->execute([
						'tree_id' => $tree->getTreeId(),
						'type'    => $type,
					])->fetchAll();
					break;
			}
		}

		$data = [];

		foreach ($tmp as $value) {
			$data[$value->xref] = $value;
		}

		ksort($tmp);

		return $data;
	}

	/**
	 * Scan the plugin folder for a list of plugins
	 *
	 * @return BatchUpdateBasePlugin[]
	 */
	private function getPluginList() {
		$plugins = [];

		$dir_handle = opendir(__DIR__ . '/BatchUpdate');
		while (($file = readdir($dir_handle)) !== false) {
			if (substr($file, -10) == 'Plugin.php' && $file !== 'BatchUpdateBasePlugin.php') {
				$class           = '\Fisharebest\Webtrees\Module\BatchUpdate\\' . basename($file, '.php');
				$plugins[$class] = new $class;
			}
		}
		closedir($dir_handle);

		return $plugins;
	}

	/**
	 * @param stdClass $record
	 * @param Tree     $tree
	 *
	 * @return GedcomRecord
	 */
	public function getRecord(stdClass $record, Tree $tree): GedcomRecord {
		switch ($record->type) {
			case 'INDI':
				return Individual::getInstance($record->xref, $tree, $record->gedcom);

			case 'FAM':
				return Family::getInstance($record->xref, $tree, $record->gedcom);

			case 'SOUR':
				return Source::getInstance($record->xref, $tree, $record->gedcom);

			case 'REPO':
				return Repository::getInstance($record->xref, $tree, $record->gedcom);

			case 'OBJE':
				return Media::getInstance($record->xref, $tree, $record->gedcom);

			case 'NOTE':
				return Note::getInstance($record->xref, $tree, $record->gedcom);

			default:
				return GedcomRecord::getInstance($record->xref, $tree, $record->gedcom);
		}
	}

	/**
	 * The URL to a page where the user can modify the configuration of this module.
	 * These links are displayed in the admin page menu.
	 *
	 * @return string
	 */
	public function getConfigLink() {
		return route('module', ['module' => $this->getName(), 'action' => 'Admin']);
	}
}