Skip to content

Commit 2a8b81b

Browse files
authored
Merge pull request #100 from iMattPro/move-icons
Use a unique images/icons directory
2 parents 024252f + 6c87f5b commit 2a8b81b

10 files changed

+160
-26
lines changed

controller/manifest.php

+2-2
Original file line numberDiff line numberDiff line change
@@ -82,12 +82,12 @@ public function handle(): JsonResponse
8282
{
8383
$manifest['icons'] = [
8484
[
85-
'src' => $board_url . '/' . $this->config['icons_path'] . '/' . $this->config['pwa_icon_small'],
85+
'src' => $board_url . '/' . ext::PWA_ICON_DIR . '/' . $this->config['pwa_icon_small'],
8686
'sizes' => '192x192',
8787
'type' => 'image/png'
8888
],
8989
[
90-
'src' => $board_url . '/' . $this->config['icons_path'] . '/' . $this->config['pwa_icon_large'],
90+
'src' => $board_url . '/' . ext::PWA_ICON_DIR . '/' . $this->config['pwa_icon_large'],
9191
'sizes' => '512x512',
9292
'type' => 'image/png'
9393
]

event/listener.php

+6-6
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ class listener implements EventSubscriberInterface
6464
* @param template $template Template object
6565
* @param user $user
6666
* @param manager $phpbb_notifications Notifications manager object
67-
* @param $root_path
67+
* @param string $root_path
6868
*/
6969
public function __construct(config $config, controller_helper $controller_helper, FastImageSize $imagesize, form_helper $form_helper, language $language, template $template, user $user, manager $phpbb_notifications, $root_path)
7070
{
@@ -144,7 +144,7 @@ public function pwa_manifest()
144144
{
145145
$this->template->assign_vars([
146146
'U_MANIFEST_URL' => $this->controller_helper->route('phpbb_webpushnotifications_manifest_controller'),
147-
'U_TOUCH_ICON' => $this->config['pwa_icon_small'],
147+
'U_TOUCH_ICON' => $this->config['pwa_icon_small'] ? ext::PWA_ICON_DIR . '/' . $this->config['pwa_icon_small'] : null,
148148
'SHORT_SITE_NAME' => $this->config['pwa_short_name'] ?: $this->trim_shortname($this->config['sitename']),
149149
]);
150150
}
@@ -201,7 +201,7 @@ public function acp_pwa_allow_emoji($event)
201201
*/
202202
public function pwa_icon_name($value, $key)
203203
{
204-
return $this->config['icons_path'] . '/<input id="' . $key . '" type="text" size="40" maxlength="255" name="config[' . $key . ']" value="' . $value . '">';
204+
return ext::PWA_ICON_DIR . '/<input id="' . $key . '" type="text" size="40" maxlength="255" name="config[' . $key . ']" value="' . $value . '">';
205205
}
206206

207207
/**
@@ -267,12 +267,12 @@ public function validate_pwa_options($event)
267267
// Don't allow empty values, if one icon is set, both must be set.
268268
if (empty($value))
269269
{
270-
$this->add_error($event, 'PWA_IMAGE_NOT_PROVIDED', $this->language->lang(strtoupper($event['config_name'])));
270+
$this->add_error($event, 'PWA_ICON_NOT_PROVIDED', $this->language->lang(strtoupper($event['config_name'])));
271271
return;
272272
}
273273

274274
// Check if image is valid
275-
$image = $this->root_path . $this->config['icons_path'] . '/' . $value;
275+
$image = $this->root_path . ext::PWA_ICON_DIR . '/' . $value;
276276
$image_info = $this->imagesize->getImageSize($image);
277277
if ($image_info !== false)
278278
{
@@ -289,7 +289,7 @@ public function validate_pwa_options($event)
289289
}
290290
else
291291
{
292-
$this->add_error($event, 'PWA_IMAGE_INVALID', $value);
292+
$this->add_error($event, 'PWA_ICON_INVALID', $value);
293293
}
294294
break;
295295
}

ext.php

+5
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,11 @@
1515
*/
1616
class ext extends \phpbb\extension\base
1717
{
18+
/**
19+
* Location for storing PWA touch/app icons.
20+
*/
21+
public const PWA_ICON_DIR = 'images/site_icons';
22+
1823
/**
1924
* Require phpBB 3.3.12 due to new template and core events.
2025
*/

language/en/info_acp_webpushnotifications.php

+5-2
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,9 @@
4242
'ACP_WEBPUSH_REMOVE_WARNING' => 'Web Push Notifications are now built into phpBB',
4343
'ACP_WEBPUSH_REMOVE_NOTICE' => 'The extension “phpBB Browser Push Notifications” is no longer needed and should be uninstalled and removed.<br>All settings and user preferences associated with the extension will be migrated into phpBB’s built-in push notifications when you uninstall the extension.',
4444
'LOG_CONFIG_WEBPUSH' => '<strong>Altered Web Push settings</strong>',
45-
'LOG_WEBPUSH_MESSAGE_FAIL' => '<strong>Web Push message could not be sent:</strong> %s',
46-
'LOG_WEBPUSH_SUBSCRIPTION_REMOVED' => '<strong>Removed Web Push subscription:</strong>» %s',
45+
'LOG_WEBPUSH_MESSAGE_FAIL' => '<strong>Web Push message could not be sent:</strong><br>» %s',
46+
'LOG_WEBPUSH_SUBSCRIPTION_REMOVED' => '<strong>Removed Web Push subscription:</strong><br>» %s',
47+
'LOG_WEBPUSH_ICON_DIR_FAIL' => '<strong>Webpush Notifications could not migrate the following item in phpBB’s images directory:</strong><br>» %1$s » %2$s',
48+
'LOG_WEBPUSH_ICON_DIR_SUCCESS' => '<strong>Webpush Notifications added the following directory:</strong><br>» <samp>%s</samp>',
49+
'LOG_WEBPUSH_ICON_COPY_SUCCESS' => '<strong>Webpush Notifications copied existing PWA touch icons to:</strong><br>» <samp>%s</samp>',
4750
]);

language/en/webpushnotifications_common_acp.php

+4-4
Original file line numberDiff line numberDiff line change
@@ -43,11 +43,11 @@
4343
'PWA_SHORT_NAME_EXPLAIN' => 'Your site name in 12 characters or fewer, which may be used as a label for an icon on a mobile device’s home screen. (If this field is left empty, the first 12 characters of the <samp>Site name</samp> will be used.)',
4444
'PWA_SHORT_NAME_INVALID' => '“Short site name” exceeds the 12 character limit.',
4545
'PWA_ICON_SMALL' => 'Small mobile device icon',
46-
'PWA_ICON_SMALL_EXPLAIN' => 'File name of a 192px x 192px PNG image. This file must be uploaded to your board’s <samp>icons</samp> directory.',
46+
'PWA_ICON_SMALL_EXPLAIN' => 'File name of a 192px x 192px PNG image. This file must be uploaded to your board’s <samp>' . \phpbb\webpushnotifications\ext::PWA_ICON_DIR . '</samp> directory.',
4747
'PWA_ICON_LARGE' => 'Large mobile device icon',
48-
'PWA_ICON_LARGE_EXPLAIN' => 'File name of a 512px x 512px PNG image. This file must be uploaded to your board’s <samp>icons</samp> directory.',
48+
'PWA_ICON_LARGE_EXPLAIN' => 'File name of a 512px x 512px PNG image. This file must be uploaded to your board’s <samp>' . \phpbb\webpushnotifications\ext::PWA_ICON_DIR . '</samp> directory.',
4949
'PWA_ICON_SIZE_INVALID' => '“%s” does not have the correct image dimensions.',
5050
'PWA_ICON_MIME_INVALID' => '“%s” must be a PNG image file.',
51-
'PWA_IMAGE_INVALID' => '“%s” does not appear to be a valid image file.',
52-
'PWA_IMAGE_NOT_PROVIDED' => '%s field must not be empty. All icon fields must contain an image.',
51+
'PWA_ICON_INVALID' => '“%s” is not a valid image file or is missing from the expected location. Verify the file name and location are correct.',
52+
'PWA_ICON_NOT_PROVIDED' => '%s field must not be empty. All icon fields must contain an image.',
5353
]);

