xref: /webtrees/app/Module/UserMessagesModule.php (revision d32a32162970e6bfef5abe5397602a75311438d3)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2018 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16namespace Fisharebest\Webtrees\Module;
17
18use Fisharebest\Webtrees\Auth;
19use Fisharebest\Webtrees\Database;
20use Fisharebest\Webtrees\Filter;
21use Fisharebest\Webtrees\Functions\FunctionsDate;
22use Fisharebest\Webtrees\I18N;
23use Fisharebest\Webtrees\Tree;
24use Fisharebest\Webtrees\User;
25use Symfony\Component\HttpFoundation\RedirectResponse;
26use Symfony\Component\HttpFoundation\Request;
27use Symfony\Component\HttpFoundation\Response;
28
29/**
30 * Class UserMessagesModule
31 */
32class UserMessagesModule extends AbstractModule implements ModuleBlockInterface {
33	/** {@inheritdoc} */
34	public function getTitle() {
35		return /* I18N: Name of a module */ I18N::translate('Messages');
36	}
37
38	/** {@inheritdoc} */
39	public function getDescription() {
40		return /* I18N: Description of the “Messages” module */ I18N::translate('Communicate directly with other users, using private messages.');
41	}
42
43	/**
44	 * Delete one or messages belonging to a user.
45	 *
46	 * @param Request $request
47	 *
48	 * @return Response
49	 */
50	public function postDeleteMessageAction(Request $request): Response {
51		/** @var Tree $tree */
52		$tree = $request->attributes->get('tree');
53
54		$message_ids = (array) $request->get('message_id', []);
55
56		$stmt = Database::prepare("DELETE FROM `##message` WHERE user_id = :user_id AND message_id = :message_id");
57
58		foreach ($message_ids as $message_id) {
59			$stmt->execute([
60				'message_id' => $message_id,
61				'user_id'    => Auth::id(),
62			]);
63		}
64
65		if ($request->get('ctype') === 'user') {
66			$url = route('user-page', ['ged' => $tree->getName()]);
67		} else {
68			$url = route('tree-page', ['ged' => $tree->getName()]);
69		}
70
71		return new RedirectResponse($url);
72	}
73
74	/**
75	 * Generate the HTML content of this block.
76	 *
77	 * @param int      $block_id
78	 * @param bool     $template
79	 * @param string[] $cfg
80	 *
81	 * @return string
82	 */
83	public function getBlock($block_id, $template = true, $cfg = []): string {
84		global $ctype, $WT_TREE;
85
86		$messages = Database::prepare("SELECT message_id, sender, subject, body, UNIX_TIMESTAMP(created) AS created FROM `##message` WHERE user_id=? ORDER BY message_id DESC")
87			->execute([Auth::id()])
88			->fetchAll();
89
90		$count = count($messages);
91		$users = array_filter(User::all(), function (User $user) {
92			return $user->getUserId() !== Auth::id() && $user->getPreference('verified_by_admin') && $user->getPreference('contactmethod') !== 'none';
93		});
94
95		$content = '';
96		if (!empty($users)) {
97			$url = route('user-page', ['ged' => $WT_TREE->getName()]);
98			$content .= '<form onsubmit="return $(&quot;#to&quot;).val() !== &quot;&quot;">';
99			$content .= '<input type="hidden" name="route" value="message">';
100			$content .= '<input type="hidden" name="ged" value="' . e($WT_TREE->getName()) . '">';
101			$content .= '<input type="hidden" name="url" value="' . e($url) . '">';
102			$content .= '<label for="to">' . I18N::translate('Send a message') . '</label>';
103			$content .= '<select id="to" name="to">';
104			$content .= '<option value="">' . I18N::translate('&lt;select&gt;') . '</option>';
105			foreach ($users as $user) {
106				$content .= sprintf('<option value="%1$s">%2$s - %1$s</option>', e($user->getUserName()), e($user->getRealName()));
107			}
108			$content .= '</select>';
109			$content .= '<button type="submit">' . I18N::translate('Send') . '</button><br><br>';
110			$content .= '</form>';
111		}
112		$content .= '<form id="messageform" name="messageform" method="post" action="' . e(route('module', ['action' => 'DeleteMessage', 'module' => $this->getName(), 'ctype' => $ctype, 'ged' => $WT_TREE->getName()])) . '" data-confirm="' . I18N::translate('Are you sure you want to delete this message? It cannot be retrieved later.') . '" onsubmit="return confirm(this.dataset.confirm);">';
113		$content .= csrf_field();
114
115		if (!empty($messages)) {
116			$content .= '<table class="list_table w-100"><tr>';
117			$content .= '<th class="list_label">' . I18N::translate('Delete') . '<br><a href="#" onclick="$(\'#block-' . $block_id . ' :checkbox\').prop(\'checked\', true); return false;">' . I18N::translate('All') . '</a></th>';
118			$content .= '<th class="list_label">' . I18N::translate('Subject') . '</th>';
119			$content .= '<th class="list_label">' . I18N::translate('Date sent') . '</th>';
120			$content .= '<th class="list_label">' . I18N::translate('Email address') . '</th>';
121			$content .= '</tr>';
122			foreach ($messages as $message) {
123				$content .= '<tr>';
124				$content .= '<td class="list_value_wrap center"><input type="checkbox" name="message_id[]" value="' . $message->message_id . '" id="cb_message' . $message->message_id . '"></td>';
125				$content .= '<td class="list_value_wrap"><a href="#" onclick="return expand_layer(\'message' . $message->message_id . '\');"><i id="message' . $message->message_id . '_img" class="icon-plus"></i> <b dir="auto">' . e($message->subject) . '</b></a></td>';
126				$content .= '<td class="list_value_wrap">' . FunctionsDate::formatTimestamp($message->created + WT_TIMESTAMP_OFFSET) . '</td>';
127				$content .= '<td class="list_value_wrap">';
128				$user = User::findByIdentifier($message->sender);
129				if ($user) {
130					$content .= '<span dir="auto">' . e($user->getRealName()) . '</span> - <span dir="auto">' . $user->getEmail() . '</span>';
131				} else {
132					$content .= '<a href="mailto:' . e($message->sender) . '">' . e($message->sender) . '</a>';
133				}
134				$content .= '</td>';
135				$content .= '</tr>';
136				$content .= '<tr><td class="list_value_wrap" colspan="4"><div id="message' . $message->message_id . '" style="display:none;">';
137				$content .= '<div dir="auto" style="white-space: pre-wrap;">' . Filter::expandUrls($message->body, $WT_TREE) . '</div><br>';
138				if (strpos($message->subject, /* I18N: When replying to an email, the subject becomes “RE: <subject>” */ I18N::translate('RE: ')) !== 0) {
139					$message->subject = I18N::translate('RE: ') . $message->subject;
140				}
141
142				// If this user still exists, show a reply link.
143				if ($user) {
144					$reply_url = route('message', ['to' => $user->getUserName(), 'subject' => $message->subject, 'ged' => $WT_TREE->getName()]);
145					$content .= '<a class="btn btn-primary" href="' . e($reply_url) . '" title="' . I18N::translate('Reply') . '">' . I18N::translate('Reply') . '</a> ';
146				}
147				$content .= '<button type="button" class="btn btn-danger" data-confirm="' . I18N::translate('Are you sure you want to delete this message? It cannot be retrieved later.') . '" onclick="if (confirm(this.dataset.confirm)) {$(\'#messageform :checkbox\').prop(\'checked\', false); $(\'#cb_message' . $message->message_id . '\').prop(\'checked\', true); document.messageform.submit();}">' . I18N::translate('Delete') . '</button></div></td></tr>';
148			}
149			$content .= '</table>';
150			$content .= '<p><button type="submit">' . I18N::translate('Delete selected messages') . '</button></p>';
151		}
152		$content .= '</form>';
153
154		if ($template) {
155			return view('blocks/template', [
156				'block'      => str_replace('_', '-', $this->getName()),
157				'id'         => $block_id,
158				'config_url' => '',
159				'title'      => I18N::plural('%s message', '%s messages', $count, I18N::number($count)),
160				'content'    => $content,
161			]);
162		} else {
163			return $content;
164		}
165	}
166
167	/** {@inheritdoc} */
168	public function loadAjax(): bool {
169		return false;
170	}
171
172	/** {@inheritdoc} */
173	public function isUserBlock(): bool {
174		return true;
175	}
176
177	/** {@inheritdoc} */
178	public function isGedcomBlock(): bool {
179		return false;
180	}
181
182	/**
183	 * An HTML form to edit block settings
184	 *
185	 * @param int $block_id
186	 *
187	 * @return void
188	 */
189	public function configureBlock($block_id) {
190	}
191}
192