Thursday, April 23, 2015

Installing full LAMP stack + phpmyadmin on Ubntu 14.04 LTS AWS EC2 instance

Just a step by step tutorial:

1. sudo apt-get update
2. sudo apt-get install apache2
3. Check if apache installed correctly by visiting your servers public IP address:

http://your-servers-ip

4. sudo apt-get install mysql-server php5-mysql #installing mysql
5. sudo mysql_install_db #create database directory structure
6. sudo mysql_secure_installation #run secure installation (just follow the instructions)
7. sudo apt-get install php5 libapache2-mod-php5 php5-mcrypt php5-curl php5-json #install php and some extensions (optionally), like mcrypt, curl and json

You can view all available php5 extensions by running this command in terminal: 

apt-cache search php5-

8. sudo nano /etc/apache2/mods-enabled/dir.conf #place index.php on the first position (instead of index.html by default)

Finally it should look like  

<IfModule mod_dir.c>
    DirectoryIndex index.php index.html index.cgi index.pl # and so on...
</IfModule>

9. sudo service apache2 restart
10. In order to install phpmyadmin you should have mcrypt php5 module installed and activated

sudo apt-get install php5-mcrypt #downloading mcrypt extension

sudo php5enmod mcrypt #activating mcrypt extension

11. sudo apt-get install phpmyadmin
12. sudo service apache2 restart

Now if you will visit http://your-public-ip/phpmyadmin, phpmyadmin page should appear BUT for me it was 404 not found error. To fix this bug you need to follow steps below:

13. sudo ln -s /usr/share/phpmyadmin /var/www/html #create symlink
14. sudo nano /etc/phpmyadmin/apache.conf #open phpmyadmin apache config file and add this line to the end of a file:

Include /etc/phpmyadmin/apache.conf

15. sudo service apache2 restart #restart apache server and try to visit http://your-public-ip/phpmyadmin

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

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

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

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

Thursday, December 5, 2013

Без автора "Одиноким людям не спится..."

Одиноким людям не спится.
Им до жути скучно ночами.
Таким людям однажды не спиться бы,
Вы по ним
Никогда
Не скучали.

Они сходят с ума ежедневно.
Одиночки
От жизни устали.
Они пишут стихи, но, наверное,
Вы Такое
Читать бы
Не стали.

Они замкнуты,
Словом ранены.
Им страшно кого-то любить.
Они чешут душевные ссадины.
Они жаждут
Кого-то
Забыть.

Saturday, November 23, 2013

LAMP: Creating virtual hosts and resolving 500 Internal server error

This guide expects, that you already have web server on your machine.

1. Copy file /etc/apache2/sites-available/default and rename it to your host name. (for example testweb.net. Also your web application must be in /var/www/testweb.net/ directory.) Dont forget to add permissions to your web application directory using
sudo chmod -R 755 /var/www/testweb.net/ For development you can use 777, but it is still not the best practice.
sudo cp /etc/apache2/sites-available/default /etc/apache2/sites-available/testweb.net

2. Configure testweb.net file
gksudo gedit /etc/apache2/sites-available/testweb.net

This command will open testweb.net file in gedit text editor.

ServerName testweb.net
<VirtualHost *:80>
 ServerAdmin admin@mail.com
 ServerName testweb.net
 ServerAlias www.testweb.net
 [...]

DocumentRoot /var/www/testweb.net
I'm using my own hosts configuration file:
    ServerNametestweb.net
    ServerAlias www.testweb.net

    DocumentRoot /var/www/testweb.net
    <Directory /var/www/testweb.net>
        # enable the .htaccess rewrites
        AllowOverride All
        Order allow,deny
        Allow from All
    </Directory>

    ErrorLog /var/log/apache2/project_error.log
    CustomLog /var/log/apache2/project_access.log combined
</VirtualHost>

3. Activate your host

sudo a2ensite testweb.net

4. Edit /etc/hosts
gksudo gedit /etc/hosts
Add this line to hosts file:

127.0.0.1    testweb.net

5. Now you need to restart your apache service.
sudo service apache2 restart
Voila, your virtual host is now available!

What should you do, if you have 500 Internal Server Error? 

This problem might be caused by .htaccess file in your project root dir. First of all, check your logs (/var/log/apache2/) and try to access your site by this link: localhost/testweb.net. But for me it was not enough, so I found this solution (not sure what this command do, so run it on your own risk T_T)

sudo a2enmod rewrite
sudo service apache2 restart

Here you can read about 500 error solving: http://askubuntu.com/questions/148246/apache2-htaccess

This resource was really helpful: https://www.digitalocean.com/community/articles/how-to-set-up-apache-virtual-hosts-on-ubuntu-12-04-lts

P.S. YEAH, I know, there are LOTS of english mistakes, sorry for that :(

Thursday, November 14, 2013

SVN resolving problem: "containing working copy admin area is missing"

For an instance, we're having this error: "some/folder/.svn containing working copy admin area is missing".

There are lots of solutions here: http://stackoverflow.com/questions/1394076/how-to-fix-containing-working-copy-admin-area-is-missing-in-svn, but here's the one, that worked for me (not the most elegant, I suppose, but it worked):

1. Remove the conflicted folder (if there are some uncommited files, we need to back them up)
cd /your/project/root
sudo rm -rf some/folder
svn up
2. Commit your changes!

Wednesday, November 13, 2013

Setting up permissions on Ubuntu for /var/www (web server)

In ubuntu all web projects are in /var/www folder, so you need to set up permissions on writing files, as by default this folder belongs to root user.

1. First of all you need to ensure, that your current user belongs to www-data group. Adding user to www-data group:

sudo adduser username www-data

You can find your username by typing this command:

whoami

2. Next we need to change /var/www folder owner and owner group:

sudo chown username:www-data -R /var/www

3. Next we need to change /var/www permissions to 755 (777 not recommended due security reasons)

sudo chmod 755 -R /var/www
sudo chmod g+s -R /var/www

Information from: http://askubuntu.com/questions/162866/correct-permissions-for-var-www-and-wordpress

Wednesday, November 6, 2013

Ruby: exceptions

raise "Exception message" // this will throw RuntimeError exception with message "Exception message"

begin
  10/0 // This will raise an DivisionByZero exception
rescue DivisionByZero
  puts "Devision by zero exception"
end
Creating custom exception:
class CustomException > StandardError
end

Ruby: OOP (privacy)

Methods are public by default in Ruby.

class Test

  def public_m
  end

  private
  def private_m
  end

  // Again private method, because all methods after private keyword will be private
  def private_m_2
  end

end
Modules are containers for methods and constants.

module MyModule
  // Call it: MyModule::MOD_CONSTANT
  MOD_CONSTANT = "Module constat"

  // Call it: MyModule.my_method
  def my_method
  end
end
Require module by typing require 'MyModule', so it will be available in whole file (Module.my_method)

Include module to class, so it will be available inside class and all the methods can be called without module name:


class SimpleClass
  include MyModule // Without '
  def m
    my_method
  end
end
Infromation from: www.codeacademy.com