Ken Guest’s online diary

July 14, 2022

“Hive token as expired”

Filed under: home assistant — kenguest @ 13:24

( The Hive “climate platform” is a set of products from that allow for remote control of your heating system, including thermostats. )

The HACS Hive integration in Home Assistant threw this into the logs today, which meant that I had to do things via the Hive app this morning instead of using the integration in Home Assistant.

“Hive token as expired when calling – HTTP status is – 401”

I had been using a release of the Hive integration several releases behind the current release – version 2021.2.6, where I didn’t have 2FA enabled in the app because that was breaking authentication for this integration. Then I upgraded to 2022.7.3 and found that the “Hive token as expired” message was being reported.

The fix was simple, somewhere along the updates the maintainers of the Hive Integration must have added support for Hive’s 2FA and I just needed to :

  1. Delete the hive section from Home Assistant’s configuration.yaml file
  2. Enable 2FA in the Hive app
  3. Reinstall the latest version of the Hive integration (I uninstalled it after encountering the problem)
  4. Re-enter my credentials, including the new Hive verification code when prompted by Home Assistant.


Or something.

May 31, 2021

Setting emails in Yii1 to not trigger Out of Office responses.

Filed under: php,yii — kenguest @ 11:18
Tags: ,

Christian Weiske recently wrote on how to set emails in Laravel to not trigger Out of Office responses.

This is typically done for emails that are auto-generated – for processes such as “Forgot Password” functionality and the like. There’s an RFC for this. In essence, you add an “Auto-Submitted: auto-generated” header to the email.

As I’ve been adding “Forgot Password” functionality for a legacy project, I thought I would see how this would be done in Yii1:

$yMessage = new YiiMailMessage();

$yMessage->setFrom($fromEmail, $fromName);

$yMessage->setBody($htmlMessage, "text/html", "UTF-8");

$yMessage->setSubject(Yii::t("Link for resetting your password"));

// Mark the email as auto-generated so "Out of office" responses aren't triggered. (RFC-3834)


$yMessage->getHeaders()->addTextHeader("Auto-Submitted", "auto-generated");


This is much simpler in Yii1 than Laravel as no callbacks are required.

March 21, 2019

Upgrading to PHP 7.1.27 – how to fix the GPG error: error.

Filed under: apt,php — kenguest @ 09:22

If, like me, you’re still using PHP7.1, then you should upgrade to the most current security release which is 7.1.27 and was released on the 7th of March. Prior to that we were on 7.1.24 and missed out on fixed for a number of CVEs that were addressed in 7.1.26  and 7.1.25 – and fixes for a segmentation fault or two as well.

This morning, doing this on Debian Jessie yielded the error:

W: An error occurred during the signature verification. 
The repository is not updated and the previous index files will be used.
GPG error: jessie InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY B188E2B695BD4743

This is because Ondřej Surý – who maintains the packages there – had to change over to a new DPA signing key as it was present on a server which got compromised.

This means that to install packages from there since the new one was switched to, I needed to download the new key:

# wget -O /etc/apt/trusted.gpg.d/php.gpg

After doing that a quick apt-get update set things straight again and apt-get upgrade could then carry on and move things along to 7.1.27.

Realising then that we’d missed out on upgrading to 7.1.27 sooner, I’ve added an additional check to our own product’s status page to determine whether the version of PHP being used is the newest “on-branch” version. It looks something like:

