Setting up PHP CodeSniffer on Sublime for applying WordPress Coding Standards

I spent a shameful amount of time trying to troubleshoot various issues while trying to make it work. The following are the steps I used to finally get it right.

The software that we’ll rely on

  • Sublime Text 3 – as it’s the most common and rather light code editor out there;
  • PHP 5.4 or higher;
  • PHP CodeSniffer 3.3.1 or higher. If you got a lower version, you’d be getting some weird errors when running it against the WordPress standards, as it’s WPCS that requires that version;
  • PHP Mess Detector;
  • PHP Code Sniffer Sublime package;
  • PHP Code Beautifier Sublime package;
  • Composer;
  • Debian based Linux. You can do that whole setup on almost any other OS, but there will be some differences in the commands. I did it on a Linux Mint 19.2 Tina, based on Ubuntu 18.04 bionic.

Step 1: Installation

Let’s assume that you already have Sublime Text installed. Check your version just to make sure you are working on v3 or higher.

subl -v

Checking PHP’s version is done in a similar manner:

php -v

There are several ways of installing PHP CodeSniffer, Mess Detector and Composer.

1.1. You could start with the easiest one, trying to get these packages from the distribution’s package manager:

sudo apt install composer php-codesniffer phpmd

After the installation is over, check whether phpcs that you just installed is 3.3.1 or higher version. If it’s lower, better remove it and a more manual approach.

1.2. Manually installing the needed packages isn’t too much of a deal, but updating them would cost you some extra efforts, compared to having them through your package manager. Here are the commands for each of the packages you need. If you have some of them from your package manager, don’t waste your time getting them through this method.

mkdir ~/bin && cd ~/bin //preparing a directory where we’ll download all the software we need

git clone https://github.com/squizlabs/PHP_CodeSniffer.git phpcs

git clone git://github.com/phpmd/phpmd.git

curl -s http://getcomposer.org/installer | php

After we’ve downloaded them, we need to make them executable without having to write relative or absolute paths:

sudo ln -s ~/bin/phpcs/bin/phpcs /usr/local/bin/phpcs
sudo ln -s ~/bin/phpmd/src/bin/phpmd /usr/local/bin/phpmd
sudo ln -s ~/bin/phpcs/bin/phpcbf /usr/local/bin/phpcbf
sudo ln -s ~/bin/composer.phar /usr/local/bin/composer

There’s one more step required for PHP Mess Detector:

cd ~/bin/phpmd && composer install

If installation is done properly, you should have the given commands available: phpcs, phpmd, phpcbf and composer.

Step 2. Getting WordPress Coding Standards

You could clone the repo straight from GitHub:

git clone https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards.git ~/bin/wpcs

That’s it. Now you need to

Step 3. Configure PHP CodeSniffer to work with WPCS

Two commands are needed here. First will let phpcs know that there’s a bunch of new standards in town. To see the current ones, run:

phpcs -i

If you don’t see WordPress there, which is actually what usually happens with a clean install, run this:

phpcs --config-set installed_paths ~/bin/wpcs

At this point, if you check with the previous command again, you should see something like this:

The installed coding standards are MySource, PSR12, PSR2, PSR1, PEAR, Zend, Squiz, WordPress-Docs, WordPress-Extra, WordPress-Core and WordPress

Cool. Now let’s make WordPress the default standard:

phpcs --config-set default_standard WordPress

Step 4. Check if it works in command line

Create a test file with some badly formatted PHP. Here’s a sample for you:

