Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use a unique images/icons directory #100

Merged
merged 11 commits into from
Dec 13, 2024
4 changes: 2 additions & 2 deletions controller/manifest.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,12 @@ public function handle(): JsonResponse
{
$manifest['icons'] = [
[
'src' => $board_url . '/' . $this->config['icons_path'] . '/' . $this->config['pwa_icon_small'],
'src' => $board_url . '/' . ext::PWA_ICON_DIR . '/' . $this->config['pwa_icon_small'],
'sizes' => '192x192',
'type' => 'image/png'
],
[
'src' => $board_url . '/' . $this->config['icons_path'] . '/' . $this->config['pwa_icon_large'],
'src' => $board_url . '/' . ext::PWA_ICON_DIR . '/' . $this->config['pwa_icon_large'],
'sizes' => '512x512',
'type' => 'image/png'
]
Expand Down
12 changes: 6 additions & 6 deletions event/listener.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ class listener implements EventSubscriberInterface
* @param template $template Template object
* @param user $user
* @param manager $phpbb_notifications Notifications manager object
* @param $root_path
* @param string $root_path
*/
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)
{
Expand Down Expand Up @@ -144,7 +144,7 @@ public function pwa_manifest()
{
$this->template->assign_vars([
'U_MANIFEST_URL' => $this->controller_helper->route('phpbb_webpushnotifications_manifest_controller'),
'U_TOUCH_ICON' => $this->config['pwa_icon_small'],
'U_TOUCH_ICON' => $this->config['pwa_icon_small'] ? ext::PWA_ICON_DIR . '/' . $this->config['pwa_icon_small'] : null,
'SHORT_SITE_NAME' => $this->config['pwa_short_name'] ?: $this->trim_shortname($this->config['sitename']),
]);
}
Expand Down Expand Up @@ -201,7 +201,7 @@ public function acp_pwa_allow_emoji($event)
*/
public function pwa_icon_name($value, $key)
{
return $this->config['icons_path'] . '/<input id="' . $key . '" type="text" size="40" maxlength="255" name="config[' . $key . ']" value="' . $value . '">';
return ext::PWA_ICON_DIR . '/<input id="' . $key . '" type="text" size="40" maxlength="255" name="config[' . $key . ']" value="' . $value . '">';
}

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

// Check if image is valid
$image = $this->root_path . $this->config['icons_path'] . '/' . $value;
$image = $this->root_path . ext::PWA_ICON_DIR . '/' . $value;
$image_info = $this->imagesize->getImageSize($image);
if ($image_info !== false)
{
Expand All @@ -289,7 +289,7 @@ public function validate_pwa_options($event)
}
else
{
$this->add_error($event, 'PWA_IMAGE_INVALID', $value);
$this->add_error($event, 'PWA_ICON_INVALID', $value);
}
break;
}
Expand Down
5 changes: 5 additions & 0 deletions ext.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@
*/
class ext extends \phpbb\extension\base
{
/**
* Location for storing PWA touch/app icons.
*/
public const PWA_ICON_DIR = 'images/site_icons';

/**
* Require phpBB 3.3.12 due to new template and core events.
*/
Expand Down
7 changes: 5 additions & 2 deletions language/en/info_acp_webpushnotifications.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@
'ACP_WEBPUSH_REMOVE_WARNING' => 'Web Push Notifications are now built into phpBB',
'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.',
'LOG_CONFIG_WEBPUSH' => '<strong>Altered Web Push settings</strong>',
'LOG_WEBPUSH_MESSAGE_FAIL' => '<strong>Web Push message could not be sent:</strong> %s',
'LOG_WEBPUSH_SUBSCRIPTION_REMOVED' => '<strong>Removed Web Push subscription:</strong>» %s',
'LOG_WEBPUSH_MESSAGE_FAIL' => '<strong>Web Push message could not be sent:</strong><br>» %s',
'LOG_WEBPUSH_SUBSCRIPTION_REMOVED' => '<strong>Removed Web Push subscription:</strong><br>» %s',
'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',
'LOG_WEBPUSH_ICON_DIR_SUCCESS' => '<strong>Webpush Notifications added the following directory:</strong><br>» <samp>%s</samp>',
'LOG_WEBPUSH_ICON_COPY_SUCCESS' => '<strong>Webpush Notifications copied existing PWA touch icons to:</strong><br>» <samp>%s</samp>',
]);
8 changes: 4 additions & 4 deletions language/en/webpushnotifications_common_acp.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@
'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.)',
'PWA_SHORT_NAME_INVALID' => '“Short site name” exceeds the 12 character limit.',
'PWA_ICON_SMALL' => 'Small mobile device icon',
'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.',
'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.',
'PWA_ICON_LARGE' => 'Large mobile device icon',
'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.',
'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.',
'PWA_ICON_SIZE_INVALID' => '“%s” does not have the correct image dimensions.',
'PWA_ICON_MIME_INVALID' => '“%s” must be a PNG image file.',
'PWA_IMAGE_INVALID' => '“%s” does not appear to be a valid image file.',
'PWA_IMAGE_NOT_PROVIDED' => '%s field must not be empty. All icon fields must contain an image.',
'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.',
'PWA_ICON_NOT_PROVIDED' => '%s field must not be empty. All icon fields must contain an image.',
]);
7 changes: 5 additions & 2 deletions language/ru/info_acp_webpushnotifications.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@
'ACP_WEBPUSH_REMOVE_WARNING' => 'Браузерные push—уведомления теперь встроены в phpBB',
'ACP_WEBPUSH_REMOVE_NOTICE' => 'Расширение «phpBB Browser Push Notifications» больше не требуется и должно быть удалено.<br>Все системные и пользовательские настройки, связанные с данным расширением, будут перенесены в соответствующие настройки браузерных push—уведомлений конференции автоматически при удалении данного расширения.',
'LOG_CONFIG_WEBPUSH' => '<strong>Изменены настройки браузерных push—уведомлений</strong>',
'LOG_WEBPUSH_MESSAGE_FAIL' => '<strong>Не удалось отправить браузерное push—уведомление:</strong> %s',
'LOG_WEBPUSH_SUBSCRIPTION_REMOVED' => '<strong>Удалена подписка на браузерные push—уведомления:</strong>» %s',
'LOG_WEBPUSH_MESSAGE_FAIL' => '<strong>Не удалось отправить браузерное push—уведомление:</strong><br>» %s',
'LOG_WEBPUSH_SUBSCRIPTION_REMOVED' => '<strong>Удалена подписка на браузерные push—уведомления:</strong><br>» %s',
'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',
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rxu can you help with these?

