Friday, August 1, 2014

Resolving Laravel blade template engine and angularjs conflict

If you use angular.js with laravel for the first time, then you might be interested in how to solve double curly brackets conflict.

{{ variable }}

How can we solve this? Actually we have several ways:

1. Change the angular.js tags

var angularAppName = angular.module('angularAppName', [], function($interpolateProvider) {
    $interpolateProvider.startSymbol('{%'); // This might be dangerous, if you use Twig (if you know what I mean)
    $interpolateProvider.endSymbol('%}');
});

Now you can use your angular expressions like: {% 1 + 2 %}

2. Change the blade templating tags

Blade::setContentTags('<%', '%>'); // For average variables
Blade::setEscapedContentTags('<%%', '%%>'); // For escaped variables

Now you can use your blade expressions like: {% $someVariable %}

Of course you can refuse to use Blade Templates and use Twig instead (search for Laravel Twig bridge in google), or use native PHP as a template engine. This can also solve this problem.

This note was made by me, but original article you can finde here: http://scotch.io/bar-talk/quick-tip-using-laravel-blade-with-angularjs

Thursday, July 31, 2014

VK.com CURL authorization (without standart API)

Few days ago I decided to write a bot for http://olike.ru. Bot was successfully written, but one of my VK.com accounts was frozen for few minutes. So, if you'r planning to use bots in VK.com, be aware, big brother is watching you :)

How can we login into VK.com ? I'ts not that hard, but it has some tricky steps.

1. Firstly we need to send GET request to http://m.vk.com and get "ip_h" parameter (it will be needed later)

$curl = curl_init();
$options = [
    CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; rv:26.0) Gecko/20100101 Firefox/26.0', // You can use any other user agent
    CURLOPT_URL => 'http://m.vk.com',
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_TIMEOUT => 30
];

curl_setopt_array($curl, $options);
$response = curl_exec($curl);

preg_match('/ip\_h\=(.*?)\&/is', $response, $match);

$ip_h = $match[1];

2. Next, using ip_h parameter, we need to create next url for POST request to vk.com. This request if needed to get the link for actual authentication.

$data = [
    'email' => 'Your vk.com login or email',
    'password' => 'Your vk.com password'
];

$url = 'https://login.vk.com/?act=login&_origin=http://m.vk.com&ip_h='.$ip_h.'&role=pda&utf8=1';

$options = [
    CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; rv:26.0) Gecko/20100101 Firefox/26.0',
    CURLOPT_URL => $url,
    CURLOPT_POSTFIELDS => http_build_query($data),
    CURLOPT_POST => 1,
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_HEADER => 1,
    CURLOPT_SSL_VERIFYPEER => 0,
    CURLOPT_SSL_VERIFYHOST => 0,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_COOKIEFILE => 'Path to cookie.txt file', // You can create this file wherever you want. As for me, it was in the same folder as script
    CURLOPT_COOKIEJAR => 'Path to cookie.txt file',
];

curl_setopt_array($curl, $options);
$response = curl_exec($curl);

3. Now we need to parse a little response from the last request, and get from there URL, so we can finally log into the system and make some dirty things

// Getting our login URL
preg_match('/Location: (.*?)\n/is', $response, $match);

// Removing all whitespaces
$url = trim($match[1]);

// Sending request and now we must be logged in
$options = [
    CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; rv:26.0) Gecko/20100101 Firefox/26.0',
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_HEADER => 1,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_COOKIEFILE => 'Path to cookie.txt file',
    CURLOPT_COOKIEJAR => 'Path to cookie.txt file'
];

curl_setopt_array($curl, $options);
curl_exec($curl);

// Closing CURL
curl_close($curl);

This is it :) Now you can send some request, that requires authorization (e.g. add likes to photos, join groups and so on)

Tuesday, July 29, 2014

Laravel package review: Sentry - authentication & authorization system

Brief view

Cartalyst/Sentry is one of the best packages for Laravel 4 (not only), that provides authentication and authorization features. Besides authentication and authorization, Sentry provides group management, permission control, registration, custom hashing and additional security features. You can read full documentation on official Cartalyst page: https://cartalyst.com/manual/sentry

