Encrypting links for WP-NoExternalLinks

Warning! I no longer support this plugin after version 3.5.9.9! Please ask questions on wordpress support page.

This article is based on this one and the latest version of plugin. Now you can easily encrypt your links without changing plugin code.

  1. Ensure that you have php-mcrypt installed:

For CentOS, type

sudo yum install php-mcrypt

For ubuntu, type

sudo apt-get install php5-mcrypt

For windows, enable this extension in php.ini:

extension=php_mcrypt.dll
  1. Create file wp-content/uploads/custom-parser.php and add here the following:
salt ='ms8-sRt-kBs5-s1wQ';
    $this->iv=mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND);
  }
  function encode_link($url)
  {
    if(!$this->salt)
      $this->init_crypt();
    return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->salt, $url, MCRYPT_MODE_ECB, $this->iv)));
  }
  function decode_link($url)
  { 
    if(!$this->salt)
      $this->init_crypt();
    return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->salt, base64_decode($url), MCRYPT_MODE_ECB, $this->iv));
  }
}
?>

Do not forget to change $salt to any custom value! Also, add statistic handling from the original function if you use statistics.

Custom parser for WP-NoExternalLinks

Warning! I no longer support this plugin after version 3.5.9.9! Please ask questions on wordpress support page.

Recently I added a new feature to this plugin. Now you can extend it yourself without danger of plugin update which could remove all your changes in plugin code.

In this sample, we will overwrite function check_follow, which checks if link is posted by admin and has rel=”follow” attribute. Let’s imagine we want all our authors to have the same options. How can we accomplish it? Easily! Just create file custom-parser.php in directory wp-content/uploads and replace

user_can($author,'manage_options' );
from original function with
user_can($author,'publish_posts' );
- voila!

Here is the full code of our new modified class which will be loaded instead of basic one:

wp-content/uploads/custom-parser.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php
if(!defined('DB_NAME'))
die('Error: Plugin "wp-noexternallinks" does not support standalone calls, damned hacker.');

#include base parser
include_once(ABSPATH . 'wp-content/plugins/wp-noexternallinks/wp-noexternallinks-parser.php');

class custom_parser extends wp_noexternallinks_parser
{
function check_follow($matches)
{
#support of "meta=follow" option for admins. disabled by default to minify processing.
if(!$this->options['dont_mask_admin_follow'])
return false;
$id=array(get_comment_ID(),get_the_ID());//it is either page or post
if($id[0])
$this->debug_info('It is a comment. id '.$id[0]);
elseif($id[1])
$this->debug_info('It is a page. id '.$id[1]);
$author=false;
if($id[0])
$author=get_comment_author($id[0]);
else if($id[1])
$author=get_the_author_meta('ID');
if(!$author)
$this->debug_info('it is neither post or page, applying usual rules');
elseif(user_can($author,'publish_posts' )&&(stripos($matches[0],'rel="follow"')!==FALSE || stripos($matches[0],"rel='follow'")!==FALSE))
{
$this->debug_info('This link has a follow atribute and is posted by author, not masking it.');
#wordpress adds rel="nofollow" by itself when posting new link in comments. get rid of it! Also, remove our follow attibute - it is unneccesary.
return str_ireplace(array('rel="follow"',"rel='follow'",'rel="nofollow"'),'',$matches[0]);
}
else
$this->debug_info('it does not have rel follow or is not posted by author, masking it');
return false;
}
}
?>

One more sample is encrypting links.

Бегущий в лабиринте - победа маркетинга над разумом