'LOG_WEBPUSH_ICON_DIR_SUCCESS' => '<strong>Webpush Notifications added the following directory:</strong><br>» <samp>%s</samp>',
'LOG_WEBPUSH_ICON_COPY_SUCCESS' => '<strong>Webpush Notifications copied existing PWA touch icons to:</strong><br>» <samp>%s</samp>',
iMattPro marked this conversation as resolved.
Show resolved Hide resolved
]);
8 changes: 4 additions & 4 deletions language/ru/webpushnotifications_common_acp.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@
'PWA_SHORT_NAME_EXPLAIN' => 'Краткое имя сайта длиной не более 12 символов, которое будет использовано в качестве подписи к значку на домашнем экране мобильного устройства. Если оставить пустым, будут использованы первые 12 символов значения настройки, заданной в поле <samp>Название конференции</samp>.',
'PWA_SHORT_NAME_INVALID' => 'Заданное значение в поле «Краткое имя сайта» превышает 12 символов.',
'PWA_ICON_SMALL' => 'Маленький значок для мобильного устройства',
'PWA_ICON_SMALL_EXPLAIN' => 'Имя файла изображения формата PNG размером 192 x 192 пикселя. Файл изображения должен быть загружен на сервер в папку <samp>images/icons</samp>.',
'PWA_ICON_SMALL_EXPLAIN' => 'Имя файла изображения формата PNG размером 192 x 192 пикселя. Файл изображения должен быть загружен на сервер в папку <samp>' . \phpbb\webpushnotifications\ext::PWA_ICON_DIR . '</samp>.',
'PWA_ICON_LARGE' => 'Большой значок для мобильного устройства',
'PWA_ICON_LARGE_EXPLAIN' => 'Имя файла изображения формата PNG размером 512 x 512 пикселей. Файл изображения должен быть загружен на сервер в папку <samp>images/icons</samp>.',
'PWA_ICON_LARGE_EXPLAIN' => 'Имя файла изображения формата PNG размером 512 x 512 пикселей. Файл изображения должен быть загружен на сервер в папку <samp>' . \phpbb\webpushnotifications\ext::PWA_ICON_DIR . '</samp>.',
'PWA_ICON_SIZE_INVALID' => 'Изображение «%s» имеет некорректные размеры.',
'PWA_ICON_MIME_INVALID' => 'Файл изображения «%s» должен иметь формат PNG.',
'PWA_IMAGE_INVALID' => 'Файл «%s» не яввляется файлом изображения.',
'PWA_IMAGE_NOT_PROVIDED' => 'Настройка «%s» не может быть пустой. Необходимо задать все пути к значкам для мобильного устройства.',
'PWA_ICON_INVALID' => 'Файл «%s» не яввляется файлом изображения.',
'PWA_ICON_NOT_PROVIDED' => 'Настройка «%s» не может быть пустой. Необходимо задать все пути к значкам для мобильного устройства.',
iMattPro marked this conversation as resolved.
Show resolved Hide resolved
]);
120 changes: 120 additions & 0 deletions migrations/setup_site_icons.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
<?php
/**
*
* phpBB Browser Push Notifications. An extension for the phpBB Forum Software package.
*
* @copyright (c) 2024, phpBB Limited <https://www.phpbb.com>
* @license GNU General Public License, version 2 (GPL-2.0)
*
*/