language/ru/info_acp_webpushnotifications.php

+5-2
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,9 @@
4242
'ACP_WEBPUSH_REMOVE_WARNING' => 'Браузерные push—уведомления теперь встроены в phpBB',
4343
'ACP_WEBPUSH_REMOVE_NOTICE' => 'Расширение «phpBB Browser Push Notifications» больше не требуется и должно быть удалено.<br>Все системные и пользовательские настройки, связанные с данным расширением, будут перенесены в соответствующие настройки браузерных push—уведомлений конференции автоматически при удалении данного расширения.',
4444
'LOG_CONFIG_WEBPUSH' => '<strong>Изменены настройки браузерных push—уведомлений</strong>',
45-
'LOG_WEBPUSH_MESSAGE_FAIL' => '<strong>Не удалось отправить браузерное push—уведомление:</strong> %s',
46-
'LOG_WEBPUSH_SUBSCRIPTION_REMOVED' => '<strong>Удалена подписка на браузерные push—уведомления:</strong>» %s',
45+
'LOG_WEBPUSH_MESSAGE_FAIL' => '<strong>Не удалось отправить браузерное push—уведомление:</strong><br>» %s',
46+
'LOG_WEBPUSH_SUBSCRIPTION_REMOVED' => '<strong>Удалена подписка на браузерные push—уведомления:</strong><br>» %s',
47+
'LOG_WEBPUSH_ICON_DIR_FAIL' => '<strong>Не удалось перенести в папку изображений файл значка прогрессивного веб—приложения (PWA):</strong><br>» %1$s » %2$s',
48+
'LOG_WEBPUSH_ICON_DIR_SUCCESS' => '<strong>Папка изображений прогрессивного веб—приложения (PWA) успешно создана:</strong><br>» <samp>%s</samp>',
49+
'LOG_WEBPUSH_ICON_COPY_SUCCESS' => '<strong>Файлы значков прогрессивного веб—приложения (PWA) успешно скопированы в папку:</strong><br>» <samp>%s</samp>',
4750
]);

