From 5813cbc6682646daec1eec39ade83cd7ec7a82aa Mon Sep 17 00:00:00 2001 From: Jan Tojnar Date: Fri, 26 Jun 2026 00:20:38 +0200 Subject: [PATCH 01/11] tests: Use mock web server This will allow the tests to work offline or if the servers have an outage, and they will not break if the site changes. --- README.md | 3 +- composer.json | 2 +- tests/Mf2/ParserTest.php | 51 +- tests/Mf2/aaron.pk_4Zn5.html | 426 +++++++++ tests/Mf2/waterpigs.co.uk_index.html | 1227 ++++++++++++++++++++++++++ tests/Mf2/waterpigs.co.uk_photo.jpg | Bin 0 -> 4614 bytes 6 files changed, 1691 insertions(+), 18 deletions(-) create mode 100644 tests/Mf2/aaron.pk_4Zn5.html create mode 100644 tests/Mf2/waterpigs.co.uk_index.html create mode 100644 tests/Mf2/waterpigs.co.uk_photo.jpg diff --git a/README.md b/README.md index 0c86b81..207c8e8 100644 --- a/README.md +++ b/README.md @@ -363,14 +363,13 @@ Pull requests very welcome, please try to maintain stylistic, structural and nam Run `composer install` and `composer check-and-tests`. This will run `phpcs`, the php-mf2 tests, and the cross-platform [microformats/tests](https://github.com/microformats/tests) (excluding mf1; more details below). -The php-mf2 tests are in `/tests/Mf2` and contain many parsing examples, internal parser tests, and regression tests for specific issues over its history. If you need to run tests without an internet connection, run `composer tests-no-internet`. +The php-mf2 tests are in `/tests/Mf2` and contain many parsing examples, internal parser tests, and regression tests for specific issues over its history. `microformats/tests` are included via `MicroformatsTestSuiteTest.php`. It has tests for mf2 and mf1. php-mf2 will fail some of the mf1 tests, so the `check-and-tests` script will skip them currently. It **is** a goal to pass those mf1 tests, so you can run them with `composer microformats-tests-mf1`. There are additional composer scripts listed below for running parts of this test suite on their own. **Composer scripts** - phpcs: run with `composer cs-check` - php-mf2 tests + microformats/tests, except mf1: run with `composer tests` - - same, but exclude tests that require internet: `composer tests-no-internet` - microformats/tests suite: - run mf1 tests with `composer microformats-tests-mf1` - run mf2 tests with `composer microformats-tests-mf2` diff --git a/composer.json b/composer.json index b2eb2e2..6051b71 100644 --- a/composer.json +++ b/composer.json @@ -21,6 +21,7 @@ } }, "require-dev": { + "donatj/mock-webserver": "^2.10", "mf2/tests": "dev-master#e9e2b905821ba0a5b59dab1a8eaf40634ce9cd49", "squizlabs/php_codesniffer": "^3.10.2", "dealerdirect/phpcodesniffer-composer-installer": "^1.0", @@ -30,7 +31,6 @@ "scripts": { "cs-check": "phpcs", "tests": "XDEBUG_MODE=coverage ./vendor/bin/phpunit tests --coverage-text --whitelist Mf2", - "tests-no-internet": "@tests --exclude-group internet,microformats/tests/mf1", "microformats-tests-mf1": "./vendor/bin/phpunit --group microformats/tests/mf1", "microformats-tests-mf2": "./vendor/bin/phpunit --group microformats/tests/mf2", "microformats-tests-mixed": "./vendor/bin/phpunit --group microformats/tests/mixed", diff --git a/tests/Mf2/ParserTest.php b/tests/Mf2/ParserTest.php index a6cd9d4..0346b4f 100644 --- a/tests/Mf2/ParserTest.php +++ b/tests/Mf2/ParserTest.php @@ -2,6 +2,8 @@ namespace Mf2\Parser\Test; +use donatj\MockWebServer\MockWebServer; +use donatj\MockWebServer\Response as MockWebServerResponse; use Mf2\Parser; use Mf2; use Yoast\PHPUnitPolyfills\TestCases\TestCase; @@ -267,16 +269,30 @@ public function testParsesNestedMicroformatsWithClassnamesInAnyOrder() { $this->assertEquals('Name', $output['items'][0]['properties']['in-reply-to'][0]['properties']['name'][0]); } - /** - * @group internet - */ public function testFetchMicroformats() { - $mf = Mf2\fetch('https://microformats.org/'); + $server = new MockWebServer(); + $server->start(); + + // Obtained from http://waterpigs.co.uk/ + $indexUrl = $server->setResponseOfPath( + '/', + new MockWebServerResponse(file_get_contents(__DIR__ . '/waterpigs.co.uk_index.html'), [], 200) + ); + + // Obtained from http://waterpigs.co.uk/photo.jpg + $photoUrl = $server->setResponseOfPath( + '/photo.jpg', + new MockWebServerResponse(file_get_contents(__DIR__ . '/waterpigs.co.uk_photo.jpg'), ['content-type: image/jpeg'], 200) + ); + + $mf = Mf2\fetch($indexUrl); $this->assertArrayHasKey('items', $mf); - $mf = Mf2\fetch('https://microformats.org/microformats-logo.png', null, $curlInfo); + $mf = Mf2\fetch($photoUrl, null, $curlInfo); $this->assertNull($mf); - $this->assertStringContainsString('image/png', $curlInfo['content_type']); + $this->assertStringContainsString('jpeg', $curlInfo['content_type']); + + $server->stop(); } /** @@ -382,22 +398,27 @@ public function testApplyTransformationToSrcset() { /** * @see https://github.com/indieweb/php-mf2/issues/84 - * @group internet - * - * 2024-04-07: The final photo URL in this test changed over time. - * Updated it to only check that the final URL's hostname was correct, - * not the full photo URL. */ public function testRelativeURLResolvedWithFinalURL() { - $mf = Mf2\fetch('http://aaron.pk/4Zn5'); + $server = new MockWebServer(); + $server->start(); + + // Obtained from http://aaron.pk/4Zn5 + $url = $server->setResponseOfPath( + '/4Zn5', + new MockWebServerResponse(file_get_contents(__DIR__ . '/aaron.pk_4Zn5.html'), [], 200) + ); + + $mf = Mf2\fetch($url); + + $server->stop(); $this->assertArrayHasKey('photo', $mf['items'][0]['properties']); $hostname = parse_url($mf['items'][0]['properties']['photo'][0], PHP_URL_HOST); - $this->assertEquals('aaronparecki.com', $hostname); + $this->assertEquals('127.0.0.1', $hostname); - // previous assertion: not the photo URL changed over time - // $this->assertEquals('https://aaronparecki.com/img/1240x0/2014/12/23/5/photo.jpeg', $mf['items'][0]['properties']['photo'][0]); + $this->assertEquals($server->getServerRoot() . '/img/1240x,q60/2014/12/23/5/photo.jpeg', $mf['items'][0]['properties']['photo'][0]); } public function testScriptTagContentsRemovedFromTextValue() { diff --git a/tests/Mf2/aaron.pk_4Zn5.html b/tests/Mf2/aaron.pk_4Zn5.html new file mode 100644 index 0000000..38b8d7c --- /dev/null +++ b/tests/Mf2/aaron.pk_4Zn5.html @@ -0,0 +1,426 @@ + + + + + + SFO ✈️ SLC ✈️ PDX #travel • Aaron Parecki + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/Mf2/waterpigs.co.uk_index.html b/tests/Mf2/waterpigs.co.uk_index.html new file mode 100644 index 0000000..3f17605 --- /dev/null +++ b/tests/Mf2/waterpigs.co.uk_index.html @@ -0,0 +1,1227 @@ + + + + + + + + + + + + + Barnaby Walters + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

+ + Barnaby + Walters + +

+ +
+

Arranging atoms and pressurising air in a variety of manners, such as:

+ + +
+ +

Pronouns: they/he

+ + + + + + + + +
+ +
+
    +
  1. + +
    +
    + +
    +

    New corollary to the 2010s classic snarky programmer adage “the cloud is someone else’s computer”:

    + +

    “AI is someone else’s GPU”

    + +

    from which it follows that

    + +

    “I’m starting a new company with AI someone else’s GPU”

    + +

    “I spent hours talking to AI someone else’s GPU about my life and the AI someone else’s GPU told me to break up with my boyfriend”

    + +

    “I’m worried that my job is in danger of being replaced by AI someone else’s GPU“

    + +

    “It’s crazy what convincing images AI someone else’s GPU can generate these days!” (okay, that one doesn’t sound so far-fetched)

    + +

    “Users expect our product to have advanced features and integration with AI someone else’s GPU”

    + +

    “AI someone else’s GPU is the defining technology of the decade, if not the century”

    + + +
    + + + +
    +
    +
  2. +
  3. + + +
  4. +
  5. + +
    +
    + +
    +

    Here’s a KDE Plasma service menu (dolphin context menu action) for creating a valid CACHEDIR.TAG file in the selected folder. Useful for excluding things from being backed up! (e.g. via restic with the --exclude-caches option)

    + +
    [Desktop Entry]
    +Type=Service
    +MimeType=inode/directory
    +Actions=create_cachedir_tag
    +
    +[Desktop Action create_cachedir_tag]
    +Name=Create CACHEDIR.TAG
    +Icon=breeze/actions/22/document-edit-encrypt
    +Exec=echo "Signature: 8a477f597d28d172789f06886806bc55" > %u/CACHEDIR.TAG
    +
    + +

    Put it somewhere like .local/share/kio/servicemenus/cachedir-tag.desktop, make it executable and it should show up in your context menu.

    + + + +
    +
    +
  6. +
  7. + +
    +
    + +
    +

    At the time of writing, due to a packaging mess-up, the builds of SDR++ (and many other SDR tools by the looks of it) have suddenly and unintentionally dropped support for the popular RTL-SDR software defined radio dongle. Until this is fixed, users will have to build these applications themselves. The instructions are a little lacking in details, so here’s exactly how to do that, working on Kubuntu:

    + +

    +# To install:
    +sudo aptitude install cmake libfftw3-dev libglfw3-dev libvolk-dev zstd libairspy-dev librtlsdr-dev
    +git clone https://github.com/AlexandreRouma/SDRPlusPlus.git
    +cd SDRPlusPlus
    +mkdir build
    +cd build
    +cmake ..
    +make -j5 # 5 is the number of threads to use for building. adjust to your preference
    +sh ../create_root.sh
    +sudo make install
    +
    +# To run:
    +sdrpp
    +
    + +

    + + + +
    +
    +
  8. +
  9. + +
    +
    + +
    +

    Reddit recently underwent another new, unpopular redesign, meaning that there are now three different UIs for accessing the website. Out of habit I would look at new-new reddit before remembering to switch to old-new reddit, and quickly noticed that looking at new-new reddit causes my laptop’s fans instantly start spinning.

    + +

    Here’s a firefox performance profile for 20-30s of each iteration of the reddit homepage. I simply loaded the page and did absolutely nothing.

    + +

    old.reddit.com: constant ~5% CPU usage with occasional spikes up to ~90%

    + +

    + +

    new.reddit.com: usually 0% CPU usage with occasional bursts up to ~50%

    + +

    + +

    reddit.com (new-new reddit): constant 30% CPU usage with occasional spikes even higher

    + +

    + +

    I don’t have the time or knowledge required to dig into the performance profiler but I would be fascinated to know how old-new reddit ended up more efficient than old-old reddit, and exactly what new-new reddit is doing with 30% of my CPU??

    + + +
    + + + +
    +
    +
  10. +
  11. + +
    +
    + +
    +

    When importing photos into DigiKam, I want them to be renamed based on the ISO8601 datetime they were taken, ideally to millisecond precision to avoid conflicts when multiple images were taken in a single second. This has the nice side-effect that photos from multiple camera sources are guaranteed to be displayed in the correct order when browsing files, which is important and practical for me.

    + +

    I started out using this custom file renaming template on import:

    + +
    [date:"yyyy-MM-ddTHHMMss"]-[file]
    +
    + +

    as DigiKam’s [date] placeholder didn’t have an option for milliseconds, and I couldn‘t find a counter option which could handle my desired “append -# per-collision if this renaming scheme results in collisions”, so ended up just adding the entire camera-generated filename to the end.

    + +

    Unfortunately, this led to my files all being in the wrong order, even from the same camera. I haven’t quite figured out why, but it seems that there are several different internal datetime values stored in the image files: file creation date (which is completely wrong), the values used in DigiKam’s [date] templates (which are mostly wrong), and the DateTimeOriginal values stored in Exif data, which are not only correct but provide sub-second resolution too!

    + +

    So here’s the DigiKam import naming template which I will be using going forward:

    + +
    [meta:Exif.Photo.DateTimeOriginal]{range:1,10}{replace:":","-"}T[meta:Exif.Photo.DateTimeOriginal]{range:12,}{replace:":",""}s[meta:Exif.Photo.SubSecTimeOriginal]
    +
    + +

    which produces ISO8601-ish filenames like this:

    + +
    2023-06-16T143139s922.JPG
    +
    + +

    Broken down,

    + +
    [meta:Exif.Photo.DateTimeOriginal]
    +
    + +

    evalulates to a string like

    + +
    2023:06:16 14:31:39
    +
    + +

    but I don’t want colons in filenames for portability, so I take only the date part with {range:1,10}, replace the colons with hyphens {replace:":","-"}, add a literal T separator to avoid spaces in filenames, take the time part of the datetime and remove the colons completely, add a literal s separator to delimit seconds and milliseconds as I wanted to keep them separate but not use the typical . delimiter.

    + + +
    + + + +
    +
    +
  12. +
  13. + +
    +
    + +
    +

    Ended up getting frustrated with the old version of DigiKam available on Kubuntu, so tried installing an AppImage. The state of AppImage integration with Kubuntu is abysmal, and I open DigiKam fairly regularly, so I finally tried installing AppImageLauncher, which is recommended by DigiKam and is supposed to be a good tool for integrating AppImages with the desktop environment (something which Plasma should surely do itself, if AppImages are really going to be part of the future of linux app packaging).

    + +

    Unfortunately, installing AppImageLauncher completely broke my desktop environment, causing it to hang and preventing me from logging in. Looked it up and it was clearly related to whatever this issue is about, as moving .local/share/mime fixed it. Removing AppImageLauncher and the mime cache got things working again, and, lo, before it broke my system, AppImageLauncher had kindly made .desktop files for all my AppImages!

    + +

    At this point I decided to take a more manual approach to integrating AppImages I cared about with my DE, so I added a link from ~/Applications (where I store AppImages and other applications not installed via the package manager) to ~/.local/share/applications, where .desktop files are kept. Having quick access to this location makes manually managing .desktop files much more bearable, and I went about improving the ones AppImageLauncher had made (e.g. adding version numbers to the names – I find it very useful to know what version of an app I’m launching).

    + +

    So, back to DigiKam: at this point I had a DigiKam 8.3 AppImage installed and openable via launchers thanks to the .desktop file. It had to re-download the facial recognition files, but other than that picked up everything from before. However, in the main photo list view, the maximum size of the thumbnails was tiny.

    + +

    I spent some time poking around in settings and tweaking the QT scaling factor via the .desktop file, but I’ll spare you the details. tl;dr: if you want the DigiKam 8.3 AppImage to let you see large thumbnails on a high-DPI screen, you need to check the following boxes:

    + +
      +
    • Miscellaneous → System → Use high DPI scaling from the screen factor
    • +
    • Vews → Icons → Use large thumbnail size for high screen resolution
    • +
    + +

    Restart DigiKam, and it should let you make thumbnails large enough to be useful. This is especially necessary seeing as how DigiKam’s photo list view has a horribly wasteful layout, with almost as much whitespace as photo surface area.

    + + +
    + + + +
    +
    +
  14. +
  15. + + +
  16. +
  17. + + +
  18. +
  19. + +
    +
    + +
    +

    Some tips for using Teensy on linux:

    + +

    The teensy board support package is only supported in the Arduino applications downloaded directly from the arduino site, NOT on versions distributed by package managers. I used the AppImage and it worked fine. If you try to install the teensy board package on an unsupported version of Arduino you might see errors like “archive not supported”.

    + +

    Even when you have a supported version of Arduino installed, installing the Teensy board package isn’t totally reliable. The first time I downloaded it, compiling would fail with the following error:

    + +
    fork/exec /home/barnaby/.arduino15/packages/teensy/tools/teensy-compile/11.3.1/arm/bin/arm-none-eabi-g++: no such file or directory
    +
    +Compilation error: fork/exec /home/barnaby/.arduino15/packages/teensy/tools/teensy-compile/11.3.1/arm/bin/arm-none-eabi-g++: no such file or directory
    +
    + +

    The 11.3.1 folder existed, but was empty. Down- then upgrading the board package didn‘t fix it. Removing the board package and reinstalling it did work.

    + + +
    + + + +
    +
    +
  20. +
  21. + +
    +
    + +
    +

    If you’re getting the following error in Inkscape on (k)ubuntu when trying to open the Extension Manager:

    + +
    [long traceback snipped]
    +ModuleNotFoundError: No module named 'appdirs'
    +
    + +

    the best way to deal with it seems to be sudo apt install python3-appdirs, as trying to install the appdirs module with pip or pip3 might not put it in the right place for the system python3 which inkscape is using, especially if you use something like conda or pyenv.

    + + +
    + + + +
    +
    +
  22. +
  23. + + +
  24. +
  25. + +
    +
    + +
    +

    If you’re in the unfortunate position of needing to use MuseScore4 on linux for some reason (for example to use its excellent MIDI to notation conversion) and are having issues with the Flatpak version having an unreadably tiny UI on high-DPI screens, here’s how to fix it.

    + +

    Open the .desktop file for MuseScore 4 – mine was in /var/lib/flatpak/app/org.musescore.MuseScore/current/active/export/share/applications/org.musescore.MuseScore.desktop

    + +

    Find the Exec key, and change the command to include --env=QT_SCALE_FACTOR=2. Mine ended up looking like this:

    + +
    Exec=/usr/bin/flatpak run --env=QT_SCALE_FACTOR=2 --branch=stable --arch=x86_64 --command=mscore --file-forwarding org.musescore.MuseScore @@ %F @@
    +
    + +

    Save (you’ll need to enter your password, or to have launched the editor with sudo).

    + +

    Try launching MuseScore again. If you’re lucky, it’ll have a readable UI. If not, try restarting and launching it again — I haven’t found a way of successfully getting KDE to force-update all its .desktop files. Presumably there’s a cache somewhere? If anyone knows how to reliably do this, please let me know!

    + + +

    This should work for any Flatpak which uses QT, on any desktop environment which uses .desktop files. I really hope “UI Scale” becomes a standard per-application setting in the near future.

    + +

    EDIT: thanks to carmanaught on the KDE forums for this additional suggestion to copy the .desktop file to ~/.local/share/applications rather than editing it in-place, and for details about how to set up a service to watch this folder and clear the desktop file cache whenever it’s edited.

    + + + +
    +
    +
  26. +
  27. +
    +
    + + ↪ + + + + + + + Barnaby Walters: + + + Notes from the first day using a Slimbook Executive running Kubuntu (probably applies to anyone moving from macos to Kubuntu on similar hardware) + +Generally, very good first impressions. The hardware is nice, the connectivity is perfect for me, it boots fast, the screen looks amazing. The keyboard and trackpad are fine, except for the surfboard trackpad button design. Came with a bunch of stupid marketing stickers on (what year is this, 2005?), most of which were easily removed. +Here are the first settings I tweaked to make things more familiar: UI Scaling +Settings -> Display and Monitor -> Global Scale = 200% for a readable UI while still remaining beautifully crisp. +Settings -> Appearance -> Cursors -> Size: 48 +Settings -> Startup and Shutdown -> Login Screen -> Apply Plasma Settings so that your login screen is a sensible size. +Right click status bar, enter edit mode, Panel height: 100 Sleep +Default sleep mode seems to be a hibernation which takes 10-20s to wake up from, including whenever you close the lid. +Fix this by: In settings -> Power Management, in AC Powered tab set lid close to just turn off screen (or lock if desired). This will just turn off the screen when closed on AC power, but actually put the laptop to sleep when the lid is closed on battery power, to reduce power consumption. +Then, sudo nano /etc/systemd/sleep.conf and uncomment AllowSuspendThenHibernate=yes, and reboot. This changes the behaviour of sleep to initially just suspend the system, keeping data in RAM and allowing immediate wake-ups. When the battery goes under 5%, it’ll instead hibernate, which takes 10-20s to wake up from but stores the contents of RAM on the SSD. +EDIT: On further testing, this sadly doesn’t fix the issue completely (or at all? It’s hard to tell). Putting the computer to sleep using the meta menu works absolutely fine, but using F1 or the laptop lid (which I assume are handled the same way internally) leads to this blank screen with a cursor and hidden password entry field for 20s on wake up issue. I have no idea what’s causing it, and IMO it’s a big reason not to use KDE Plasma on these laptops — sadly, as it’s easily my favourite of the linux desktop environments I’ve tried so far. +FURTHER EDIT: turns out this was all due to the laptop coming with an outdated linux kernel installed, which didn’t support the hardware. A fresh install of the latest Kubuntu works perfectly. Firefox +By default, Firefox treats scroll events from the trackpad as scroll wheel inputs, causing jerky scrolling. To fix: echo MOZ_USE_XINPUT2=1 | sudo tee -a /etc/environment Touchpad +Settings -> Input Devices -> Touchpad +Pointer acceleration: 0.6 +Tap-to-click, tap-and-drag enabled +Two-finger tap: right click +Scrolling: two fingers, invert scroll direction +Right click: press anywhere with two fingers Function Buttons +Boot holding F2 to open BIOS settings, dig around to find and enable “Fn lock” to make the function keys perform their alternative functions by default (with numbered function inputs available by holding Fn, as on a MacBook) +Next pain points which I didn’t find a solution to yet: Occasional trackpad issues where the cursor freezes and only starts moving again after a two finger tap (right click). At the beginning this happened all the time, now it seems much better. Need to keep an eye on it. File browser not having a column view. Apparently this is an ongoing struggle for years in Kubuntu, which seems hard to believe. I tried to install the ElementaryOS file viewer but it didn’t seem to work. Setting up the keyboard for international typing. I got extremely used to typing special characters, diacritics and fancy punctuation on my macbook keyboard and am reluctant to have to re-learn all of that. Ideally I’d like to get a least a large subset of the key combinations working again. +
    + +
    + +
    +

    Macbook -> Kubuntu Slimbook update 2:

    + +

    After a brief dalliance with PopOS (which I liked well enough, but convinced me that I much prefer Plasma over Gnome), thanks to advice from someone on r/Kubuntu I discovered that most of my Kubuntu issues had been due to Slimbook delivering laptops with an old version of Kubuntu and the linux kernel on, which isn’t really compatible with their laptops (and I had foolishly assumed that the system software update would also update the kernel — not so) tl;dr: if you buy a Slimbook laptop and want to run Kubuntu on it, install it yourself!

    + +

    Desktop Environment

    + +

    After trying out Plasma on both X11 and Wayland, I decided to opt for sticking with Wayland, despite a few “showstoppers” and other minor annoyances. It has excellent support for a lot of quite slick features, such as fractional per-monitor UI scaling and multitouch gestures for switching virtual desktops (currently not yet configurable, hopefully this will change in the future).

    + +

    The current stable release of GIMP uses an old version of GTK which doesn’t scale well under Wayland, but fortunately the development release (2.99.16) has GTK3 support and the UI scales just fine.

    + +

    VLC also looks very weird under Plasma. I kept it around as it’s so useful, but also installed Celluloid 0.25.1 from their PPA as a potential Plasma-friendly replacement.

    + +

    Keyboards

    + +

    I type almost exclusively in ABC-Extended on my macbook, which gives me quick access to all the international characters I need access to, as well as some nice punctuation like en+em dashes, ellipses and curly quotes.

    + +

    I tried several keyboard layouts on my slimbook, and eventually settled for the English (Macintosh) one, which is almost the same with a few small differences. I will probably end up making my own keyboard layout which shifts some things around and replaces unused things with useful characters.

    + +

    For quick reference and learning different keyboard layouts, I recommend assigning this command to a global shortcut (I used ctrl+alt+shift+k), which brings up a keyboard preview, scaled to look good on my monitor. I haven’t found a good way of dismissing it other than using the trackpad (ideally I’d like it to only be displayed while I hold the shortcut), but it’s still very convenient.

    + +
    tastenbrett -qwindowgeometry 2500x850
    +
    + +

    For some reason, my F2 button’s special feature is “toggle whether the super key is locked, without indicating the current status to the user at all”. Apparently this is a common feature, but some cursory research did not reveal why this would ever be useful, or what the intended use is. I also didn’t find many other people asking about it. What am I missing here? Why does anyone need an entire button dedicated to disabling another, unrelated button? Why can’t I make it do something useful?

    + +

    Mail

    + +

    For the moment I decided for Thunderbird for mail, contacts and calendars (more about those later), and it was easy enough to set up for mail. I’d much prefer something which looks and works like mac os Mail, but installing the Conversation extension went a long way to making it usable (despite not always finding all messages in a thread for some reason).

    + +

    Music

    + +

    For the moment I chose Quod Libet as a basic iTunes replacement. It successfully scanned the contents of Music/iTunes/iTunes Media/Music with no complaints, and even played the AAC m4a files after I installed kubuntu-restricted-extras. Unfortuantely Quod Libet (and every other media player I tried) seems to be unable to inhibit sleep under Wayland — hopefully this will be remedied soon, as the “create a NoSleep activity and switch to it whenever you want to play music” ““workaround”” is not particularly appealing. I’d also settle for a status bar widget which let me switch power profiles quickly.

    + +

    Photos

    + +

    Moving my photo library took a little more effort, but not much, thanks to osxphotos. Additionally installing exiftools and then running one command created a structured export of my entire library, with all the metadata I care about stored safely in EXIF fields:

    + +
    osxphotos export /Volumes/migration/photos --directory "{created.year}/{created.mm}" --filename "{created}T{created.hour}{created.min}{created.sec}{title?_,}{title,}" --skip-original-if-edited --jpeg-ext jpeg --exiftool
    +
    + +

    This command takes the edited version of each file (falling back to the original), and stores them in a /YYYY/MM/YYYY-MM-DDTHHMMSS[_title].jpeg folder structure, which is my preferred way of organising photos on disk.

    + +

    I then imported this library into DigiKam, which quickly read all the metadata and made everything searchable. To get newly imported photos to fit into the same structure, I had to go into the Import Settings (plug in a camera or card, go “Import from device” and then open the sidebar on the right — unfortunately these settings don’t seem to be exposed anywhere else) and set the default filename to be the datetime, and the default “Album” to be YYYY/mm.

    + +

    I’m not a huge fan of DigiKam, as it’s cluttered, unstable and requires some very akward workflows (editing images opens them in a separate window? adding a tag requires opening the “tag manager”?? “hierarchical tags”??? I think the developers did not understand what a tag is and what makes them useful) but will do for now. To ensure longevity (and ease migrating to a different management application if I find something better suited to my workflow) I opted to store all metadata in EXIF fields in the files themselves. This way, DigiKam’s external database works as an ephemeral index and cache, which I can throw away or rebuild at any time without losing anything.

    + +

    A useful tip I learned along the way (thanks to ChatGPT): exiftool -a -u -g1 <file_name> will list all EXIF data found in a given file.

    + +

    Calendars and Contacts

    + +

    I set up a Nextcloud instance on my web host to see how much of my (already limited) iCloud usage it could replace. Despite learning that Hostinger doesn’t allow access to the .well-known directory required for zero-config carddav and caldav setup, I successfully managed to get my calendar and contacts migrated there. Thunderbird was able to sync with both without any issues, and mac os Calendar did eventually read my calendars from Nextcloud. No such luck with mac os Contacts unfortunately, but that’s much lower priority than calendar anyway.

    + +

    Pages and Numbers documents

    + +

    I had hoped that there would be a way of easily and mostly-losslessly batch converting all my Pages and Numbers documents into their microsoft XML equivalents, before then converting them to Libreoffice documents later on. Alas, that is only partially true. I ended up modifying a script provided by Viking OSX, which finds all Pages documents in a given folder and exports them as word docs to a separate folder. My changes instead export them in-place, and additionally export a PDF version so that I have a lossless read-only copy of each document exactly as it was:

    + +
    #!/bin/zsh
    +
    +: <<"COMMENT"
    +Do a recursive descent on a folder hierarchy gathering Pages document. Export these
    +documents from Pages as Word .docx and .pdf documents in the same location.
    +Tested: Ventura 13.0.1
    +VikingOSX, 2022-12-06, Apple Support Communities, No implicit warranty or support.
    +Adapted by Barnaby Walters 2023-09-08
    +COMMENT
    +
    +typeset -gi pagesCnt=0 docxCnt=0
    +
    +STARTDIR=$1
    +
    +function pages_export () {
    +
    +    /usr/bin/osascript <<-AS
    +    use scripting additions
    +
    +    tell application "Pages"
    +        activate
    +        try
    +            set infile to POSIX file "${1}"
    +            set outfile to POSIX file "${2}"
    +            set outfile_pdf to POSIX file "${3}"
    +
    +            set thisDoc to open infile as alias
    +
    +            with timeout of 1200 seconds
    +                export thisDoc to file outfile as Microsoft Word
    +            end timeout
    +            with timeout of 1200 seconds
    +                export thisDoc to file outfile_pdf as PDF
    +            end timeout
    +            close thisDoc saving no
    +        on error errmsg number errNo
    +            display dialog "[ " & errNo & " ]: " & errmsg
    +        end try
    +    end tell
    +    -- unhide the exported filename extensions
    +    tell application "Finder"
    +        if exists (item outfile as alias) then
    +            set extension hidden of (item outfile as alias) to false
    +        end if
    +    end tell
    +    return
    +AS
    +}
    +
    +function completion () {
    +    /usr/bin/osascript <<-AS
    +    use scripting additions
    +
    +    set DialogIcon to "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/MultipleItemsIcon.icns"
    +
    +    display dialog "Pages documents found: " & "${1}" & return & ¬
    +        "Pages documents exported to Word and PDF docx: " & "${2}" with title "Processing Complete" with icon POSIX file DialogIcon
    +    return
    +AS
    +}
    +
    +# do a case-insensitive recursion finding Pages documents and sorting by name
    +setopt nocaseglob
    +for f in ${STARTDIR}/**/*.pages(.Non);
    +do
    +    (( ++pagesCnt ))
    +    # if there is no Word folder at this file location, then make one
    +
    +    # construct the full path to the word docx document to be exported
    +    wordfile="${f:a:h:r}/${f:r:t}.docx"
    +    pdffile="${f:a:h:r}/${f:r:t}.pdf"
    +
    +    pages_export "${f}" "${wordfile}" "${pdffile}"
    +
    +    # do we have an exported docx that is non-zero in size?
    +    [[ -s $wordfile ]] && (( ++docxCnt ))
    +done
    +
    +# give the user statistics
    +completion $pagesCnt $docxCnt
    +
    + +

    (aside: I initially tried to get ChatGPT to generate the necessary applescript to do this entire task for me, as I’d heard that it was good at that, and applescript is a notoriously unintuitive and badly documented language. It seemd to get fairly close but I was unable to debug the (incomprehensible) errors in its scripts. The approach taken by VikingOSX is much more efficient: use applescript only for the things it’s absolutely necessary for, and do the rest in bash or python)

    + +

    I did the same thing for Numbers documents, the necessary script changes for that are left as an exercise for the reader.

    + +

    Unfortunately, these exports (and/or their subsequent imports into Libreoffice) were not very successful except for the simplest of documents. I only actively use a total of maybe 5 documents, which I will simply reconstruct from scratch in Libreoffice, and for the rest a combination of lossless read-only PDF and potentially-broken Office XML files should be sufficient.

    + +

    Prusa Slicer, AppImages and KDE Plasma LC_ALL issues

    + +

    The official way of installing Prusa Slicer on linux is using an AppImage, a format which I’ve had mixed experiences with. This was no different, as opening it in Dolphin had no result. Opening it in a console revealed some sort of locale error, and suggested some commands to fix it, but they also had no effect.

    + +

    After doing some digging, it turns out that it’s KDE Plasma’s fault. Plasma splits your localization settings up into various categories (language, time format, currency etc.) — an excellent feature by itself. Unfortunately, if you pick different locales for any of these categories, it leave the LC_ALL environment variable empty.

    + +

    The Prusa Slicer AppImage (and who knows what other software) was expecting an LC_ALL environment variable, and refused to run without it. tl;dr, editing /etc/defaults/locale to set LC_ALL and LANG to en_GB.utf-8 allowed PS to run, without having caused any other issues (yet…?).

    + +

    Once it managed to run, Prusa Slicer somehow told the system about itself in a way which lets me launch it from the application launcher (not something every AppImage does), and worked absolutely fine. Importing my settings as a config bundle worked perfectly.

    + +

    Documents and file syncing

    + +

    For the moment I decided against trying to set up two-way sync of my ~50GB documents folder between os x and Kubuntu. Nextcloud on my cheap web host is out of the question, and Syncthing look promising but I’d want to test its limitations and performance on something smaller first. For the moment, I decided to just use rsync for a one-way migration, and can repeat it in the future as I convert more proprietary files to linux-compatible formats.

    + +
    rsync -avzu --exclude venv --exclude .DS_Store --exclude .h5 Documents/ slimbook:Documents
    +
    + +

    venv and .h5 files are excluded to avoid transferring another ~30GB of unnecessary data. For syncronization after the first one, I need to make sure that rsync isn’t going to delete or replace newer files, but I will figure that out when I get to it. -u makes sure that files which are newer (i.e. made or changed) on the kubuntu side are not overwritten on subsequent syncs

    + +

    Pain points and next steps

    + +
      +
    • DigiKam seems powerful but its UI kinda sucks
    • +
    • Plasma is great but has some drawbacks which will hopefully be fixed Soon™
    • +
    • Notes — I’m a heavy mac os Notes user, and have fairly high standards for its replacement. Nextcloud notes looks promising, but the iOS app has two editor modes: one which is fast but sucks, and another which is good but takes ~7s to load each note.
    • +
    • Converting proprietary file formats to their linux equivalents. I have some old Sketch documents and a LOT of Eazydraw documents, all of which need converting losslessly and perfectly to well-structured SVGs for use with inkscape, before I can switch completely to Kubuntu for work tasks. I had hoped to use a similar Applescript trick, but haven’t been able to figure it out yet as Eazydraw lacks an applescript interface. Using System Events to manually manipulate the menus could work, but seems fiddly
    • +
    • …
    • +
    +
    + + + +
    +
  28. +
  29. + +
    +
    + +
    +

    Notes from the first day using a Slimbook Executive running Kubuntu (probably applies to anyone moving from macos to Kubuntu on similar hardware)

    + +

    + +

    Generally, very good first impressions. The hardware is nice, the connectivity is perfect for me, it boots fast, the screen looks amazing. The keyboard and trackpad are fine, except for the surfboard trackpad button design. Came with a bunch of stupid marketing stickers on (what year is this, 2005?), most of which were easily removed.

    + +

    Here are the first settings I tweaked to make things more familiar:

    + +

    UI Scaling

    + +

    Settings -> Display and Monitor -> Global Scale = 200% for a readable UI while still remaining beautifully crisp.

    + +

    Settings -> Appearance -> Cursors -> Size: 48

    + +

    Settings -> Startup and Shutdown -> Login Screen -> Apply Plasma Settings so that your login screen is a sensible size.

    + +

    Right click status bar, enter edit mode, Panel height: 100

    + +

    Sleep

    + +

    Default sleep mode seems to be a hibernation which takes 10-20s to wake up from, including whenever you close the lid.

    + +

    Fix this by: In settings -> Power Management, in AC Powered tab set lid close to just turn off screen (or lock if desired). This will just turn off the screen when closed on AC power, but actually put the laptop to sleep when the lid is closed on battery power, to reduce power consumption.

    + +

    Then, sudo nano /etc/systemd/sleep.conf and uncomment AllowSuspendThenHibernate=yes, and reboot. This changes the behaviour of sleep to initially just suspend the system, keeping data in RAM and allowing immediate wake-ups. When the battery goes under 5%, it’ll instead hibernate, which takes 10-20s to wake up from but stores the contents of RAM on the SSD.

    + +

    EDIT: On further testing, this sadly doesn’t fix the issue completely (or at all? It’s hard to tell). Putting the computer to sleep using the meta menu works absolutely fine, but using F1 or the laptop lid (which I assume are handled the same way internally) leads to this blank screen with a cursor and hidden password entry field for 20s on wake up issue. I have no idea what’s causing it, and IMO it’s a big reason not to use KDE Plasma on these laptops — sadly, as it’s easily my favourite of the linux desktop environments I’ve tried so far.

    + +

    FURTHER EDIT: turns out this was all due to the laptop coming with an outdated linux kernel installed, which didn’t support the hardware. A fresh install of the latest Kubuntu works perfectly.

    + +

    Firefox

    + +

    By default, Firefox treats scroll events from the trackpad as scroll wheel inputs, causing jerky scrolling. To fix: echo MOZ_USE_XINPUT2=1 | sudo tee -a /etc/environment

    + +

    Touchpad

    + +

    Settings -> Input Devices -> Touchpad
    +Pointer acceleration: 0.6
    +Tap-to-click, tap-and-drag enabled
    +Two-finger tap: right click
    +Scrolling: two fingers, invert scroll direction
    +Right click: press anywhere with two fingers

    + +

    Function Buttons

    + +

    Boot holding F2 to open BIOS settings, dig around to find and enable “Fn lock” to make the function keys perform their alternative functions by default (with numbered function inputs available by holding Fn, as on a MacBook)

    + +
    + +

    Next pain points which I didn’t find a solution to yet:

    + +
      +
    • Occasional trackpad issues where the cursor freezes and only starts moving again after a two finger tap (right click). At the beginning this happened all the time, now it seems much better. Need to keep an eye on it.
    • +
    • File browser not having a column view. Apparently this is an ongoing struggle for years in Kubuntu, which seems hard to believe. I tried to install the ElementaryOS file viewer but it didn’t seem to work.
    • +
    • Setting up the keyboard for international typing. I got extremely used to typing special characters, diacritics and fancy punctuation on my macbook keyboard and am reluctant to have to re-learn all of that. Ideally I’d like to get a least a large subset of the key combinations working again.
    • +
    +
    + + + +
    +
    +
  30. +
  31. + + +
  32. +
  33. + +
  34. +
  35. + +
    +
    + +
    +

    I’m a couple of weeks into 3D printing with a Creality Ender 3 S1 Pro. My initial impressions are: tl;dr: mechanically good, firmware bad. Either install synman’s pro firmware (requires a screen downgrade) or klipper (drops the screen and requires a raspberry pi — I went with MainsailOS) and you’ll have a very good printer for the price.

    + +

    Here’s my best 3D Benchy so far, printed in 55 minutes in PETG using Klipper +

    + +

    Pros:

    + +
      +
    • Mechanically solid and well built, comes very well packed, does not feel like the stereotypical “cheap chinese” product at all
    • +
    • Quick and easy to assemble (I recommend using loctite on all screws to prevent them coming loose from vibrations)
    • +
    • Some replacement parts available
    • +
    • Well supported with (mostly quite good) profiles available for various pieces of software
    • +
    • Touchscreen interface is fast and convenient to use if you’re satisfied with the stock firmware
    • +
    • Main board is not locked-down so it’s easy to install different firmware, and just as easy to revert to stock in the unlikely event that you want to
    • +
    + +

    Cons:

    + +
      +
    • The stock firmware is very limited and has various problems. + +
        +
      • Most notably, the “print on resume” feature causes uncontrollable pauses between layers, during which the nozzle will leak filament, causing huge blobs and stringing. Not possible to turn off in the UI, requires a M413 S0 command added to the start g-code in your slicer (or changing to a different firmware, which you should do anyway). Here’s a comparison of the exact same part with and without “resume on power loss” enabled, both printed back when I was using the stock firmware:
      • +
      • The auto bed leveling feels extremely unreliable and hard to trust
      • +
      • You can only see the first few characters of gcode files, so it’s impossible to differentiate between two similar files with different suffixes
      • +
    • +
    • Fiddly to perform firmware updates — screen and main board require separate files, sometimes in different folders depending on the chipset you have (which you can only check by opening the printer and looking at the hard-to-read MCU part number), always with a new filename otherwise it’ll fail silently, both will accept firmwares for different models with weird failure modes like a rotated screen
    • +
    • v-wheels riding in aluminium extrusions have a limited accuracy. Definitely good enough for a lot of purposes, but can warp and wear over time, will never be as good as precision-ground linear rods or (even better,) rails
    • +
    • XZ gantry arrived with loose Z nuts, causing huge amounts of Z kickback and preventing any kind of accurate movement. No indication that you have to tighten these in the instructions, and sources on the web inconsistent about what you should do about it. I ended up tightening mine up so they don’t rattle and have had no further issues.
    • +
    • Flex cable XZ clip position sticker was placed slightly wrong and awkward to adjust once in, and the flex cable end at the extruder requires better stress relief IMO. I added ~6cm of heatshrink tubing around it which works great
    • +
    • The provided slicer is horrible, I only tried it out to see if it’d fix my z blobbing problems. Fortunately Prusa Slicer works great with these printers
    • +
    + +

    I tuned mine up with the usual tools until I was satisfied with the prints using the stock firmware. Then I installed klipper and set up pressure advance and input shaping, vastly improving performance and usability.

    + +

    20mm calibration cubes printed 1) on the stock firmware, 2) Klipper with a speed profile, and 3) Klipper with a detail profile (i.e. slower outer perimeters):

    + +

    + +

    Here’s my current Prusa Slicer config files for the printer itself (Klipper) and my 0.16mm layer height optimal speed print profile.

    + +

    Here’s what my Klipper START_PRINT and END_PRINT macros ended up looking like:

    + +
    +[gcode_macro START_PRINT]
    +gcode:
    +  {% set TOTAL_LAYER_COUNT = params.TOTAL_LAYER_COUNT|int %}
    +  {% set BED_TEMP = params.BED_TEMP|float %}
    +  {% set EXTRUDER_TEMP = params.EXTRUDER_TEMP|float %}
    +
    +SET_PRINT_STATS_INFO TOTAL_LAYER={TOTAL_LAYER_COUNT}
    +  G90 ; use absolute coordinates
    +  M83 ; extruder relative mode
    +  M140 S{BED_TEMP} ; set final bed temp
    +  M104 S{EXTRUDER_TEMP - 90} ; set temporary nozzle temp to prevent oozing during homing and auto bed leveling
    +  G4 S10 ; allow partial nozzle warmup
    +  G28 ; home all axis
    +  M190 S{BED_TEMP} ; wait for bed temp to stabilize so that the bed mesh is accurate
    +  BED_MESH_CALIBRATE
    +  M104 S{EXTRUDER_TEMP} ; set final nozzle temp
    +  G1 Z50 F240
    +  G1 X2 Y10 F3000
    +  M109 S{EXTRUDER_TEMP} ; wait for nozzle temp to stabilize
    +  G1 Z0.28 F240
    +  G92 E0
    +  G1 Y140 E10 F1500 ; prime the nozzle
    +  G1 X2.3 F5000
    +  G92 E0
    +  G1 Y10 E10 F1200 ; prime the nozzle
    +  G92 E0
    +
    +[gcode_macro END_PRINT]
    +gcode:
    +  M140 S0 ; turn off heatbed
    +  M104 S0 ; turn off temperature
    +  M107 ; turn off fan
    +  # Move nozzle away from print while retracting
    +  G91
    +  G1 X-2 Y-2 E-3 F300
    +  # Raise nozzle by 10mm
    +  G1 Z10 F3000
    +  # Move out of the way
    +  G90
    +  G0 X20 Y150
    +  # Disable steppers
    +  M84 X Y E
    +
    + + + +
    +
    +
  36. +
  37. + + +
  38. +
  39. + + +
  40. +