Только что дочитал трилогию, по которой недавно вышел фильм, покрывший первую книгу. Ужасное впечатление. Похоже на подвиг графомана-любителя. Как такое могло стать бестселлером и тем более выйти на экран - загадка загадок. Дабы не быть голословным, распишу немного по пунктам.

  1. за всю трилогию нет никакой эволюции персонажей. Какими они были с самого начала - такими и остались.
  2. “глубокие переживания” и эмоции персонажей поднимаются не выше пятого класса средней школы. Всё просто как сценарий телевизионного ток шоу на канале тнт. С учётом того, что нам ещё и пытаются скормить, что это самые умные и наиболее эмоциональные подростки… It smells.
  3. рояли выпрыгивают из кустов с такой скоростью и в таком количестве, что повествование даже нельзя воспринимать всерьёз. Ты заранее знаешь, что тебя наёбывают. Причём делают это крайне топорным методом - например, загадка разрешается ответом “просто всемогущие наблюдатели, которые могут делать что угодно с их мозгом, подменили их восприятие”.
  4. на корню отсутствует хоть какая-то оригинальность мира и сюжета. Впрочем, даже автор признаётся, что именно он так убого копировал.
  5. главной идеи, озарения, катарсиса к концу трилогии - ничего нет. Всё те же рояли.
  6. так же полностью отсутствует какая-либо выразительность и колорит, который раскрашивает черновик повествования. Даже сленг в книге состоит менее чем из десятка слов, и убог донельзя.
  7. персонажи картонные. У большинства даже нет имён. Так и говорится “и тут погибло ещё десять человек, имён которых Томас не знал”. Именные персонажи в общем-то тоже никакие, безо всякой индивидуальности.
  8. абсолютно никак не раскрыты многие идеи и фишки. Например, практически немая и безымянная группа девушек, или сама телепатия. Недаром из фильма её вообще убрали - зачем собаке пятая нога?
  9. на закуску дабы показать примером общую характеристику трилогии. Главный герой убегает из рушащегося строения с двумя неравнодушными к нему девками. Я уже какое-то время задаюсь вопросом, как автор это разрешит. И тут автор разрешает. Одна из них выпихивает его из-под подающих обломков и умирает. Наверное, один из самых скучных штампов за всю историю книгопечатания, в котором автор полностью расписывается в своей беспомощности относительно того, чтобы как-то решить повествовательную задачу. Кстати, только сейчас подумал, что за трилогию это вторая такая идиотская смерть - первым был Чак, который заслонил главного героя грудью от ножа. Феерически бездарный и неправдоподобный штамп.

В общем, смотрите “обитель зла” и читайте “игру эндера” (на самом деле, можно и читать и смотреть и то и другое). А это… Обойдите стороной, сэкономьте время. Дико обидно, что такие вот бездушные и пустые подделки как-то находят путь на прилавки и в кинотеатры.

Пожалуйста, не здоровайтесь со мной

Немного о наболевшем. Есть люди, которые в рабочем общении (скажем, в скайпе) пишут тебе “привет”. И ждут потом. Могут ждать минуты, часы, дни. А суть вопроса так и не напишут. Видимо, они считают это вежливым общением - то ли просто не делают разницу между живым и электронным общением. Мне очень хочется, чтобы к концу прочтения этой статьи они так уже не считали.

  1. Когда вы пишете “привет”, я знаю, что вам от меня что-то нужно. И вы не просто так здороваетесь и интересуетесь, что у меня нового. Так что всё это лирическое вступление без какого-либо рабочего наполнения по определению является мусором.

  2. Вы пишете штук пять бессмысленных тирад, и на каждую из них мне приходится переключиться, чтобы выдать вам бессмысленный ответ. Это занимает время на то, чтобы переключиться на вас, прочитать бессмысленный текст, придумать пустой ответ и попытаться вернуться к своей задаче. Таким образом, на эти предварительные ласки у меня может уйти 5-10 минут, в течении которых я мог бы в концентрации делать свои задачи. Я понимаю, что вам наплевать на моё время, но мне-то нет.

  3. Вы упрямо ждёте, что я окажусь онлайн вместе с вами. А что если нет? Тогда мы потратим трое суток на обмен любезностями, прежде чем вы мне наконец расскажете, в чём дело?

  4. Когда мы наконец перейдём к сути вопроса, вы будете выдавливать в чат по одному предложению, заставляя меня таращиться на этот грёбаный карандаш. Скайп будет непрерывно булькать, чат-мигать, и я вообще ничего не смогу делать. Ещё 10 минут на этот бардак.

  5. Не знаю, как у вас, а со мной так здороваются в день несколько человек. И никто их них почему-то не понимает, когда я прошу этого не делать. И каждый продолжает тратить моё время. В итоге, у меня час уходит на пустое бульканье чата.

Вместо заключения.

Быть вежливым очень просто - пожалуйста, пишите сразу и своё приветствие и суть вашего вопроса. Целиком, одним сообщением. Подробно. Со всем, что, как вы знаете, я у вас спрошу. Если у вас не работает программа - не надо писать “у меня не работает программа”. Вы же не только что с горшка встали. Вы можете написать мне её лог, текст или номер ошибки, в конце концов - скриншот.