language/ru/webpushnotifications_common_acp.php

+4-4
Original file line numberDiff line numberDiff line change
@@ -43,11 +43,11 @@
4343
'PWA_SHORT_NAME_EXPLAIN' => 'Краткое имя сайта длиной не более 12 символов, которое будет использовано в качестве подписи к значку на домашнем экране мобильного устройства. Если оставить пустым, будут использованы первые 12 символов значения настройки, заданной в поле <samp>Название конференции</samp>.',
4444
'PWA_SHORT_NAME_INVALID' => 'Заданное значение в поле «Краткое имя сайта» превышает 12 символов.',
4545
'PWA_ICON_SMALL' => 'Маленький значок для мобильного устройства',
46-
'PWA_ICON_SMALL_EXPLAIN' => 'Имя файла изображения формата PNG размером 192 x 192 пикселя. Файл изображения должен быть загружен на сервер в папку <samp>images/icons</samp>.',
46+
'PWA_ICON_SMALL_EXPLAIN' => 'Имя файла изображения формата PNG размером 192 x 192 пикселя. Файл изображения должен быть загружен на сервер в папку <samp>' . \phpbb\webpushnotifications\ext::PWA_ICON_DIR . '</samp>.',
4747
'PWA_ICON_LARGE' => 'Большой значок для мобильного устройства',
48-
'PWA_ICON_LARGE_EXPLAIN' => 'Имя файла изображения формата PNG размером 512 x 512 пикселей. Файл изображения должен быть загружен на сервер в папку <samp>images/icons</samp>.',
48+
'PWA_ICON_LARGE_EXPLAIN' => 'Имя файла изображения формата PNG размером 512 x 512 пикселей. Файл изображения должен быть загружен на сервер в папку <samp>' . \phpbb\webpushnotifications\ext::PWA_ICON_DIR . '</samp>.',
4949
'PWA_ICON_SIZE_INVALID' => 'Изображение «%s» имеет некорректные размеры.',
5050
'PWA_ICON_MIME_INVALID' => 'Файл изображения «%s» должен иметь формат PNG.',
51-
'PWA_IMAGE_INVALID' => 'Файл «%s» не яввляется файлом изображения.',
52-
'PWA_IMAGE_NOT_PROVIDED' => 'Настройка «%s» не может быть пустой. Необходимо задать все пути к значкам для мобильного устройства.',
51+
'PWA_ICON_INVALID' => 'Файл «%s» не является файлом изображения или отсутствует по указанному пути. Проверьте правильность имени файла и его расположения.',
52+
'PWA_ICON_NOT_PROVIDED' => 'Настройка «%s» не может быть пустой. Необходимо задать все пути к файлам значков для мобильных устройств.',
5353
]);