Requirements

  • PHP 5.3+

Supports

  • Laravel 4+
  • Code Igniter 3.0-dev
  • Fuel PHP 1.x
  • Native PHP

Review

First of all, Sentry is really easy to install package. Using Composer your authentication/authorization system will be ready to use in minutes, you just need to add "cartalyst/sentry": "2.1.*" string to your composer.json require array and run composer update.
After installation you will need to configure app.php laravel config, to register provider and its alias, run migrations and publish Sentry config. More detailed documentation you can view on the official Cartalyst page.
Its really easy to work with Sentry. All errors are thrown as an exceptions, and you can easily handle them. As an example, i will show you registration code:

try
{
    // Let's register a user.
    $user = Sentry::register(array(
        'email'    => 'john.doe@example.com',
        'password' => 'test',
    ));

    // Let's get the activation code
    $activationCode = $user->getActivationCode();

    // Send activation code to the user so he can activate the account

}
catch (Cartalyst\Sentry\Users\LoginRequiredException $e)
{
    echo 'Login field is required.';
}
catch (Cartalyst\Sentry\Users\PasswordRequiredException $e)
{
    echo 'Password field is required.';
}
catch (Cartalyst\Sentry\Users\UserExistsException $e)
{
    echo 'User with this login already exists.';
}

As you can see, this code is really straight forward. All other functions of Sentry works the same. Code is clear and follows FIG standarts. As for me, I was able to integrate this package with my own social authentication module, because of high customization level of Sentry.
Despite all advantages, I actually had one problem. Sentry has its own social authentication package (Sentry-social), which can work together with Cartalyst. Sad, but I was unable to configure latest version of Sentry with Sentry-social because of some errors. Moreover, i was even unable to find on github source codes of Sentry-social.

Conclusion

As for me, this is one of the best authentication/authorization packages I have ever worked with, not only on Laravel, but on Kohana and Code Igniter too. I strongly recommend you to try it out despite working on your own authorization system.

Friday, July 25, 2014

"Why do I fail?" story


Useful tips on how to create successful business for less than 100$

Based on an article by Tim Ferris: http://fourhourworkweek.com/2012/05/24/six-figure-businesses-built-for-less-than-100-17-lessons-learned/. I just wrote down few interesting moments to sum up the article.

1. Create something, that people don't know how to do (or its hard to understand), but they are interested in this. Provide your product with results (photos, videos, experience etc.)
2. Make things simple. Provide articles with detailed explanations, images, how-to videos.
3. Start quick and start cheap.
4. You always can find money, just be smart. Use kickstarter like websites, try to find the solution. "No" is not always the end answer.
5. Add payment functions to your website. Make them simple.
6. Take a look on something, that people love and hate. This can be a good business model. Make things for those, who love it.
7. Don't work hard, work smart.
8. Try to make things better. You can base on your previous experience and do better experience for your potential customers.
9. Be open to change, test new ideas and new ways.
10. "Make your offer so compelling that buyers have no reason to say no. Give them an offer they can’t refuse."
11. Give people what they really want. Dig deeper into the problem, try to figure out what people really want, not what they say they want.
12. Sell happiness
13. Focus on your actual customers
14. Offer a strong guarantee. Make people trust you, be open.
15. If you have no money on marketing, try to self-promote your product, "hustle" around.
16. Plan your product launch long before actual start. Make people excited, make people want your product like "movie trailers and so on"
17. Learn from mistakes. Learn from your mistakes and other people mistakes too.

Thursday, July 10, 2014

How to configure SSL under Apache 2 + Laravel

Quick tips on how to setup SSL under LAMP stack + Laravel 4.2 PHP framework.

We need to get certificate itself. In order to run your webpage through HTTPS protocol, we will need 3 files:

  1. SSL certificate private key file (.key)
  2. Certificate Signin Request (.csr)
  3. SSL certificate file (.crt)
  4. SSL chain file (.ca-bundle)

This extensions (.key .crt etc.) can differ. In different guides i saw different extensions, like .pem or .ca, so dont worry about that.

1st and 2nd file we will generate on our server machine; 3rd and 4th file we will get from certification service.