* Get the current/latest version released on branch x for PHP_VERSION.
* @param string $version Branch/Version to check for. e.g. 7.1 or 7.1.23...
* @return string
function getLatestPHPReleaseOnBranch($version)
    $v = explode(".", $version);
    $branch = "{$v[0]}.{$v[1]}";
    $major = $v[0];
    if (extension_loaded('curl')) {
        $url = "";
        $curl = curl_init($url);

        // Use browser's user agent string.
        $agent = $_SERVER['HTTP_USER_AGENT'];

        curl_setopt($curl, CURLOPT_USERAGENT, $agent);
        curl_setopt($curl, CURLOPT_FAILONERROR, true);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $json = curl_exec($curl);
        $decoded = json_decode($json, true);
        $version = $decoded[$major][$branch]['version'];
        return $version;
    } else {
        return null;
$latestPHP = getLatestPHPReleaseOnBranch(PHP_VERSION);
if ($latestPHP !== null) {
    echo "Using most recent on-branch PHP release? ", version_compare($current, $latestPHP, "==") ? "Yes" : "No", " (Latest release is $latestPHP Currently on ", PHP_VERSION , ")";

Please use this, or something similar, to determine when and if you need to update your PHP install.

July 31, 2017

And another phing…

Filed under: phing,php — kenguest @ 20:57

Additional things learnt from developing the Mercurial tasks for phing, the php build system based on Java’s Ant tool.

Versions and compatibility.

As much as we might want to ignore versions of PHP that have been EOL-ed (ones
that are no longer supported officially by the good people at, phing
requires that code defining [new] tasks parse ok when linted by php 5.2.
In other words – namespaces are out, “use” is not to be used, short array
syntax is forbidden, the elvis operator has to leave the building etc etc.

Best thing to do, that doesn’t involve installing an age-old version of PHP?
Use Wim Godden’s excellent PHPCompatibility sniffs for PHP_CodeSniffer, and set
it to lint for 5.2. This doesn’t mean that new tasks developed for Phing 2.x have to work in PHP5.2, it just means that loading the main task code has to lint ok.
This is going to change in phing 3.0 where the minimum version of PHP is going to be 5.6, for those slackers that haven’t upgraded to PHP 7 yet.

Don’t reinvent.

In phing xml syntax, you can specify ‘truthy’ values as “yes”, “on”, “true”, “t”, “no”, “off”, “false” and “f”. The best way to handle all this is with:

$bValue = StringHelper::booleanValue($xmlValue);

Much neater than rolling your own, which I was guilty of earlier on! It’s interesting to note though that there is also a Project::toBoolean($value) static function which does something quite similar, but doesn’t consider ‘t’ or ‘f’ as truthy values.

There’s also a StringHelper::isBoolean function that could also be of use,
depending on what you need.

If you refactor things out to a base or abstract class, make sure that you
pull in that class

e.g. require_once ‘phing/tasks/ext/directory/Filename.php’

Internal Properties

There are a number of “internal properties” available, listed at – to get the values
of these inside a Task subclass:

$project = $this->getProject();
$dir = $project->getProperty(‘application.startdir’);

Setting Properties

If you’re at the stage of coding a phing extension/task, you’ll most certainly
know how to define a property in phing XML:

But, defining a phing property in PHP?
You can do it with either:
$project->setNewProperty(“prop”, “value”);
$project->setProperty(“existingProp”, “newValue”);
depending on what you want to do.

Update your grammar

The etc/phing-grammar.rng file is used in PHPStorm and other such IDEs to
provide syntax highlighting and validation for phing build.xml files – so you
can tell at a glance whether you might have typed in xmlint instead of xmllint,
for example.

So it makes sense especially so if you’re adding a new attribute to an existing
phing task or type to update this file.

If you’re adding properties that take default values, this can be indicated in the phing-grammar.rng file as can be seen in the definition for the truncate task:

 <define name="truncate">
     <element name="truncate">
         <attribute name="file"/>
             <attribute name="adjust"/>
             <attribute name="length"/>
     <attribute name="create" a:defaultValue="true">
         <data type="boolean"/>
         <attribute name="mkdirs" a:defaultValue="false">
             <data type="boolean"/>


That’s all for now – just a quick blog entry this time!

June 2, 2017

Installing PHPDOC via PEAR when there are Certificate problems.

Filed under: php — kenguest @ 10:34

There are currently some SSL Certificate issues with installing phpDocumentor from their pear channel. ([1])

This is how to circumvent those issues, while still installing phpdoc onto a “clean” server that doesn’t even have the phpdoc channel added:
$ wget –no-check-certificate
$ wget –no-check-certificate
$ sudo pear channel-add channel.xml
$ sudo pear install –force –alldeps phpDocumentor-2.9.0.tgz



August 17, 2016

Command Line Scripts in Laravel.

Filed under: laravel,php — kenguest @ 19:16

A while ago I had reason to write some command line tools using the Laravel framework. These are some notes on what I’ve learnt from the experience.

The basics.

Command line tools written for Laravel should subclass Illuminate\Console\Command.

The description and signature properties of the class are used in the artisan
listing of commands, for displaying a command specific help paragraph and
specifying what parameters the command takes.

If setting the signature in the constructor, this must be done before calling the parent’s constructor.

The main entry point is the class’s handle method.

use Illuminate\Console\Command;

class MyCommand extends Command
  protected $description = "Does this and that.";
  protected $signature = '';

  public function __construct()
    $foo = env('SOME_ENVIRONMENT_SETTING', 'myCommand');
    $this->signature = "$foo:assorted {--s|setting=$option : option's description.} {arg1 : arg1's description}";

  public function handle()
    // get arg1 as entered at the command line.
    $arg1 = $this->argument('arg1');

    // To determine if 'quiet' was set, we need all options first.
    $options = $this->option();
    $option = $options['option'];
    $this->quiet = $options['quiet'];

    // Onwards...
    if (!this->quiet) {
    try {
    } catch(\Exception $ex) {
    } finally {
    if (!this->quiet) {

Using PSR3 logging methods (such as “info”, “error” and the others), is better than just doing an echo $message as these can be presented differently depending on what style logger you might choose to use later.
As it stands, the various messages are output to the console in different colours, for example “error” lines are printed in red, “info” messages are displayed in green, and so on.
If you want to display an ordinary, non-coloured line, then use the line method:

  $this->gt;line("Plain line of text.");


A progressbar can be displayed at the command-line instead of filling up the scrollback with however many lines which might essentially indicate the same but less succinctly.

To initialise the standard progress bar:

  $this->output->progressStart($max); // $max is the total number of items being "progressed", e.g. 516 or whatever

To advance:

  while($this->completeAPortionOfWork()) {

And to finish it off at 100%:


December 25, 2015

USB Lamp tweaks.

Filed under: phing,python — kenguest @ 22:04

My wife got me a cheeky webmail notifier (an USB lamp that changes colour) as a part of my over-generous Christmas present.

After a little diversion to Christian’s write-up, I downloaded the  usblamp project from GitHub and made a few little pythonic tweaks I decided to share:

  1. is more configurable (the mailbox and lamp colour had been hard-coded).
  2. The lamp is turned off once new emails have been opened.
  3. closes cleanly, turning off the lamp too –
  4. usblamp recognises ‘pink’ as a colour, which my wife kinda insisted on 🙂 [ e.g. $ usblamp pink works 🙂 ]

So now my lamp turns pink when I receive a new email from Aisling, and turns off once I read it.

There is one issue that I haven’t addressed: what if the lamp is already on, and set to some other colour when it is supposed to switch on in If, for example, I have phing switching it to red because a build has failed, I might want it to flash between the two colours.

I guess that’s something I’ll have to leave for another day.

November 6, 2015

Scan your code for old-style constructors using phpcs.

Filed under: php — kenguest @ 13:53

There are less than seven days left until PHP 7 is released, which drops support for old-style constructors – the ones where a method is a constructor if it shares the same name as the class.

You don’t want to spend too much time scrolling through codebases for that though do you? Better things to do, like watch videos of conference talks you’ve missed and such.

Well, you’re in luck. If you use php_codesniffer (and if you don’t, well shame on you), you’ll be able to get a report of old-style constructors fairly quickly.

This will run php code sniffer and identify old-style constructors.

    $ phpcs --standard=Squiz --extensions=php --sniffs=Generic.NamingConventions.ConstructorName .

It’s a bit long-winded, so wrap it up in a bash alias, say in your .bashrc:

    $ alias findoldphpconstructors='phpcs --standard=Squiz --extensions=php --sniffs=Generic.NamingConventions.ConstructorName .'

Want a CSV report of the same? Use this:

alias findoldphpconstructorsToCSV=’phpcs –standard=Squiz –report=csv  –extensions=php –sniffs=Generic.NamingConventions.ConstructorName . | cut -f1,2 -d,’

Remember your unit tests.
Naturally when you do anything at all like this you really should write and run unit tests to ensure no side-effects have been caused inadvertently.

November 5, 2015

Getting phing custom tasks up to PR standard. What I did.

Filed under: phing,php — kenguest @ 13:44
Tags: ,


Phing is a build system that I’ve written about before which is open source, and developed in PHP.

Two custom tasks that I wrote have been merged into the main phing repository on github and I thought I might write up my notes on what I did to get them up to “PR Standard”.

The first task is for creating and modifying .ini files and is now documented at

The second one is simply a ‘task-wrapper’ (trademark pending) for running notify-send so that pop-up or toaster messages (whatever you want to call them) get displayed at certain stages of a build. This is more efficient for me that alt-tabbing to the window that I’ve phing running in to see what’s going on.

I’m not going to describe how to use them here; hopefully the documentation that I wrote for them in phing is sufficient.

I’m also not going to outline how to write custom tasks – there’s already good documentation for that at

Instead I want to document what I learnt in the process of taking the earlier version of NotifySendTask ( ) and the IniFileTask, and getting them to Pull Request standard for inclusion in phing.

Who knows, this might help some of you decide to add a phing Pull Request of your own.

Documentation Driven Development.

Documentation is always a factor on how well an OSS project will be used, so this is one of the first things that I wanted to address.

The inifile task is an optional one – it is not a core phing task – so I added a new section to the optionaltasks docbook file at

Because the IniFileTask is pretty much a direct port of the ant-contrib equivalent, I took the documentation from and made just a few changes as I wanted to add support for a ‘haltonerror’
Converting it over to docbook from HTML was relatively trivial.

If I wanted, I could have used a docbook specific editor for doing this, but I was comfortable using vim, so I did.

I did something similar for the NotifySend task, except that there is an intentional non-documented attribute.


I added some examples to the documentation and only after the PR for inifiletask did I look at the PDF version of the manual.

I noticed only then that example listings look best when kept to a maximum length of 80 characters per line – after 90 characters or so the lines get truncated.

On with the code.


Obviously in a build system it is expected to see messages being logged, and possibly at differing levels of importance.

To log a message at the default level:
    $this->log("Log this message");

Or, explicitly:
    $this->log("Log this message", Project::MSG_INFO);

These are the levels/priorities that messages can be inserted into the log at:

  • Project::MSG_DEBUG
  • Project::MSG_ERR
  • Project::MSG_INFO
  • Project::MSG_VERBOSE
  • Project::MSG_WARN

You will see below that you can assert against entries being present, or not, in the log.

Knowing all this makes it easier to assert in unit tests that various edge cases are being tested properly, and without adding any visual clutter when the task is being run casually.

Enabling a new task by default.

To make the tasks visible by default, for testing and also so they can be used with the minimum of hassle, I referenced them in the file classes/phing/tasks/ by adding these lines:



The location of the unit test file for the task has to mirror the location of the actual task files; so because the ‘working’ code for the task is in phing/classes/phing/tasks/ext/inifile I put the unit tests into the test/classes/phing/tasks/ext/inifile/ directory.

The NotifySendTask that I developed is less complex in that it requires just one class rather than the four for the IniFileTask so the files for that are ini the tasks/ext directory instead of requiring a separate subdirectory for them. Though if I split out the unit tests for that into separate files then I would’ve created a subdirectory for them rather than clutter up tasks/ext.

Test specific build files for unit tests can be used, they are executed via the executeTarget and should be placed inside the etc/tasks/ext directory structure.

For example: etc/tasks/ext/NotifySendTaskTest.xml

Or a separate subdirectory structure such as ./etc/tasks/ext/inifile/inifile.xml

The unit test class should be a subclass of BuildFileTest.

BuildFileTest provides a number of helper methods, for example assertInLogsassertNotInLogs, configureProject and executeTarget, expectBuildException and others.

Use configureProject in the setUp method to initialise the project that the unit tests are for.

assertInLogs("Assert this text exists in the logs");
assertInLogs("Assert this text exists in the logs", Project::MSG_DEBUG);

 * Configure the project to point to the correct .xml file for these tests
public function setUp() {
    $this->configureProject(PHING_TEST_BASE . "/etc/tasks/ext/inifile/inifile.xml");
    $this->object = new ThisIsTheNewTask();

public function testSetterOutsideXml() {
    $this->object->setTitleProperty("test title");
    $this->assertEquals("test title", $this->object->getTitleProperty());

public function testInTarget()
    $this->assertInLogs("expected as debug log entry", Project::MSG_DEBUG);

public function testTargetUsingHelper()
    $this->expectDebuglog("targetToTest", "expected as debug log entry");

The PHING_TEST_BASE constant is used to refer to the base directory for all phing test files. As well as that, the test functions testInTarget and testTargetUsingHelper are functionally identical. There are many other useful methods in the BuildFileTest class and I looked through phing/test/classes/phing/BuildFileTest.php to get familiar with
what else it can do.
There is also a PhingTestListener class in that BuildFileTest.php file, but there currently are no tasks with unit tests which utilise it.

As mentioned earlier, build files can be used in unit tests. This is very useful so that you can test that the setters in tasks load and work properly when phing parses the XML files. Explicitly calling setters and getters for your unit tests will only go so far, while testing against actual build files will highlight whether or not setters that are expected to be called will be.
The build file to use for unit tests is specified in the configureProject call.
There are a number of helper functions that go along with the executeTarget method, such as expectPropertySet, expectLog, expectLogContaining, expectDebuglog, expectOutput, expectOutputAndError, and two more related to
catching expected exceptions.

Working on the Task code.

One of the main things that I added to the Pull-Request version of the NotifySendTask was additional logging and getters that could be utilised for unit testing.

I also added extra validation on the values being set – checking generic icon values are valid, and if a specified icon is a filename then the task logs whether the file actually exists and so on.

After considering how to handle unit tests being run on systems where notify-send itself wasn’t installed – I added a control parameter, in the vein of an Operator Presence Control, so the system can essentially fake running successfully.

This is the one attribute that I didn’t add to the documentation.

The IniFileTask code is perhaps a level of complexity above that for NotifySendTask – in that there are extra XML elements required, and so extra classes are required as well; all of which have their respective setter methods by necesitty. Also I opted to add corresponding getter methods to these to allow unit tests that don’t require specific build files for each test.

This is also why inifile got a subdirectory for itself and the simpler notifysend task did not.


That’s all folks!

If there’s anything you think I should have covered, let me know and I’ll either edit this with an update or write a follow-up, depending on how substantial it is 🙂

July 17, 2015

When a Coding Standard isn’t.

Filed under: php — kenguest @ 13:16

If Tommy Cooper were still alive and into developing software, I think he’d have a great many oneliners to share.

The best one being “When is a coding standard not a coding standard? When it’s your own individual one!”.

Seriously though, hearing people say they follow their own style or coding-standard just makes me cringe.

If the coding standard that you use is an individual one, then please don’t call it a “standard” because by definition it isn’t. It’s an anti-standard.

Pick one that’s supported by the main IDEs (phpstorm, netbeans et al) and php_codesniffer (don’t forget it can also analyse your JavaScript and CSS). To be honest in one way I don’t really care which CS standard you choose, just pick one* and stick with it. Making up your own one, especially if it’s specific to yourself and nobody else, is just wasting other people’s time and will cost you later on. I’d go as far as to say it’s disrespectful.

Even if you’re just a one-guy-code-house. Somebody else may be called in to work on your code and the last thing they need to do is waste time parsing your [convoluted] code when the guy that paid you for it is pestering them for an update to get a specific bug that is costing them money (twice if you stop to think about it) fixed.

Consider the next guy who has to pick up your wonderfully-unique-snowflake-of-rubbish and get it working again.

If you’re working in a team, you should know all this anyway and be mature enough to know to play/code well with others and quit wasting their time. Otherwise just grow up.


* $DEITY knows there are enough to choose from. Doing a quick “phpcs -i” on my laptop results shows me this list:

“The installed coding standards are Made, Ecg, PSR2, MySource, PSR1, PHPCompatibility, PEAR, Squiz, CodeIgniter, PHPCS and Zend”

Next Page »

Create a free website or blog at