+ + +
+ + + + + + + + + \ No newline at end of file diff --git a/tests/Mf2/waterpigs.co.uk_photo.jpg b/tests/Mf2/waterpigs.co.uk_photo.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e0f436f3e06e3f38ae13ae6e0dce665681e81c21 GIT binary patch literal 4614 zcmb7HWmJ?=w|<97njr*9sXeX%M7Eln|sO z28KpLDMh}~>$mRxd!P55wcfSPI?ptTe!7Fvv&5gKQ(i}A zu3*#o9X3u-3LSKL)TzIeeWgBwrj)RZt3^a_Zx5DfR7{LN*A9Oy8-{9{ovFHrUlOV9j`hk4;^pWa4b$~+U?9wlU2ZvR9xU6NtUvM01$*^>Hh)-hCmS@ zGIID|JIUxsE4xce;rte96lK2=9)sJWPo1j`7L|}p!PSsVxdNQ4PzlleeqB!e;zKq6 z!WdbL$5D?+%xs|l@!|hrhC`qL$*q5h!GDO6LZ0Hqy(U_ZN0~u_Dfc8^!#>C2&l5B$ zI$fjfQutI812}H`a}+(28-vYcGoV&Tv;w4kZ~%ajc>bLlL`FI>3=SZW^bCyWc$k>E z`NaO+5eN!Wkv6)t@HV{U9s7t`Krc>bcSEM^djl98${P*p_F58|ti&;mTy|IMa?ug! z%h}*(k)v{6eB%(VH&@L1qJKDhOINR*ny6%~r(%|^LSJ6~cIv3z!LzEUWDN|Kxs{OX zRq|S6cy;;oPHOk?Kx-kqFk!KK4cc?$@4@^ zn}6uJN4F`EWx8a&TJS|!SR#P2%)OZW(C1_x;+6X2v5KHk7DrM{t>rO|r2kNCcV&aj zGLLJDSbMQt{-7DE2#?w@H3-AGMvGtT#Q%ID^DgyL|4NNea=HCByG+rNU>XM&vl;iE z%3y7&B~#=Lreu=c`22Y4z^Uilosh;stYp;7J4bf(;ZO$8zS7H>ZdU&DGEZyull8=s z&i6&JT4fk}^+k+DPIcrv;>uAvW=4B$S~;~U<(m;xIto0c%`QVxEb=}*0rI)g#BOds49~gP2F?QY? zICvbketlzUboL3=M`_uO={hzRiO7k&l<7V?3SRA-CL7~a5D~&McVt(zKFpgD<);Di`jGTh&D1>anGKZ zo<@o4A~wBR=>yIDGy|*o&WR9{4;?9DDyk6$@77fcIED;pf+PJL#-1q<^OYTXVe$Gg z6P8{+;WOa3j^ebXv&#Dy?=zkOqyU$tBdH>o3=DpuT@YW?PRV+da$fQ32H;!m*Qha9I&{!7SwTq6=+$p0FE%DyTE7e%WGYN0-XQtFuD+`9j=4 zaT}^(j;X(ZG(rr6x9r;y=- zoK|(H^giiQirYkTt7Dp|{7j&DWLh}m{2Ncb?I3hoy6TB_w~Wt0vjg0 zcYjPwmOH(FGSgdB+gTSw%Xg=zA_^XN`nm9HgzX>;j%IB%(1^G(v*|u47%{O|RxJ{9 zO;Eke+K1v=*49Y*N5-UEEOi(u{-P<{k9J{4Yj2=tKk=Jrwk#z+yp=#$dE^{Zr{6bd zl$blgh_D`}@ncoQ5M^?SD3spI5BI`F3Kg{kX;7lRvak zGK|uGOe=t5OSZ&^SB`lzQE!#SNMwH+Pr9o9Q7d#M#m3NWSab}mzGA-cAml~Q8=+>- z)7P1H@`ixi9l5A@#Z^Mh{kF32y`j3i*@CTKCEn!jxF>$7Pp^<$q)v!XF$+<7&%bkq9KL~qwSV`+poca9eYkRyn8XaHQ zrR&NX@Q%B~<|WtjN#_N!rL8FKIIo5V=i3TI1p$%g(D+Bq*T(`uj4k+w z^zKD$RVBpO@%;q)jbwYurG}=__+@ zA*#S7X(Y+~W^8wzFk+XJiC2m;__>V2Bi)174l=3cvi-Nj3~3}Bxz=S0tLl88vv{u& zC0_}j0rIgyqX}eq?xsj{zu_*76)`|(t+ir8}8Z1v?-9rHxp`ursh08v{ zKmDd^3vtWpXyrYgWOn^E(-HB_ZmSFez1nk;p30C3P^h?13W5cV*$pw+l;M4!|GM!L zLrGtG?5v2-i>{))%Er0gYu6Z}W;dEA-&}5M!1o%Wg1NZD@*7RHmE~~>VSO_c0n)ac zT@uot8$W3HQkW^?#aP_rYSrx?D zKNQ=UP8U%^;OfgQE&5Rri&@2r(#q(|Jk?fFKaWQfLa~$QVa=|0{YBg4RwQ~kema7cw8nLJFf56bSaqN*lU78}M!DnrlcEdt)yQ18`8mD18 zoTreiePQ_0(m_Fiw`#@b8HOg%>R7GzelVLwf=9s)<~Ok^_1w7{0OB+w^|TG1bI3aa zazcM-QQuyaw^NsrGoDk}~hsy10tkQfc-?)u1-M#~+x}qG{^LV}F zeQyy5Yn&s-eOnNms26?K-@0%27!je{U8^Y~M z9oy1xsrx3j=Y?KlrR+agsZlmJd;+VsXwvqOG+~|rY@o2U{r#c?Dz@ME>*4dwzbtcb^4kGr+t`xNp#$5LkFFFso z&M%P92ZZlv=@5efNE9&Ri*wCq(GS-0`!@ytT1__SmX4 zb0bU@eNvh)ltVkBpNqz5)36cG9om-*I}cW2$@?mKkLpH5xr6Al`&PE{@eOrVWNg;(=$*(mi2Kmp=$LjlDv&2zMb^nexea_IDK4ZNFcio9(~AJqsvm&oULLjUzmq%Mlo-XOVQ^b90bf?MON>BK_vhZ&i8#5?{< z6RCez0wfY8rY?J{E;ZIZN^CcsWnb#;p9=XFS87L2hS+>gtQ+)o=4inQsA%coh{KVdilpmiOcjd$J_P!q{st=8s#5F!_5#Ga< z))UpE56rl=MAl{+V%d|$s8%aRtuvTv7LF5fPqLX7r`V-;qUDOe5ew?Zv@d=gE}h~a zN8+tpnI&}V7hd}J@?#EuYej0StDPJFteV*S{Dl1~jT6QL|GUQ1d~s1?Q=~$)`Y9}i zRzjD~tz}@~RU=%jIp#M12(vYMOeT%`v!C4a%}qB2bHZU~qw|X=(jPl72S-WvX2mn1 zK8bdBakd&w6z7US%0uga&)F0PM{|54tZ&_FDwgY3--E`#7!S-DD2$nJR&$RG%MZq5 z{afWb0mL1+RaD%`I2pv<#;M$awEfFmV@gdI92Ua|at8G)28 zlz{Z<&6-TxVg8q6ezuKD4C|DiV$eut37q}ih1Rm0J6_kPP8J#}yR9Yn8z>~On=D96v2 zEtOgIt9qX^XCQD=%kd0gVeJJdfok73t_Cf$E6LLO3*~g=?56`UyR$u(Q1Fz6DyP{a zV^iY`zB-EYrq(|^Q)ilSojLg*mz~IuyBCGi*eY9^58Bq{Z5)=yDLP7X4RyyKNg2V0 wngT*h?t)_nG`yZ(r-T%(eX62Ooi&WP$kCRNWXFB66p)qNd@+ymczibb9}^QW8~^|S literal 0 HcmV?d00001 From 712d7ebc4e798f4f636f1f213c0303a3b5054f47 Mon Sep 17 00:00:00 2001 From: Jan Tojnar Date: Sun, 1 Nov 2026 21:40:43 +0100 Subject: [PATCH 02/11] Remove unused variables Reported by PHPStan --- Mf2/Parser.php | 1 - 1 file changed, 1 deletion(-) diff --git a/Mf2/Parser.php b/Mf2/Parser.php index cb2aea6..5650469 100644 --- a/Mf2/Parser.php +++ b/Mf2/Parser.php @@ -215,7 +215,6 @@ function nestedMfPropertyNamesFromElement(\DOMElement $e) { * @return string */ function convertTimeFormat($time) { - $hh = $mm = $ss = ''; preg_match('/(\d{1,2}):?(\d{2})?:?(\d{2})?(a\.?m\.?|p\.?m\.?)?/i', $time, $matches); // If no am/pm is specified: From 6d27b3b31cd1725b7a525f80e17ba2e2ac6fea1a Mon Sep 17 00:00:00 2001 From: Jan Tojnar Date: Mon, 2 Nov 2026 09:31:10 +0100 Subject: [PATCH 03/11] Remove unused private method Reported by PHPStan. --- Mf2/Parser.php | 6 ------ 1 file changed, 6 deletions(-) diff --git a/Mf2/Parser.php b/Mf2/Parser.php index 5650469..f526cdb 100644 --- a/Mf2/Parser.php +++ b/Mf2/Parser.php @@ -942,12 +942,6 @@ public function parseE(\DOMElement $e) { return $return; } - private function removeTags(\DOMElement &$e, $tagName) { - while(($r = $e->getElementsByTagName($tagName)) && $r->length) { - $r->item(0)->parentNode->removeChild($r->item(0)); - } - } - /** * Recursively parse microformats * From 272e23aa8e5e6fec9dddeb97628883c4ae7dd2d7 Mon Sep 17 00:00:00 2001 From: Jan Tojnar Date: Sun, 1 Nov 2026 21:27:35 +0100 Subject: [PATCH 04/11] parseU: Handle images properly `parseImg` can return `array` in which case we would not resolve the URL properly. --- Mf2/Parser.php | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/Mf2/Parser.php b/Mf2/Parser.php index f526cdb..d43044f 100644 --- a/Mf2/Parser.php +++ b/Mf2/Parser.php @@ -542,6 +542,20 @@ public function parseImg(DOMElement $el) } return $el->getAttribute('src'); } + + /** + * @param array{value: string, alt: string}|string $img + * @return array{value: string, alt: string}|string + */ + private function resolveImg($img) { + if (is_array($img)) { + return ['value' => $this->resolveUrl($img['value'])] + $img; + } + + return $this->resolveUrl($img); + } + + /** * This method parses the language of an element * @param DOMElement $el @@ -676,7 +690,7 @@ public function parseU(\DOMElement $u) { if (($u->tagName == 'a' or $u->tagName == 'area' or $u->tagName == 'link') and $u->hasAttribute('href')) { $uValue = $u->getAttribute('href'); } elseif ( $u->tagName == 'img' and $u->hasAttribute('src') ) { - $uValue = $this->parseImg($u); + return $this->resolveImg($this->parseImg($u)); } elseif (in_array($u->tagName, array('audio', 'video', 'source', 'iframe')) and $u->hasAttribute('src')) { $uValue = $u->getAttribute('src'); } elseif ($u->tagName == 'video' and !$u->hasAttribute('src') and $u->hasAttribute('poster')) { @@ -1208,7 +1222,7 @@ public function parseImpliedPhoto(\DOMElement $e) { // img.h-x[src] if ($e->tagName == 'img') { - return $this->resolveUrl($this->parseImg($e)); + return $this->resolveImg($this->parseImg($e)); } // object.h-x[data] @@ -1234,7 +1248,7 @@ public function parseImpliedPhoto(\DOMElement $e) { $el = $els->item(0); if ($el->tagName == 'img') { $return = $this->parseImg($el); - return $this->resolveUrl($return); + return $this->resolveImg($return); } else if ($el->tagName == 'object') { return $this->resolveUrl($el->getAttribute('data')); } From 626a6107c3c113ad2ca1c3c834a1b05c86f3836e Mon Sep 17 00:00:00 2001 From: Jan Tojnar Date: Sun, 1 Nov 2026 23:02:24 +0100 Subject: [PATCH 05/11] Remove @access modifiers from PHPDoc This is already declared using native PHP keyword. --- Mf2/Parser.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/Mf2/Parser.php b/Mf2/Parser.php index d43044f..7f0fb64 100644 --- a/Mf2/Parser.php +++ b/Mf2/Parser.php @@ -529,7 +529,6 @@ private function elementToString(DOMElement $input, $implied = false) /** * Given an img property, parse its value and/or alt text * @param DOMElement $el - * @access public * @return string|array */ public function parseImg(DOMElement $el) @@ -559,7 +558,6 @@ private function resolveImg($img) { /** * This method parses the language of an element * @param DOMElement $el - * @access public * @return string */ public function language(DOMElement $el) From a36401f2d6ddd87ef17f2c7f411c3ed35df8e629 Mon Sep 17 00:00:00 2001 From: Jan Tojnar Date: Tue, 3 Nov 2026 00:54:11 +0100 Subject: [PATCH 06/11] Parser: Add PHP type hints Performed automatically using Rector. --- Mf2/Parser.php | 58 +++++++++++++++++++++++++------------------------- 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/Mf2/Parser.php b/Mf2/Parser.php index 7f0fb64..e4e16e8 100644 --- a/Mf2/Parser.php +++ b/Mf2/Parser.php @@ -113,7 +113,7 @@ function fetch($url, $convertClassic = true, &$curlInfo = []) { * @param string $input String containing characters to convert into HTML entities * @return string */ -function unicodeToHtmlEntities($input) { +function unicodeToHtmlEntities($input): string { // Convert all non-ASCII characters to HTML numeric entities. $convmap = [ 0x80, 0x1FFFFF, 0, 0x10FFFF, @@ -136,7 +136,7 @@ function unicodeTrim($str) { * @param string $prefix The prefix to look for * @return string|array The prefixed name of the first microfomats class found or false */ -function mfNamesFromClass($class, $prefix = 'h-') { +function mfNamesFromClass($class, $prefix = 'h-'): array { $class = str_replace(array(' ', ' ', "\n"), ' ', $class); $classes = explode(' ', $class); $classes = preg_grep('#^(h|p|u|dt|e)-([a-z0-9]+-)?[a-z]+(-[a-z]+)*$#', $classes); @@ -158,7 +158,7 @@ function mfNamesFromClass($class, $prefix = 'h-') { * @param string $class * @return bool */ -function classHasMf2RootClassname($class) { +function classHasMf2RootClassname($class): bool { return count(mfNamesFromClass($class, 'h-')) > 0; } @@ -171,7 +171,7 @@ function classHasMf2RootClassname($class) { * @param string $class * @return array */ -function nestedMfPropertyNamesFromClass($class) { +function nestedMfPropertyNamesFromClass($class): array { $prefixes = array('p-', 'u-', 'dt-', 'e-'); $propertyNames = array(); @@ -258,7 +258,7 @@ function convertTimeFormat($time) { * @param string $dtValue * @return string */ -function normalizeOrdinalDate($dtValue) { +function normalizeOrdinalDate($dtValue): string { list($year, $day) = explode('-', $dtValue, 2); $day = intval($day); if ($day < 367 && $day > 0) { @@ -276,7 +276,7 @@ function normalizeOrdinalDate($dtValue) { * @param string $dtValue * @return string isolated, normalized TZ offset for implied TZ for other dt- properties */ -function normalizeTimezoneOffset(&$dtValue) { +function normalizeTimezoneOffset(&$dtValue): ?string { preg_match('/Z|[+-]\d{1,2}:?(\d{2})?$/i', $dtValue, $matches); if (empty($matches)) { @@ -300,7 +300,7 @@ function normalizeTimezoneOffset(&$dtValue) { return $timezoneOffset; } -function applySrcsetUrlTransformation($srcset, $transformation) { +function applySrcsetUrlTransformation($srcset, $transformation): string { return implode(', ', array_filter(array_map(function ($srcsetPart) use ($transformation) { $parts = explode(" \t\n\r\0\x0B", trim($srcsetPart), 2); $parts[0] = rtrim($parts[0]); @@ -424,7 +424,7 @@ public function __construct($input, $url = null, $jsonMode = false) { $this->jsonMode = $jsonMode; } - private function elementPrefixParsed(\DOMElement $e, $prefix) { + private function elementPrefixParsed(\DOMElement $e, string $prefix): void { if (!$this->parsed->offsetExists($e)) $this->parsed->offsetSet($e, array()); @@ -439,7 +439,7 @@ private function elementPrefixParsed(\DOMElement $e, $prefix) { * @param string $prefix * @return bool */ - private function isElementParsed(\DOMElement $e, $prefix) { + private function isElementParsed(\DOMElement $e, string $prefix): bool { if (!$this->parsed->offsetExists($e)) { return false; } @@ -459,7 +459,7 @@ private function isElementParsed(\DOMElement $e, $prefix) { * @param string $property * @return bool */ - private function isElementUpgraded(\DOMElement $el, $property) { + private function isElementUpgraded(\DOMElement $el, $property): bool { if ( $this->upgraded->offsetExists($el) ) { if ( in_array($property, $this->upgraded[$el]) ) { return true; @@ -469,7 +469,7 @@ private function isElementUpgraded(\DOMElement $el, $property) { return false; } - private function resolveChildUrls(DOMElement $el) { + private function resolveChildUrls(DOMElement $el): void { $hyperlinkChildren = $this->xpath->query('.//*[@src or @href or @data]', $el); foreach ($hyperlinkChildren as $child) { @@ -962,7 +962,7 @@ public function parseE(\DOMElement $e) { * @param bool $has_nested_mf Whether this microformat has a nested microformat * @return array A representation of the values contained within microformat $e */ - public function parseH(\DOMElement $e, $is_backcompat = false, $has_nested_mf = false) { + public function parseH(\DOMElement $e, $is_backcompat = false, $has_nested_mf = false): ?array { // If it’s already been parsed (e.g. is a child mf), skip if ($this->parsed->offsetExists($e)) { return null; @@ -1267,7 +1267,7 @@ public function parseImpliedPhoto(\DOMElement $e) { * in parsed results if $this->enableAlternates = true. * @return array|stdClass */ - public function parseRelsAndAlternates() { + public function parseRelsAndAlternates(): array { $rels = array(); $rel_urls = array(); $alternates = array(); @@ -1367,7 +1367,7 @@ public function parseRelsAndAlternates() { * which will then be upgraded to p-category during backcompat. * @param DOMElement $el */ - public function upgradeRelTagToCategory(DOMElement $el) { + public function upgradeRelTagToCategory(DOMElement $el): void { $rel_tag = $this->xpath->query('.//a[contains(concat(" ",normalize-space(@rel)," ")," tag ") and not(contains(concat(" ", normalize-space(@class), " "), " category ")) and @href]', $el); if ( $rel_tag->length ) { @@ -1393,7 +1393,7 @@ public function upgradeRelTagToCategory(DOMElement $el) { * @param DOMElement $context optionally specify an element from which to parse microformats * @return array An array containing all the microformats found in the current document */ - public function parse($convertClassic = true, ?DOMElement $context = null) { + public function parse($convertClassic = true, ?DOMElement $context = null): array { $this->convertClassic = $convertClassic; $mfs = $this->parseRecursive($context); @@ -1421,7 +1421,7 @@ public function parse($convertClassic = true, ?DOMElement $context = null) { * @param int $depth: recursion depth * @return array */ - public function parseRecursive(?DOMElement $context = null, $depth = 0) { + public function parseRecursive(?DOMElement $context = null, $depth = 0): array { $mfs = array(); $mfElements = $this->getRootMF($context); @@ -1567,7 +1567,7 @@ public function getRootMF(?DOMElement $context = null) { * @param bool $isParentMf2 * @see http://microformats.org/wiki/microformats2-parsing#algorithm */ - public function backcompat(DOMElement $el, $context = '', $isParentMf2 = false) { + public function backcompat(DOMElement $el, $context = '', $isParentMf2 = false): void { if ( $context ) { $mf1Classes = array($context); @@ -1738,7 +1738,7 @@ public function backcompat(DOMElement $el, $context = '', $isParentMf2 = false) * @param DOMElement $el * @param string|array $property */ - public function addUpgraded(DOMElement $el, $property) { + public function addUpgraded(DOMElement $el, $property): void { if ( !is_array($property) ) { $property = array($property); } @@ -1757,7 +1757,7 @@ public function addUpgraded(DOMElement $el, $property) { * @param DOMElement $el * @param string $classes */ - public function addMfClasses(DOMElement $el, $classes) { + public function addMfClasses(DOMElement $el, $classes): void { $existingClasses = str_replace(array("\t", "\n"), ' ', $el->getAttribute('class')); $existingClasses = array_filter(explode(' ', $existingClasses)); @@ -1772,7 +1772,7 @@ public function addMfClasses(DOMElement $el, $classes) { * Check an element for mf2 h-* class, typically to determine if backcompat should be used * @param DOMElement $el */ - public function hasRootMf2(\DOMElement $el) { + public function hasRootMf2(\DOMElement $el): bool { $class = str_replace(array("\t", "\n"), ' ', $el->getAttribute('class')); // Check for valid mf2 root classnames, not just any classname with a h- prefix. @@ -1787,7 +1787,7 @@ public function hasRootMf2(\DOMElement $el) { * * @return Parser $this */ - public function convertLegacy() { + public function convertLegacy(): self { $doc = $this->doc; $xp = new DOMXPath($doc); @@ -2221,7 +2221,7 @@ public function query($expression, $context = null) { ); } -function parseUriToComponents($uri) { +function parseUriToComponents($uri): array { $result = array( 'scheme' => null, 'authority' => null, @@ -2259,7 +2259,7 @@ function parseUriToComponents($uri) { return $result; } -function resolveUrl($baseURI, $referenceURI) { +function resolveUrl($baseURI, $referenceURI): string { $target = array( 'scheme' => null, 'authority' => null, @@ -2343,7 +2343,7 @@ function resolveUrl($baseURI, $referenceURI) { } # 5.2.3 Merge Paths -function mergePaths($base, $reference) { +function mergePaths(array $base, array $reference) { # If the base URI has a defined authority component and an empty # path, if($base['authority'] && $base['path'] == null) { @@ -2367,7 +2367,7 @@ function mergePaths($base, $reference) { } # 5.2.4.A Remove leading ../ or ./ -function removeLeadingDotSlash(&$input) { +function removeLeadingDotSlash(&$input): void { if(substr($input, 0, 3) == '../') { $input = substr($input, 3); } elseif(substr($input, 0, 2) == './') { @@ -2376,7 +2376,7 @@ function removeLeadingDotSlash(&$input) { } # 5.2.4.B Replace leading /. with / -function removeLeadingSlashDot(&$input) { +function removeLeadingSlashDot(&$input): void { if(substr($input, 0, 3) == '/./') { $input = '/' . substr($input, 3); } else { @@ -2385,7 +2385,7 @@ function removeLeadingSlashDot(&$input) { } # 5.2.4.C Given leading /../ remove component from output buffer -function removeOneDirLevel(&$input, &$output) { +function removeOneDirLevel(&$input, &$output): void { if(substr($input, 0, 4) == '/../') { $input = '/' . substr($input, 4); } else { @@ -2395,7 +2395,7 @@ function removeOneDirLevel(&$input, &$output) { } # 5.2.4.D Remove . and .. if it's the only thing in the input -function removeLoneDotDot(&$input) { +function removeLoneDotDot(&$input): void { if($input == '.') { $input = substr($input, 1); } else { @@ -2404,7 +2404,7 @@ function removeLoneDotDot(&$input) { } # 5.2.4.E Move one segment from input to output -function moveOneSegmentFromInput(&$input, &$output) { +function moveOneSegmentFromInput(&$input, &$output): void { if(substr($input, 0, 1) != '/') { $pos = strpos($input, '/'); } else { From 56572ec18acedbeb7af6a9759d73032afbc6a748 Mon Sep 17 00:00:00 2001 From: Jan Tojnar Date: Sun, 1 Nov 2026 20:51:15 +0100 Subject: [PATCH 07/11] Parser: Adjust type hints --- Mf2/Parser.php | 189 ++++++++++-------------- tests/Mf2/MicroformatsTestSuiteTest.php | 2 +- tests/Mf2/ParserTest.php | 3 +- 3 files changed, 78 insertions(+), 116 deletions(-) diff --git a/Mf2/Parser.php b/Mf2/Parser.php index e4e16e8..44b073a 100644 --- a/Mf2/Parser.php +++ b/Mf2/Parser.php @@ -41,7 +41,7 @@ * @param bool $convertClassic whether or not to convert classic microformats * @return array Canonical MF2 array structure */ -function parse($input, $url = null, $convertClassic = true) { +function parse($input, ?string $url = null, bool $convertClassic = true): array { $parser = new Parser($input, $url); return $parser->parse($convertClassic); } @@ -62,7 +62,7 @@ function parse($input, $url = null, $convertClassic = true) { * @param array &$curlInfo (optional) the results of curl_getinfo will be placed in this variable for debugging * @return array|null canonical microformats2 array structure on success, null on failure */ -function fetch($url, $convertClassic = true, &$curlInfo = []) { +function fetch(string $url, bool $convertClassic = true, array &$curlInfo = []): ?array { $version = '0'; if (is_array($curl = curl_version())) { $version = $curl['version']; @@ -111,9 +111,8 @@ function fetch($url, $convertClassic = true, &$curlInfo = []) { /** * Unicode to HTML Entities * @param string $input String containing characters to convert into HTML entities - * @return string */ -function unicodeToHtmlEntities($input): string { +function unicodeToHtmlEntities(string $input): string { // Convert all non-ASCII characters to HTML numeric entities. $convmap = [ 0x80, 0x1FFFFF, 0, 0x10FFFF, @@ -122,7 +121,7 @@ function unicodeToHtmlEntities($input): string { return mb_encode_numericentity($input, $convmap, mb_detect_encoding($input), true); } -function unicodeTrim($str) { +function unicodeTrim(string $str): string { return preg_replace('/^\s+|\s+$/u', '', $str); } @@ -134,9 +133,9 @@ function unicodeTrim($str) { * * @param string $class A space delimited list of classnames * @param string $prefix The prefix to look for - * @return string|array The prefixed name of the first microfomats class found or false + * @return string[] The prefixed name of the first microfomats class found or false */ -function mfNamesFromClass($class, $prefix = 'h-'): array { +function mfNamesFromClass(string $class, string $prefix = 'h-'): array { $class = str_replace(array(' ', ' ', "\n"), ' ', $class); $classes = explode(' ', $class); $classes = preg_grep('#^(h|p|u|dt|e)-([a-z0-9]+-)?[a-z]+(-[a-z]+)*$#', $classes); @@ -155,10 +154,8 @@ function mfNamesFromClass($class, $prefix = 'h-'): array { /** * Registered with the XPath object and used within XPaths for finding root elements. - * @param string $class - * @return bool */ -function classHasMf2RootClassname($class): bool { +function classHasMf2RootClassname(string $class): bool { return count(mfNamesFromClass($class, 'h-')) > 0; } @@ -168,10 +165,9 @@ function classHasMf2RootClassname($class): bool { * Returns all the p-, u-, dt- or e- prefixed classnames it finds in a * space-separated string. * - * @param string $class - * @return array + * @return array> */ -function nestedMfPropertyNamesFromClass($class): array { +function nestedMfPropertyNamesFromClass(string $class): array { $prefixes = array('p-', 'u-', 'dt-', 'e-'); $propertyNames = array(); @@ -194,17 +190,19 @@ function nestedMfPropertyNamesFromClass($class): array { * * @param DOMElement $e The element to get the classname for * @param string $prefix The prefix to look for - * @return mixed See return value of mf2\Parser::mfNameFromClass() + * @return string[] See return value of mf2\Parser::mfNamesFromClass() */ -function mfNamesFromElement(\DOMElement $e, $prefix = 'h-') { +function mfNamesFromElement(\DOMElement $e, string $prefix = 'h-'): array { $class = $e->getAttribute('class'); return mfNamesFromClass($class, $prefix); } /** - * Wraps nestedMfPropertyNamesFromClass to handle an element as input + * Wraps nestedMfPropertyNamesFromClass to handle an element as input* + * + * @return array> */ -function nestedMfPropertyNamesFromElement(\DOMElement $e) { +function nestedMfPropertyNamesFromElement(\DOMElement $e): array { $class = $e->getAttribute('class'); return nestedMfPropertyNamesFromClass($class); } @@ -212,9 +210,8 @@ function nestedMfPropertyNamesFromElement(\DOMElement $e) { /** * Converts various time formats to HH:MM * @param string $time The time to convert - * @return string */ -function convertTimeFormat($time) { +function convertTimeFormat(string $time): string { preg_match('/(\d{1,2}):?(\d{2})?:?(\d{2})?(a\.?m\.?|p\.?m\.?)?/i', $time, $matches); // If no am/pm is specified: @@ -255,10 +252,8 @@ function convertTimeFormat($time) { * Normalize an ordinal date to YYYY-MM-DD * This function should only be called after validating the $dtValue * matches regex \d{4}-\d{2} - * @param string $dtValue - * @return string */ -function normalizeOrdinalDate($dtValue): string { +function normalizeOrdinalDate(string $dtValue): string { list($year, $day) = explode('-', $dtValue, 2); $day = intval($day); if ($day < 367 && $day > 0) { @@ -273,10 +268,9 @@ function normalizeOrdinalDate($dtValue): string { /** * If a date value has a timezone offset, normalize it. - * @param string $dtValue - * @return string isolated, normalized TZ offset for implied TZ for other dt- properties + * @return ?string isolated, normalized TZ offset for implied TZ for other dt- properties */ -function normalizeTimezoneOffset(&$dtValue): ?string { +function normalizeTimezoneOffset(string &$dtValue): ?string { preg_match('/Z|[+-]\d{1,2}:?(\d{2})?$/i', $dtValue, $matches); if (empty($matches)) { @@ -300,7 +294,10 @@ function normalizeTimezoneOffset(&$dtValue): ?string { return $timezoneOffset; } -function applySrcsetUrlTransformation($srcset, $transformation): string { +/** + * @param callable(string): string $transformation + */ +function applySrcsetUrlTransformation(string $srcset, callable $transformation): string { return implode(', ', array_filter(array_map(function ($srcsetPart) use ($transformation) { $parts = explode(" \t\n\r\0\x0B", trim($srcsetPart), 2); $parts[0] = rtrim($parts[0]); @@ -326,48 +323,42 @@ function applySrcsetUrlTransformation($srcset, $transformation): string { */ class Parser { /** @var string The baseurl (if any) to use for this parse */ - public $baseurl; + public string $baseurl; /** @var DOMXPath object which can be used to query over any fragment*/ - public $xpath; + public DOMXPath $xpath; /** @var DOMDocument */ - public $doc; + public DOMDocument $doc; - /** @var SplObjectStorage */ - protected $parsed; + protected SplObjectStorage $parsed; - /** - * @var bool - */ - public $jsonMode; + public bool $jsonMode; - /** @var boolean Whether to include experimental language parsing in the result */ - public $lang = false; + /** @var bool Whether to include experimental language parsing in the result */ + public bool $lang = false; /** @var bool Whether to include alternates object (dropped from spec in favor of rel-urls) */ - public $enableAlternates = false; + public bool $enableAlternates = false; /** - * Elements upgraded to mf2 during backcompat - * @var SplObjectStorage + * @var SplObjectStorage Elements upgraded to mf2 during backcompat */ - protected $upgraded; + protected SplObjectStorage $upgraded; /** - * Whether to convert classic microformats - * @var bool + * @var bool Whether to convert classic microformats */ - public $convertClassic; + public bool $convertClassic; /** * Constructor * - * @param DOMDocument|string $input The data to parse. A string of HTML or a DOMDocument - * @param string $url The URL of the parsed document, for relative URL resolution - * @param boolean $jsonMode Whether or not to use a stdClass instance for an empty `rels` dictionary. This breaks PHP looping over rels, but allows the output to be correctly serialized as JSON. + * @param DOMDocument|string|null $input The data to parse. A string of HTML or a DOMDocument + * @param ?string $url The URL of the parsed document, for relative URL resolution + * @param bool $jsonMode Whether or not to use a stdClass instance for an empty `rels` dictionary. This breaks PHP looping over rels, but allows the output to be correctly serialized as JSON. */ - public function __construct($input, $url = null, $jsonMode = false) { + public function __construct($input, ?string $url = null, bool $jsonMode = false) { $emptyDocDefault = ''; libxml_use_internal_errors(true); if (is_string($input)) { @@ -394,6 +385,7 @@ public function __construct($input, $url = null, $jsonMode = false) { $this->xpath->registerNamespace('php', 'http://php.net/xpath'); $this->xpath->registerPhpFunctions('\\Mf2\\classHasMf2RootClassname'); + $url = $url ?? ''; $baseurl = $url; foreach ($this->xpath->query('//base[@href]') as $base) { $baseElementUrl = $base->getAttribute('href'); @@ -455,11 +447,8 @@ private function isElementParsed(\DOMElement $e, string $prefix): bool { /** * Determine if the element's specified property has already been upgraded during backcompat - * @param DOMElement $el - * @param string $property - * @return bool */ - private function isElementUpgraded(\DOMElement $el, $property): bool { + private function isElementUpgraded(\DOMElement $el, string $property): bool { if ( $this->upgraded->offsetExists($el) ) { if ( in_array($property, $this->upgraded[$el]) ) { return true; @@ -486,11 +475,9 @@ private function resolveChildUrls(DOMElement $el): void { /** * The following two methods implements plain text parsing. - * @param DOMElement $element - * @param bool $implied * @see https://wiki.zegnat.net/media/textparsing.html **/ - public function textContent(DOMElement $element, $implied = false) + public function textContent(DOMElement $element, bool $implied = false): string { return preg_replace( '/(^[\t\n\f\r ]+| +(?=\n)|(?<=\n) +| +(?= )|[\t\n\f\r ]+$)/', @@ -498,7 +485,7 @@ public function textContent(DOMElement $element, $implied = false) $this->elementToString($element, $implied) ); } - private function elementToString(DOMElement $input, $implied = false) + private function elementToString(DOMElement $input, bool $implied = false): string { $output = ''; foreach ($input->childNodes as $child) { @@ -528,8 +515,7 @@ private function elementToString(DOMElement $input, $implied = false) /** * Given an img property, parse its value and/or alt text - * @param DOMElement $el - * @return string|array + * @return array{value: string, alt: string}|string */ public function parseImg(DOMElement $el) { @@ -557,10 +543,8 @@ private function resolveImg($img) { /** * This method parses the language of an element - * @param DOMElement $el - * @return string */ - public function language(DOMElement $el) + public function language(DOMElement $el): string { // element has a lang attribute; use it if ($el->hasAttribute('lang')) { @@ -584,11 +568,7 @@ public function language(DOMElement $el) } # end method language() // TODO: figure out if this has problems with sms: and geo: URLs - public function resolveUrl($url) { - // If not a string then return. - if (!is_string($url)){ - return $url; - } + public function resolveUrl(string $url): string { // If the URL is seriously malformed it’s probably beyond the scope of this // parser to try to do anything with it. if (parse_url($url) === false) { @@ -617,7 +597,7 @@ public function resolveUrl($url) { * @param string $separator = '' if multiple value-title elements, join with this string * @return string|null the parsed value or null if value-class or -title aren’t in use */ - public function parseValueClassTitle(\DOMElement $e, $separator = '') { + public function parseValueClassTitle(\DOMElement $e, string $separator = ''): ?string { $valueClassElements = $this->xpath->query('./*[contains(concat(" ", normalize-space(@class), " "), " value ")]', $e); if ($valueClassElements->length !== 0) { @@ -653,7 +633,7 @@ public function parseValueClassTitle(\DOMElement $e, $separator = '') { * @return string The plaintext value of $p, dependant on type * @todo Make this adhere to value-class */ - public function parseP(\DOMElement $p) { + public function parseP(\DOMElement $p): string { $classTitle = $this->parseValueClassTitle($p, ' '); if ($classTitle !== null) { @@ -681,7 +661,7 @@ public function parseP(\DOMElement $p) { * Given an element with class="u-*", get the value of the URL * * @param DOMElement $u The element to parse - * @return string The plaintext value of $u, dependant on type + * @return string|array{value: string, alt: string} The plaintext or array value of $u, dependant on type * @todo make this adhere to value-class */ public function parseU(\DOMElement $u) { @@ -713,10 +693,9 @@ public function parseU(\DOMElement $u) { * * @param DOMElement $dt The element to parse * @param array $dates Array of dates processed so far - * @param string $impliedTimezone * @return string The datetime string found */ - public function parseDT(\DOMElement $dt, &$dates = array(), &$impliedTimezone = null) { + public function parseDT(\DOMElement $dt, array &$dates = array(), ?string &$impliedTimezone = null): string { // Check for value-class pattern $valueClassChildren = $this->xpath->query('./*[contains(concat(" ", normalize-space(@class), " "), " value ") or contains(concat(" ", normalize-space(@class), " "), " value-title ")]', $dt); $dtValue = false; @@ -910,7 +889,7 @@ public function parseDT(\DOMElement $dt, &$dates = array(), &$impliedTimezone = * Given the root element of some embedded markup, return a string representing that markup * * @param DOMElement $e The element to parse - * @return string $e’s innerHTML + * @return string|array{html: string, value: string, lang?: string} * * @todo need to mark this element as e- parsed so it doesn’t get parsed as it’s parent’s e-* too */ @@ -962,7 +941,7 @@ public function parseE(\DOMElement $e) { * @param bool $has_nested_mf Whether this microformat has a nested microformat * @return array A representation of the values contained within microformat $e */ - public function parseH(\DOMElement $e, $is_backcompat = false, $has_nested_mf = false): ?array { + public function parseH(\DOMElement $e, bool $is_backcompat = false, bool $has_nested_mf = false): ?array { // If it’s already been parsed (e.g. is a child mf), skip if ($this->parsed->offsetExists($e)) { return null; @@ -1215,6 +1194,7 @@ public function parseH(\DOMElement $e, $is_backcompat = false, $has_nested_mf = /** * @see http://microformats.org/wiki/microformats2-parsing#parsing_for_implied_properties + * @return array{value: string, alt: string}|string|false */ public function parseImpliedPhoto(\DOMElement $e) { @@ -1265,7 +1245,7 @@ public function parseImpliedPhoto(\DOMElement $e) { * optimizing for JSON serialization. Otherwise they will be returned as an empty array. * Note that $alternates is deprecated in the microformats spec in favor of $rel_urls. $alternates only appears * in parsed results if $this->enableAlternates = true. - * @return array|stdClass + * @return array{0: array, 1: array, 2: array} */ public function parseRelsAndAlternates(): array { $rels = array(); @@ -1393,7 +1373,7 @@ public function upgradeRelTagToCategory(DOMElement $el): void { * @param DOMElement $context optionally specify an element from which to parse microformats * @return array An array containing all the microformats found in the current document */ - public function parse($convertClassic = true, ?DOMElement $context = null): array { + public function parse(bool $convertClassic = true, ?DOMElement $context = null): array { $this->convertClassic = $convertClassic; $mfs = $this->parseRecursive($context); @@ -1419,9 +1399,8 @@ public function parse($convertClassic = true, ?DOMElement $context = null): arra * Keeps track of whether inside a backcompat root or not * @param DOMElement $context: node to start with * @param int $depth: recursion depth - * @return array */ - public function parseRecursive(?DOMElement $context = null, $depth = 0): array { + public function parseRecursive(?DOMElement $context = null, int $depth = 0): array { $mfs = array(); $mfElements = $this->getRootMF($context); @@ -1522,9 +1501,8 @@ public function parse_recursive(?DOMElement $context = null, $depth = 0) { * * @param string $id * @param bool $convertClassic whether or not to convert classic microformats - * @return array */ - public function parseFromId($id, $convertClassic = true) { + public function parseFromId(string $id, bool $convertClassic = true): array { $matches = $this->xpath->query("//*[@id='{$id}']"); if (empty($matches)) @@ -1535,10 +1513,8 @@ public function parseFromId($id, $convertClassic = true) { /** * Get the root microformat elements - * @param DOMElement $context - * @return DOMNodeList */ - public function getRootMF(?DOMElement $context = null) { + public function getRootMF(?DOMElement $context = null): DOMNodeList { // start with mf2 root class name xpath $xpaths = array( '(php:function("\\Mf2\\classHasMf2RootClassname", normalize-space(@class)))' @@ -1562,12 +1538,9 @@ public function getRootMF(?DOMElement $context = null) { /** * Apply the backcompat algorithm to upgrade mf1 classes to mf2. * This method is called recursively. - * @param DOMElement $el - * @param string $context - * @param bool $isParentMf2 * @see http://microformats.org/wiki/microformats2-parsing#algorithm */ - public function backcompat(DOMElement $el, $context = '', $isParentMf2 = false): void { + public function backcompat(DOMElement $el, ?string $context = '', bool $isParentMf2 = false): void { if ( $context ) { $mf1Classes = array($context); @@ -1735,7 +1708,6 @@ public function backcompat(DOMElement $el, $context = '', $isParentMf2 = false): /** * Add element + property as upgraded during backcompat - * @param DOMElement $el * @param string|array $property */ public function addUpgraded(DOMElement $el, $property): void { @@ -1754,10 +1726,8 @@ public function addUpgraded(DOMElement $el, $property): void { /** * Add the provided classes to an element. * Does not add duplicate if class name already exists. - * @param DOMElement $el - * @param string $classes */ - public function addMfClasses(DOMElement $el, $classes): void { + public function addMfClasses(DOMElement $el, string $classes): void { $existingClasses = str_replace(array("\t", "\n"), ' ', $el->getAttribute('class')); $existingClasses = array_filter(explode(' ', $existingClasses)); @@ -1770,7 +1740,6 @@ public function addMfClasses(DOMElement $el, $classes): void { /** * Check an element for mf2 h-* class, typically to determine if backcompat should be used - * @param DOMElement $el */ public function hasRootMf2(\DOMElement $el): bool { $class = str_replace(array("\t", "\n"), ' ', $el->getAttribute('class')); @@ -1784,8 +1753,6 @@ public function hasRootMf2(\DOMElement $el): bool { * * Adds microformats2 classnames into a document containing only legacy * semantic classnames. - * - * @return Parser $this */ public function convertLegacy(): self { $doc = $this->doc; @@ -1815,20 +1782,15 @@ public function convertLegacy(): self { * * Runs an XPath query over the current document. Works in exactly the same * way as DOMXPath::query. - * - * @param string $expression - * @param DOMNode $context - * @return DOMNodeList */ - public function query($expression, $context = null) { + public function query(string $expression, ?DOMNode $context = null): DOMNodeList { return $this->xpath->query($expression, $context); } /** - * Classic Root Classname map - * @var array + * @var array Classic Root Classname map */ - public $classicRootMap = array( + public array $classicRootMap = array( 'vcard' => 'h-card', 'hfeed' => 'h-feed', 'hentry' => 'h-entry', @@ -1843,10 +1805,9 @@ public function query($expression, $context = null) { ); /** - * Mapping of mf1 properties to mf2 and the context they're parsed with - * @var array + * @var array Mapping of mf1 properties to mf2 and the context they're parsed with */ - public $classicPropertyMap = array( + public array $classicPropertyMap = array( 'vcard' => array( 'fn' => array( 'replace' => 'p-name' @@ -2221,7 +2182,7 @@ public function query($expression, $context = null) { ); } -function parseUriToComponents($uri): array { +function parseUriToComponents(string $uri): array { $result = array( 'scheme' => null, 'authority' => null, @@ -2259,7 +2220,7 @@ function parseUriToComponents($uri): array { return $result; } -function resolveUrl($baseURI, $referenceURI): string { +function resolveUrl(string $baseURI, string $referenceURI): string { $target = array( 'scheme' => null, 'authority' => null, @@ -2343,7 +2304,7 @@ function resolveUrl($baseURI, $referenceURI): string { } # 5.2.3 Merge Paths -function mergePaths(array $base, array $reference) { +function mergePaths(array $base, array $reference): string { # If the base URI has a defined authority component and an empty # path, if($base['authority'] && $base['path'] == null) { @@ -2367,7 +2328,7 @@ function mergePaths(array $base, array $reference) { } # 5.2.4.A Remove leading ../ or ./ -function removeLeadingDotSlash(&$input): void { +function removeLeadingDotSlash(string &$input): void { if(substr($input, 0, 3) == '../') { $input = substr($input, 3); } elseif(substr($input, 0, 2) == './') { @@ -2376,7 +2337,7 @@ function removeLeadingDotSlash(&$input): void { } # 5.2.4.B Replace leading /. with / -function removeLeadingSlashDot(&$input): void { +function removeLeadingSlashDot(string &$input): void { if(substr($input, 0, 3) == '/./') { $input = '/' . substr($input, 3); } else { @@ -2385,7 +2346,7 @@ function removeLeadingSlashDot(&$input): void { } # 5.2.4.C Given leading /../ remove component from output buffer -function removeOneDirLevel(&$input, &$output): void { +function removeOneDirLevel(string &$input, string &$output): void { if(substr($input, 0, 4) == '/../') { $input = '/' . substr($input, 4); } else { @@ -2395,7 +2356,7 @@ function removeOneDirLevel(&$input, &$output): void { } # 5.2.4.D Remove . and .. if it's the only thing in the input -function removeLoneDotDot(&$input): void { +function removeLoneDotDot(string &$input): void { if($input == '.') { $input = substr($input, 1); } else { @@ -2404,7 +2365,7 @@ function removeLoneDotDot(&$input): void { } # 5.2.4.E Move one segment from input to output -function moveOneSegmentFromInput(&$input, &$output): void { +function moveOneSegmentFromInput(string &$input, string &$output): void { if(substr($input, 0, 1) != '/') { $pos = strpos($input, '/'); } else { @@ -2421,11 +2382,11 @@ function moveOneSegmentFromInput(&$input, &$output): void { } # 5.2.4 Remove Dot Segments -function removeDotSegments($path) { +function removeDotSegments(?string $path): string { # 1. The input buffer is initialized with the now-appended path # components and the output buffer is initialized to the empty # string. - $input = $path; + $input = $path ?? ''; $output = ''; $step = 0; diff --git a/tests/Mf2/MicroformatsTestSuiteTest.php b/tests/Mf2/MicroformatsTestSuiteTest.php index 9a90ede..03e8c7c 100644 --- a/tests/Mf2/MicroformatsTestSuiteTest.php +++ b/tests/Mf2/MicroformatsTestSuiteTest.php @@ -7,7 +7,7 @@ final class TestSuiteParser extends \Mf2\Parser { /** Actually textContent from before the whitespace normalisation merge (e8da04f93d548d26287a8980eca4216639cbc61d) */ - public function textContent(\DOMElement $el, $dummy = false) { + public function textContent(\DOMElement $el, bool $dummy = false): string { $excludeTags = array('noframe', 'noscript', 'script', 'style', 'frames', 'frameset'); if (isset($el->tagName) and in_array(strtolower($el->tagName), $excludeTags)) { diff --git a/tests/Mf2/ParserTest.php b/tests/Mf2/ParserTest.php index 0346b4f..00d4222 100644 --- a/tests/Mf2/ParserTest.php +++ b/tests/Mf2/ParserTest.php @@ -288,7 +288,8 @@ public function testFetchMicroformats() { $mf = Mf2\fetch($indexUrl); $this->assertArrayHasKey('items', $mf); - $mf = Mf2\fetch($photoUrl, null, $curlInfo); + $curlInfo = []; + $mf = Mf2\fetch($photoUrl, false, $curlInfo); $this->assertNull($mf); $this->assertStringContainsString('jpeg', $curlInfo['content_type']); From 3554757e334acf7cbe8950dbcc96b87e867d680c Mon Sep 17 00:00:00 2001 From: Jan Tojnar Date: Sun, 1 Nov 2026 22:28:19 +0100 Subject: [PATCH 08/11] Url::removeOneDirLevel: Handle extra `/..` PHP would complain about passing `false` to `substr` with `strict_types` enabled. --- Mf2/Parser.php | 7 ++++++- tests/Mf2/URLTest.php | 2 ++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/Mf2/Parser.php b/Mf2/Parser.php index 44b073a..bf215f3 100644 --- a/Mf2/Parser.php +++ b/Mf2/Parser.php @@ -2352,7 +2352,12 @@ function removeOneDirLevel(string &$input, string &$output): void { } else { $input = '/' . substr($input, 3); } - $output = substr($output, 0, strrpos($output, '/')); + $end = strrpos($output, '/'); + if ($end === false) { + $output = ''; + } else { + $output = substr($output, 0, $end); + } } # 5.2.4.D Remove . and .. if it's the only thing in the input diff --git a/tests/Mf2/URLTest.php b/tests/Mf2/URLTest.php index 2da4691..2c83ea1 100644 --- a/tests/Mf2/URLTest.php +++ b/tests/Mf2/URLTest.php @@ -109,6 +109,8 @@ public function removeDotSegmentsData() { '/a/b/c/d/../../../g', '/a/g'), array('Should not add leading slash', 'a/b/c', 'a/b/c'), + array('Should remove extra ..', + '/a/b/../../../..', '/'), ); } From 9ec5eb7778d0f30b0349e630675819698f3eb212 Mon Sep 17 00:00:00 2001 From: Jan Tojnar Date: Sun, 1 Nov 2026 21:28:32 +0100 Subject: [PATCH 09/11] Parser: enable strict_types To catch type errors rather than having PHP silently mangle the data and maybe do something incorrect. --- Mf2/Parser.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Mf2/Parser.php b/Mf2/Parser.php index bf215f3..b6960fc 100644 --- a/Mf2/Parser.php +++ b/Mf2/Parser.php @@ -1,5 +1,7 @@ Date: Sun, 1 Nov 2026 23:30:12 +0100 Subject: [PATCH 10/11] Add types using PHPDoc to xpath results To satisfy PHPStan level 2. --- Mf2/Parser.php | 37 +++++++++++++++++++++++-- tests/Mf2/MicroformatsTestSuiteTest.php | 3 ++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/Mf2/Parser.php b/Mf2/Parser.php index b6960fc..572b9aa 100644 --- a/Mf2/Parser.php +++ b/Mf2/Parser.php @@ -6,6 +6,7 @@ use DOMDocument; use DOMElement; +use DOMText; use DOMXPath; use DOMNode; use DOMNodeList; @@ -389,6 +390,7 @@ public function __construct($input, ?string $url = null, bool $jsonMode = false) $url = $url ?? ''; $baseurl = $url; + /** @var DOMElement $base */ foreach ($this->xpath->query('//base[@href]') as $base) { $baseElementUrl = $base->getAttribute('href'); @@ -407,6 +409,7 @@ public function __construct($input, ?string $url = null, bool $jsonMode = false) } // Ignore