So lets start! We need to open terminal and paste commands below (commands will be explained):

1. cd ~/Documents/SSL
SSL is a custom folder created by me. You can store your certification files wherever you want, I used path above.

2. sudo openssl genrsa -des3 -out private.key 2048
Generating "private.key" file with 2048 bit encryption. We will need this to generate our CSR (2nd file) and later, when we will setup apache virtual hosts.

3. sudo openssl req -new -key private.key -out server.csr
Generating "server.csr" file in order to get our certificate. While this step You will need to fill in some information, that system will request you:

Country Name (2 letter code) [AU]: EE
State or Province Name (full name) [Some-State]: Harjumaa
Locality Name (eg, city) []: Tallinn
Organization Name (eg, company) [Internet Widgits Pty Ltd]: Your Company Name Ltd
Organizational Unit Name (eg, section) []: IT
Common Name (eg, YOUR name) []: www.yourdomain.com
Email Address []: youremail@gmail.com
A challenge password []: (you can leave it blank)
An optional company name []: (you can leave it blank)

Of course you can edit all those fields as you want.

4. Now we'r going to http://www.comodo.com/e-commerce/ssl-certificates/free-ssl-certificate.php and registering our certificate. In order to get certificate, you will need to provide CSR, that we already generated. Opening server.csr with, for example, nano sudo nano server.csr (or gedit, or vim, or download it through filezilla etc.) and copy text in server.csr. It should look like:

-----BEGIN CERTIFICATE REQUEST-----
MIIDUDCCArkCAQAwdTEWMBQGA1UEAxMNdGVzdC50ZXN0LmNvbTESMBAGA1UECxMJ
TWFya2V0aW5nMREwDwYDVQQKEwhUZXN0IE9yZzESMBAGA1UEBxMJVGVzdCBDaXR5
(more encoded data).......
Rq+blLr5X5iQdzyF1pLqP1Mck5Ve1eCz0R9/OekGSRno7ow4TVyxAF6J6ozDaw7e
GisfZw40VLT0/6IGvK2jX0i+t58RFQ8WYTOcTRlPnkG8B/uV
-----END CERTIFICATE REQUEST-----
In "Select the server software used to generate the CSR" field choose Apache-ModSSL (if you use LAMP stack, of course).

In "Select the hash algorithm you would prefer us to use when signing your Certificate" choose anything you want.

Complete the registration. You will need to confirm your domain, because of that confirmation will be sent one one of your domain emails (like admin@yourdomain.com or webmaster@yourdomain.com).

When you will totally complete registration, certificate will be sent to your email in zip archive. This archive will contain 2 files: certificate file (.crt) and chain file (.ca-bundle). Dont ask me, why we need this .ca-bundle, just google it :)

5. Upload this 2 files on your server certificate directory (for me it was ~/Documents/SSL/)

6. Edit your apache virtual host, as now we'r going to use secured connection. You will need to create new secured virtual host:
sudo cp /etc/apache2/sites-available/example.conf /etc/apache2/sites-available/yoursite.com.secured.conf
I dont actually remember name of the example.conf file, but you need to create copy of the virtual host, or just create new one with touch /etc/apache2/sites-available/yoursite.com.secured.conf

7. Add inside <VirtualHost> tag instuctions below, and dont forget to change virtual host port to 433:
SSLEngine on
SSLCertificateFile /home/ubuntu/Documents/SSL/your_domain.crt
SSLCertificateKeyFile /home/ubuntu/Documents/SSL/private.key
SSLCACertificateFile /home/ubuntu/Documents/SSL/your_domain.ca-bundle
8.  sudo a2ensite yoursite.com.secured.conf
To activate this virtual host
Besides your secured virtual host, you must have your regular virtual host with 80 port and without SSLEngine on etc. 

9. Change your Laravel .htaccess text to text below, so it will redirect all regular http request to https
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^(yourdomain.com)
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI}%{QUERY_STRING} [L,R]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
10. sudo service apache2 restart :)

Thank you.
Here's an example: https://andymarrel.eu
        

Saturday, May 24, 2014

Github switch between branches after cloning repo