namespace phpbb\webpushnotifications\migrations;

use phpbb\db\migration\container_aware_migration;
use phpbb\filesystem\exception\filesystem_exception;
use phpbb\filesystem\filesystem;

class setup_site_icons extends container_aware_migration
{
private const NEW_ICON_DIR = 'images/site_icons';
private const OLD_ICON_DIR = 'images/icons';

/* @var filesystem $filesystem */
private $filesystem;

public function effectively_installed()
{
return $this->get_filesystem()->exists($this->container->getParameter('core.root_path') . self::NEW_ICON_DIR);
}

public static function depends_on()
{
return ['\phpbb\webpushnotifications\migrations\add_acp_pwa_configs'];
}

public function update_data(): array
{
return [
['custom', [[$this, 'configure_site_icons']]],
];
}

/**
* Create a site_icons directory in the images directory (and copy existing PWA the icons there)
*
* @return void
*/
public function configure_site_icons()
{
// Cache frequently used services and values
$filesystem = $this->get_filesystem();
$root_path = $this->container->getParameter('core.root_path');
$user = $this->container->get('user');
$log = $this->container->get('log');

// Prepare paths once
$new_icon_path = $root_path . self::NEW_ICON_DIR;
$old_icon_path = $root_path . self::OLD_ICON_DIR;

// Batch get config values
$icons = [
'small' => $this->config->offsetGet('pwa_icon_small'),
'large' => $this->config->offsetGet('pwa_icon_large')
];

try
{
// Create directory only if needed (give an empty index.htm too)
if (!$filesystem->exists($new_icon_path))
{
$filesystem->mkdir($new_icon_path, 0755);
$filesystem->touch($new_icon_path . '/index.htm');
}

// Process icons
$copied = false;
foreach ($icons as $icon)
{
$old_file = $old_icon_path . '/' . $icon;
$new_file = $new_icon_path . '/' . $icon;

if (!empty($icon) && $filesystem->exists($old_file))
{
$filesystem->copy($old_file, $new_file);
$copied = true;
}
}

// Set up a log message result
$result = [
'lang_key' => $copied ? 'LOG_WEBPUSH_ICON_COPY_SUCCESS' : 'LOG_WEBPUSH_ICON_DIR_SUCCESS',
'params' => [self::NEW_ICON_DIR],
];
}
catch (filesystem_exception $e)
{
$result = [
'lang_key' => 'LOG_WEBPUSH_ICON_DIR_FAIL',
'params' => [$e->get_filename(), $e->getMessage()]
];
}

// Log result
$log->add('admin', $user->data['user_id'], $user->ip, $result['lang_key'], false, $result['params']);
}

/**
* Get the filesystem object
*
* @return filesystem
*/
protected function get_filesystem()
{
if ($this->filesystem === null)
{
$this->filesystem = $this->container->get('filesystem');
}

return $this->filesystem;
}
}
4 changes: 3 additions & 1 deletion styles/all/template/event/overall_header_head_append.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@
<!-- Link to app's configuration manifest -->
<link rel="manifest" href="{{ U_MANIFEST_URL }}">

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

{% if NOTIFICATIONS_WEBPUSH_ENABLE %}
{% include '@phpbb_webpushnotifications/ucp_notifications_webpush.html' %}
Expand Down
11 changes: 6 additions & 5 deletions tests/event/listener_test.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

namespace phpbb\webpushnotifications\tests\event;

use phpbb\webpushnotifications\ext;

require_once __DIR__ . '/../../../../../includes/functions_acp.php';

class listener_test extends \phpbb_database_test_case
Expand Down Expand Up @@ -320,7 +322,7 @@ public function test_pwa_manifest()
->method('assign_vars')
->with([
'U_MANIFEST_URL' => $this->controller_helper->route('phpbb_webpushnotifications_manifest_controller'),
'U_TOUCH_ICON' => 'icon-192x192.png',
'U_TOUCH_ICON' => ext::PWA_ICON_DIR . '/icon-192x192.png',
'SHORT_SITE_NAME' => 'Test',
]);

Expand Down Expand Up @@ -450,7 +452,6 @@ public function validate_pwa_options_data()
*/
public function test_validate_pwa_options($validate, $cfg_array, $expected_error)
{
$this->config['icons_path'] = 'images/icons';
$config_name = key($cfg_array);
$config_definition = ['validate' => $validate];

Expand All @@ -467,9 +468,9 @@ public function test_validate_pwa_options($validate, $cfg_array, $expected_error
$this->imagesize->expects($pwa_icon_small && $pwa_icon_large ? self::once() : self::never())
->method('getImageSize')
->willReturnMap([
[$this->root_path . $this->config['icons_path'] . '/', '', false],
[$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]],
[$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]],
[$this->root_path . ext::PWA_ICON_DIR . '/', '', false],
[$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]],
[$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]],
]);

$dispatcher = new \phpbb\event\dispatcher();
Expand Down