migrations/setup_site_icons.php

+120
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
<?php
2+
/**
3+
*
4+
* phpBB Browser Push Notifications. An extension for the phpBB Forum Software package.
5+
*
6+
* @copyright (c) 2024, phpBB Limited <https://www.phpbb.com>
7+
* @license GNU General Public License, version 2 (GPL-2.0)
8+
*
9+
*/
10+
11+
namespace phpbb\webpushnotifications\migrations;
12+
13+
use phpbb\db\migration\container_aware_migration;
14+
use phpbb\filesystem\exception\filesystem_exception;
15+
use phpbb\filesystem\filesystem;
16+
17+
class setup_site_icons extends container_aware_migration
18+
{
19+
private const NEW_ICON_DIR = 'images/site_icons';
20+
private const OLD_ICON_DIR = 'images/icons';
21+
22+
/* @var filesystem $filesystem */
23+
private $filesystem;
24+
25+
public function effectively_installed()
26+
{
27+
return $this->get_filesystem()->exists($this->container->getParameter('core.root_path') . self::NEW_ICON_DIR);
28+
}
29+
30+
public static function depends_on()
31+
{
32+
return ['\phpbb\webpushnotifications\migrations\add_acp_pwa_configs'];
33+
}
34+
35+
public function update_data(): array
36+
{
37+
return [
38+
['custom', [[$this, 'configure_site_icons']]],
39+
];
40+
}
41+
42+
/**
43+
* Create a site_icons directory in the images directory (and copy existing PWA the icons there)
44+
*
45+
* @return void
46+
*/
47+
public function configure_site_icons()
48+
{
49+
// Cache frequently used services and values
50+
$filesystem = $this->get_filesystem();
51+
$root_path = $this->container->getParameter('core.root_path');
52+
$user = $this->container->get('user');
53+
$log = $this->container->get('log');
54+
55+
// Prepare paths once
56+
$new_icon_path = $root_path . self::NEW_ICON_DIR;
57+
$old_icon_path = $root_path . self::OLD_ICON_DIR;
58+
59+
// Batch get config values
60+
$icons = [
61+
'small' => $this->config->offsetGet('pwa_icon_small'),
62+
'large' => $this->config->offsetGet('pwa_icon_large')
63+
];
64+
65+
try
66+
{
67+
// Create directory only if needed (give an empty index.htm too)
68+
if (!$filesystem->exists($new_icon_path))
69+
{
70+
$filesystem->mkdir($new_icon_path, 0755);
71+
$filesystem->touch($new_icon_path . '/index.htm');
72+
}
73+
74+
// Process icons
75+
$copied = false;
76+
foreach ($icons as $icon)
77+
{
78+
$old_file = $old_icon_path . '/' . $icon;
79+
$new_file = $new_icon_path . '/' . $icon;
80+
81+
if (!empty($icon) && $filesystem->exists($old_file))
82+
{
83+
$filesystem->copy($old_file, $new_file);
84+
$copied = true;
85+
}
86+
}
87+
88+
// Set up a log message result
89+
$result = [
90+
'lang_key' => $copied ? 'LOG_WEBPUSH_ICON_COPY_SUCCESS' : 'LOG_WEBPUSH_ICON_DIR_SUCCESS',
91+
'params' => [self::NEW_ICON_DIR],
92+
];
93+
}
94+
catch (filesystem_exception $e)
95+
{
96+
$result = [
97+
'lang_key' => 'LOG_WEBPUSH_ICON_DIR_FAIL',
98+
'params' => [$e->get_filename(), $e->getMessage()]
99+
];
100+
}
101+
102+
// Log result
103+
$log->add('admin', $user->data['user_id'], $user->ip, $result['lang_key'], false, $result['params']);
104+
}
105+
106+
/**
107+
* Get the filesystem object
108+
*
109+
* @return filesystem
110+
*/
111+
protected function get_filesystem()
112+
{
113+
if ($this->filesystem === null)
114+
{
115+
$this->filesystem = $this->container->get('filesystem');
116+
}
117+
118+
return $this->filesystem;
119+
}
120+
}