git clone <somerepo> .
git branch -a // View all branches
git checkout -b <branch_name> origin/<branch_name>

Sunday, March 23, 2014

LAMP: Updating PHP from 5.3.x-ubuntu to 5.4.x (custom rep.)

sudo apt-get install python-software-properties
sudo add-apt-repository ppa:ondrej/php5-oldstable
sudo apt-get update; sudo apt-get install php5

Thanks to: http://askubuntu.com/questions/343560/update-server-php-version-to-5-4-10-via-the-command-line

Wednesday, March 19, 2014

CSS #1

CSS position:
Absolute positioning

HTML:
<div class="container">
<div class="innter-container">
</div>
</div>

CSS:
.container { position: relative; }
.inner-container { position: absolute }


CSS after and clearfix:
// This will add 'Sample text' after each p element
//  It also can be p:after, but :: is a CSS 3 syntax
p::after {
content: 'Sample text';
}

// Fixing parent container height, when using inner elements with float:right/left
.container::after {
content: '.';
display: block;
height: 0;
clear: both;
}

CSS Triangle:
width: 0;
height: 0;
border-top: 10px solid #000;
border-left: 10px solid transparent;
border-right: 10px solid transparent;

CSS background:
background-image: url(path_to_img), url(path_to_2_img);
background-repeat: no-repeat, repeat;


Monday, March 17, 2014

Ежедневные достижения

Считаю, что любой человек должен постоянно совершенствоваться. Никогда не поздо начать, правда?  Я упустил много возможностий, совершил кучу ошибок, которые так или иначе повлияли на мою жизнь. Чёрная полоса, затем белая, затем снова чёрная и так всегда. Сначала ты создаешь себя, идешь за своими мечтами, а потом всё сжигаешь и встаёшь на путь саморазрушения.
Однажды я прочитал (а может мне рассказали, или я вообще это сам себе придумал) про человека, который ежедневно записывал свои достижения. Под достижениями он имел в виду не глобальные события, а совсем, с первого взгляда, незначительные вещи (такие как сходил на прогулку, прочитал статью и т.д.), т.е. абсолютно всё, благодаря чему можно стать немного лучше. Именно этим я и планирую заняться. Полагаю, что это хороший способ мотивировать себя. Ну а если не выйдет, я по крайней мере попробовал :)

Достижения за сегодня:
1. Сделал несколько упражнений на лингуалео, начал изучать новые английские слова.
2. Занимался веб-разработкой (делал каркас нового сайта). Скриншот можно посмотреть ниже.










UPDATE:
Откровенно говоря на следующий день я осознал, что если каждый день буду записывать в блог по 1-2 достижения, то забью его совершенно бесполезной информацией. Думаю весь этот фестиваль перекочует в Твиттер.

Tuesday, March 4, 2014

Laravel custom application autoloading folder

1. Creating folder in your /app/YOUR_DIRECTORY_NAME
2. Adding this directory to array in /app/start/global.php 
ClassLoader::addDirectories(array(
   app_path().'/commands',
   app_path().'/controllers',
   app_path().'/models',
   app_path().'/database/seeds',
   app_path().'/YOUR_DIRECTORY_NAME',
));
3. Now you can add new classes to your /app/YOUR_DIRECTORY_NAME without any namespace (if this class is not in subfolder)

Thursday, January 9, 2014

Мэтью Арнольд "Доверья океан..."

Доверья океан
Когда-то полон был и, брег земли обвив,
Как пояс радужный, в спокойствии лежал
Но нынче слышу я
Лишь долгий грустный стон да ропщущий отлив
Гонимый сквозь туман
Порывом бурь, разбитый о края
Житейских голых скал.

Дозволь нам, о любовь,
Друг другу верным быть. Ведь этот мир, что рос
Пред нами, как страна исполнившихся грез,-
Так многолик, прекрасен он и нов,-
Не знает, в сущности, ни света, ни страстей,
Ни мира, ни тепла, ни чувств, ни состраданья,
И в нем мы бродим, как по полю брани,
Хранящему следы смятенья, бегств, смертей,
Где полчища слепцов сошлись в борьбе своей