<?php $JustAVar ='nope'; if($JustAVar == true) { echo 'Hi there!'; ///whatever

Let’s have this code in a new file, located in /tmp/ugly.php

The test would be to run phpcs /tmp/ugly.php. The result we are looking for, is something like this:

FILE: /tmp/ugly.php
FOUND 11 ERRORS AND 1 WARNING AFFECTING 3 LINES
1 | ERROR | [ ] Missing file doc comment
1 | ERROR | [ ] Variable “$JustAVar” is not in valid snake_case format, try “$just_a_var”
1 | ERROR | [x] Expected 1 space after “=”; 0 found
1 | ERROR | [x] Space after opening control structure is required
1 | ERROR | [x] Expected 1 space(s) after IF keyword; 0 found
1 | ERROR | [x] Inline control structures are not allowed
1 | ERROR | [ ] Variable “$JustAVar” is not in valid snake_case format, try “$just_a_var”
1 | WARNING | [ ] Found: ==. Use strict comparisons (=== or !==).
1 | ERROR | [ ] Use Yoda Condition checks, you must.
1 | ERROR | [x] Each PHP statement must be on a line by itself
2 | ERROR | [x] No space found before comment text; expected “// /whatever” but found “///whatever”
3 | ERROR | [ ] PHP syntax error: syntax error, unexpected end of file
PHPCBF CAN FIX THE 6 MARKED SNIFF VIOLATIONS AUTOMATICALLY
Time: 130ms; Memory: 8MB

Neat, isn’t it?

It’s time to

Step 5. Configure Sublime Text

If you still don’t have the two Sublime packages that I mentioned earlier, install them:

Press Ctrl + Shift + P, type “install” and select “phpcs”, then repeat the same procedure for “CodeBeautifier”.

Now you need to edit the PHP Code Sniffer package configuration in order to set the executable paths for phpcs, phpcbf and phpmd. What I did was copy the default configuration from Preferences -> Package Settings -> PHP Code Sniffer -> Settings - Default in Settings - User and edit the following variables:

"phpcs_executable_path": "/usr/local/bin/phpcs"
"phpcbf_executable_path": "/usr/local/bin/phpcbf"
"phpmd_executable_path": "/usr/local/bin/phpmd"

Furthermore, you should comment out settings for PHP-CS-Fixer, or even delete them, as you won’t be using this package (unless you actually plan on using it).

Finally, you should set the standard to be used for all of the commands to WordPress. Look for lines, with a key "--standard" and set them all to WordPress like this:

"--standard": "WordPress"

Feel free to check the rest of the settings, available in the configuration in order to avoid unwanted automatic fixes or checks.

After you save the configuration, open that funny file again:

subl /tmp/ugly.php

Save it and see if you get any notifications about it. Fixing some of these would be as simple as right-clicking in the editor and selecting PHP Code Sniffer -> Fix this file -> PHP Code Beautifier (phpcbf).

Have in mind that there might be some issues with the configuration, leading to triggering code fixing even if you didn’t set it this way, so make sure to test all of this before running it on a client’s codebase.

This article was originally created for my team-mates from DevriX.

How to contribute to the community by translating WordPress

I’ve been general translations editors for the Bulgarian language in the local WordPress community for years, yet I decided to write this article in English, as I believe the approach here could be followed for just any other language.

Prerequisites:

In order to contribute to WordPress through translating the project in another language, you should:

  • have solid knowledge in English and the language you are translating to. Needless to say, otherwise you could be dealing more harm than actually helping the community.
  • have an active account in wordpress.org, as you’ll need it for working in translate.wordpress.org and wordpress.slack.com. Local communities might have other slack addresses using that account too.
  • bring a laptop with yourself at the event you are attending or have one at home if you are contributing remotely.
  • know that you don’t need to be a programmer or be extremely experienced in WordPress in order to be helpful. Having that knowledge could be of use to you, but is definitelly not required.

Before you actually start translating:

There are a few resources you should get aquainted with, before you dive into the work you are preparing for:

  1. Local language translation guidelines – each language with an active translating community should have such a source of documentation. For Bulgarian it’s located here: https://bg.wordpress.org/превод-на-български. If you can’t find such for your language of choice, contact folks in the #polyglots channel in wordpress.slack.com and ask them about it directly. Or even better, contact the local community, if listed in this page: https://make.wordpress.org/polyglots/handbook/about/teams/local-slacks/
    Translating without getting to know these guidelines could lead to bad translations and lack of consistency between your translations and those already done by other translators.
  2. Locale glossary – usually it’s located in GlotPress under the main local page. Here’s the one for Bulgarian: https://translate.wordpress.org/locale/bg/default/glossary/ . It’s the place where most common terms are listed with their translation for sake of consistency. Always check the glossary if you are unsure of what could be the best translation for a technical term.
    If you haven’t translated WordPress before, it’s a must-read.
  3. Polyglots handbook – this is the general handbook for translations in WordPress: https://make.wordpress.org/polyglots/handbook/
    It’s a pretty extensive material, so feel free to skip it if you feel confident enough or if you are too eager to already start translating.
  4. Project-specific glossaries – if you are translating a specific plugin or theme, it’s good idea to check whether there is a glossary for the terms used in that project. Here’s an example with a glossary specifically for WooCommerce in Bulgarian: https://translate.wordpress.org/projects/wp-plugins/woocommerce/stable/bg/default/glossary/
  5. GlotPress – it’s the software that is hosted on translate.wordpress.org, the main translations portal for the WordPress community. You can start your contribution here.

How it actually works?

Strings of all WordPress projects are available for translation in translate.wordpress.org, where anyone with an active account can contribute by suggesting translations to a specific language. The suggestions by all translators are then being reviewed by translation editors who could be global for the given language (GTE), or responsible for that specific project (PTE).

Start from picking a project that you’d like to contribute to:

Core always comes first!

Usually WordPress Core (button WordPress) from the list is the highest priority. From that list always focus on the current and future versions of the project, unless you want to edit a specific old string which is not translated well. There are separate projects for each major WordPress version, but no projects for the minor ones, as they don’t bring too many new strings.

Themes & Plugins buttons are self-explanatory, Meta is meant for internal projects as wordpress.org, make.wordpress.org, support forums, plugins and themes directories and a few others. Apps is used for two mobile applications, used by the SaaS wordpress.com, owned by Automattic (which is odd), and an Android app for WordCamps.

If you have difficulty deciding on the plugins or themes that it’s worth working on, have a look a the Stats divide in plugins and themes groups, where you’ll see the list of the most popular ones with info on how much work is left there.

Once you’ve chosen a project to work on, you might have to decide on the subproject. WordPress Core has a few sub projects, related to the context:

WordPress Core sub projects

Plugins have different ones – development and stable, depending whether you’d be translating the latest string from “trunk” of the SVN repository (development) or the latest release of the plugin (stable). These two sub projects are divided further into strings from the project and strings from the readme.txt file, which is being displayed in the Plugin Directory.

A plugin translations sub projects

As translations from Development are directly being applied to the Stable release, whenever they match, you should always prefer the Development sub projects, when translating a project.

There are a number of fields one can use for filtering the strings for adding a translation or editing existing ones. See the image below:

Filters for translatable strings

Searching for strings, containing a specific word is done by using the “Term” field. The rest of the options there are self-explanatory.

Above the search and filter form there is a number of statuses for direct filtering of all strings for the project. When you are starting your contribution efforts best is to focus on the Untranslated list. “Fuzzy” are suggestions that were once valid, but after changes in the strings from the code are in a state of uncertainty and need to be checked in order to ensure no bad translations are entering the project. “Warning” translations are such that have mismatched punctuation, placeholders, HTML tags, spacing or other issues, that are automatically detected. Some of them could easily be fixed, so feel free to go through them, if you find any. “Waiting” are the strings that someone already have a proposed translation. This doesn’t mean that you can’t suggest a better one.

While translating, GlotPress provides you a number of tools you can use for doing a better job with your contribution. See the image below:

Goodies in GlotPress when translating a string
  1. Code references display the source of the string. If you have even the most basic understanding of PHP code, you will be able to gain additional context on the string that you are translating by checking the line in the code where this string is available.
  2. The button clones the original string in the text field for translation. Helpful when you are translating a string with special characters and HTML – typing them again could lead to typos.
  3. The help button provides some links to resources and explanation for the different statuses a translation might have.
  4. Suggestions, listed in this section, are taken from the consistency search (see it in the “useful tools” section). These come quite handy sometimes, but you should be careful to not apply blindly translations that are from a different context.
  5. In some rare occasions seeing the translation of the string in another language could help for making the right decision for your language.

Have in mind that if your translations get edited, even for just a typo or missing punctuation, they will no longer be accounted as your translations.

Useful tools during translation:

  • Google Translate – it’s the obvious one, but it’s important to remember, that it’s often far from perfect and the translation might totally miss the context of what you are translating. Still, it remains the best tool for getting a rough draft of a long paragraph that you could later edit and make more human-readable.
  • Glosbe Dictionary – extremely useful dictionary that searches terms in existing translations of documents, software and so on in order to provide the best options for the word or phrase you are looking for. I’ve had quite a few cases when this was more useful than Google Translate.
  • POEdit – it’s a desktop translation files editor that you can use in case you are offline or prefer not to work in the browser.
  • Consistency search – GlotPress provides a nice tool for searching a string in existing translations for the given locale within translate.wordpress.org. Bear in mind that not all translations are following the guidelines and and not all are relevant for your context.
  • Poopy Life – if you need a quick live test of a plugin or theme in order to see where a string is being displayed, this site will spin up a clean new WordPress instance in a minute and will remain for 24 hours. This is the perfect solution for anyone who doesn’t have a site of their own, nor a local testing environment. This could be used in combination with WP Reset and WP Rollback plugins in order to get a clean db after doing some tests or getting an older version of a plugin or theme.

This document was originally created for my team-mates from DevriX, who are organizing an internal contributor weekend (yay!). Hopefully it would help others get into translations as well!

Няколкото инструмента на WordPress преводача

Пиша си списък за следващия път, когато се захвана да превеждам нещо от чужда машина, където нямам запазени съответните връзки. Ако намерите полезен и за вас инструмент или сайт – халал да ви е!

  • Търсачката за други преводи на конкретен низ сред екосистемата на WordPress (Translation Consistency Search). Важно е да вземете предвид, че не винаги ще получавате търсения резултат дори да сте сигурни, че той съществува някъде там. Въпреки това е доста полезен инструмент както за откриване на подходящи преводи, така и за откриване на други места, където е наложен грешен превод от типа “breadcrumb” -> “навигационна пътека” срещу “хлебна троха”.
  • Гугълските преводи – колкото и да са популярни, реших да ги спомена. Не винаги най-читавите преводи идват от там, но за някои термини е удобно да се види и това “мнение”.
  • Многоезичен онлайн речник Glosbe – изключително полезен сайт-речник, в който можете да разчитате на преводи на думи и фрази, извличани от официални преводи на европейски документи, наръчници и всякакви други текстове, които ви дават шанса да се докоснете до доста по-професионални преводи. Имах моменти, в които този речник ми беше няколко пъти по-полезен от гугълския, така че горещо препоръчвам да си го имате под ръка, когато не сте сигурни как да преведете някакъв термин.
  • Напътствия и общи правила за българските преводи – препрочитам си ги от време на време, за да не забравя нещо. Следването на тези правила помага за по-малко странно звучащите текстове и надписи из българския WordPress.
  • Обичайните преводи на често срещани термини в WordPress – речникът се допълва от време на време от активните преводачи, а термините вътре е добре да сте ги прочели поне веднъж, за да не се случи “plugin” да го преведете някъде като “плъгин”.
  • Брояч на думи и низове – това е конзолен инструмент за Линукс, с който лесно се броят думите и низовете в даден .po файл, като се изчислява % на преведените, непреведените и т.н. Полезно е, когато трябва да оцените прогреса си или колко работа всъщност ви очаква, защото броя низове в GlotPress не винаги е най-обективната информация за обема, през който трябва да минете.

*Като казвам WordPress преводач, имам предвид доброволец (или платен такъв), заловил се да превежда низове на теми, разширения или самото ядро на платформата. Няма съществено значение дали преводите се правят през GlotPress (translate.wordpress.org) или друг инструмент (примерно POEdit).

 

Как разширение за WordPress с наличен код в GitHub направи $100k продажби за по-малко от година

Обожавам успешните примери в света на отворения код, особено когато са свързани с бизнес, който да гарантира по-дългосрочна устойчивост.

В конкретния случай, който няма да преразказвам, добавка към платеното WordPress разширение Gravity Forms, оригинално правено за контактни формуляри, прави много сериозни пари, без да си крие кода зад система за плащане.

Просто прочетете:

GravityView has passed $100k in sales – GravityView

Да подкараш Tzar под Линукс

Известно време имах ужасяващата драма с невъзможността да подкарам Tzar: The burden of the crown на Linux Mint 17 заради някакъв проблем със Setup.exe, заради което не успявах да си затъркалям първоначалната конфигурация, която да позволи пускането на самата игра. Едва днес разбрах, че мога да пиша в конзолата:

wine Setup.exe

за да разбера какво точно се случва. Оказа се, че липсва dll файл:

err:module:import_dll Loading library MFC42.DLL

Решението пък е безкрайно просто. Инсталираме winetricks и го убеждаваме да ни реши проблема:

sudo apt-get install winetricks
winetricks mfc42

Предполагам, че по същия начин winetricks би работил и за други сравнително популярни dll библиотеки.

Error 500 when opening Statistics in OpenX 2.8

OpenX versions before 2.8.10 got an issue with PHP 5.4, so if you can’t access Statistics on your OpenX server, there is a good chance you’ve hit this incompatibility.

Fixing it is pretty easy once you know the solution – either go to OpenX v.2.8.10 or edit the following files in order to remove the pointers:

<openx-root-folder>/lib/OA/Admin/Statistics/Delivery/CommonEntity.php – the block starting at line 292:

$oPlugin->mergeAds(&$this->childrendata[‘ad_id’]); //BEFORE

$oPlugin->mergeAds($this->childrendata[‘ad_id’]); //AFTER

 

<openx-root-folder>/lib/OA/Admin/Statistics/Delivery/CommonEntity.php – the block starting at line 322:

$oPlugin->mergeZones(&$this->childrendata[‘zone_id’]); //BEFORE

$oPlugin->mergeZones($this->childrendata[‘zone_id’]); //AFTER

 

<openx-root-folder>/lib/OA/Admin/Statistics/Delivery/CommonHistory.php – the function starting at line 160:

parent::prepare(&$aParams); //BEFORE

parent::prepare($aParams); //AFTER

 

Credits for the solution go to Aleksandr Cherniyh, his article openx-2.8 and php-5.4 and  the comment with solution by Crow.

Internal Server Error при ползване на APC с WP Super Cache

При преместването на една WordPress инстанция към нов сървър, където се оказа пуснато APC кеширане, сайтът взе да изчезва в произволни моменти, изкарвайки Internal Server Error 500. Рестартиране на Apache оправяше проблемът до следващия уж случаен момент, в който отново сайта пукваше. Пуснах debug mode на WordPress, за да видя следната грешка:

Fatal error: Internal Zend error – Missing class information for in wp-cache-base.php on line 5

Това, което препоръчват за решаването на този проблем е да се вкара един ред в конфигурацията на APC (/etc/php5/conf.d/apc.ini):

apc.include_once_override = 0

И те такам.

Инсталация на Sublime Text в Linux

Вместо да се захващам тепърва да го свалям от някъде и да го компилирам, правя следното (в терминала):

sudo add-apt-repository ppa:webupd8team/sublime-text-2
sudo apt-get update
sudo apt-get install sublime-text

Какво се случва? С първата команда вкарваме в списъка със източници за обновяване и софтуер източника на Sublime. С втората си обновяваме списъка с пакети, които можем да инсталираме от всички наши източници (включително новия) и с последната команда го инсталираме.

Обновяване на Linux Mint 11 до Mint 14 Nadia

Дълго време си кретах щастливо Mint 11, та чак в тия дни се изненадах, като забелязах, че актуалната версия е 14. Не че съм умрял за cutting-edge технологиите чак толкова, ама реших да се прехвърля на нещо по-ново.

Ето как става това, без да се прави чиста преинсталация Ето как си счупих пингвина, след което се наложи чиста инсталация от bootable flash drive:

  1. Отваря се терминал, в който се пише sudo bash и се отваря за редакция /etc/apt/sources.list (списъка с източници за обновяване). Примерно с gedit /etc/apt/sources.list
  2. Заместват се наличните записи с тези:deb http://packages.linuxmint.com/ nadia main upstream import
    deb http://archive.ubuntu.com/ubuntu/ quantal main restricted universe multiverse
    deb http://archive.ubuntu.com/ubuntu/ quantal-updates main restricted universe multiverse
    deb http://security.ubuntu.com/ubuntu/ quantal-security main restricted universe multiverse
    deb http://archive.canonical.com/ubuntu/ quantal partner
    deb http://packages.medibuntu.org/ quantal free non-free
    # deb http://archive.getdeb.net/ubuntu quantal-getdeb apps
    # deb http://archive.getdeb.net/ubuntu quantal-getdeb games

  3. После се засилва apt-get update;
  4. Същинската част, за която вече ще трябва да има направени backup-и на всичко важно е тук – apt-get dist-upgrade, след което трябва да се случи и apt-get update.
  5. Ако всичко е минало (що-годе) както трябва, накрая ще е се наложи само да рестартирате, за да се появи новата Мента.

Сега рестартирам, за да видя при мен до колко са се омазали нещата…

Та тъй де, рестартирах и Gnome-а повече не пожела да работи. След още известни заигравки в recovery mode установих, че все пак ще трябва да си направя чиста инсталация. С други думи – bootable usb flash drive го сглабям със свалено iso от linuxmint.com и го натъпквам с unetbootin на самата флашка. Рестартирам компа, стараейки се да избера стартиране от flash-ката и от там насетне вече е познат процеса.

 

Изчистване на dns кеша на Chrome

Внимание! Статията е стара и вероятно няма да проработи за последните версии на Chrome! По-долу има актуално решение.

Безкрайно досадно явление на моменти е кеширания стар адрес на даден сайт, когато ние сме го пренасочили другаде. Chrome я прави тая дивна глупост, без да предоставя някакъв по-интуитивен начин за изчистването му. Реално трябва да му се бръкне малко “в червата”, за да стане номера.

chrome://net-internals/#dns

Този адрес съдържа страничката със всички текущо кеширани dns-и на сайтове, които са били отваряни или към които са отивали заявки поради някаква причина. Clear host cache бутона ни освобождава от всичко, запазено до момента, след което броузъра си търси ip-тата от dns-а на доставчика ни. Та в следващия момент ако идва отново грешно ip, то това е заради доставчика вече.

Новото решение (писано 2013.11.24):

В един момент проблемът спря да се оправя от тоя адрес и когато си създавах записи в hosts файла към различни адреси, те не се отразяваха в броузъра. Това, което се оказа решението, колкото и да е тъпо, бе да се отиде в настройките и да се изчисти историята: Settings -> Privacy -> Clear browsing data… -> Clear browsing history & cache (не съм сигурен кое от двете беше).