Тогда я максимально быстро смогу вам помочь в один присест.

Ну или хотя бы, когда вы пишете приветствие - считайте, что я вам молча пожал руку - и продолжайте дальше.

Searching through skype history

If you have more then 300 contacts and they have overlapping conversations - you understand that it’s impossible to find anything with simple Ctrl+F approach.

Fortunately, Skype uses SQLite database and we can make a direct connect to it and search there directly. So, you need to:

  1. Download SQLite client (i used http://sqlitebrowser.org/ but you can install any client you like)
  2. Find your history file as it is decribed on skype web site:
    Hold down the Windows key The Windows key on your keyboard, then press R to bring up the Run window. If you are using a touch screen device on Windows 8, you can bring up the Run window from the Search charm. Type %appdata%\Skype into the Run window and press Enter. Open the folder named after your Skype Name. Find the main.db file in the folder, this file is your chat history.
  3. Use your SQLite client to open this file.
  4. Open database table “messages”
  5. Use any SQL queries you want to search for message you need. Here’s an example of me searching for “git” word in conversations - but there are many field that you can use for searching and ordering.

Simple bash linux script to login and update web sites from Git repositories

We have some web sites which must be updated from Git repositories by users who have no other permissions on web server. For this task, I imported SSH key to server for authorizing on bitbucket and wrote a simple bash script for four different repos:

#!/bin/bash
 
while true; do
echo "Please choose api to update (enter number)"
select repo in "dev" "a" "b" "test" "EXIT"; do
    case $repo in
        dev ) cd /web/dev;echo "updating:";pwd;git pull origin master; break;;
        a ) cd /web/a;echo "updating:";pwd;git pull origin master; break;;
        b) cd /web/b;echo "updating:";pwd;git pull origin master; break;;
        test ) cd /web/test;echo "updating:";pwd;git pull origin master; break;;
        EXIT ) exit;break;;
    esac
done
echo "Update finished. Want to update more?"
echo ""
done

This bash script is set as login shell for those users - so they can login and update their servers.

Java applet not working after refresh

I had a funny problem with my java applet in web start application - it worked every second time I refreshed web page.

After a little debug I found out that java machine didn’t make it in time to shutdown, start and show applet.

Solution was rather fun:

1
<param name="separate_jvm" value="true" />

It helped because now new instance off applet launched in a new JVM, simultaneously with closing old instance of applet in old JVM.

But be careful if your applet writes something to user disk or etc - both old and new instance can be doing is for a little time!

Invalid signature file digest for Manifest main attributes

Today i run into error

Invalid signature file digest for Manifest main attributes
while running my java web start applet.

I wondered for a while and finally found the reason - yesterday I modified my .pfx key for signing applet, but manifests in jars merge with each other - so I really had jar with invalid digest.

To fix it, I just had to remove META-INF folder from all my jars, add them manifest again and re-sign them. You can remove it with any archiver - for example, with 7-zip.

Warning: The signer`s certificate chain is not validated

I had a week of trouble, signing my web start java applet.

While I signed (with a good COMODO code signing certificate), there was

**Warning: The signer's certificate chain is not validated.**
But I didn't pay much attention to it.

And my signed applet appeared to be of unknown publisher even through “Show details” in browser showed me that applet is signed with the correct certificate. Of cause, it was much restricted - and I need to read user disc, etc… It could be solved my directly installing CA to user computer - but that’s unreasonable to request every user to do it manually. So I suffered for a week and suddenly came up with a solution, inspired by this post (thank you, Supriya Roy):

  1. Install your .pfx certificate with the “Mark this key as exportable. This will allow you to back up or transport your keys at a later time” and “Include all extended properties” checked.

  2. Check that that you have full certificate chain for this certificate and it is valid. Otherwise, install neccessary CA.

  3. Export the installed certificate with “Yes, export the private key” option and “Include all certificates in the certification path if possible” and “Export all extended properties” checked under the option .PFX or PKCS #12.

  4. Use exported .pfx file to sign the JAR. Don’t forget that it could change alias - get new one with

    keytool.exe -list -keystore D:\keys\code.pfx -storetype pkcs12

Worked like magic - warning disappeared and my jars are trusted now!