styles/all/template/event/overall_header_head_append.html

+3-1
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,10 @@
1616
<!-- Link to app's configuration manifest -->
1717
<link rel="manifest" href="{{ U_MANIFEST_URL }}">
1818

19+
{% if U_TOUCH_ICON %}
1920
<!-- App icon for iOS, a fallback to icons defined in the manifest -->
20-
{% if U_TOUCH_ICON %}<link rel="apple-touch-icon" href="{{ T_ICONS_PATH ~ U_TOUCH_ICON }}">{% endif %}
21+
<link rel="apple-touch-icon" href="{{ ROOT_PATH ~ U_TOUCH_ICON }}">
22+
{% endif %}
2123

2224
{% if NOTIFICATIONS_WEBPUSH_ENABLE %}
2325
{% include '@phpbb_webpushnotifications/ucp_notifications_webpush.html' %}

tests/event/listener_test.php

+6-5
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010

1111
namespace phpbb\webpushnotifications\tests\event;
1212

13+
use phpbb\webpushnotifications\ext;
14+
1315
require_once __DIR__ . '/../../../../../includes/functions_acp.php';
1416

1517
class listener_test extends \phpbb_database_test_case
@@ -320,7 +322,7 @@ public function test_pwa_manifest()
320322
->method('assign_vars')
321323
->with([
322324
'U_MANIFEST_URL' => $this->controller_helper->route('phpbb_webpushnotifications_manifest_controller'),
323-
'U_TOUCH_ICON' => 'icon-192x192.png',
325+
'U_TOUCH_ICON' => ext::PWA_ICON_DIR . '/icon-192x192.png',
324326
'SHORT_SITE_NAME' => 'Test',
325327
]);
326328

@@ -450,7 +452,6 @@ public function validate_pwa_options_data()
450452
*/
451453
public function test_validate_pwa_options($validate, $cfg_array, $expected_error)
452454
{
453-
$this->config['icons_path'] = 'images/icons';
454455
$config_name = key($cfg_array);
455456
$config_definition = ['validate' => $validate];
456457

@@ -467,9 +468,9 @@ public function test_validate_pwa_options($validate, $cfg_array, $expected_error
467468
$this->imagesize->expects($pwa_icon_small && $pwa_icon_large ? self::once() : self::never())
468469
->method('getImageSize')
469470
->willReturnMap([
470-
[$this->root_path . $this->config['icons_path'] . '/', '', false],
471-
[$this->root_path . $this->config['icons_path'] . '/' . $pwa_icon_small, '', ['width' => (int) $small_image_name, 'height' => (int) $small_image_name, 'type' => $small_image_ext === 'png' ? IMAGETYPE_PNG : IMAGETYPE_UNKNOWN]],
472-
[$this->root_path . $this->config['icons_path'] . '/' . $pwa_icon_large, '', ['width' => (int) $large_image_name, 'height' => (int) $large_image_name, 'type' => $large_image_ext === 'png' ? IMAGETYPE_PNG : IMAGETYPE_UNKNOWN]],
471+
[$this->root_path . ext::PWA_ICON_DIR . '/', '', false],
472+
[$this->root_path . ext::PWA_ICON_DIR . '/' . $pwa_icon_small, '', ['width' => (int) $small_image_name, 'height' => (int) $small_image_name, 'type' => $small_image_ext === 'png' ? IMAGETYPE_PNG : IMAGETYPE_UNKNOWN]],
473+
[$this->root_path . ext::PWA_ICON_DIR . '/' . $pwa_icon_large, '', ['width' => (int) $large_image_name, 'height' => (int) $large_image_name, 'type' => $large_image_ext === 'png' ? IMAGETYPE_PNG : IMAGETYPE_UNKNOWN]],
473474
]);
474475

475476
$dispatcher = new \phpbb\event\dispatcher();

0 commit comments

Comments
 (0)