Skip to content

Скептична яма за идеи

и други бележки към мене си

  • начало
  • tech
  • блог
  • здраве
  • приключения
  • ядене
  • бизнес
  • деца
  • Кой?

Category: tech

Уж се занимавам с технологии от 2000, ако не и по-отдавна, но продължавам да не пиша много по въпроса. Част от нещата, които счета за нужно да бъдат документирани все пак, ще се появяват тук, били те свързани с Linux, WordPress, програмиране, компютрите като цяло или каквото и да било друго в тази посока.

Getting into wp-admin through the file system

Posted on 2020.03.24 by vloo

Let’s say we have access to a WordPress-based website’s file system and we want to get in the administration. Usually one could do that by creating a new user in the database after getting the credentials for the DB from wp-config.php. Sure, but there might be some ridiculous cases when we don’t have access to that.

A simple approach could be to work around the login system in order to get a valid administrator session by editing just a single symbol in the core. If you would need to return again and again, you could even create a user of your own.

Here’s the following line of code in wp-includes/user.php on line 177:

if ( ! wp_check_password( $password, $user->user_pass, $user->ID ) ) {

The obvious approach would be to remove !, thus allowing for any attempt with a valid user to be successful, apart from the one with the correct password. It’s probably needless to say that the login should be protected from other login attempts, as this could otherwise lead to a random brute-forcing bot to get inside too.

Posted in techLeave a comment

Locking a WordPress website against anonymous users

Posted on 2020.01.16 - 2020.01.13 by vloo

For a long period of time I used Members plugin for locking up the website and redirecting all requests to the default WordPress login page whenever I needed to create a private website. Recently I had a similar task, to I tried the same approach, but I was surprised by the changes that have taken place while I was “gone”.

The plugin is now called User Role Editor by Members – Best User, Role and Capability Management Plugin for WordPress. I do remember a rule that was saying a title has to be a title and not a bloody description of the plugin, but hey, who am I to judge?

Another change was the set of functionalities that the plugin now has. The current owners and developers have created something of a freemium add-ons based business model. That’s cool, but I just need a plugin for closing my site for the general public.

Anyways, I tried disabling all features but the one for redirecting anonymous traffic to my login page + restricting the feeds and the REST API… result was repeating redirection to the login page every time I provide correct credentials. Meh…

As I did not have enough time to investigate why it wouldn’t work on a mint WordPress 5.3.2 installation, I decided to move along and find another one that would fit my needs without all the new features.

My Private Site turned out to be a neat simple plugin that is no longer maintained, but yet – it works like a charm with just a single checkbox clicked from its settings. I guess I’ll be switching to this one on my other sites then.

P.S. It’s somewhat important to have in mind, that My Private Site falls short in hiding the content from the RSS Feeds and REST API, so you should take some extra measures to lock these. Disable Feeds and Disable REST API plugins did the job for me, but generally these could be achieved by a few lines of PHP code for returning “false” for a bunch of filters.

Posted in techTagged plugins, wordpressLeave a comment

Replacing Jetpack’s mosaic galleries by independent plugins

Posted on 2020.01.13 - 2020.01.13 by vloo

If you are fed up with Jetpack’s obtrusiveness, you might consider replacing it. One of the fine features I’ve seen in it is the image carousel with mosaic preview of the standard WordPress galleries.

Plugins I use and seem to be doing the job rather well are Tiled Galleries Carousel Without Jetpack, combined with Simple Lightbox. If you are using a modern version of WordPress, then you must be familiar with Gutenberg – the new content editor. Sadly, the Tiled Galleries Carousel Without Jetpack plugin is not actively maintained, so it does not work well with the new editor, which is why as a temporary workaround, you’ll have to install Classic Editor plugin too, in order to edit the posts or pages with galleries with it. It’s an inconvenience, but still a minor one.

Posted in techTagged advanced galleries, Gutenberg incompatibility, Jetpack, plugins, wordpressLeave a comment

Downloading videos from Facebook

Posted on 2019.11.24 - 2019.12.18 by vloo

I guess this is already written in way too many places, but I found it out by accident, so decided to document it for future reference.

  1. Open a video in Facebook to a URL, looking like this one:
    https://www.facebook.com/advert.ge/videos/2368003426792387/
  2. Get the ID of the video, being the number that you see after /videos/ part.
  3. Visit the following URL, replacing the number with the ID you have from the original video:
    https://m.facebook.com/watch/?v=2368003426792387
  4. Click on the video – it would open and start playing in a new browser tab.
  5. Save the video by pressing Ctrl + S. This would trigger a download, probably asking you where to save the .mp4 file and how to rename it.

That’s it, lemme know if this works for you.

Posted in techLeave a comment

Setting up PHP CodeSniffer on Sublime for applying WordPress Coding Standards

Posted on 2019.11.01 by vloo

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.

Posted in techTagged code smells, linter, linux, phpcbf, phpcs, programming, sublime, wpcsLeave a comment

How to contribute to the community by translating WordPress

Posted on 2019.10.22 - 2019.12.18 by vloo

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!

Posted in techTagged contribution, glotpress, translation, wordpress, работаLeave a comment

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

Posted on 2018.09.14 - 2018.11.25 by vloo

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

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

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

 

Posted in techLeave a comment

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

Posted on 2015.10.14 by vloo

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

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

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

GravityView has passed $100k in sales – GravityView

Posted in tech, бизнесLeave a comment

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

Posted on 2014.08.20 - 2016.12.04 by vloo

Известно време имах ужасяващата драма с невъзможността да подкарам 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 библиотеки.

Posted in techTagged linux, tzar, wineLeave a comment

Облак си търси мрежар

Posted on 2014.07.16 - 2019.12.18 by vloo
GetClouder е най-новата българска услуга за облачен хостинг. Няма да ги хваля, преди да съм ги ползвал, но знам какви хора стоят зад нея, заради което си заслужават споменаването.
Мариян Маринов ми сподели, че си търсят нов мрежар. И не става въпрос за стажантска позиция, а такава, в която човекът поназнайва в повечко.
Ще се изгражда облачна инфраструктура, multiple datacenters, redundacy… Всъщност цитирам и това:
Имаме infiniband и softswitches с openvswitch & openflow + ще правим един интересен DDoS mitigation device на 40-80Gbit/s
 Не разбирам, щото съм гном, но ми звучи като нещо предизвикателно. Ако ви е станала интересна цялата тази работа, пишете ми в коментарите, във формуляра на сайта (някъде наоколо беше) или каквито други мои контакти успеете да stalk-нете.
Posted in techTagged работаLeave a comment

Posts navigation

Older posts
Newer posts
Proudly powered by WordPress | Theme: micro, developed by DevriX.